2004-11-29 Sebastien Pouliot <sebastien@ximian.com>
[mono.git] / mono / metadata / metadata.c
1 /*
2  * metadata.c: Routines for accessing the metadata
3  *
4  * Authors:
5  *   Miguel de Icaza (miguel@ximian.com)
6  *   Paolo Molaro (lupus@ximian.com)
7  *
8  * (C) 2001-2002 Ximian, Inc.
9  */
10
11 #include <config.h>
12 #include <stdio.h> 
13 #include <stdlib.h>
14 #include <string.h>
15 #include <glib.h>
16 #include "metadata.h"
17 #include "tabledefs.h"
18 #include "mono-endian.h"
19 #include "cil-coff.h"
20 #include "tokentype.h"
21 #include "metadata-internals.h"
22 #include "class-internals.h"
23 #include "private.h"
24 #include "class.h"
25
26 static void do_mono_metadata_parse_type (MonoType *type, MonoImage *m, MonoGenericContainer *generic_container,
27                                          const char *ptr, const char **rptr);
28
29 static gboolean do_mono_metadata_type_equal (MonoType *t1, MonoType *t2, gboolean signature_only);
30
31 /*
32  * Encoding of the "description" argument:
33  *
34  * identifier [CODE ARG]
35  *
36  * If CODE is ':', then a lookup on table ARG is performed
37  * If CODE is '=', then a lookup in the aliased-table ARG is performed
38  * If CODE is '#', then this encodes a flag, ARG is the flag name. 
39  *
40  * Aliased table for example is `CustomAttributeType' which depending on the
41  * information might refer to different tables.
42  */
43
44 const static MonoMetaTable AssemblySchema [] = {
45         { MONO_MT_UINT32,     "HashId" },
46         { MONO_MT_UINT16,     "Major" },  
47         { MONO_MT_UINT16,     "Minor" },
48         { MONO_MT_UINT16,     "BuildNumber" },
49         { MONO_MT_UINT16,     "RevisionNumber" },
50         { MONO_MT_UINT32,     "Flags" },
51         { MONO_MT_BLOB_IDX,   "PublicKey" },
52         { MONO_MT_STRING_IDX, "Name" },
53         { MONO_MT_STRING_IDX, "Culture" },
54         { MONO_MT_END, NULL }
55 };
56         
57 const static MonoMetaTable AssemblyOSSchema [] = {
58         { MONO_MT_UINT32,     "OSPlatformID" },
59         { MONO_MT_UINT32,     "OSMajor" },
60         { MONO_MT_UINT32,     "OSMinor" },
61         { MONO_MT_END, NULL }
62 };
63
64 const static MonoMetaTable AssemblyProcessorSchema [] = {
65         { MONO_MT_UINT32,     "Processor" },
66         { MONO_MT_END, NULL }
67 };
68
69 const static MonoMetaTable AssemblyRefSchema [] = {
70         { MONO_MT_UINT16,     "Major" },
71         { MONO_MT_UINT16,     "Minor" },
72         { MONO_MT_UINT16,     "Build" },
73         { MONO_MT_UINT16,     "Revision" },
74         { MONO_MT_UINT32,     "Flags" },
75         { MONO_MT_BLOB_IDX,   "PublicKeyOrToken" },
76         { MONO_MT_STRING_IDX, "Name" },
77         { MONO_MT_STRING_IDX, "Culture" },
78         { MONO_MT_BLOB_IDX,   "HashValue" },
79         { MONO_MT_END, NULL }
80 };
81
82 const static MonoMetaTable AssemblyRefOSSchema [] = {
83         { MONO_MT_UINT32,     "OSPlatformID" },
84         { MONO_MT_UINT32,     "OSMajorVersion" },
85         { MONO_MT_UINT32,     "OSMinorVersion" },
86         { MONO_MT_TABLE_IDX,  "AssemblyRef:AssemblyRef" },
87         { MONO_MT_END, NULL }
88 };
89
90 const static MonoMetaTable AssemblyRefProcessorSchema [] = {
91         { MONO_MT_UINT32,     "Processor" },
92         { MONO_MT_TABLE_IDX,  "AssemblyRef:AssemblyRef" },
93         { MONO_MT_END, NULL }   
94 };
95
96 const static MonoMetaTable ClassLayoutSchema [] = {
97         { MONO_MT_UINT16,     "PackingSize" },
98         { MONO_MT_UINT32,     "ClassSize" },
99         { MONO_MT_TABLE_IDX,  "Parent:TypeDef" },
100         { MONO_MT_END, NULL }
101 };
102
103 const static MonoMetaTable ConstantSchema [] = {
104         { MONO_MT_UINT8,      "Type" },
105         { MONO_MT_UINT8,      "PaddingZero" },
106         { MONO_MT_CONST_IDX,  "Parent" },
107         { MONO_MT_BLOB_IDX,   "Value" },
108         { MONO_MT_END, NULL }
109 };
110
111 const static MonoMetaTable CustomAttributeSchema [] = {
112         { MONO_MT_HASCAT_IDX, "Parent" },
113         { MONO_MT_CAT_IDX,    "Type" },
114         { MONO_MT_BLOB_IDX,   "Value" },
115         { MONO_MT_END, NULL }
116 };
117
118 const static MonoMetaTable DeclSecuritySchema [] = {
119         { MONO_MT_UINT16,     "Action" },
120         { MONO_MT_HASDEC_IDX, "Parent" },
121         { MONO_MT_BLOB_IDX,   "PermissionSet" },
122         { MONO_MT_END, NULL }   
123 };
124
125 const static MonoMetaTable EventMapSchema [] = {
126         { MONO_MT_TABLE_IDX,  "Parent:TypeDef" },
127         { MONO_MT_TABLE_IDX,  "EventList:Event" },
128         { MONO_MT_END, NULL }   
129 };
130
131 const static MonoMetaTable EventSchema [] = {
132         { MONO_MT_UINT16,     "EventFlags#EventAttribute" },
133         { MONO_MT_STRING_IDX, "Name" },
134         { MONO_MT_TABLE_IDX,  "EventType" }, /* TypeDef or TypeRef */
135         { MONO_MT_END, NULL }   
136 };
137
138 const static MonoMetaTable ExportedTypeSchema [] = {
139         { MONO_MT_UINT32,     "Flags" },
140         { MONO_MT_TABLE_IDX,  "TypeDefId" },
141         { MONO_MT_STRING_IDX, "TypeName" },
142         { MONO_MT_STRING_IDX, "TypeNameSpace" },
143         { MONO_MT_IMPL_IDX,   "Implementation" },
144         { MONO_MT_END, NULL }   
145 };
146
147 const static MonoMetaTable FieldSchema [] = {
148         { MONO_MT_UINT16,     "Flags" },
149         { MONO_MT_STRING_IDX, "Name" },
150         { MONO_MT_BLOB_IDX,   "Signature" },
151         { MONO_MT_END, NULL }   
152 };
153 const static MonoMetaTable FieldLayoutSchema [] = {
154         { MONO_MT_UINT32,     "Offset" },
155         { MONO_MT_TABLE_IDX,  "Field:Field" },
156         { MONO_MT_END, NULL }   
157 };
158
159 const static MonoMetaTable FieldMarshalSchema [] = {
160         { MONO_MT_HFM_IDX,    "Parent" },
161         { MONO_MT_BLOB_IDX,   "NativeType" },
162         { MONO_MT_END, NULL }   
163 };
164 const static MonoMetaTable FieldRVASchema [] = {
165         { MONO_MT_UINT32,     "RVA" },
166         { MONO_MT_TABLE_IDX,  "Field:Field" },
167         { MONO_MT_END, NULL }   
168 };
169
170 const static MonoMetaTable FileSchema [] = {
171         { MONO_MT_UINT32,     "Flags" },
172         { MONO_MT_STRING_IDX, "Name" },
173         { MONO_MT_BLOB_IDX,   "Value" }, 
174         { MONO_MT_END, NULL }
175 };
176
177 const static MonoMetaTable ImplMapSchema [] = {
178         { MONO_MT_UINT16,     "MappingFlag" },
179         { MONO_MT_MF_IDX,     "MemberForwarded" },
180         { MONO_MT_STRING_IDX, "ImportName" },
181         { MONO_MT_TABLE_IDX,  "ImportScope:ModuleRef" },
182         { MONO_MT_END, NULL }
183 };
184
185 const static MonoMetaTable InterfaceImplSchema [] = {
186         { MONO_MT_TABLE_IDX,  "Class:TypeDef" }, 
187         { MONO_MT_TDOR_IDX,  "Interface=TypeDefOrRef" },
188         { MONO_MT_END, NULL }
189 };
190
191 const static MonoMetaTable ManifestResourceSchema [] = {
192         { MONO_MT_UINT32,     "Offset" },
193         { MONO_MT_UINT32,     "Flags" },
194         { MONO_MT_STRING_IDX, "Name" },
195         { MONO_MT_IMPL_IDX,   "Implementation" },
196         { MONO_MT_END, NULL }
197 };
198
199 const static MonoMetaTable MemberRefSchema [] = {
200         { MONO_MT_MRP_IDX,    "Class" },
201         { MONO_MT_STRING_IDX, "Name" },
202         { MONO_MT_BLOB_IDX,   "Signature" },
203         { MONO_MT_END, NULL }
204 };
205
206 const static MonoMetaTable MethodSchema [] = {
207         { MONO_MT_UINT32,     "RVA" },
208         { MONO_MT_UINT16,     "ImplFlags#MethodImplAttributes" },
209         { MONO_MT_UINT16,     "Flags#MethodAttribute" },
210         { MONO_MT_STRING_IDX, "Name" },
211         { MONO_MT_BLOB_IDX,   "Signature" },
212         { MONO_MT_TABLE_IDX,  "ParamList:Param" },
213         { MONO_MT_END, NULL }
214 };
215
216 const static MonoMetaTable MethodImplSchema [] = {
217         { MONO_MT_TABLE_IDX,  "Class:TypeDef" },
218         { MONO_MT_MDOR_IDX,   "MethodBody" },
219         { MONO_MT_MDOR_IDX,   "MethodDeclaration" },
220         { MONO_MT_END, NULL }
221 };
222
223 const static MonoMetaTable MethodSemanticsSchema [] = {
224         { MONO_MT_UINT16,     "MethodSemantic" },
225         { MONO_MT_TABLE_IDX,  "Method:Method" },
226         { MONO_MT_HS_IDX,     "Association" },
227         { MONO_MT_END, NULL }
228 };
229
230 const static MonoMetaTable ModuleSchema [] = {
231         { MONO_MT_UINT16,     "Generation" },
232         { MONO_MT_STRING_IDX, "Name" },
233         { MONO_MT_GUID_IDX,   "MVID" },
234         { MONO_MT_GUID_IDX,   "EncID" },
235         { MONO_MT_GUID_IDX,   "EncBaseID" },
236         { MONO_MT_END, NULL }
237 };
238
239 const static MonoMetaTable ModuleRefSchema [] = {
240         { MONO_MT_STRING_IDX, "Name" },
241         { MONO_MT_END, NULL }
242 };
243
244 const static MonoMetaTable NestedClassSchema [] = {
245         { MONO_MT_TABLE_IDX,  "NestedClass:TypeDef" },
246         { MONO_MT_TABLE_IDX,  "EnclosingClass:TypeDef" },
247         { MONO_MT_END, NULL }
248 };
249
250 const static MonoMetaTable ParamSchema [] = {
251         { MONO_MT_UINT16,     "Flags" },
252         { MONO_MT_UINT16,     "Sequence" },
253         { MONO_MT_STRING_IDX, "Name" },
254         { MONO_MT_END, NULL }   
255 };
256
257 const static MonoMetaTable PropertySchema [] = {
258         { MONO_MT_UINT16,     "Flags" },
259         { MONO_MT_STRING_IDX, "Name" },
260         { MONO_MT_BLOB_IDX,   "Type" },
261         { MONO_MT_END, NULL }   
262 };
263
264 const static MonoMetaTable PropertyMapSchema [] = {
265         { MONO_MT_TABLE_IDX,  "Parent:TypeDef" },
266         { MONO_MT_TABLE_IDX,  "PropertyList:Property" },
267         { MONO_MT_END, NULL }
268 };
269
270 const static MonoMetaTable StandaloneSigSchema [] = {
271         { MONO_MT_BLOB_IDX,   "Signature" },
272         { MONO_MT_END, NULL }
273 };
274
275 const static MonoMetaTable TypeDefSchema [] = {
276         { MONO_MT_UINT32,     "Flags" },
277         { MONO_MT_STRING_IDX, "Name" },
278         { MONO_MT_STRING_IDX, "Namespace" },
279         { MONO_MT_TDOR_IDX,   "Extends" },
280         { MONO_MT_TABLE_IDX,  "FieldList:Field" },
281         { MONO_MT_TABLE_IDX,  "MethodList:Method" },
282         { MONO_MT_END, NULL }
283 };
284
285 const static MonoMetaTable TypeRefSchema [] = {
286         { MONO_MT_RS_IDX,     "ResolutionScope=ResolutionScope" },
287         { MONO_MT_STRING_IDX, "Name" },
288         { MONO_MT_STRING_IDX, "Namespace" },
289         { MONO_MT_END, NULL }
290 };
291
292 const static MonoMetaTable TypeSpecSchema [] = {
293         { MONO_MT_BLOB_IDX,   "Signature" },
294         { MONO_MT_END, NULL }
295 };
296
297 const static MonoMetaTable GenericParamSchema [] = {
298         { MONO_MT_UINT16,     "Number" },
299         { MONO_MT_UINT16,     "Flags" },
300         { MONO_MT_TABLE_IDX,  "Owner" }, /* TypeDef or MethodDef */
301         { MONO_MT_STRING_IDX, "Name" },
302
303         /* soon to be removed */
304         { MONO_MT_TABLE_IDX,  "Kind" }, 
305         
306         { MONO_MT_END, NULL }
307 };
308
309 const static MonoMetaTable MethodSpecSchema [] = {
310         { MONO_MT_MDOR_IDX,   "Method" },
311         { MONO_MT_BLOB_IDX,   "Signature" },
312         { MONO_MT_END, NULL }
313 };
314
315 const static MonoMetaTable GenericParamConstraintSchema [] = {
316         { MONO_MT_TABLE_IDX,  "GenericParam" },
317         { MONO_MT_TDOR_IDX,   "Constraint" },
318         { MONO_MT_END, NULL }
319 };
320
321 const static struct {
322         const MonoMetaTable *table;
323         const char    *name;
324 } tables [] = {
325         /*  0 */ { ModuleSchema,               "Module" },
326         /*  1 */ { TypeRefSchema,              "TypeRef" },
327         /*  2 */ { TypeDefSchema,              "TypeDef" },
328         /*  3 */ { NULL,                       NULL },
329         /*  4 */ { FieldSchema,                "Field" },
330         /*  5 */ { NULL,                       NULL },
331         /*  6 */ { MethodSchema,               "Method" },
332         /*  7 */ { NULL,                       NULL },
333         /*  8 */ { ParamSchema,                "Param" },
334         /*  9 */ { InterfaceImplSchema,        "InterfaceImpl" },
335         /*  A */ { MemberRefSchema,            "MemberRef" },
336         /*  B */ { ConstantSchema,             "Constant" },
337         /*  C */ { CustomAttributeSchema,      "CustomAttribute" },
338         /*  D */ { FieldMarshalSchema,         "FieldMarshal" },
339         /*  E */ { DeclSecuritySchema,         "DeclSecurity" },
340         /*  F */ { ClassLayoutSchema,          "ClassLayout" },
341         /* 10 */ { FieldLayoutSchema,          "FieldLayout" },
342         /* 11 */ { StandaloneSigSchema,        "StandaloneSig" },
343         /* 12 */ { EventMapSchema,             "EventMap" },
344         /* 13 */ { NULL,                       NULL },
345         /* 14 */ { EventSchema,                "Event" },
346         /* 15 */ { PropertyMapSchema,          "PropertyMap" },
347         /* 16 */ { NULL,                       NULL },
348         /* 17 */ { PropertySchema,             "PropertyTable" },
349         /* 18 */ { MethodSemanticsSchema,      "MethodSemantics" },
350         /* 19 */ { MethodImplSchema,           "MethodImpl" },
351         /* 1A */ { ModuleRefSchema,            "ModuleRef" },
352         /* 1B */ { TypeSpecSchema,             "TypeSpec" },
353         /* 1C */ { ImplMapSchema,              "ImplMap" },
354         /* 1D */ { FieldRVASchema,             "FieldRVA" },
355         /* 1E */ { NULL,                       NULL },
356         /* 1F */ { NULL,                       NULL },
357         /* 20 */ { AssemblySchema,             "Assembly" },
358         /* 21 */ { AssemblyProcessorSchema,    "AssemblyProcessor" },
359         /* 22 */ { AssemblyOSSchema,           "AssemblyOS" },
360         /* 23 */ { AssemblyRefSchema,          "AssemblyRef" },
361         /* 24 */ { AssemblyRefProcessorSchema, "AssemblyRefProcessor" },
362         /* 25 */ { AssemblyRefOSSchema,        "AssemblyRefOS" },
363         /* 26 */ { FileSchema,                 "File" },
364         /* 27 */ { ExportedTypeSchema,         "ExportedType" },
365         /* 28 */ { ManifestResourceSchema,     "ManifestResource" },
366         /* 29 */ { NestedClassSchema,          "NestedClass" },
367         /* 2A */ { GenericParamSchema,         "GenericParam" },
368         /* 2B */ { MethodSpecSchema,           "MethodSpec" },
369         /* 2C */ { GenericParamConstraintSchema, "GenericParamConstraint" },
370 };
371
372 /**
373  * mono_meta_table_name:
374  * @table: table index
375  *
376  * Returns the name for the @table index
377  */
378 const char *
379 mono_meta_table_name (int table)
380 {
381         if ((table < 0) || (table > 0x2c))
382                 return "";
383         
384         return tables [table].name;
385 }
386
387 /* The guy who wrote the spec for this should not be allowed near a
388  * computer again.
389  
390 If  e is a coded token(see clause 23.1.7) that points into table ti out of n possible tables t0, .. tn-1, 
391 then it is stored as e << (log n) & tag{ t0, .. tn-1}[ ti] using 2 bytes if the maximum number of 
392 rows of tables t0, ..tn-1, is less than 2^16 - (log n), and using 4 bytes otherwise. The family of 
393 finite maps tag{ t0, ..tn-1} is defined below. Note that to decode a physical row, you need the 
394 inverse of this mapping.
395
396  */
397 #define rtsize(s,b) (((s) < (1 << (b)) ? 2 : 4))
398 #define idx_size(tableidx) (meta->tables [(tableidx)].rows < 65536 ? 2 : 4)
399
400 /* Reference: Partition II - 23.2.6 */
401 /*
402  * mono_metadata_compute_size:
403  * @meta: metadata context
404  * @tableindex: metadata table number
405  * @result_bitfield: pointer to guint32 where to store additional info
406  * 
407  * mono_metadata_compute_size() computes the lenght in bytes of a single
408  * row in a metadata table. The size of each column is encoded in the
409  * @result_bitfield return value along with the number of columns in the table.
410  * the resulting bitfield should be handed to the mono_metadata_table_size()
411  * and mono_metadata_table_count() macros.
412  */
413 int
414 mono_metadata_compute_size (MonoImage *meta, int tableindex, guint32 *result_bitfield)
415 {
416         guint32 bitfield = 0;
417         int size = 0, field_size = 0;
418         int i, n, code;
419         int shift = 0;
420         const MonoMetaTable *table = tables [tableindex].table;
421
422         for (i = 0; (code = table [i].code) != MONO_MT_END; i++){
423                 switch (code){
424                 case MONO_MT_UINT32:
425                         field_size = 4; break;
426                         
427                 case MONO_MT_UINT16:
428                         field_size = 2; break;
429                         
430                 case MONO_MT_UINT8:
431                         field_size = 1; break;
432                         
433                 case MONO_MT_BLOB_IDX:
434                         field_size = meta->idx_blob_wide ? 4 : 2; break;
435                         
436                 case MONO_MT_STRING_IDX:
437                         field_size = meta->idx_string_wide ? 4 : 2; break;
438                         
439                 case MONO_MT_GUID_IDX:
440                         field_size = meta->idx_guid_wide ? 4 : 2; break;
441
442                 case MONO_MT_TABLE_IDX:
443                         /* Uhm, a table index can point to other tables besides the current one
444                          * so, it's not correct to use the rowcount of the current table to
445                          * get the size for this column - lupus 
446                          */
447                         switch (tableindex) {
448                         case MONO_TABLE_ASSEMBLYREFOS:
449                                 g_assert (i == 3);
450                                 field_size = idx_size (MONO_TABLE_ASSEMBLYREF); break;
451                         case MONO_TABLE_ASSEMBLYPROCESSOR:
452                                 g_assert (i == 1);
453                                 field_size = idx_size (MONO_TABLE_ASSEMBLYREF); break;
454                         case MONO_TABLE_CLASSLAYOUT:
455                                 g_assert (i == 2);
456                                 field_size = idx_size (MONO_TABLE_TYPEDEF); break;
457                         case MONO_TABLE_EVENTMAP:
458                                 g_assert (i == 0 || i == 1);
459                                 field_size = i ? idx_size (MONO_TABLE_EVENT):
460                                         idx_size(MONO_TABLE_TYPEDEF); 
461                                 break;
462                         case MONO_TABLE_EVENT:
463                                 g_assert (i == 2);
464                                 field_size = MAX (idx_size (MONO_TABLE_TYPEDEF), idx_size(MONO_TABLE_TYPEREF));
465                                 field_size = MAX (field_size, idx_size(MONO_TABLE_TYPESPEC));
466                                 break;
467                         case MONO_TABLE_EXPORTEDTYPE:
468                                 g_assert (i == 1);
469                                 /* the index is in another metadata file, so it must be 4 */
470                                 field_size = 4; break;
471                         case MONO_TABLE_FIELDLAYOUT:
472                                 g_assert (i == 1);
473                                 field_size = idx_size (MONO_TABLE_FIELD); break;
474                         case MONO_TABLE_FIELDRVA:
475                                 g_assert (i == 1);
476                                 field_size = idx_size (MONO_TABLE_FIELD); break;
477                         case MONO_TABLE_IMPLMAP:
478                                 g_assert (i == 3);
479                                 field_size = idx_size (MONO_TABLE_MODULEREF); break;
480                         case MONO_TABLE_INTERFACEIMPL:
481                                 g_assert (i == 0);
482                                 field_size = idx_size (MONO_TABLE_TYPEDEF); break;
483                         case MONO_TABLE_METHOD:
484                                 g_assert (i == 5);
485                                 field_size = idx_size (MONO_TABLE_PARAM); break;
486                         case MONO_TABLE_METHODIMPL:
487                                 g_assert (i == 0);
488                                 field_size = idx_size (MONO_TABLE_TYPEDEF); break;
489                         case MONO_TABLE_METHODSEMANTICS:
490                                 g_assert (i == 1);
491                                 field_size = idx_size (MONO_TABLE_METHOD); break;
492                         case MONO_TABLE_NESTEDCLASS:
493                                 g_assert (i == 0 || i == 1);
494                                 field_size = idx_size (MONO_TABLE_TYPEDEF); break;
495                         case MONO_TABLE_PROPERTYMAP:
496                                 g_assert (i == 0 || i == 1);
497                                 field_size = i ? idx_size (MONO_TABLE_PROPERTY):
498                                         idx_size(MONO_TABLE_TYPEDEF); 
499                                 break;
500                         case MONO_TABLE_TYPEDEF:
501                                 g_assert (i == 4 || i == 5);
502                                 field_size = i == 4 ? idx_size (MONO_TABLE_FIELD):
503                                         idx_size(MONO_TABLE_METHOD);
504                         case MONO_TABLE_GENERICPARAM:
505                                 g_assert (i == 2 || i == 4 || i == 5);
506                                 if (i == 2)
507                                         field_size = MAX (idx_size (MONO_TABLE_METHOD), idx_size (MONO_TABLE_TYPEDEF));
508                                 else if (i == 4)
509                                         field_size = idx_size (MONO_TABLE_TYPEDEF);
510                                 else if (i == 5)
511                                         field_size = idx_size (MONO_TABLE_TYPEDEF);
512                                 break;
513
514                         case MONO_TABLE_GENERICPARAMCONSTRAINT:
515                                 g_assert (i == 0);
516                                 field_size = idx_size (MONO_TABLE_GENERICPARAM);
517                                 break;
518                                 
519                         default:
520                                 g_assert_not_reached ();
521                         }
522                         if (tableindex != MONO_TABLE_EXPORTEDTYPE && field_size != idx_size (tableindex))
523                                 g_warning ("size changed (%d to %d)", idx_size (tableindex), field_size);
524                         
525                         break;
526
527                         /*
528                          * HasConstant: ParamDef, FieldDef, Property
529                          */
530                 case MONO_MT_CONST_IDX:
531                         n = MAX (meta->tables [MONO_TABLE_PARAM].rows,
532                                  meta->tables [MONO_TABLE_FIELD].rows);
533                         n = MAX (n, meta->tables [MONO_TABLE_PROPERTY].rows);
534
535                         /* 2 bits to encode tag */
536                         field_size = rtsize (n, 16-2);
537                         break;
538
539                         /*
540                          * HasCustomAttribute: points to any table but
541                          * itself.
542                          */
543                 case MONO_MT_HASCAT_IDX:
544                         /*
545                          * We believe that since the signature and
546                          * permission are indexing the Blob heap,
547                          * we should consider the blob size first
548                          */
549                         /* I'm not a believer - lupus
550                         if (meta->idx_blob_wide){
551                                 field_size = 4;
552                                 break;
553                         }*/
554                         
555                         n = MAX (meta->tables [MONO_TABLE_METHOD].rows,
556                                  meta->tables [MONO_TABLE_FIELD].rows);
557                         n = MAX (n, meta->tables [MONO_TABLE_TYPEREF].rows);
558                         n = MAX (n, meta->tables [MONO_TABLE_TYPEDEF].rows);
559                         n = MAX (n, meta->tables [MONO_TABLE_PARAM].rows);
560                         n = MAX (n, meta->tables [MONO_TABLE_INTERFACEIMPL].rows);
561                         n = MAX (n, meta->tables [MONO_TABLE_MEMBERREF].rows);
562                         n = MAX (n, meta->tables [MONO_TABLE_MODULE].rows);
563                         n = MAX (n, meta->tables [MONO_TABLE_DECLSECURITY].rows);
564                         n = MAX (n, meta->tables [MONO_TABLE_PROPERTY].rows);
565                         n = MAX (n, meta->tables [MONO_TABLE_EVENT].rows);
566                         n = MAX (n, meta->tables [MONO_TABLE_STANDALONESIG].rows);
567                         n = MAX (n, meta->tables [MONO_TABLE_MODULEREF].rows);
568                         n = MAX (n, meta->tables [MONO_TABLE_TYPESPEC].rows);
569                         n = MAX (n, meta->tables [MONO_TABLE_ASSEMBLY].rows);
570                         n = MAX (n, meta->tables [MONO_TABLE_ASSEMBLYREF].rows);
571                         n = MAX (n, meta->tables [MONO_TABLE_FILE].rows);
572                         n = MAX (n, meta->tables [MONO_TABLE_EXPORTEDTYPE].rows);
573                         n = MAX (n, meta->tables [MONO_TABLE_MANIFESTRESOURCE].rows);
574
575                         /* 5 bits to encode */
576                         field_size = rtsize (n, 16-5);
577                         break;
578
579                         /*
580                          * CustomAttributeType: TypeDef, TypeRef, MethodDef, 
581                          * MemberRef and String.  
582                          */
583                 case MONO_MT_CAT_IDX:
584                         /* String is a heap, if it is wide, we know the size */
585                         /* See above, nope. 
586                         if (meta->idx_string_wide){
587                                 field_size = 4;
588                                 break;
589                         }*/
590                         
591                         n = MAX (meta->tables [MONO_TABLE_TYPEREF].rows,
592                                  meta->tables [MONO_TABLE_TYPEDEF].rows);
593                         n = MAX (n, meta->tables [MONO_TABLE_METHOD].rows);
594                         n = MAX (n, meta->tables [MONO_TABLE_MEMBERREF].rows);
595
596                         /* 3 bits to encode */
597                         field_size = rtsize (n, 16-3);
598                         break;
599
600                         /*
601                          * HasDeclSecurity: Typedef, MethodDef, Assembly
602                          */
603                 case MONO_MT_HASDEC_IDX:
604                         n = MAX (meta->tables [MONO_TABLE_TYPEDEF].rows,
605                                  meta->tables [MONO_TABLE_METHOD].rows);
606                         n = MAX (n, meta->tables [MONO_TABLE_ASSEMBLY].rows);
607
608                         /* 2 bits to encode */
609                         field_size = rtsize (n, 16-2);
610                         break;
611
612                         /*
613                          * Implementation: File, AssemblyRef, ExportedType
614                          */
615                 case MONO_MT_IMPL_IDX:
616                         n = MAX (meta->tables [MONO_TABLE_FILE].rows,
617                                  meta->tables [MONO_TABLE_ASSEMBLYREF].rows);
618                         n = MAX (n, meta->tables [MONO_TABLE_EXPORTEDTYPE].rows);
619
620                         /* 2 bits to encode tag */
621                         field_size = rtsize (n, 16-2);
622                         break;
623
624                         /*
625                          * HasFieldMarshall: FieldDef, ParamDef
626                          */
627                 case MONO_MT_HFM_IDX:
628                         n = MAX (meta->tables [MONO_TABLE_FIELD].rows,
629                                  meta->tables [MONO_TABLE_PARAM].rows);
630
631                         /* 1 bit used to encode tag */
632                         field_size = rtsize (n, 16-1);
633                         break;
634
635                         /*
636                          * MemberForwarded: FieldDef, MethodDef
637                          */
638                 case MONO_MT_MF_IDX:
639                         n = MAX (meta->tables [MONO_TABLE_FIELD].rows,
640                                  meta->tables [MONO_TABLE_METHOD].rows);
641
642                         /* 1 bit used to encode tag */
643                         field_size = rtsize (n, 16-1);
644                         break;
645
646                         /*
647                          * TypeDefOrRef: TypeDef, ParamDef, TypeSpec
648                          * LAMESPEC
649                          * It is TypeDef, _TypeRef_, TypeSpec, instead.
650                          */
651                 case MONO_MT_TDOR_IDX:
652                         n = MAX (meta->tables [MONO_TABLE_TYPEDEF].rows,
653                                  meta->tables [MONO_TABLE_TYPEREF].rows);
654                         n = MAX (n, meta->tables [MONO_TABLE_TYPESPEC].rows);
655
656                         /* 2 bits to encode */
657                         field_size = rtsize (n, 16-2);
658                         break;
659
660                         /*
661                          * MemberRefParent: TypeDef, TypeRef, MethodDef, ModuleRef, TypeSpec, MemberRef
662                          */
663                 case MONO_MT_MRP_IDX:
664                         n = MAX (meta->tables [MONO_TABLE_TYPEDEF].rows,
665                                  meta->tables [MONO_TABLE_TYPEREF].rows);
666                         n = MAX (n, meta->tables [MONO_TABLE_METHOD].rows);
667                         n = MAX (n, meta->tables [MONO_TABLE_MODULEREF].rows);
668                         n = MAX (n, meta->tables [MONO_TABLE_TYPESPEC].rows);
669                         n = MAX (n, meta->tables [MONO_TABLE_MEMBERREF].rows);
670
671                         /* 3 bits to encode */
672                         field_size = rtsize (n, 16 - 3);
673                         break;
674                         
675                 case MONO_MT_MDOR_IDX:
676
677                         /*
678                          * MethodDefOrRef: MethodDef, MemberRef
679                          */
680                 case MONO_MT_HS_IDX:
681                         n = MAX (meta->tables [MONO_TABLE_METHOD].rows,
682                                  meta->tables [MONO_TABLE_MEMBERREF].rows);
683
684                         /* 1 bit used to encode tag */
685                         field_size = rtsize (n, 16-1);
686                         break;
687
688                         /*
689                          * ResolutionScope: Module, ModuleRef, AssemblyRef, TypeRef
690                          */
691                 case MONO_MT_RS_IDX:
692                         n = MAX (meta->tables [MONO_TABLE_MODULE].rows,
693                                  meta->tables [MONO_TABLE_MODULEREF].rows);
694                         n = MAX (n, meta->tables [MONO_TABLE_ASSEMBLYREF].rows);
695                         n = MAX (n, meta->tables [MONO_TABLE_TYPEREF].rows);
696
697                         /* 2 bits used to encode tag (ECMA spec claims 3) */
698                         field_size = rtsize (n, 16 - 2);
699                         break;
700                 }
701
702                 /*
703                  * encode field size as follows (we just need to
704                  * distinguish them).
705                  *
706                  * 4 -> 3
707                  * 2 -> 1
708                  * 1 -> 0
709                  */
710                 bitfield |= (field_size-1) << shift;
711                 shift += 2;
712                 size += field_size;
713                 /*g_print ("table %02x field %d size %d\n", tableindex, i, field_size);*/
714         }
715
716         *result_bitfield = (i << 24) | bitfield;
717         return size;
718 }
719
720 /**
721  * mono_metadata_compute_table_bases:
722  * @meta: metadata context to compute table values
723  *
724  * Computes the table bases for the metadata structure.
725  * This is an internal function used by the image loader code.
726  */
727 void
728 mono_metadata_compute_table_bases (MonoImage *meta)
729 {
730         int i;
731         const char *base = meta->tables_base;
732         
733         for (i = 0; i < 64; i++){
734                 if (meta->tables [i].rows == 0)
735                         continue;
736
737                 meta->tables [i].row_size = mono_metadata_compute_size (
738                         meta, i, &meta->tables [i].size_bitfield);
739                 meta->tables [i].base = base;
740                 base += meta->tables [i].rows * meta->tables [i].row_size;
741         }
742 }
743
744 /**
745  * mono_metadata_locate:
746  * @meta: metadata context
747  * @table: table code.
748  * @idx: index of element to retrieve from @table.
749  *
750  * Returns a pointer to the @idx element in the metadata table
751  * whose code is @table.
752  */
753 const char *
754 mono_metadata_locate (MonoImage *meta, int table, int idx)
755 {
756         /* idx == 0 refers always to NULL */
757         g_return_val_if_fail (idx > 0 && idx <= meta->tables [table].rows, "");
758            
759         return meta->tables [table].base + (meta->tables [table].row_size * (idx - 1));
760 }
761
762 /**
763  * mono_metadata_locate_token:
764  * @meta: metadata context
765  * @token: metadata token
766  *
767  * Returns a pointer to the data in the metadata represented by the
768  * token #token.
769  */
770 const char *
771 mono_metadata_locate_token (MonoImage *meta, guint32 token)
772 {
773         return mono_metadata_locate (meta, token >> 24, token & 0xffffff);
774 }
775
776 /**
777  * mono_metadata_get_table:
778  * @table: table to retrieve
779  *
780  * Returns the MonoMetaTable structure for table @table
781  */
782 const MonoMetaTable *
783 mono_metadata_get_table (MonoMetaTableEnum table)
784 {
785         int x = (int) table;
786
787         g_return_val_if_fail ((x > 0) && (x <= MONO_TABLE_LAST), NULL);
788
789         return tables [table].table;
790 }
791
792 /**
793  * mono_metadata_string_heap:
794  * @meta: metadata context
795  * @index: index into the string heap.
796  *
797  * Returns: an in-memory pointer to the @index in the string heap.
798  */
799 const char *
800 mono_metadata_string_heap (MonoImage *meta, guint32 index)
801 {
802         g_return_val_if_fail (index < meta->heap_strings.size, "");
803         return meta->heap_strings.data + index;
804 }
805
806 /**
807  * mono_metadata_user_string:
808  * @meta: metadata context
809  * @index: index into the user string heap.
810  *
811  * Returns: an in-memory pointer to the @index in the user string heap ("#US").
812  */
813 const char *
814 mono_metadata_user_string (MonoImage *meta, guint32 index)
815 {
816         g_return_val_if_fail (index < meta->heap_us.size, "");
817         return meta->heap_us.data + index;
818 }
819
820 /**
821  * mono_metadata_blob_heap:
822  * @meta: metadata context
823  * @index: index into the blob.
824  *
825  * Returns: an in-memory pointer to the @index in the Blob heap.
826  */
827 const char *
828 mono_metadata_blob_heap (MonoImage *meta, guint32 index)
829 {
830         g_return_val_if_fail (index < meta->heap_blob.size, "");
831         return meta->heap_blob.data + index;
832 }
833
834 /**
835  * mono_metadata_guid_heap:
836  * @meta: metadata context
837  * @index: index into the guid heap.
838  *
839  * Returns: an in-memory pointer to the @index in the guid heap.
840  */
841 const char *
842 mono_metadata_guid_heap (MonoImage *meta, guint32 index)
843 {
844         --index;
845         index *= 16; /* adjust for guid size and 1-based index */
846         g_return_val_if_fail (index < meta->heap_guid.size, "");
847         return meta->heap_guid.data + index;
848 }
849
850 static const char *
851 dword_align (const char *ptr)
852 {
853 #if SIZEOF_VOID_P == 8
854         return (const char *) (((guint64) (ptr + 3)) & ~3);
855 #else
856         return (const char *) (((guint32) (ptr + 3)) & ~3);
857 #endif
858 }
859
860 /**
861  * mono_metadata_decode_row:
862  * @t: table to extract information from.
863  * @idx: index in table.
864  * @res: array of @res_size cols to store the results in
865  *
866  * This decompresses the metadata element @idx in table @t
867  * into the guint32 @res array that has res_size elements
868  */
869 void
870 mono_metadata_decode_row (const MonoTableInfo *t, int idx, guint32 *res, int res_size)
871 {
872         guint32 bitfield = t->size_bitfield;
873         int i, count = mono_metadata_table_count (bitfield);
874         const char *data = t->base + idx * t->row_size;
875         
876         g_assert (res_size == count);
877         
878         for (i = 0; i < count; i++){
879                 int n = mono_metadata_table_size (bitfield, i);
880
881                 switch (n){
882                 case 1:
883                         res [i] = *data; break;
884                 case 2:
885                         res [i] = read16 (data); break;
886                         
887                 case 4:
888                         res [i] = read32 (data); break;
889                         
890                 default:
891                         g_assert_not_reached ();
892                 }
893                 data += n;
894         }
895 }
896
897 /**
898  * mono_metadata_decode_row_col:
899  * @t: table to extract information from.
900  * @idx: index for row in table.
901  * @col: column in the row.
902  *
903  * This function returns the value of column @col from the @idx
904  * row in the table @t.
905  */
906 guint32
907 mono_metadata_decode_row_col (const MonoTableInfo *t, int idx, guint col)
908 {
909         guint32 bitfield = t->size_bitfield;
910         int i;
911         register const char *data = t->base + idx * t->row_size;
912         register int n;
913         
914         g_assert (col < mono_metadata_table_count (bitfield));
915
916         n = mono_metadata_table_size (bitfield, 0);
917         for (i = 0; i < col; ++i) {
918                 data += n;
919                 n = mono_metadata_table_size (bitfield, i + 1);
920         }
921         switch (n){
922         case 1:
923                 return *data;
924         case 2:
925                 return read16 (data);
926         case 4:
927                 return read32 (data);
928         default:
929                 g_assert_not_reached ();
930         }
931         return 0;
932 }
933 /**
934  * mono_metadata_decode_blob_size:
935  * @ptr: pointer to a blob object
936  * @rptr: the new position of the pointer
937  *
938  * This decodes a compressed size as described by 23.1.4 (a blob or user string object)
939  *
940  * Returns: the size of the blob object
941  */
942 guint32
943 mono_metadata_decode_blob_size (const char *xptr, const char **rptr)
944 {
945         const unsigned char *ptr = (const unsigned char *)xptr;
946         guint32 size;
947         
948         if ((*ptr & 0x80) == 0){
949                 size = ptr [0] & 0x7f;
950                 ptr++;
951         } else if ((*ptr & 0x40) == 0){
952                 size = ((ptr [0] & 0x3f) << 8) + ptr [1];
953                 ptr += 2;
954         } else {
955                 size = ((ptr [0] & 0x1f) << 24) +
956                         (ptr [1] << 16) +
957                         (ptr [2] << 8) +
958                         ptr [3];
959                 ptr += 4;
960         }
961         if (rptr)
962                 *rptr = ptr;
963         return size;
964 }
965
966
967 /**
968  * mono_metadata_decode_value:
969  * @ptr: pointer to decode from
970  * @rptr: the new position of the pointer
971  *
972  * This routine decompresses 32-bit values as specified in the "Blob and
973  * Signature" section (22.2)
974  *
975  * Returns: the decoded value
976  */
977 guint32
978 mono_metadata_decode_value (const char *_ptr, const char **rptr)
979 {
980         const unsigned char *ptr = (const unsigned char *) _ptr;
981         unsigned char b = *ptr;
982         guint32 len;
983         
984         if ((b & 0x80) == 0){
985                 len = b;
986                 ++ptr;
987         } else if ((b & 0x40) == 0){
988                 len = ((b & 0x3f) << 8 | ptr [1]);
989                 ptr += 2;
990         } else {
991                 len = ((b & 0x1f) << 24) |
992                         (ptr [1] << 16) |
993                         (ptr [2] << 8) |
994                         ptr [3];
995                 ptr += 4;
996         }
997         if (rptr)
998                 *rptr = ptr;
999         
1000         return len;
1001 }
1002
1003 /*
1004  * mono_metadata_parse_typedef_or_ref:
1005  * @m: a metadata context.
1006  * @ptr: a pointer to an encoded TypedefOrRef in @m
1007  * @rptr: pointer updated to match the end of the decoded stream
1008  *
1009  * Returns: a token valid in the @m metadata decoded from
1010  * the compressed representation.
1011  */
1012 guint32
1013 mono_metadata_parse_typedef_or_ref (MonoImage *m, const char *ptr, const char **rptr)
1014 {
1015         guint32 token;
1016         token = mono_metadata_decode_value (ptr, &ptr);
1017         if (rptr)
1018                 *rptr = ptr;
1019         return mono_metadata_token_from_dor (token);
1020 }
1021
1022 /*
1023  * mono_metadata_parse_custom_mod:
1024  * @m: a metadata context.
1025  * @dest: storage where the info about the custom modifier is stored (may be NULL)
1026  * @ptr: a pointer to (possibly) the start of a custom modifier list
1027  * @rptr: pointer updated to match the end of the decoded stream
1028  *
1029  * Checks if @ptr points to a type custom modifier compressed representation.
1030  *
1031  * Returns: #TRUE if a custom modifier was found, #FALSE if not.
1032  */
1033 int
1034 mono_metadata_parse_custom_mod (MonoImage *m, MonoCustomMod *dest, const char *ptr, const char **rptr)
1035 {
1036         MonoCustomMod local;
1037         if ((*ptr == MONO_TYPE_CMOD_OPT) ||
1038             (*ptr == MONO_TYPE_CMOD_REQD)) {
1039                 if (!dest)
1040                         dest = &local;
1041                 dest->required = *ptr == MONO_TYPE_CMOD_REQD ? 1 : 0;
1042                 dest->token = mono_metadata_parse_typedef_or_ref (m, ptr + 1, rptr);
1043                 return TRUE;
1044         }
1045         return FALSE;
1046 }
1047
1048 /*
1049  * mono_metadata_parse_array:
1050  * @m: a metadata context.
1051  * @ptr: a pointer to an encoded array description.
1052  * @rptr: pointer updated to match the end of the decoded stream
1053  *
1054  * Decodes the compressed array description found in the metadata @m at @ptr.
1055  *
1056  * Returns: a #MonoArrayType structure describing the array type
1057  * and dimensions.
1058  */
1059 MonoArrayType *
1060 mono_metadata_parse_array_full (MonoImage *m, MonoGenericContainer *generic_container,
1061                                 const char *ptr, const char **rptr)
1062 {
1063         int i;
1064         MonoArrayType *array = g_new0 (MonoArrayType, 1);
1065         MonoType *etype;
1066         
1067         etype = mono_metadata_parse_type_full (m, generic_container, MONO_PARSE_TYPE, 0, ptr, &ptr);
1068         array->eklass = mono_class_from_mono_type (etype);
1069         array->rank = mono_metadata_decode_value (ptr, &ptr);
1070
1071         array->numsizes = mono_metadata_decode_value (ptr, &ptr);
1072         if (array->numsizes)
1073                 array->sizes = g_new0 (int, array->numsizes);
1074         for (i = 0; i < array->numsizes; ++i)
1075                 array->sizes [i] = mono_metadata_decode_value (ptr, &ptr);
1076
1077         array->numlobounds = mono_metadata_decode_value (ptr, &ptr);
1078         if (array->numlobounds)
1079                 array->lobounds = g_new0 (int, array->numlobounds);
1080         for (i = 0; i < array->numlobounds; ++i)
1081                 array->lobounds [i] = mono_metadata_decode_value (ptr, &ptr);
1082
1083         if (rptr)
1084                 *rptr = ptr;
1085         return array;
1086 }
1087
1088 MonoArrayType *
1089 mono_metadata_parse_array (MonoImage *m, const char *ptr, const char **rptr)
1090 {
1091         return mono_metadata_parse_array_full (m, NULL, ptr, rptr);
1092 }
1093
1094 /*
1095  * mono_metadata_free_array:
1096  * @array: array description
1097  *
1098  * Frees the array description returned from mono_metadata_parse_array().
1099  */
1100 void
1101 mono_metadata_free_array (MonoArrayType *array)
1102 {
1103         g_free (array->sizes);
1104         g_free (array->lobounds);
1105         g_free (array);
1106 }
1107
1108 /*
1109  * need to add common field and param attributes combinations:
1110  * [out] param
1111  * public static
1112  * public static literal
1113  * private
1114  * private static
1115  * private static literal
1116  */
1117 static MonoType
1118 builtin_types[] = {
1119         /* data, attrs, type,              nmods, byref, pinned */
1120         {{NULL}, 0,     MONO_TYPE_VOID,    0,     0,     0},
1121         {{NULL}, 0,     MONO_TYPE_BOOLEAN, 0,     0,     0},
1122         {{NULL}, 0,     MONO_TYPE_BOOLEAN, 0,     1,     0},
1123         {{NULL}, 0,     MONO_TYPE_CHAR,    0,     0,     0},
1124         {{NULL}, 0,     MONO_TYPE_CHAR,    0,     1,     0},
1125         {{NULL}, 0,     MONO_TYPE_I1,      0,     0,     0},
1126         {{NULL}, 0,     MONO_TYPE_I1,      0,     1,     0},
1127         {{NULL}, 0,     MONO_TYPE_U1,      0,     0,     0},
1128         {{NULL}, 0,     MONO_TYPE_U1,      0,     1,     0},
1129         {{NULL}, 0,     MONO_TYPE_I2,      0,     0,     0},
1130         {{NULL}, 0,     MONO_TYPE_I2,      0,     1,     0},
1131         {{NULL}, 0,     MONO_TYPE_U2,      0,     0,     0},
1132         {{NULL}, 0,     MONO_TYPE_U2,      0,     1,     0},
1133         {{NULL}, 0,     MONO_TYPE_I4,      0,     0,     0},
1134         {{NULL}, 0,     MONO_TYPE_I4,      0,     1,     0},
1135         {{NULL}, 0,     MONO_TYPE_U4,      0,     0,     0},
1136         {{NULL}, 0,     MONO_TYPE_U4,      0,     1,     0},
1137         {{NULL}, 0,     MONO_TYPE_I8,      0,     0,     0},
1138         {{NULL}, 0,     MONO_TYPE_I8,      0,     1,     0},
1139         {{NULL}, 0,     MONO_TYPE_U8,      0,     0,     0},
1140         {{NULL}, 0,     MONO_TYPE_U8,      0,     1,     0},
1141         {{NULL}, 0,     MONO_TYPE_R4,      0,     0,     0},
1142         {{NULL}, 0,     MONO_TYPE_R4,      0,     1,     0},
1143         {{NULL}, 0,     MONO_TYPE_R8,      0,     0,     0},
1144         {{NULL}, 0,     MONO_TYPE_R8,      0,     1,     0},
1145         {{NULL}, 0,     MONO_TYPE_STRING,  0,     0,     0},
1146         {{NULL}, 0,     MONO_TYPE_STRING,  0,     1,     0},
1147         {{NULL}, 0,     MONO_TYPE_OBJECT,  0,     0,     0},
1148         {{NULL}, 0,     MONO_TYPE_OBJECT,  0,     1,     0},
1149         {{NULL}, 0,     MONO_TYPE_TYPEDBYREF,  0,     0,     0},
1150         {{NULL}, 0,     MONO_TYPE_I,       0,     0,     0},
1151         {{NULL}, 0,     MONO_TYPE_I,       0,     1,     0},
1152         {{NULL}, 0,     MONO_TYPE_U,       0,     0,     0},
1153         {{NULL}, 0,     MONO_TYPE_U,       0,     1,     0},
1154 };
1155
1156 #define NBUILTIN_TYPES() (sizeof (builtin_types) / sizeof (builtin_types [0]))
1157
1158 static GHashTable *type_cache = NULL;
1159
1160 /*
1161  * MonoTypes with modifies are never cached, so we never check or use that field.
1162  */
1163 static guint
1164 mono_type_hash (gconstpointer data)
1165 {
1166         const MonoType *type = (const MonoType *) data;
1167         return type->type | (type->byref << 8) | (type->attrs << 9);
1168 }
1169
1170 static gint
1171 mono_type_equal (gconstpointer ka, gconstpointer kb)
1172 {
1173         const MonoType *a = (const MonoType *) ka;
1174         const MonoType *b = (const MonoType *) kb;
1175         
1176         if (a->type != b->type || a->byref != b->byref || a->attrs != b->attrs || a->pinned != b->pinned)
1177                 return 0;
1178         /* need other checks */
1179         return 1;
1180 }
1181
1182 /**
1183  * mono_metadata_init:
1184  *
1185  *  Initialize the global variables of this module.
1186  */
1187 void
1188 mono_metadata_init (void)
1189 {
1190         int i;
1191
1192         type_cache = g_hash_table_new (mono_type_hash, mono_type_equal);
1193
1194         for (i = 0; i < NBUILTIN_TYPES (); ++i)
1195                 g_hash_table_insert (type_cache, &builtin_types [i], &builtin_types [i]);
1196 }
1197
1198 /*
1199  * mono_metadata_parse_type:
1200  * @m: metadata context
1201  * @mode: king of type that may be found at @ptr
1202  * @opt_attrs: optional attributes to store in the returned type
1203  * @ptr: pointer to the type representation
1204  * @rptr: pointer updated to match the end of the decoded stream
1205  * 
1206  * Decode a compressed type description found at @ptr in @m.
1207  * @mode can be one of MONO_PARSE_MOD_TYPE, MONO_PARSE_PARAM, MONO_PARSE_RET,
1208  * MONO_PARSE_FIELD, MONO_PARSE_LOCAL, MONO_PARSE_TYPE.
1209  * This function can be used to decode type descriptions in method signatures,
1210  * field signatures, locals signatures etc.
1211  *
1212  * To parse a generic type, `generic_container' points to the current class'es
1213  * (the `generic_container' field in the MonoClass) or the current generic method's
1214  * (the `generic_container' field in the MonoMethodNormal) generic container.
1215  * When we encounter any MONO_TYPE_VAR or MONO_TYPE_MVAR's, they're looked up in
1216  * this MonoGenericContainer.
1217  *
1218  * Returns: a #MonoType structure representing the decoded type.
1219  */
1220 MonoType*
1221 mono_metadata_parse_type_full (MonoImage *m, MonoGenericContainer *generic_container, MonoParseTypeMode mode,
1222                                short opt_attrs, const char *ptr, const char **rptr)
1223 {
1224         MonoType *type, *cached;
1225         MonoType stype;
1226         gboolean byref = FALSE;
1227         gboolean pinned = FALSE;
1228         const char *tmp_ptr;
1229         int count = 0;
1230         gboolean found;
1231
1232         /*
1233          * According to the spec, custom modifiers should come before the byref
1234          * flag, but the IL produced by ilasm from the following signature:
1235          *   object modopt(...) &
1236          * starts with a byref flag, followed by the modifiers. (bug #49802)
1237          * Also, this type seems to be different from 'object & modopt(...)'. Maybe
1238          * it would be better to treat byref as real type constructor instead of
1239          * a modifier...
1240          * Also, pinned should come before anything else, but some MSV++ produced
1241          * assemblies violate this (#bug 61990).
1242          */
1243
1244         /* Count the modifiers first */
1245         tmp_ptr = ptr;
1246         found = TRUE;
1247         while (found) {
1248                 switch (*tmp_ptr) {
1249                 case MONO_TYPE_PINNED:
1250                 case MONO_TYPE_BYREF:
1251                         ++tmp_ptr;
1252                         break;
1253                 case MONO_TYPE_CMOD_REQD:
1254                 case MONO_TYPE_CMOD_OPT:
1255                         count ++;
1256                         mono_metadata_parse_custom_mod (m, NULL, tmp_ptr, &tmp_ptr);
1257                         break;
1258                 default:
1259                         found = FALSE;
1260                 }
1261         }
1262
1263         if (count) {
1264                 type = g_malloc0 (sizeof (MonoType) + ((gint32)count - MONO_ZERO_LEN_ARRAY) * sizeof (MonoCustomMod));
1265                 type->num_mods = count;
1266                 if (count > 64)
1267                         g_warning ("got more than 64 modifiers in type");
1268         }
1269         else {
1270                 type = &stype;
1271                 memset (type, 0, sizeof (MonoType));
1272         }
1273
1274         /* Parse pinned, byref and custom modifiers */
1275         found = TRUE;
1276         count = 0;
1277         while (found) {
1278                 switch (*ptr) {
1279                 case MONO_TYPE_PINNED:
1280                         pinned = TRUE;
1281                         ++ptr;
1282                         break;
1283                 case MONO_TYPE_BYREF:
1284                         byref = TRUE;
1285                         ++ptr;
1286                         break;
1287                 case MONO_TYPE_CMOD_REQD:
1288                 case MONO_TYPE_CMOD_OPT:
1289                         mono_metadata_parse_custom_mod (m, &(type->modifiers [count]), ptr, &ptr);
1290                         count ++;
1291                         break;
1292                 default:
1293                         found = FALSE;
1294                 }
1295         }
1296         
1297         type->attrs = opt_attrs;
1298         type->byref = byref;
1299         type->pinned = pinned ? 1 : 0;
1300
1301         do_mono_metadata_parse_type (type, m, generic_container, ptr, &ptr);
1302
1303         if (rptr)
1304                 *rptr = ptr;
1305
1306         
1307         /* FIXME: remove the != MONO_PARSE_PARAM condition, this accounts for
1308          * almost 10k (about 2/3rds) of all MonoType's we create.
1309          */
1310         if (mode != MONO_PARSE_PARAM && !type->num_mods) {
1311                 /* no need to free type here, because it is on the stack */
1312                 if ((type->type == MONO_TYPE_CLASS || type->type == MONO_TYPE_VALUETYPE) && !type->pinned && !type->attrs) {
1313                         if (type->byref)
1314                                 return &type->data.klass->this_arg;
1315                         else
1316                                 return &type->data.klass->byval_arg;
1317                 }
1318                 /* No need to use locking since nobody is modifying the hash table */
1319                 if ((cached = g_hash_table_lookup (type_cache, type)))
1320                         return cached;
1321         }
1322         
1323         /*printf ("%x%c %s\n", type->attrs, type->pinned ? 'p' : ' ', mono_type_full_name (type));*/
1324         
1325         if (type == &stype)
1326                 type = g_memdup (&stype, sizeof (MonoType));
1327         return type;
1328 }
1329
1330 MonoType*
1331 mono_metadata_parse_type (MonoImage *m, MonoParseTypeMode mode, short opt_attrs,
1332                           const char *ptr, const char **rptr)
1333 {
1334         return mono_metadata_parse_type_full (m, NULL, mode, opt_attrs, ptr, rptr);
1335 }
1336
1337 /*
1338  * mono_metadata_parse_signature:
1339  * @image: metadata context
1340  * @toke: metadata token
1341  *
1342  * Decode a method signature stored in the STANDALONESIG table
1343  *
1344  * Returns: a MonoMethodSignature describing the signature.
1345  */
1346 MonoMethodSignature *
1347 mono_metadata_parse_signature_full (MonoImage *image, MonoGenericContainer *generic_container, guint32 token)
1348 {
1349         MonoTableInfo *tables = image->tables;
1350         guint32 idx = mono_metadata_token_index (token);
1351         guint32 sig;
1352         const char *ptr;
1353
1354         if (image->dynamic)
1355                 return mono_lookup_dynamic_token (image, token);
1356
1357         g_assert (mono_metadata_token_table(token) == MONO_TABLE_STANDALONESIG);
1358                 
1359         sig = mono_metadata_decode_row_col (&tables [MONO_TABLE_STANDALONESIG], idx - 1, 0);
1360
1361         ptr = mono_metadata_blob_heap (image, sig);
1362         mono_metadata_decode_blob_size (ptr, &ptr);
1363
1364         return mono_metadata_parse_method_signature_full (image, generic_container, FALSE, ptr, NULL); 
1365 }
1366
1367 MonoMethodSignature *
1368 mono_metadata_parse_signature (MonoImage *image, guint32 token)
1369 {
1370         return mono_metadata_parse_signature_full (image, NULL, token);
1371 }
1372
1373 MonoMethodSignature*
1374 mono_metadata_signature_alloc (MonoImage *m, guint32 nparams)
1375 {
1376         MonoMethodSignature *sig;
1377
1378         /* later we want to allocate signatures with mempools */
1379         sig = g_malloc0 (sizeof (MonoMethodSignature) + ((gint32)nparams - MONO_ZERO_LEN_ARRAY) * sizeof (MonoType*));
1380         sig->param_count = nparams;
1381         sig->sentinelpos = -1;
1382
1383         return sig;
1384 }
1385
1386 MonoMethodSignature*
1387 mono_metadata_signature_dup (MonoMethodSignature *sig)
1388 {
1389         int sigsize;
1390
1391         sigsize = sizeof (MonoMethodSignature) + sig->param_count * sizeof (MonoType *);
1392         return g_memdup (sig, sigsize);
1393 }
1394
1395 /*
1396  * mono_metadata_parse_method_signature:
1397  * @m: metadata context
1398  * @def: the MethodDef index or 0 for Ref signatures.
1399  * @ptr: pointer to the signature metadata representation
1400  * @rptr: pointer updated to match the end of the decoded stream
1401  *
1402  * Decode a method signature stored at @ptr.
1403  *
1404  * Returns: a MonoMethodSignature describing the signature.
1405  */
1406 MonoMethodSignature *
1407 mono_metadata_parse_method_signature_full (MonoImage *m, MonoGenericContainer *generic_container,
1408                                            int def, const char *ptr, const char **rptr)
1409 {
1410         MonoMethodSignature *method;
1411         int i, ret_attrs = 0, *pattrs = NULL;
1412         guint32 hasthis = 0, explicit_this = 0, call_convention, param_count;
1413         guint32 gen_param_count = 0;
1414         gboolean is_open = FALSE;
1415         MonoGenericContainer *container = NULL;
1416
1417         if (*ptr & 0x10)
1418                 gen_param_count = 1;
1419         if (*ptr & 0x20)
1420                 hasthis = 1;
1421         if (*ptr & 0x40)
1422                 explicit_this = 1;
1423         call_convention = *ptr & 0x0F;
1424         ptr++;
1425         if (gen_param_count)
1426                 gen_param_count = mono_metadata_decode_value (ptr, &ptr);
1427         param_count = mono_metadata_decode_value (ptr, &ptr);
1428         pattrs = g_new0 (int, param_count);
1429
1430         if (def) {
1431                 MonoTableInfo *paramt = &m->tables [MONO_TABLE_PARAM];
1432                 MonoTableInfo *methodt = &m->tables [MONO_TABLE_METHOD];
1433                 guint32 cols [MONO_PARAM_SIZE];
1434                 guint lastp, param_index = mono_metadata_decode_row_col (methodt, def - 1, MONO_METHOD_PARAMLIST);
1435
1436                 if (def < methodt->rows)
1437                         lastp = mono_metadata_decode_row_col (methodt, def, MONO_METHOD_PARAMLIST);
1438                 else
1439                         lastp = paramt->rows + 1;
1440                 for (i = param_index; i < lastp; ++i) {
1441                         mono_metadata_decode_row (paramt, i - 1, cols, MONO_PARAM_SIZE);
1442                         if (!cols [MONO_PARAM_SEQUENCE])
1443                                 ret_attrs = cols [MONO_PARAM_FLAGS];
1444                         else
1445                                 pattrs [cols [MONO_PARAM_SEQUENCE] - 1] = cols [MONO_PARAM_FLAGS];
1446                 }
1447         }
1448         method = mono_metadata_signature_alloc (m, param_count);
1449         method->hasthis = hasthis;
1450         method->explicit_this = explicit_this;
1451         method->call_convention = call_convention;
1452         method->generic_param_count = gen_param_count;
1453
1454         if (gen_param_count)
1455                 method->has_type_parameters = 1;
1456
1457         if (gen_param_count && (!generic_container || !generic_container->is_method)) {
1458                 container = g_new0 (MonoGenericContainer, 1);
1459                 container->parent = generic_container;
1460                 container->is_signature = 1;
1461
1462                 container->context = g_new0 (MonoGenericContext, 1);
1463                 container->context->container = container;
1464
1465                 container->type_argc = gen_param_count;
1466                 container->type_params = g_new0 (MonoGenericParam, gen_param_count);
1467
1468                 for (i = 0; i < gen_param_count; i++) {
1469                         container->type_params [i].owner = container;
1470                         container->type_params [i].num = i;
1471                 }
1472         } else
1473                 container = generic_container;
1474
1475         if (call_convention != 0xa) {
1476                 method->ret = mono_metadata_parse_type_full (m, container, MONO_PARSE_RET, ret_attrs, ptr, &ptr);
1477                 is_open = mono_class_is_open_constructed_type (method->ret);
1478         }
1479
1480         if (method->param_count) {
1481                 method->sentinelpos = -1;
1482                 
1483                 for (i = 0; i < method->param_count; ++i) {
1484                         if (*ptr == MONO_TYPE_SENTINEL) {
1485                                 if (method->call_convention != MONO_CALL_VARARG || def)
1486                                                 g_error ("found sentinel for methoddef or no vararg method");
1487                                 method->sentinelpos = i;
1488                                 ptr++;
1489                         }
1490                         method->params [i] = mono_metadata_parse_type_full (
1491                                 m, container, MONO_PARSE_PARAM, pattrs [i], ptr, &ptr);
1492                         if (!is_open)
1493                                 is_open = mono_class_is_open_constructed_type (method->params [i]);
1494                 }
1495         }
1496
1497         method->has_type_parameters = is_open;
1498
1499         if (def && (method->call_convention == MONO_CALL_VARARG))
1500                 method->sentinelpos = method->param_count;
1501
1502         g_free (pattrs);
1503
1504         if (rptr)
1505                 *rptr = ptr;
1506         /*
1507          * Add signature to a cache and increase ref count...
1508          */
1509         return method;
1510 }
1511
1512 MonoMethodSignature *
1513 mono_metadata_parse_method_signature (MonoImage *m, int def, const char *ptr, const char **rptr)
1514 {
1515         return mono_metadata_parse_method_signature_full (m, NULL, def, ptr, rptr);
1516 }
1517
1518 /*
1519  * mono_metadata_free_method_signature:
1520  * @sig: signature to destroy
1521  *
1522  * Free the memory allocated in the signature @sig.
1523  */
1524 void
1525 mono_metadata_free_method_signature (MonoMethodSignature *sig)
1526 {
1527         int i;
1528         mono_metadata_free_type (sig->ret);
1529         for (i = 0; i < sig->param_count; ++i)
1530                 mono_metadata_free_type (sig->params [i]);
1531
1532         g_free (sig);
1533 }
1534
1535 static void
1536 do_mono_metadata_parse_generic_inst (MonoType *type, MonoImage *m, MonoGenericContainer *generic_container,
1537                                      const char *ptr, const char **rptr)
1538 {
1539         MonoGenericInst *ginst = g_new0 (MonoGenericInst, 1);
1540         MonoGenericInst *cached;
1541         MonoClass *gklass;
1542         int i, count;
1543
1544         type->data.generic_inst = ginst;
1545
1546         ginst->context = g_new0 (MonoGenericContext, 1);
1547         ginst->context->ginst = ginst;
1548
1549         ginst->klass = g_new0 (MonoClass, 1);
1550
1551         ginst->generic_type = mono_metadata_parse_type_full (m, generic_container, MONO_PARSE_TYPE, 0, ptr, &ptr);
1552         ginst->type_argc = count = mono_metadata_decode_value (ptr, &ptr);
1553         ginst->type_argv = g_new0 (MonoType*, count);
1554
1555         gklass = mono_class_from_mono_type (ginst->generic_type);
1556         g_assert ((ginst->container = gklass->generic_container) != NULL);
1557
1558         /*
1559          * Create the klass before parsing the type arguments.
1560          * This is required to support "recursive" definitions.
1561          * See mcs/tests/gen-23.cs for an example.
1562          */
1563
1564         ginst->init_pending = TRUE;
1565
1566         mono_class_create_generic (ginst);
1567
1568         for (i = 0; i < ginst->type_argc; i++) {
1569                 MonoType *t = mono_metadata_parse_type_full (m, generic_container, MONO_PARSE_TYPE, 0, ptr, &ptr);
1570
1571                 ginst->type_argv [i] = t;
1572                 if (!ginst->is_open)
1573                         ginst->is_open = mono_class_is_open_constructed_type (t);
1574         }
1575
1576         mono_class_create_generic_2 (ginst);
1577
1578         if (rptr)
1579                 *rptr = ptr;
1580
1581         /*
1582          * We may be called multiple times on different metadata to create the same
1583          * instantiated type.  This happens for instance if we're part of a method or
1584          * local variable signature.
1585          *
1586          * It's important to return the same MonoGenericInst * for each particualar
1587          * instantiation of a generic type (ie "Stack<Int32>") to make static fields
1588          * work.
1589          *
1590          * According to the spec ($26.1.5), a static variable in a generic class
1591          * declaration is shared amongst all instances of the same closed constructed
1592          * type.
1593          */
1594
1595         cached = g_hash_table_lookup (m->generic_inst_cache, ginst);
1596         if (cached) {
1597                 g_free (ginst->klass);
1598                 g_free (ginst->type_argv);
1599                 g_free (ginst);
1600
1601                 type->data.generic_inst = cached;
1602                 return;
1603         } else {
1604                 g_hash_table_insert (m->generic_inst_cache, ginst, ginst);
1605
1606                 mono_stats.generic_instance_count++;
1607                 mono_stats.generics_metadata_size += sizeof (MonoGenericInst) +
1608                         sizeof (MonoGenericContext) +
1609                         ginst->type_argc * sizeof (MonoType);
1610         }
1611
1612         ginst->init_pending = FALSE;
1613 }
1614
1615 /* 
1616  * do_mono_metadata_parse_generic_param:
1617  * @generic_container: Our MonoClass's or MonoMethodNormal's MonoGenericContainer;
1618  *                     see mono_metadata_parse_type_full() for details.
1619  * Internal routine to parse a generic type parameter.
1620  */
1621 static MonoGenericParam *
1622 mono_metadata_parse_generic_param (MonoImage *m, MonoGenericContainer *generic_container,
1623                                    gboolean is_mvar, const char *ptr, const char **rptr)
1624 {
1625         int index;
1626
1627         index = mono_metadata_decode_value (ptr, &ptr);
1628         if (rptr)
1629                 *rptr = ptr;
1630
1631         if (!is_mvar) {
1632                 g_assert (generic_container);
1633                 if (generic_container->parent) {
1634                         /*
1635                          * The current MonoGenericContainer is a generic method -> its `parent'
1636                          * points to the containing class'es container.
1637                          */
1638                         generic_container = generic_container->parent;
1639                 }
1640                 g_assert (generic_container && !generic_container->is_method);
1641                 g_assert (index < generic_container->type_argc);
1642
1643                 return &generic_container->type_params [index];
1644         } else {
1645                 g_assert (generic_container && (generic_container->is_method || generic_container->is_signature));
1646                 g_assert (index < generic_container->type_argc);
1647
1648                 return &generic_container->type_params [index];
1649         }
1650 }
1651
1652 /* 
1653  * do_mono_metadata_parse_type:
1654  * @type: MonoType to be filled in with the return value
1655  * @
1656  * Internal routine used to "fill" the contents of @type from an 
1657  * allocated pointer.  This is done this way to avoid doing too
1658  * many mini-allocations (particularly for the MonoFieldType which
1659  * most of the time is just a MonoType, but sometimes might be augmented).
1660  *
1661  * This routine is used by mono_metadata_parse_type and
1662  * mono_metadata_parse_field_type
1663  *
1664  * This extracts a Type as specified in Partition II (22.2.12) 
1665  */
1666 static void
1667 do_mono_metadata_parse_type (MonoType *type, MonoImage *m, MonoGenericContainer *generic_container,
1668                              const char *ptr, const char **rptr)
1669 {
1670         type->type = mono_metadata_decode_value (ptr, &ptr);
1671         
1672         switch (type->type){
1673         case MONO_TYPE_VOID:
1674         case MONO_TYPE_BOOLEAN:
1675         case MONO_TYPE_CHAR:
1676         case MONO_TYPE_I1:
1677         case MONO_TYPE_U1:
1678         case MONO_TYPE_I2:
1679         case MONO_TYPE_U2:
1680         case MONO_TYPE_I4:
1681         case MONO_TYPE_U4:
1682         case MONO_TYPE_I8:
1683         case MONO_TYPE_U8:
1684         case MONO_TYPE_R4:
1685         case MONO_TYPE_R8:
1686         case MONO_TYPE_I:
1687         case MONO_TYPE_U:
1688         case MONO_TYPE_STRING:
1689         case MONO_TYPE_OBJECT:
1690         case MONO_TYPE_TYPEDBYREF:
1691                 break;
1692         case MONO_TYPE_VALUETYPE:
1693         case MONO_TYPE_CLASS: {
1694                 guint32 token;
1695                 token = mono_metadata_parse_typedef_or_ref (m, ptr, &ptr);
1696                 type->data.klass = mono_class_get (m, token);
1697                 break;
1698         }
1699         case MONO_TYPE_SZARRAY: {
1700                 MonoType *etype = mono_metadata_parse_type_full (m, generic_container, MONO_PARSE_MOD_TYPE, 0, ptr, &ptr);
1701                 type->data.klass = mono_class_from_mono_type (etype);
1702                 mono_metadata_free_type (etype);
1703                 break;
1704         }
1705         case MONO_TYPE_PTR:
1706                 type->data.type = mono_metadata_parse_type_full (m, generic_container, MONO_PARSE_MOD_TYPE, 0, ptr, &ptr);
1707                 break;
1708         case MONO_TYPE_FNPTR:
1709                 type->data.method = mono_metadata_parse_method_signature_full (m, generic_container, 0, ptr, &ptr);
1710                 break;
1711         case MONO_TYPE_ARRAY:
1712                 type->data.array = mono_metadata_parse_array_full (m, generic_container, ptr, &ptr);
1713                 break;
1714
1715         case MONO_TYPE_MVAR:
1716                 type->data.generic_param = mono_metadata_parse_generic_param (m, generic_container, TRUE, ptr, &ptr);
1717                 break;
1718
1719         case MONO_TYPE_VAR:
1720                 type->data.generic_param = mono_metadata_parse_generic_param (m, generic_container, FALSE, ptr, &ptr);
1721                 break;
1722
1723         case MONO_TYPE_GENERICINST:
1724                 do_mono_metadata_parse_generic_inst (type, m, generic_container, ptr, &ptr);
1725                 break;
1726                 
1727         default:
1728                 g_error ("type 0x%02x not handled in do_mono_metadata_parse_type", type->type);
1729         }
1730         
1731         if (rptr)
1732                 *rptr = ptr;
1733 }
1734
1735 /*
1736  * mono_metadata_free_type:
1737  * @type: type to free
1738  *
1739  * Free the memory allocated for type @type.
1740  */
1741 void
1742 mono_metadata_free_type (MonoType *type)
1743 {
1744         if (type >= builtin_types && type < builtin_types + NBUILTIN_TYPES ())
1745                 return;
1746         
1747         switch (type->type){
1748         case MONO_TYPE_OBJECT:
1749         case MONO_TYPE_STRING:
1750                 if (!type->data.klass)
1751                         break;
1752                 /* fall through */
1753         case MONO_TYPE_CLASS:
1754         case MONO_TYPE_VALUETYPE:
1755                 if (type == &type->data.klass->byval_arg || type == &type->data.klass->this_arg)
1756                         return;
1757                 break;
1758         case MONO_TYPE_PTR:
1759                 mono_metadata_free_type (type->data.type);
1760                 break;
1761         case MONO_TYPE_FNPTR:
1762                 mono_metadata_free_method_signature (type->data.method);
1763                 break;
1764         case MONO_TYPE_ARRAY:
1765                 mono_metadata_free_array (type->data.array);
1766                 break;
1767         }
1768         g_free (type);
1769 }
1770
1771 #if 0
1772 static void
1773 hex_dump (const char *buffer, int base, int count)
1774 {
1775         int show_header = 1;
1776         int i;
1777
1778         if (count < 0){
1779                 count = -count;
1780                 show_header = 0;
1781         }
1782         
1783         for (i = 0; i < count; i++){
1784                 if (show_header)
1785                         if ((i % 16) == 0)
1786                                 printf ("\n0x%08x: ", (unsigned char) base + i);
1787
1788                 printf ("%02x ", (unsigned char) (buffer [i]));
1789         }
1790         fflush (stdout);
1791 }
1792 #endif
1793
1794 /** 
1795  * @mh: The Method header
1796  * @ptr: Points to the beginning of the Section Data (25.3)
1797  */
1798 static void
1799 parse_section_data (MonoImage *m, MonoMethodHeader *mh, const unsigned char *ptr)
1800 {
1801         unsigned char sect_data_flags;
1802         const unsigned char *sptr;
1803         int is_fat;
1804         guint32 sect_data_len;
1805         
1806         while (1) {
1807                 /* align on 32-bit boundary */
1808                 /* FIXME: not 64-bit clean code */
1809                 sptr = ptr = dword_align (ptr); 
1810                 sect_data_flags = *ptr;
1811                 ptr++;
1812                 
1813                 is_fat = sect_data_flags & METHOD_HEADER_SECTION_FAT_FORMAT;
1814                 if (is_fat) {
1815                         sect_data_len = (ptr [2] << 16) | (ptr [1] << 8) | ptr [0];
1816                         ptr += 3;
1817                 } else {
1818                         sect_data_len = ptr [0];
1819                         ++ptr;
1820                 }
1821                 /*
1822                 g_print ("flags: %02x, len: %d\n", sect_data_flags, sect_data_len);
1823                 hex_dump (sptr, 0, sect_data_len+8);
1824                 g_print ("\nheader: ");
1825                 hex_dump (sptr-4, 0, 4);
1826                 g_print ("\n");
1827                 */
1828                 
1829                 if (sect_data_flags & METHOD_HEADER_SECTION_EHTABLE) {
1830                         const unsigned char *p = dword_align (ptr);
1831                         int i;
1832                         mh->num_clauses = is_fat ? sect_data_len / 24: sect_data_len / 12;
1833                         /* we could just store a pointer if we don't need to byteswap */
1834                         mh->clauses = g_new0 (MonoExceptionClause, mh->num_clauses);
1835                         for (i = 0; i < mh->num_clauses; ++i) {
1836                                 MonoExceptionClause *ec = &mh->clauses [i];
1837                                 guint32 tof_value;
1838                                 if (is_fat) {
1839                                         ec->flags = read32 (p);
1840                                         p += 4;
1841                                         ec->try_offset = read32 (p);
1842                                         p += 4;
1843                                         ec->try_len = read32 (p);
1844                                         p += 4;
1845                                         ec->handler_offset = read32 (p);
1846                                         p += 4;
1847                                         ec->handler_len = read32 (p);
1848                                         p += 4;
1849                                         tof_value = read32 (p);
1850                                         p += 4;
1851                                 } else {
1852                                         ec->flags = read16 (p);
1853                                         p += 2;
1854                                         ec->try_offset = read16 (p);
1855                                         p += 2;
1856                                         ec->try_len = *p;
1857                                         ++p;
1858                                         ec->handler_offset = read16 (p);
1859                                         p += 2;
1860                                         ec->handler_len = *p;
1861                                         ++p;
1862                                         tof_value = read32 (p);
1863                                         p += 4;
1864                                 }
1865                                 if (ec->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
1866                                         ec->data.filter_offset = tof_value;
1867                                 } else if (ec->flags == MONO_EXCEPTION_CLAUSE_NONE) {
1868                                         ec->data.catch_class = tof_value? mono_class_get (m, tof_value): 0;
1869                                 } else {
1870                                         ec->data.catch_class = NULL;
1871                                 }
1872                                 /* g_print ("try %d: %x %04x-%04x %04x\n", i, ec->flags, ec->try_offset, ec->try_offset+ec->try_len, ec->try_len); */
1873                         }
1874
1875                 }
1876                 if (sect_data_flags & METHOD_HEADER_SECTION_MORE_SECTS)
1877                         ptr += sect_data_len - 4; /* LAMESPEC: it seems the size includes the header */
1878                 else
1879                         return;
1880         }
1881 }
1882
1883 /*
1884  * mono_metadata_parse_mh:
1885  * @m: metadata context
1886  * @ptr: pointer to the method header.
1887  *
1888  * Decode the method header at @ptr, including pointer to the IL code,
1889  * info about local variables and optional exception tables.
1890  *
1891  * Returns: a MonoMethodHeader.
1892  */
1893 MonoMethodHeader *
1894 mono_metadata_parse_mh_full (MonoImage *m, MonoGenericContainer *generic_container, const char *ptr)
1895 {
1896         MonoMethodHeader *mh;
1897         unsigned char flags = *(const unsigned char *) ptr;
1898         unsigned char format = flags & METHOD_HEADER_FORMAT_MASK;
1899         guint16 fat_flags;
1900         guint32 local_var_sig_tok, max_stack, code_size, init_locals;
1901         const unsigned char *code;
1902         int hsize;
1903         
1904         g_return_val_if_fail (ptr != NULL, NULL);
1905
1906         switch (format){
1907         case METHOD_HEADER_TINY_FORMAT:
1908                 mh = g_new0 (MonoMethodHeader, 1);
1909                 ptr++;
1910                 mh->max_stack = 8;
1911                 local_var_sig_tok = 0;
1912                 mh->code_size = flags >> 2;
1913                 mh->code = ptr;
1914                 return mh;
1915         case METHOD_HEADER_TINY_FORMAT1:
1916                 mh = g_new0 (MonoMethodHeader, 1);
1917                 ptr++;
1918                 mh->max_stack = 8;
1919                 local_var_sig_tok = 0;
1920
1921                 /*
1922                  * The spec claims 3 bits, but the Beta2 is
1923                  * incorrect
1924                  */
1925                 mh->code_size = flags >> 2;
1926                 mh->code = ptr;
1927                 return mh;
1928         case METHOD_HEADER_FAT_FORMAT:
1929                 fat_flags = read16 (ptr);
1930                 ptr += 2;
1931                 hsize = (fat_flags >> 12) & 0xf;
1932                 max_stack = read16 (ptr);
1933                 ptr += 2;
1934                 code_size = read32 (ptr);
1935                 ptr += 4;
1936                 local_var_sig_tok = read32 (ptr);
1937                 ptr += 4;
1938
1939                 if (fat_flags & METHOD_HEADER_INIT_LOCALS)
1940                         init_locals = 1;
1941                 else
1942                         init_locals = 0;
1943
1944                 code = ptr;
1945
1946                 if (!(fat_flags & METHOD_HEADER_MORE_SECTS))
1947                         break;
1948
1949                 /*
1950                  * There are more sections
1951                  */
1952                 ptr = code + code_size;
1953                 
1954                 break;
1955                 
1956         default:
1957                 return NULL;
1958         }
1959                        
1960         if (local_var_sig_tok) {
1961                 MonoTableInfo *t = &m->tables [MONO_TABLE_STANDALONESIG];
1962                 const char *locals_ptr;
1963                 guint32 cols [MONO_STAND_ALONE_SIGNATURE_SIZE];
1964                 int len=0, i, bsize;
1965
1966                 mono_metadata_decode_row (t, (local_var_sig_tok & 0xffffff)-1, cols, 1);
1967                 locals_ptr = mono_metadata_blob_heap (m, cols [MONO_STAND_ALONE_SIGNATURE]);
1968                 bsize = mono_metadata_decode_blob_size (locals_ptr, &locals_ptr);
1969                 if (*locals_ptr != 0x07)
1970                         g_warning ("wrong signature for locals blob");
1971                 locals_ptr++;
1972                 len = mono_metadata_decode_value (locals_ptr, &locals_ptr);
1973                 mh = g_malloc0 (sizeof (MonoMethodHeader) + (len - MONO_ZERO_LEN_ARRAY) * sizeof (MonoType*));
1974                 mh->num_locals = len;
1975                 for (i = 0; i < len; ++i)
1976                         mh->locals [i] = mono_metadata_parse_type_full (
1977                                 m, generic_container, MONO_PARSE_LOCAL, 0, locals_ptr, &locals_ptr);
1978         } else {
1979                 mh = g_new0 (MonoMethodHeader, 1);
1980         }
1981         mh->code = code;
1982         mh->code_size = code_size;
1983         mh->max_stack = max_stack;
1984         mh->init_locals = init_locals;
1985         if (fat_flags & METHOD_HEADER_MORE_SECTS)
1986                 parse_section_data (m, mh, (const unsigned char*)ptr);
1987         return mh;
1988 }
1989
1990 MonoMethodHeader *
1991 mono_metadata_parse_mh (MonoImage *m, const char *ptr)
1992 {
1993         return mono_metadata_parse_mh_full (m, NULL, ptr);
1994 }
1995
1996 /*
1997  * mono_metadata_free_mh:
1998  * @mh: a method header
1999  *
2000  * Free the memory allocated for the method header.
2001  */
2002 void
2003 mono_metadata_free_mh (MonoMethodHeader *mh)
2004 {
2005         int i;
2006         for (i = 0; i < mh->num_locals; ++i)
2007                 mono_metadata_free_type (mh->locals[i]);
2008         g_free (mh->clauses);
2009         g_free (mh);
2010 }
2011
2012 /**
2013  * mono_metadata_parse_field_type:
2014  * @m: metadata context to extract information from
2015  * @ptr: pointer to the field signature
2016  * @rptr: pointer updated to match the end of the decoded stream
2017  *
2018  * Parses the field signature, and returns the type information for it. 
2019  *
2020  * Returns: The MonoType that was extracted from @ptr.
2021  */
2022 MonoType *
2023 mono_metadata_parse_field_type (MonoImage *m, short field_flags, const char *ptr, const char **rptr)
2024 {
2025         return mono_metadata_parse_type (m, MONO_PARSE_FIELD, field_flags, ptr, rptr);
2026 }
2027
2028 /**
2029  * mono_metadata_parse_param:
2030  * @m: metadata context to extract information from
2031  * @ptr: pointer to the param signature
2032  * @rptr: pointer updated to match the end of the decoded stream
2033  *
2034  * Parses the param signature, and returns the type information for it. 
2035  *
2036  * Returns: The MonoType that was extracted from @ptr.
2037  */
2038 MonoType *
2039 mono_metadata_parse_param (MonoImage *m, const char *ptr, const char **rptr)
2040 {
2041         return mono_metadata_parse_type (m, MONO_PARSE_PARAM, 0, ptr, rptr);
2042 }
2043
2044 /*
2045  * mono_metadata_token_from_dor:
2046  * @dor_token: A TypeDefOrRef coded index
2047  *
2048  * dor_token is a TypeDefOrRef coded index: it contains either
2049  * a TypeDef, TypeRef or TypeSpec in the lower bits, and the upper
2050  * bits contain an index into the table.
2051  *
2052  * Returns: an expanded token
2053  */
2054 guint32
2055 mono_metadata_token_from_dor (guint32 dor_index)
2056 {
2057         guint32 table, idx;
2058
2059         table = dor_index & 0x03;
2060         idx = dor_index >> 2;
2061
2062         switch (table){
2063         case 0: /* TypeDef */
2064                 return MONO_TOKEN_TYPE_DEF | idx;
2065
2066         case 1: /* TypeRef */
2067                 return MONO_TOKEN_TYPE_REF | idx;
2068
2069         case 2: /* TypeSpec */
2070                 return MONO_TOKEN_TYPE_SPEC | idx;
2071
2072         default:
2073                 g_assert_not_reached ();
2074         }
2075
2076         return 0;
2077 }
2078
2079 /*
2080  * We use this to pass context information to the row locator
2081  */
2082 typedef struct {
2083         int idx;                        /* The index that we are trying to locate */
2084         int col_idx;            /* The index in the row where idx may be stored */
2085         MonoTableInfo *t;       /* pointer to the table */
2086         guint32 result;
2087 } locator_t;
2088
2089 /*
2090  * How the row locator works.
2091  *
2092  *   Table A
2093  *   ___|___
2094  *   ___|___         Table B
2095  *   ___|___------>  _______
2096  *   ___|___         _______
2097  *   
2098  * A column in the rows of table A references an index in table B.
2099  * For example A may be the TYPEDEF table and B the METHODDEF table.
2100  * 
2101  * Given an index in table B we want to get the row in table A
2102  * where the column n references our index in B.
2103  *
2104  * In the locator_t structure:
2105  *      t is table A
2106  *      col_idx is the column number
2107  *      index is the index in table B
2108  *      result will be the index in table A
2109  *
2110  * Examples:
2111  * Table A              Table B         column (in table A)
2112  * TYPEDEF              METHODDEF   MONO_TYPEDEF_METHOD_LIST
2113  * TYPEDEF              FIELD           MONO_TYPEDEF_FIELD_LIST
2114  * PROPERTYMAP  PROPERTY        MONO_PROPERTY_MAP_PROPERTY_LIST
2115  * INTERFIMPL   TYPEDEF         MONO_INTERFACEIMPL_CLASS
2116  * METHODSEM    PROPERTY        ASSOCIATION (encoded index)
2117  *
2118  * Note that we still don't support encoded indexes.
2119  *
2120  */
2121 static int
2122 typedef_locator (const void *a, const void *b)
2123 {
2124         locator_t *loc = (locator_t *) a;
2125         const char *bb = (const char *) b;
2126         int typedef_index = (bb - loc->t->base) / loc->t->row_size;
2127         guint32 col, col_next;
2128
2129         col = mono_metadata_decode_row_col (loc->t, typedef_index, loc->col_idx);
2130
2131         if (loc->idx < col)
2132                 return -1;
2133
2134         /*
2135          * Need to check that the next row is valid.
2136          */
2137         if (typedef_index + 1 < loc->t->rows) {
2138                 col_next = mono_metadata_decode_row_col (loc->t, typedef_index + 1, loc->col_idx);
2139                 if (loc->idx >= col_next)
2140                         return 1;
2141
2142                 if (col == col_next)
2143                         return 1; 
2144         }
2145
2146         loc->result = typedef_index;
2147         
2148         return 0;
2149 }
2150
2151 static int
2152 table_locator (const void *a, const void *b)
2153 {
2154         locator_t *loc = (locator_t *) a;
2155         const char *bb = (const char *) b;
2156         guint32 table_index = (bb - loc->t->base) / loc->t->row_size;
2157         guint32 col;
2158         
2159         col = mono_metadata_decode_row_col (loc->t, table_index, loc->col_idx);
2160
2161         if (loc->idx == col) {
2162                 loc->result = table_index;
2163                 return 0;
2164         }
2165         if (loc->idx < col)
2166                 return -1;
2167         else 
2168                 return 1;
2169 }
2170
2171 static int
2172 declsec_locator (const void *a, const void *b)
2173 {
2174         locator_t *loc = (locator_t *) a;
2175         const char *bb = (const char *) b;
2176         guint32 table_index = (bb - loc->t->base) / loc->t->row_size;
2177         guint32 col;
2178
2179         col = mono_metadata_decode_row_col (loc->t, table_index, loc->col_idx);
2180
2181         if (loc->idx == col) {
2182                 loc->result = table_index;
2183                 return 0;
2184         }
2185         if (loc->idx < col)
2186                 return -1;
2187         else
2188                 return 1;
2189 }
2190
2191 /*
2192  * mono_metadata_typedef_from_field:
2193  * @meta: metadata context
2194  * @index: FieldDef token
2195  *
2196  * Returns the 1-based index into the TypeDef table of the type that
2197  * declared the field described by @index.
2198  * Returns 0 if not found.
2199  */
2200 guint32
2201 mono_metadata_typedef_from_field (MonoImage *meta, guint32 index)
2202 {
2203         MonoTableInfo *tdef = &meta->tables [MONO_TABLE_TYPEDEF];
2204         locator_t loc;
2205
2206         if (!tdef->base)
2207                 return 0;
2208
2209         loc.idx = mono_metadata_token_index (index);
2210         loc.col_idx = MONO_TYPEDEF_FIELD_LIST;
2211         loc.t = tdef;
2212
2213         if (!bsearch (&loc, tdef->base, tdef->rows, tdef->row_size, typedef_locator))
2214                 g_assert_not_reached ();
2215
2216         /* loc_result is 0..1, needs to be mapped to table index (that is +1) */
2217         return loc.result + 1;
2218 }
2219
2220 /*
2221  * mono_metadata_typedef_from_method:
2222  * @meta: metadata context
2223  * @index: MethodDef token
2224  *
2225  * Returns the 1-based index into the TypeDef table of the type that
2226  * declared the method described by @index.
2227  * Returns 0 if not found.
2228  */
2229 guint32
2230 mono_metadata_typedef_from_method (MonoImage *meta, guint32 index)
2231 {
2232         MonoTableInfo *tdef = &meta->tables [MONO_TABLE_TYPEDEF];
2233         locator_t loc;
2234         
2235         if (!tdef->base)
2236                 return 0;
2237
2238         loc.idx = mono_metadata_token_index (index);
2239         loc.col_idx = MONO_TYPEDEF_METHOD_LIST;
2240         loc.t = tdef;
2241
2242         if (!bsearch (&loc, tdef->base, tdef->rows, tdef->row_size, typedef_locator))
2243                 g_assert_not_reached ();
2244
2245         /* loc_result is 0..1, needs to be mapped to table index (that is +1) */
2246         return loc.result + 1;
2247 }
2248
2249 /*
2250  * mono_metadata_interfaces_from_typedef:
2251  * @meta: metadata context
2252  * @index: typedef token
2253  * 
2254  * Returns and array of interfaces that the @index typedef token implements.
2255  * The number of elemnts in the array is returned in @count.
2256  */
2257 MonoClass**
2258 mono_metadata_interfaces_from_typedef_full (MonoImage *meta, guint32 index, guint *count, MonoGenericContext *context)
2259 {
2260         MonoTableInfo *tdef = &meta->tables [MONO_TABLE_INTERFACEIMPL];
2261         locator_t loc;
2262         guint32 start, i;
2263         guint32 cols [MONO_INTERFACEIMPL_SIZE];
2264         MonoClass **result;
2265         
2266         *count = 0;
2267
2268         if (!tdef->base)
2269                 return NULL;
2270
2271         loc.idx = mono_metadata_token_index (index);
2272         loc.col_idx = MONO_INTERFACEIMPL_CLASS;
2273         loc.t = tdef;
2274
2275         if (!bsearch (&loc, tdef->base, tdef->rows, tdef->row_size, table_locator))
2276                 return NULL;
2277
2278         start = loc.result;
2279         /*
2280          * We may end up in the middle of the rows... 
2281          */
2282         while (start > 0) {
2283                 if (loc.idx == mono_metadata_decode_row_col (tdef, start - 1, MONO_INTERFACEIMPL_CLASS))
2284                         start--;
2285                 else
2286                         break;
2287         }
2288         result = NULL;
2289         i = 0;
2290         while (start < tdef->rows) {
2291                 mono_metadata_decode_row (tdef, start, cols, MONO_INTERFACEIMPL_SIZE);
2292                 if (cols [MONO_INTERFACEIMPL_CLASS] != loc.idx)
2293                         break;
2294                 result = g_renew (MonoClass*, result, i + 1);
2295                 result [i] = mono_class_get_full (
2296                         meta, mono_metadata_token_from_dor (cols [MONO_INTERFACEIMPL_INTERFACE]), context);
2297                 *count = ++i;
2298                 ++start;
2299         }
2300         return result;
2301 }
2302
2303 MonoClass**
2304 mono_metadata_interfaces_from_typedef (MonoImage *meta, guint32 index, guint *count)
2305 {
2306         return mono_metadata_interfaces_from_typedef_full (meta, index, count, NULL);
2307 }
2308
2309 /*
2310  * mono_metadata_nested_in_typedef:
2311  * @meta: metadata context
2312  * @index: typedef token
2313  * 
2314  * Returns: the 1-based index into the TypeDef table of the type
2315  * where the type described by @index is nested.
2316  * Retruns 0 if @index describes a non-nested type.
2317  */
2318 guint32
2319 mono_metadata_nested_in_typedef (MonoImage *meta, guint32 index)
2320 {
2321         MonoTableInfo *tdef = &meta->tables [MONO_TABLE_NESTEDCLASS];
2322         locator_t loc;
2323         
2324         if (!tdef->base)
2325                 return 0;
2326
2327         loc.idx = mono_metadata_token_index (index);
2328         loc.col_idx = MONO_NESTED_CLASS_NESTED;
2329         loc.t = tdef;
2330
2331         if (!bsearch (&loc, tdef->base, tdef->rows, tdef->row_size, table_locator))
2332                 return 0;
2333
2334         /* loc_result is 0..1, needs to be mapped to table index (that is +1) */
2335         return mono_metadata_decode_row_col (tdef, loc.result, MONO_NESTED_CLASS_ENCLOSING) | MONO_TOKEN_TYPE_DEF;
2336 }
2337
2338 /*
2339  * mono_metadata_nesting_typedef:
2340  * @meta: metadata context
2341  * @index: typedef token
2342  * 
2343  * Returns: the 1-based index into the TypeDef table of the first type
2344  * that is nested inside the type described by @index. The search starts at
2345  * @start_index.
2346  * Returns 0 if no such type is found.
2347  */
2348 guint32
2349 mono_metadata_nesting_typedef (MonoImage *meta, guint32 index, guint32 start_index)
2350 {
2351         MonoTableInfo *tdef = &meta->tables [MONO_TABLE_NESTEDCLASS];
2352         guint32 start;
2353         guint32 class_index = mono_metadata_token_index (index);
2354         
2355         if (!tdef->base)
2356                 return 0;
2357
2358         start = start_index;
2359
2360         while (start <= tdef->rows) {
2361                 if (class_index == mono_metadata_decode_row_col (tdef, start - 1, MONO_NESTED_CLASS_ENCLOSING))
2362                         break;
2363                 else
2364                         start++;
2365         }
2366
2367         if (start > tdef->rows)
2368                 return 0;
2369         else
2370                 return start;
2371 }
2372
2373 /*
2374  * mono_metadata_packing_from_typedef:
2375  * @meta: metadata context
2376  * @index: token representing a type
2377  * 
2378  * Returns the info stored in the ClassLAyout table for the given typedef token
2379  * into the @packing and @size pointers.
2380  * Returns 0 if the info is not found.
2381  */
2382 guint32
2383 mono_metadata_packing_from_typedef (MonoImage *meta, guint32 index, guint32 *packing, guint32 *size)
2384 {
2385         MonoTableInfo *tdef = &meta->tables [MONO_TABLE_CLASSLAYOUT];
2386         locator_t loc;
2387         guint32 cols [MONO_CLASS_LAYOUT_SIZE];
2388         
2389         if (!tdef->base)
2390                 return 0;
2391
2392         loc.idx = mono_metadata_token_index (index);
2393         loc.col_idx = MONO_CLASS_LAYOUT_PARENT;
2394         loc.t = tdef;
2395
2396         if (!bsearch (&loc, tdef->base, tdef->rows, tdef->row_size, table_locator))
2397                 return 0;
2398
2399         mono_metadata_decode_row (tdef, loc.result, cols, MONO_CLASS_LAYOUT_SIZE);
2400         if (packing)
2401                 *packing = cols [MONO_CLASS_LAYOUT_PACKING_SIZE];
2402         if (size)
2403                 *size = cols [MONO_CLASS_LAYOUT_CLASS_SIZE];
2404
2405         /* loc_result is 0..1, needs to be mapped to table index (that is +1) */
2406         return loc.result + 1;
2407 }
2408
2409 /*
2410  * mono_metadata_custom_attrs_from_index:
2411  * @meta: metadata context
2412  * @index: token representing the parent
2413  * 
2414  * Returns: the 1-based index into the CustomAttribute table of the first 
2415  * attribute which belongs to the metadata object described by @index.
2416  * Returns 0 if no such attribute is found.
2417  */
2418 guint32
2419 mono_metadata_custom_attrs_from_index (MonoImage *meta, guint32 index)
2420 {
2421         MonoTableInfo *tdef = &meta->tables [MONO_TABLE_CUSTOMATTRIBUTE];
2422         locator_t loc;
2423         
2424         if (!tdef->base)
2425                 return 0;
2426
2427         loc.idx = index;
2428         loc.col_idx = MONO_CUSTOM_ATTR_PARENT;
2429         loc.t = tdef;
2430
2431         if (!bsearch (&loc, tdef->base, tdef->rows, tdef->row_size, table_locator))
2432                 return 0;
2433
2434         /* Find the first entry by searching backwards */
2435         while ((loc.result > 0) && (mono_metadata_decode_row_col (tdef, loc.result - 1, MONO_CUSTOM_ATTR_PARENT) == index))
2436                 loc.result --;
2437
2438         /* loc_result is 0..1, needs to be mapped to table index (that is +1) */
2439         return loc.result + 1;
2440 }
2441
2442 /*
2443  * mono_metadata_declsec_from_index:
2444  * @meta: metadata context
2445  * @index: token representing the parent
2446  * 
2447  * Returns: the 0-based index into the DeclarativeSecurity table of the first 
2448  * attribute which belongs to the metadata object described by @index.
2449  * Returns -1 if no such attribute is found.
2450  */
2451 guint32
2452 mono_metadata_declsec_from_index (MonoImage *meta, guint32 index)
2453 {
2454         MonoTableInfo *tdef = &meta->tables [MONO_TABLE_DECLSECURITY];
2455         locator_t loc;
2456
2457         if (!tdef->base)
2458                 return -1;
2459
2460         loc.idx = index;
2461         loc.col_idx = MONO_DECL_SECURITY_PARENT;
2462         loc.t = tdef;
2463
2464         if (!bsearch (&loc, tdef->base, tdef->rows, tdef->row_size, declsec_locator))
2465                 return -1;
2466
2467         /* Find the first entry by searching backwards */
2468         while ((loc.result > 0) && (mono_metadata_decode_row_col (tdef, loc.result - 1, MONO_DECL_SECURITY_PARENT) == index))
2469                 loc.result --;
2470
2471         return loc.result;
2472 }
2473
2474 #ifdef DEBUG
2475 static void
2476 mono_backtrace (int limit)
2477 {
2478         void *array[limit];
2479         char **names;
2480         int i;
2481         backtrace (array, limit);
2482         names = backtrace_symbols (array, limit);
2483         for (i =0; i < limit; ++i) {
2484                 g_print ("\t%s\n", names [i]);
2485         }
2486         g_free (names);
2487 }
2488 #endif
2489
2490 #ifndef __GNUC__
2491 /*#define __alignof__(a) sizeof(a)*/
2492 #define __alignof__(type) G_STRUCT_OFFSET(struct { char c; type x; }, x)
2493 #endif
2494
2495 /*
2496  * mono_type_size:
2497  * @t: the type to return the size of
2498  *
2499  * Returns: the number of bytes required to hold an instance of this
2500  * type in memory
2501  */
2502 int
2503 mono_type_size (MonoType *t, gint *align)
2504 {
2505         if (!t) {
2506                 *align = 1;
2507                 return 0;
2508         }
2509         if (t->byref) {
2510                 *align = __alignof__(gpointer);
2511                 return sizeof (gpointer);
2512         }
2513
2514         switch (t->type){
2515         case MONO_TYPE_VOID:
2516                 *align = 1;
2517                 return 0;
2518         case MONO_TYPE_BOOLEAN:
2519                 *align = __alignof__(gint8);
2520                 return 1;
2521         case MONO_TYPE_I1:
2522         case MONO_TYPE_U1:
2523                 *align = __alignof__(gint8);
2524                 return 1;
2525         case MONO_TYPE_CHAR:
2526         case MONO_TYPE_I2:
2527         case MONO_TYPE_U2:
2528                 *align = __alignof__(gint16);
2529                 return 2;               
2530         case MONO_TYPE_I4:
2531         case MONO_TYPE_U4:
2532                 *align = __alignof__(gint32);
2533                 return 4;
2534         case MONO_TYPE_R4:
2535                 *align = __alignof__(float);
2536                 return 4;
2537         case MONO_TYPE_I8:
2538         case MONO_TYPE_U8:
2539                 *align = __alignof__(gint64);
2540                 return 8;               
2541         case MONO_TYPE_R8:
2542                 *align = __alignof__(double);
2543                 return 8;               
2544         case MONO_TYPE_I:
2545         case MONO_TYPE_U:
2546                 *align = __alignof__(gpointer);
2547                 return sizeof (gpointer);
2548         case MONO_TYPE_STRING:
2549                 *align = __alignof__(gpointer);
2550                 return sizeof (gpointer);
2551         case MONO_TYPE_OBJECT:
2552                 *align = __alignof__(gpointer);
2553                 return sizeof (gpointer);
2554         case MONO_TYPE_VALUETYPE: {
2555                 if (t->data.klass->enumtype)
2556                         return mono_type_size (t->data.klass->enum_basetype, align);
2557                 else
2558                         return mono_class_value_size (t->data.klass, align);
2559         }
2560         case MONO_TYPE_CLASS:
2561         case MONO_TYPE_SZARRAY:
2562         case MONO_TYPE_PTR:
2563         case MONO_TYPE_FNPTR:
2564         case MONO_TYPE_ARRAY:
2565                 *align = __alignof__(gpointer);
2566                 return sizeof (gpointer);
2567         case MONO_TYPE_TYPEDBYREF:
2568                 return mono_class_value_size (mono_defaults.typed_reference_class, align);
2569         case MONO_TYPE_GENERICINST: {
2570                 MonoGenericInst *ginst = t->data.generic_inst;
2571
2572                 g_assert (!ginst->is_open && !ginst->klass->generic_container);
2573
2574                 if (MONO_TYPE_ISSTRUCT (ginst->generic_type)) {
2575                         MonoClass *gklass = mono_class_from_mono_type (ginst->generic_type);
2576
2577                         if (gklass->enumtype)
2578                                 return mono_type_size (gklass->enum_basetype, align);
2579                         else
2580                                 return mono_class_value_size (ginst->klass, align);
2581                 } else {
2582                         *align = __alignof__(gpointer);
2583                         return sizeof (gpointer);
2584                 }
2585         }
2586         case MONO_TYPE_VAR:
2587         case MONO_TYPE_MVAR:
2588                 *align = __alignof__(gpointer);
2589                 return sizeof (gpointer);
2590         default:
2591                 g_error ("mono_type_size: type 0x%02x unknown", t->type);
2592         }
2593         return 0;
2594 }
2595
2596 /*
2597  * mono_type_stack_size:
2598  * @t: the type to return the size it uses on the stack
2599  *
2600  * Returns: the number of bytes required to hold an instance of this
2601  * type on the runtime stack
2602  */
2603 int
2604 mono_type_stack_size (MonoType *t, gint *align)
2605 {
2606         int tmp;
2607
2608         g_assert (t != NULL);
2609
2610         if (!align)
2611                 align = &tmp;
2612
2613         if (t->byref) {
2614                 *align = __alignof__(gpointer);
2615                 return sizeof (gpointer);
2616         }
2617
2618         switch (t->type){
2619         case MONO_TYPE_BOOLEAN:
2620         case MONO_TYPE_CHAR:
2621         case MONO_TYPE_I1:
2622         case MONO_TYPE_U1:
2623         case MONO_TYPE_I2:
2624         case MONO_TYPE_U2:
2625         case MONO_TYPE_I4:
2626         case MONO_TYPE_U4:
2627         case MONO_TYPE_I:
2628         case MONO_TYPE_U:
2629         case MONO_TYPE_STRING:
2630         case MONO_TYPE_OBJECT:
2631         case MONO_TYPE_CLASS:
2632         case MONO_TYPE_SZARRAY:
2633         case MONO_TYPE_PTR:
2634         case MONO_TYPE_FNPTR:
2635         case MONO_TYPE_ARRAY:
2636                 *align = __alignof__(gpointer);
2637                 return sizeof (gpointer);
2638         case MONO_TYPE_TYPEDBYREF:
2639                 *align = __alignof__(gpointer);
2640                 return sizeof (gpointer) * 3;
2641         case MONO_TYPE_R4:
2642                 *align = __alignof__(float);
2643                 return sizeof (float);          
2644         case MONO_TYPE_I8:
2645         case MONO_TYPE_U8:
2646                 *align = __alignof__(gint64);
2647                 return sizeof (gint64);         
2648         case MONO_TYPE_R8:
2649                 *align = __alignof__(double);
2650                 return sizeof (double);
2651         case MONO_TYPE_VALUETYPE: {
2652                 guint32 size;
2653
2654                 if (t->data.klass->enumtype)
2655                         return mono_type_stack_size (t->data.klass->enum_basetype, align);
2656                 else {
2657                         size = mono_class_value_size (t->data.klass, align);
2658
2659                         *align = *align + __alignof__(gpointer) - 1;
2660                         *align &= ~(__alignof__(gpointer) - 1);
2661
2662                         size += sizeof (gpointer) - 1;
2663                         size &= ~(sizeof (gpointer) - 1);
2664
2665                         return size;
2666                 }
2667         }
2668         case MONO_TYPE_GENERICINST: {
2669                 MonoGenericInst *ginst = t->data.generic_inst;
2670
2671                 g_assert (!ginst->is_open && !ginst->klass->generic_container);
2672
2673                 if (MONO_TYPE_ISSTRUCT (ginst->generic_type)) {
2674                         MonoClass *gklass = mono_class_from_mono_type (ginst->generic_type);
2675
2676                         if (gklass->enumtype)
2677                                 return mono_type_stack_size (gklass->enum_basetype, align);
2678                         else {
2679                                 guint32 size = mono_class_value_size (ginst->klass, align);
2680
2681                                 *align = *align + __alignof__(gpointer) - 1;
2682                                 *align &= ~(__alignof__(gpointer) - 1);
2683
2684                                 size += sizeof (gpointer) - 1;
2685                                 size &= ~(sizeof (gpointer) - 1);
2686
2687                                 return size;
2688                         }
2689                 } else {
2690                         *align = __alignof__(gpointer);
2691                         return sizeof (gpointer);
2692                 }
2693         }
2694         default:
2695                 g_error ("type 0x%02x unknown", t->type);
2696         }
2697         return 0;
2698 }
2699
2700 gboolean
2701 mono_metadata_generic_inst_is_valuetype (MonoGenericInst *ginst)
2702 {
2703         return MONO_TYPE_ISSTRUCT (ginst->generic_type);
2704 }
2705
2706 guint
2707 mono_metadata_generic_inst_hash (MonoGenericInst *ginst)
2708 {
2709         return mono_metadata_type_hash (ginst->generic_type);
2710 }
2711
2712 static gboolean
2713 _mono_metadata_generic_inst_equal (MonoGenericInst *g1, MonoGenericInst *g2, gboolean signature_only)
2714 {
2715         int i;
2716
2717         if (g1->type_argc != g2->type_argc)
2718                 return FALSE;
2719         if (!do_mono_metadata_type_equal (g1->generic_type, g2->generic_type, signature_only))
2720                 return FALSE;
2721         for (i = 0; i < g1->type_argc; ++i) {
2722                 if (!do_mono_metadata_type_equal (g1->type_argv [i], g2->type_argv [i], signature_only))
2723                         return FALSE;
2724         }
2725         return TRUE;
2726 }
2727
2728 gboolean
2729 mono_metadata_generic_inst_equal (MonoGenericInst *g1, MonoGenericInst *g2)
2730 {
2731         return _mono_metadata_generic_inst_equal (g1, g2, FALSE);
2732 }
2733
2734 guint
2735 mono_metadata_generic_method_hash (MonoGenericMethod *gmethod)
2736 {
2737         return gmethod->mtype_argc;
2738 }
2739
2740 gboolean
2741 mono_metadata_generic_method_equal (MonoGenericMethod *g1, MonoGenericMethod *g2)
2742 {
2743         int i;
2744
2745         if (g1->mtype_argc != g2->mtype_argc)
2746                 return FALSE;
2747         for (i = 0; i < g1->mtype_argc; ++i) {
2748                 if (!mono_metadata_type_equal (g1->mtype_argv [i], g2->mtype_argv [i]))
2749                         return FALSE;
2750         }
2751         return TRUE;
2752 }
2753
2754
2755 /*
2756  * mono_metadata_type_hash:
2757  * @t1: a type
2758  *
2759  * Computes an hash value for @t1 to be used in GHashTable.
2760  */
2761 guint
2762 mono_metadata_type_hash (MonoType *t1)
2763 {
2764         guint hash = t1->type;
2765
2766         hash |= t1->byref << 6; /* do not collide with t1->type values */
2767         switch (t1->type) {
2768         case MONO_TYPE_VALUETYPE:
2769         case MONO_TYPE_CLASS:
2770         case MONO_TYPE_SZARRAY:
2771                 /* check if the distribution is good enough */
2772                 return ((hash << 5) - hash) ^ g_str_hash (t1->data.klass->name);
2773         case MONO_TYPE_PTR:
2774                 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
2775         case MONO_TYPE_ARRAY:
2776                 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
2777         case MONO_TYPE_GENERICINST:
2778                 return ((hash << 5) - hash) ^ mono_metadata_generic_inst_hash (t1->data.generic_inst);
2779         }
2780         return hash;
2781 }
2782
2783 static gboolean
2784 mono_metadata_generic_param_equal (MonoGenericParam *p1, MonoGenericParam *p2, gboolean signature_only)
2785 {
2786         if (p1 == p2)
2787                 return TRUE;
2788         if (p1->num != p2->num)
2789                 return FALSE;
2790
2791         g_assert (p1->owner && p2->owner);
2792         if (p1->owner == p2->owner)
2793                 return TRUE;
2794
2795         /*
2796          * If `signature_only' is true, we're comparing two (method) signatures.
2797          * In this case, the owner of two type parameters doesn't need to match.
2798          */
2799
2800         return signature_only;
2801 }
2802
2803 static gboolean
2804 mono_metadata_class_equal (MonoClass *c1, MonoClass *c2, gboolean signature_only)
2805 {
2806         if (c1 == c2)
2807                 return TRUE;
2808         if (c1->generic_inst && c2->generic_inst)
2809                 return _mono_metadata_generic_inst_equal (c1->generic_inst, c2->generic_inst, signature_only);
2810         if ((c1->byval_arg.type == MONO_TYPE_VAR) && (c2->byval_arg.type == MONO_TYPE_VAR))
2811                 return mono_metadata_generic_param_equal (
2812                         c1->byval_arg.data.generic_param, c2->byval_arg.data.generic_param, FALSE);
2813         if ((c1->byval_arg.type == MONO_TYPE_MVAR) && (c2->byval_arg.type == MONO_TYPE_MVAR))
2814                 return mono_metadata_generic_param_equal (
2815                         c1->byval_arg.data.generic_param, c2->byval_arg.data.generic_param, signature_only);
2816         return FALSE;
2817 }
2818
2819 /*
2820  * mono_metadata_type_equal:
2821  * @t1: a type
2822  * @t2: another type
2823  *
2824  * Determine if @t1 and @t2 represent the same type.
2825  * Returns: #TRUE if @t1 and @t2 are equal.
2826  */
2827 static gboolean
2828 do_mono_metadata_type_equal (MonoType *t1, MonoType *t2, gboolean signature_only)
2829 {
2830         if (t1->type != t2->type ||
2831             t1->byref != t2->byref)
2832                 return FALSE;
2833
2834         switch (t1->type) {
2835         case MONO_TYPE_VOID:
2836         case MONO_TYPE_BOOLEAN:
2837         case MONO_TYPE_CHAR:
2838         case MONO_TYPE_I1:
2839         case MONO_TYPE_U1:
2840         case MONO_TYPE_I2:
2841         case MONO_TYPE_U2:
2842         case MONO_TYPE_I4:
2843         case MONO_TYPE_U4:
2844         case MONO_TYPE_I8:
2845         case MONO_TYPE_U8:
2846         case MONO_TYPE_R4:
2847         case MONO_TYPE_R8:
2848         case MONO_TYPE_STRING:
2849         case MONO_TYPE_I:
2850         case MONO_TYPE_U:
2851         case MONO_TYPE_OBJECT:
2852         case MONO_TYPE_TYPEDBYREF:
2853                 return TRUE;
2854         case MONO_TYPE_VALUETYPE:
2855         case MONO_TYPE_CLASS:
2856         case MONO_TYPE_SZARRAY:
2857                 return mono_metadata_class_equal (t1->data.klass, t2->data.klass, signature_only);
2858         case MONO_TYPE_PTR:
2859                 return do_mono_metadata_type_equal (t1->data.type, t2->data.type, signature_only);
2860         case MONO_TYPE_ARRAY:
2861                 if (t1->data.array->rank != t2->data.array->rank)
2862                         return FALSE;
2863                 return mono_metadata_class_equal (t1->data.array->eklass, t2->data.array->eklass, signature_only);
2864         case MONO_TYPE_GENERICINST:
2865                 return _mono_metadata_generic_inst_equal (
2866                         t1->data.generic_inst, t2->data.generic_inst, signature_only);
2867         case MONO_TYPE_VAR:
2868                 return mono_metadata_generic_param_equal (
2869                         t1->data.generic_param, t2->data.generic_param, FALSE);
2870         case MONO_TYPE_MVAR:
2871                 return mono_metadata_generic_param_equal (
2872                         t1->data.generic_param, t2->data.generic_param, signature_only);
2873         default:
2874                 g_error ("implement type compare for %0x!", t1->type);
2875                 return FALSE;
2876         }
2877
2878         return FALSE;
2879 }
2880
2881 gboolean
2882 mono_metadata_type_equal (MonoType *t1, MonoType *t2)
2883 {
2884         return do_mono_metadata_type_equal (t1, t2, FALSE);
2885 }
2886
2887 /*
2888  * mono_metadata_signature_equal:
2889  * @sig1: a signature
2890  * @sig2: another signature
2891  *
2892  * Determine if @sig1 and @sig2 represent the same signature, with the
2893  * same number of arguments and the same types.
2894  * Returns: #TRUE if @sig1 and @sig2 are equal.
2895  */
2896 gboolean
2897 mono_metadata_signature_equal (MonoMethodSignature *sig1, MonoMethodSignature *sig2)
2898 {
2899         int i;
2900
2901         if (sig1->hasthis != sig2->hasthis ||
2902             sig1->param_count != sig2->param_count)
2903                 return FALSE;
2904
2905         /*
2906          * We're just comparing the signatures of two methods here:
2907          *
2908          * If we have two generic methods `void Foo<U> (U u)' and `void Bar<V> (V v)',
2909          * U and V are equal here.
2910          *
2911          * That's what the `signature_only' argument of do_mono_metadata_type_equal() is for.
2912          */
2913
2914         for (i = 0; i < sig1->param_count; i++) { 
2915                 MonoType *p1 = sig1->params[i];
2916                 MonoType *p2 = sig2->params[i];
2917                 
2918                 /* if (p1->attrs != p2->attrs)
2919                         return FALSE;
2920                 */
2921                 if (!do_mono_metadata_type_equal (p1, p2, TRUE))
2922                         return FALSE;
2923         }
2924
2925         if (!do_mono_metadata_type_equal (sig1->ret, sig2->ret, TRUE))
2926                 return FALSE;
2927         return TRUE;
2928 }
2929
2930 guint
2931 mono_signature_hash (MonoMethodSignature *sig)
2932 {
2933         guint i, res = sig->ret->type;
2934
2935         for (i = 0; i < sig->param_count; i++)
2936                 res = (res << 5) - res + sig->params[i]->type;
2937
2938         return res;
2939 }
2940
2941 /*
2942  * mono_metadata_encode_value:
2943  * @value: value to encode
2944  * @buf: buffer where to write the compressed representation
2945  * @endbuf: pointer updated to point at the end of the encoded output
2946  *
2947  * Encodes the value @value in the compressed representation used
2948  * in metadata and stores the result in @buf. @buf needs to be big
2949  * enough to hold the data (4 bytes).
2950  */
2951 void
2952 mono_metadata_encode_value (guint32 value, char *buf, char **endbuf)
2953 {
2954         char *p = buf;
2955         
2956         if (value < 0x80)
2957                 *p++ = value;
2958         else if (value < 0x4000) {
2959                 p [0] = 0x80 | (value >> 8);
2960                 p [1] = value & 0xff;
2961                 p += 2;
2962         } else {
2963                 p [0] = (value >> 24) | 0xc0;
2964                 p [1] = (value >> 16) & 0xff;
2965                 p [2] = (value >> 8) & 0xff;
2966                 p [3] = value & 0xff;
2967                 p += 4;
2968         }
2969         if (endbuf)
2970                 *endbuf = p;
2971 }
2972
2973 /*
2974  * mono_metadata_field_info:
2975  * @meta: the Image the field is defined in
2976  * @index: the index in the field table representing the field
2977  * @offset: a pointer to an integer where to store the offset that 
2978  * may have been specified for the field in a FieldLayout table
2979  * @rva: a pointer to the RVA of the field data in the image that
2980  * may have been defined in a FieldRVA table
2981  * @marshal_spec: a pointer to the marshal spec that may have been 
2982  * defined for the field in a FieldMarshal table.
2983  *
2984  * Gather info for field @index that may have been defined in the FieldLayout, 
2985  * FieldRVA and FieldMarshal tables.
2986  * Either of offset, rva and marshal_spec can be NULL if you're not interested 
2987  * in the data.
2988  */
2989 void
2990 mono_metadata_field_info (MonoImage *meta, guint32 index, guint32 *offset, guint32 *rva, 
2991                           MonoMarshalSpec **marshal_spec)
2992 {
2993         MonoTableInfo *tdef;
2994         locator_t loc;
2995
2996         loc.idx = index + 1;
2997         if (offset) {
2998                 tdef = &meta->tables [MONO_TABLE_FIELDLAYOUT];
2999
3000                 loc.col_idx = MONO_FIELD_LAYOUT_FIELD;
3001                 loc.t = tdef;
3002
3003                 if (tdef->base && bsearch (&loc, tdef->base, tdef->rows, tdef->row_size, table_locator)) {
3004                         *offset = mono_metadata_decode_row_col (tdef, loc.result, MONO_FIELD_LAYOUT_OFFSET);
3005                 } else {
3006                         *offset = (guint32)-1;
3007                 }
3008         }
3009         if (rva) {
3010                 tdef = &meta->tables [MONO_TABLE_FIELDRVA];
3011
3012                 loc.col_idx = MONO_FIELD_RVA_FIELD;
3013                 loc.t = tdef;
3014                 
3015                 if (tdef->base && bsearch (&loc, tdef->base, tdef->rows, tdef->row_size, table_locator)) {
3016                         /*
3017                          * LAMESPEC: There is no signature, no nothing, just the raw data.
3018                          */
3019                         *rva = mono_metadata_decode_row_col (tdef, loc.result, MONO_FIELD_RVA_RVA);
3020                 } else {
3021                         *rva = 0;
3022                 }
3023         }
3024         if (marshal_spec) {
3025                 const char *p;
3026                 
3027                 if ((p = mono_metadata_get_marshal_info (meta, index, TRUE))) {
3028                         *marshal_spec = mono_metadata_parse_marshal_spec (meta, p);
3029                 }
3030         }
3031
3032 }
3033
3034 /*
3035  * mono_metadata_get_constant_index:
3036  * @meta: the Image the field is defined in
3037  * @index: the token that may have a row defined in the constants table
3038  * @hint: possible position for the row
3039  *
3040  * @token must be a FieldDef, ParamDef or PropertyDef token.
3041  *
3042  * Returns: the index into the Constants table or 0 if not found.
3043  */
3044 guint32
3045 mono_metadata_get_constant_index (MonoImage *meta, guint32 token, guint32 hint)
3046 {
3047         MonoTableInfo *tdef;
3048         locator_t loc;
3049         guint32 index = mono_metadata_token_index (token);
3050
3051         tdef = &meta->tables [MONO_TABLE_CONSTANT];
3052         index <<= MONO_HASCONSTANT_BITS;
3053         switch (mono_metadata_token_table (token)) {
3054         case MONO_TABLE_FIELD:
3055                 index |= MONO_HASCONSTANT_FIEDDEF;
3056                 break;
3057         case MONO_TABLE_PARAM:
3058                 index |= MONO_HASCONSTANT_PARAM;
3059                 break;
3060         case MONO_TABLE_PROPERTY:
3061                 index |= MONO_HASCONSTANT_PROPERTY;
3062                 break;
3063         default:
3064                 g_warning ("Not a valid token for the constant table: 0x%08x", token);
3065                 return 0;
3066         }
3067         loc.idx = index;
3068         loc.col_idx = MONO_CONSTANT_PARENT;
3069         loc.t = tdef;
3070
3071         if ((hint > 0) && (hint < tdef->rows) && (mono_metadata_decode_row_col (tdef, hint - 1, MONO_CONSTANT_PARENT) == index))
3072                 return hint;
3073
3074         if (tdef->base && bsearch (&loc, tdef->base, tdef->rows, tdef->row_size, table_locator)) {
3075                 return loc.result + 1;
3076         }
3077         return 0;
3078 }
3079
3080 /*
3081  * mono_metadata_events_from_typedef:
3082  * @meta: metadata context
3083  * @index: 0-based index (in the TypeDef table) describing a type
3084  *
3085  * Returns: the 0-based index in the Event table for the events in the
3086  * type. The last event that belongs to the type (plus 1) is stored
3087  * in the @end_idx pointer.
3088  */
3089 guint32
3090 mono_metadata_events_from_typedef (MonoImage *meta, guint32 index, guint *end_idx)
3091 {
3092         locator_t loc;
3093         guint32 start, end;
3094         MonoTableInfo *tdef  = &meta->tables [MONO_TABLE_EVENTMAP];
3095
3096         *end_idx = 0;
3097         
3098         if (!tdef->base)
3099                 return 0;
3100
3101         loc.t = tdef;
3102         loc.col_idx = MONO_EVENT_MAP_PARENT;
3103         loc.idx = index + 1;
3104
3105         if (!bsearch (&loc, tdef->base, tdef->rows, tdef->row_size, table_locator))
3106                 return 0;
3107         
3108         start = mono_metadata_decode_row_col (tdef, loc.result, MONO_EVENT_MAP_EVENTLIST);
3109         if (loc.result + 1 < tdef->rows) {
3110                 end = mono_metadata_decode_row_col (tdef, loc.result + 1, MONO_EVENT_MAP_EVENTLIST) - 1;
3111         } else {
3112                 end = meta->tables [MONO_TABLE_EVENT].rows;
3113         }
3114
3115         *end_idx = end;
3116         return start - 1;
3117 }
3118
3119 /*
3120  * mono_metadata_methods_from_event:
3121  * @meta: metadata context
3122  * @index: 0-based index (in the Event table) describing a event
3123  *
3124  * Returns: the 0-based index in the MethodDef table for the methods in the
3125  * event. The last method that belongs to the event (plus 1) is stored
3126  * in the @end_idx pointer.
3127  */
3128 guint32
3129 mono_metadata_methods_from_event   (MonoImage *meta, guint32 index, guint *end_idx)
3130 {
3131         locator_t loc;
3132         guint start, end;
3133         guint32 cols [MONO_METHOD_SEMA_SIZE];
3134         MonoTableInfo *msemt = &meta->tables [MONO_TABLE_METHODSEMANTICS];
3135
3136         *end_idx = 0;
3137         if (!msemt->base)
3138                 return 0;
3139
3140         loc.t = msemt;
3141         loc.col_idx = MONO_METHOD_SEMA_ASSOCIATION;
3142         loc.idx = ((index + 1) << MONO_HAS_SEMANTICS_BITS) | MONO_HAS_SEMANTICS_EVENT; /* Method association coded index */
3143
3144         if (!bsearch (&loc, msemt->base, msemt->rows, msemt->row_size, table_locator))
3145                 return 0;
3146
3147         start = loc.result;
3148         /*
3149          * We may end up in the middle of the rows... 
3150          */
3151         while (start > 0) {
3152                 if (loc.idx == mono_metadata_decode_row_col (msemt, start - 1, MONO_METHOD_SEMA_ASSOCIATION))
3153                         start--;
3154                 else
3155                         break;
3156         }
3157         end = start + 1;
3158         while (end < msemt->rows) {
3159                 mono_metadata_decode_row (msemt, end, cols, MONO_METHOD_SEMA_SIZE);
3160                 if (cols [MONO_METHOD_SEMA_ASSOCIATION] != loc.idx)
3161                         break;
3162                 ++end;
3163         }
3164         *end_idx = end;
3165         return start;
3166 }
3167
3168 /*
3169  * mono_metadata_properties_from_typedef:
3170  * @meta: metadata context
3171  * @index: 0-based index (in the TypeDef table) describing a type
3172  *
3173  * Returns: the 0-based index in the Property table for the properties in the
3174  * type. The last property that belongs to the type (plus 1) is stored
3175  * in the @end_idx pointer.
3176  */
3177 guint32
3178 mono_metadata_properties_from_typedef (MonoImage *meta, guint32 index, guint *end_idx)
3179 {
3180         locator_t loc;
3181         guint32 start, end;
3182         MonoTableInfo *tdef  = &meta->tables [MONO_TABLE_PROPERTYMAP];
3183
3184         *end_idx = 0;
3185         
3186         if (!tdef->base)
3187                 return 0;
3188
3189         loc.t = tdef;
3190         loc.col_idx = MONO_PROPERTY_MAP_PARENT;
3191         loc.idx = index + 1;
3192
3193         if (!bsearch (&loc, tdef->base, tdef->rows, tdef->row_size, table_locator))
3194                 return 0;
3195         
3196         start = mono_metadata_decode_row_col (tdef, loc.result, MONO_PROPERTY_MAP_PROPERTY_LIST);
3197         if (loc.result + 1 < tdef->rows) {
3198                 end = mono_metadata_decode_row_col (tdef, loc.result + 1, MONO_PROPERTY_MAP_PROPERTY_LIST) - 1;
3199         } else {
3200                 end = meta->tables [MONO_TABLE_PROPERTY].rows;
3201         }
3202
3203         *end_idx = end;
3204         return start - 1;
3205 }
3206
3207 /*
3208  * mono_metadata_methods_from_property:
3209  * @meta: metadata context
3210  * @index: 0-based index (in the PropertyDef table) describing a property
3211  *
3212  * Returns: the 0-based index in the MethodDef table for the methods in the
3213  * property. The last method that belongs to the property (plus 1) is stored
3214  * in the @end_idx pointer.
3215  */
3216 guint32
3217 mono_metadata_methods_from_property   (MonoImage *meta, guint32 index, guint *end_idx)
3218 {
3219         locator_t loc;
3220         guint start, end;
3221         guint32 cols [MONO_METHOD_SEMA_SIZE];
3222         MonoTableInfo *msemt = &meta->tables [MONO_TABLE_METHODSEMANTICS];
3223
3224         *end_idx = 0;
3225         if (!msemt->base)
3226                 return 0;
3227
3228         loc.t = msemt;
3229         loc.col_idx = MONO_METHOD_SEMA_ASSOCIATION;
3230         loc.idx = ((index + 1) << MONO_HAS_SEMANTICS_BITS) | MONO_HAS_SEMANTICS_PROPERTY; /* Method association coded index */
3231
3232         if (!bsearch (&loc, msemt->base, msemt->rows, msemt->row_size, table_locator))
3233                 return 0;
3234
3235         start = loc.result;
3236         /*
3237          * We may end up in the middle of the rows... 
3238          */
3239         while (start > 0) {
3240                 if (loc.idx == mono_metadata_decode_row_col (msemt, start - 1, MONO_METHOD_SEMA_ASSOCIATION))
3241                         start--;
3242                 else
3243                         break;
3244         }
3245         end = start + 1;
3246         while (end < msemt->rows) {
3247                 mono_metadata_decode_row (msemt, end, cols, MONO_METHOD_SEMA_SIZE);
3248                 if (cols [MONO_METHOD_SEMA_ASSOCIATION] != loc.idx)
3249                         break;
3250                 ++end;
3251         }
3252         *end_idx = end;
3253         return start;
3254 }
3255
3256 guint32
3257 mono_metadata_implmap_from_method (MonoImage *meta, guint32 method_idx)
3258 {
3259         locator_t loc;
3260         MonoTableInfo *tdef  = &meta->tables [MONO_TABLE_IMPLMAP];
3261
3262         if (!tdef->base)
3263                 return 0;
3264
3265         loc.t = tdef;
3266         loc.col_idx = MONO_IMPLMAP_MEMBER;
3267         loc.idx = ((method_idx + 1) << MONO_MEMBERFORWD_BITS) | MONO_MEMBERFORWD_METHODDEF;
3268
3269         if (!bsearch (&loc, tdef->base, tdef->rows, tdef->row_size, table_locator))
3270                 return 0;
3271
3272         return loc.result + 1;
3273 }
3274
3275 /**
3276  * @image: context where the image is created
3277  * @type_spec:  typespec token
3278  *
3279  * Creates a MonoType representing the TypeSpec indexed by the @type_spec
3280  * token.
3281  */
3282 MonoType *
3283 mono_type_create_from_typespec_full (MonoImage *image, MonoGenericContainer *generic_container, guint32 type_spec)
3284 {
3285         guint32 idx = mono_metadata_token_index (type_spec);
3286         MonoTableInfo *t;
3287         guint32 cols [MONO_TYPESPEC_SIZE];       
3288         const char *ptr;
3289         guint32 len;
3290         MonoType *type;
3291
3292         mono_loader_lock ();
3293
3294         if ((type = g_hash_table_lookup (image->typespec_cache, GUINT_TO_POINTER (type_spec)))) {
3295                 mono_loader_unlock ();
3296                 return type;
3297         }
3298
3299         t = &image->tables [MONO_TABLE_TYPESPEC];
3300         
3301         mono_metadata_decode_row (t, idx-1, cols, MONO_TYPESPEC_SIZE);
3302         ptr = mono_metadata_blob_heap (image, cols [MONO_TYPESPEC_SIGNATURE]);
3303         len = mono_metadata_decode_value (ptr, &ptr);
3304
3305         type = g_new0 (MonoType, 1);
3306
3307         g_hash_table_insert (image->typespec_cache, GUINT_TO_POINTER (type_spec), type);
3308
3309         if (*ptr == MONO_TYPE_BYREF) {
3310                 type->byref = 1; 
3311                 ptr++;
3312         }
3313
3314         do_mono_metadata_parse_type (type, image, generic_container, ptr, &ptr);
3315
3316         mono_loader_unlock ();
3317
3318         return type;
3319 }
3320
3321 MonoType *
3322 mono_type_create_from_typespec (MonoImage *image, guint32 type_spec)
3323 {
3324         return mono_type_create_from_typespec_full (image, NULL, type_spec);
3325 }
3326
3327 MonoMarshalSpec *
3328 mono_metadata_parse_marshal_spec (MonoImage *image, const char *ptr)
3329 {
3330         MonoMarshalSpec *res;
3331         int len;
3332         const char *start = ptr;
3333
3334         /* fixme: this is incomplete, but I cant find more infos in the specs */
3335
3336         res = g_new0 (MonoMarshalSpec, 1);
3337         
3338         len = mono_metadata_decode_value (ptr, &ptr);
3339         res->native = *ptr++;
3340
3341         if (res->native == MONO_NATIVE_LPARRAY) {
3342                 if (ptr - start <= len)
3343                         res->data.array_data.elem_type = *ptr++;
3344                 if (ptr - start <= len)
3345                         res->data.array_data.param_num = mono_metadata_decode_value (ptr, &ptr);
3346                 if (ptr - start <= len)
3347                         res->data.array_data.num_elem = mono_metadata_decode_value (ptr, &ptr);
3348         } 
3349
3350         if (res->native == MONO_NATIVE_BYVALTSTR) {
3351                 if (ptr - start <= len)
3352                         res->data.array_data.num_elem = mono_metadata_decode_value (ptr, &ptr);
3353         }
3354
3355         if (res->native == MONO_NATIVE_BYVALARRAY) {
3356                 if (ptr - start <= len)
3357                         res->data.array_data.num_elem = mono_metadata_decode_value (ptr, &ptr);
3358         }
3359         
3360         if (res->native == MONO_NATIVE_CUSTOM) {
3361                 /* skip unused type guid */
3362                 len = mono_metadata_decode_value (ptr, &ptr);
3363                 ptr += len;
3364                 /* skip unused native type name */
3365                 len = mono_metadata_decode_value (ptr, &ptr);
3366                 ptr += len;
3367                 /* read custom marshaler type name */
3368                 len = mono_metadata_decode_value (ptr, &ptr);
3369                 res->data.custom_data.custom_name = g_strndup (ptr, len);               
3370                 ptr += len;
3371                 /* read cookie string */
3372                 len = mono_metadata_decode_value (ptr, &ptr);
3373                 res->data.custom_data.cookie = g_strndup (ptr, len);
3374         }
3375
3376         return res;
3377 }
3378
3379 void 
3380 mono_metadata_free_marshal_spec (MonoMarshalSpec *spec)
3381 {
3382         if (spec->native == MONO_NATIVE_CUSTOM) {
3383                 g_free (spec->data.custom_data.custom_name);
3384                 g_free (spec->data.custom_data.cookie);
3385         }
3386         g_free (spec);
3387 }
3388         
3389 guint32
3390 mono_type_to_unmanaged (MonoType *type, MonoMarshalSpec *mspec, gboolean as_field,
3391                         gboolean unicode, MonoMarshalConv *conv) 
3392 {
3393         MonoMarshalConv dummy_conv;
3394         int t = type->type;
3395
3396         if (!conv)
3397                 conv = &dummy_conv;
3398
3399         *conv = MONO_MARSHAL_CONV_NONE;
3400
3401         if (type->byref)
3402                 return MONO_NATIVE_UINT;
3403
3404 handle_enum:
3405         switch (t) {
3406         case MONO_TYPE_BOOLEAN: 
3407                 if (mspec) {
3408                         switch (mspec->native) {
3409                         case MONO_NATIVE_VARIANTBOOL:
3410                                 *conv = MONO_MARSHAL_CONV_BOOL_VARIANTBOOL;
3411                                 return MONO_NATIVE_VARIANTBOOL;
3412                         case MONO_NATIVE_BOOLEAN:
3413                                 *conv = MONO_MARSHAL_CONV_BOOL_I4;
3414                                 return MONO_NATIVE_BOOLEAN;
3415                         case MONO_NATIVE_I1:
3416                         case MONO_NATIVE_U1:
3417                                 return mspec->native;
3418                         default:
3419                                 g_error ("cant marshal bool to native type %02x", mspec->native);
3420                         }
3421                 }
3422                 *conv = MONO_MARSHAL_CONV_BOOL_I4;
3423                 return MONO_NATIVE_BOOLEAN;
3424         case MONO_TYPE_CHAR: return MONO_NATIVE_U2;
3425         case MONO_TYPE_I1: return MONO_NATIVE_I1;
3426         case MONO_TYPE_U1: return MONO_NATIVE_U1;
3427         case MONO_TYPE_I2: return MONO_NATIVE_I2;
3428         case MONO_TYPE_U2: return MONO_NATIVE_U2;
3429         case MONO_TYPE_I4: return MONO_NATIVE_I4;
3430         case MONO_TYPE_U4: return MONO_NATIVE_U4;
3431         case MONO_TYPE_I8: return MONO_NATIVE_I8;
3432         case MONO_TYPE_U8: return MONO_NATIVE_U8;
3433         case MONO_TYPE_R4: return MONO_NATIVE_R4;
3434         case MONO_TYPE_R8: return MONO_NATIVE_R8;
3435         case MONO_TYPE_STRING:
3436                 if (mspec) {
3437                         switch (mspec->native) {
3438                         case MONO_NATIVE_BSTR:
3439                                 *conv = MONO_MARSHAL_CONV_STR_BSTR;
3440                                 return MONO_NATIVE_BSTR;
3441                         case MONO_NATIVE_LPSTR:
3442                                 *conv = MONO_MARSHAL_CONV_STR_LPSTR;
3443                                 return MONO_NATIVE_LPSTR;
3444                         case MONO_NATIVE_LPWSTR:
3445                                 *conv = MONO_MARSHAL_CONV_STR_LPWSTR;
3446                                 return MONO_NATIVE_LPWSTR;
3447                         case MONO_NATIVE_LPTSTR:
3448                                 *conv = MONO_MARSHAL_CONV_STR_LPTSTR;
3449                                 return MONO_NATIVE_LPTSTR;
3450                         case MONO_NATIVE_ANSIBSTR:
3451                                 *conv = MONO_MARSHAL_CONV_STR_ANSIBSTR;
3452                                 return MONO_NATIVE_ANSIBSTR;
3453                         case MONO_NATIVE_TBSTR:
3454                                 *conv = MONO_MARSHAL_CONV_STR_TBSTR;
3455                                 return MONO_NATIVE_TBSTR;
3456                         case MONO_NATIVE_BYVALTSTR:
3457                                 if (unicode)
3458                                         *conv = MONO_MARSHAL_CONV_STR_BYVALWSTR;
3459                                 else
3460                                         *conv = MONO_MARSHAL_CONV_STR_BYVALSTR;
3461                                 return MONO_NATIVE_BYVALTSTR;
3462                         default:
3463                                 g_error ("cant marshal string to native type %02x", mspec->native);
3464                         }
3465                 }       
3466                 *conv = MONO_MARSHAL_CONV_STR_LPTSTR;
3467                 return MONO_NATIVE_LPTSTR; 
3468         case MONO_TYPE_PTR: return MONO_NATIVE_UINT;
3469         case MONO_TYPE_VALUETYPE: /*FIXME*/
3470                 if (type->data.klass->enumtype) {
3471                         t = type->data.klass->enum_basetype->type;
3472                         goto handle_enum;
3473                 }
3474                 return MONO_NATIVE_STRUCT;
3475         case MONO_TYPE_SZARRAY: 
3476         case MONO_TYPE_ARRAY: 
3477                 if (mspec) {
3478                         switch (mspec->native) {
3479                         case MONO_NATIVE_BYVALARRAY:
3480                                 *conv = MONO_MARSHAL_CONV_ARRAY_BYVALARRAY;
3481                                 return MONO_NATIVE_BYVALARRAY;
3482                         case MONO_NATIVE_SAFEARRAY:
3483                                 *conv = MONO_MARSHAL_CONV_ARRAY_SAVEARRAY;
3484                                 return MONO_NATIVE_SAFEARRAY;
3485                         case MONO_NATIVE_LPARRAY:                               
3486                                 *conv = MONO_MARSHAL_CONV_ARRAY_LPARRAY;
3487                                 return MONO_NATIVE_LPARRAY;
3488                         default:
3489                                 g_error ("cant marshal array as native type %02x", mspec->native);
3490                         }
3491                 }       
3492
3493                 *conv = MONO_MARSHAL_CONV_ARRAY_LPARRAY;
3494                 return MONO_NATIVE_LPARRAY;
3495         case MONO_TYPE_I: return MONO_NATIVE_INT;
3496         case MONO_TYPE_U: return MONO_NATIVE_UINT;
3497         case MONO_TYPE_CLASS: 
3498         case MONO_TYPE_OBJECT: {
3499                 /* FIXME : we need to handle ArrayList and StringBuilder here, probably */
3500                 if (mspec) {
3501                         switch (mspec->native) {
3502                         case MONO_NATIVE_STRUCT:
3503                                 return MONO_NATIVE_STRUCT;
3504                         case MONO_NATIVE_INTERFACE:
3505                                 *conv = MONO_MARSHAL_CONV_OBJECT_INTERFACE;
3506                                 return MONO_NATIVE_INTERFACE;
3507                         case MONO_NATIVE_IDISPATCH:
3508                                 *conv = MONO_MARSHAL_CONV_OBJECT_IDISPATCH;
3509                                 return MONO_NATIVE_IDISPATCH;
3510                         case MONO_NATIVE_IUNKNOWN:
3511                                 *conv = MONO_MARSHAL_CONV_OBJECT_IUNKNOWN;
3512                                 return MONO_NATIVE_IUNKNOWN;
3513                         case MONO_NATIVE_FUNC:
3514                                 if (t == MONO_TYPE_CLASS && (type->data.klass == mono_defaults.multicastdelegate_class ||
3515                                                                                          type->data.klass == mono_defaults.delegate_class || 
3516                                                                                          type->data.klass->parent == mono_defaults.multicastdelegate_class)) {
3517                                         *conv = MONO_MARSHAL_CONV_DEL_FTN;
3518                                         return MONO_NATIVE_FUNC;
3519                                 }
3520                                 else
3521                                         /* Fall through */
3522                                         ;
3523                         default:
3524                                 g_error ("cant marshal object as native type %02x", mspec->native);
3525                         }
3526                 }
3527                 if (t == MONO_TYPE_CLASS && (type->data.klass == mono_defaults.multicastdelegate_class ||
3528                                              type->data.klass == mono_defaults.delegate_class || 
3529                                              type->data.klass->parent == mono_defaults.multicastdelegate_class)) {
3530                         *conv = MONO_MARSHAL_CONV_DEL_FTN;
3531                         return MONO_NATIVE_FUNC;
3532                 }
3533                 *conv = MONO_MARSHAL_CONV_OBJECT_STRUCT;
3534                 return MONO_NATIVE_STRUCT;
3535         }
3536         case MONO_TYPE_FNPTR: return MONO_NATIVE_FUNC;
3537         case MONO_TYPE_TYPEDBYREF:
3538         default:
3539                 g_error ("type 0x%02x not handled in marshal", t);
3540         }
3541         return MONO_NATIVE_MAX;
3542 }
3543
3544 const char*
3545 mono_metadata_get_marshal_info (MonoImage *meta, guint32 idx, gboolean is_field)
3546 {
3547         locator_t loc;
3548         MonoTableInfo *tdef  = &meta->tables [MONO_TABLE_FIELDMARSHAL];
3549
3550         if (!tdef->base)
3551                 return NULL;
3552
3553         loc.t = tdef;
3554         loc.col_idx = MONO_FIELD_MARSHAL_PARENT;
3555         loc.idx = ((idx + 1) << MONO_HAS_FIELD_MARSHAL_BITS) | (is_field? MONO_HAS_FIELD_MARSHAL_FIELDSREF: MONO_HAS_FIELD_MARSHAL_PARAMDEF);
3556
3557         if (!bsearch (&loc, tdef->base, tdef->rows, tdef->row_size, table_locator))
3558                 return NULL;
3559
3560         return mono_metadata_blob_heap (meta, mono_metadata_decode_row_col (tdef, loc.result, MONO_FIELD_MARSHAL_NATIVE_TYPE));
3561 }
3562
3563 static MonoMethod*
3564 method_from_method_def_or_ref (MonoImage *m, guint32 tok)
3565 {
3566         guint32 idx = tok >> MONO_METHODDEFORREF_BITS;
3567         switch (tok & MONO_METHODDEFORREF_MASK) {
3568         case MONO_METHODDEFORREF_METHODDEF:
3569                 return mono_get_method (m, MONO_TOKEN_METHOD_DEF | idx, NULL);
3570         case MONO_METHODDEFORREF_METHODREF:
3571                 return mono_get_method (m, MONO_TOKEN_MEMBER_REF | idx, NULL);
3572         }
3573         g_assert_not_reached ();
3574         return NULL;
3575 }
3576
3577 MonoMethod**
3578 mono_class_get_overrides (MonoImage *image, guint32 type_token, gint32 *num_overrides)
3579 {
3580         locator_t loc;
3581         MonoTableInfo *tdef  = &image->tables [MONO_TABLE_METHODIMPL];
3582         guint32 start, end;
3583         gint32 i, num;
3584         guint32 cols [MONO_METHODIMPL_SIZE];
3585         MonoMethod **result;
3586
3587         if (num_overrides)
3588                 *num_overrides = 0;
3589
3590         if (!tdef->base)
3591                 return NULL;
3592
3593         loc.t = tdef;
3594         loc.col_idx = MONO_METHODIMPL_CLASS;
3595         loc.idx = mono_metadata_token_index (type_token);
3596
3597         if (!bsearch (&loc, tdef->base, tdef->rows, tdef->row_size, table_locator))
3598                 return NULL;
3599
3600         start = loc.result;
3601         end = start + 1;
3602         /*
3603          * We may end up in the middle of the rows... 
3604          */
3605         while (start > 0) {
3606                 if (loc.idx == mono_metadata_decode_row_col (tdef, start - 1, MONO_METHODIMPL_CLASS))
3607                         start--;
3608                 else
3609                         break;
3610         }
3611         while (end < tdef->rows) {
3612                 if (loc.idx == mono_metadata_decode_row_col (tdef, end, MONO_METHODIMPL_CLASS))
3613                         end++;
3614                 else
3615                         break;
3616         }
3617         num = end - start;
3618         result = g_new (MonoMethod*, num * 2);
3619         for (i = 0; i < num; ++i) {
3620                 mono_metadata_decode_row (tdef, start + i, cols, MONO_METHODIMPL_SIZE);
3621                 result [i * 2] = method_from_method_def_or_ref (image, cols [MONO_METHODIMPL_DECLARATION]);
3622                 result [i * 2 + 1] = method_from_method_def_or_ref (image, cols [MONO_METHODIMPL_BODY]);
3623         }
3624
3625         if (num_overrides)
3626                 *num_overrides = num;
3627         return result;
3628 }
3629
3630 /**
3631  * mono_guid_to_string:
3632  *
3633  * Converts a 16 byte Microsoft GUID to the standard string representation.
3634  */
3635 char *
3636 mono_guid_to_string (const guint8 *guid)
3637 {
3638         return g_strdup_printf ("%02X%02X%02X%02X-%02X%02X-%02X%02X-%02X%02X-%02X%02X%02X%02X%02X%02X", 
3639                                 guid[3], guid[2], guid[1], guid[0],
3640                                 guid[5], guid[4],
3641                                 guid[7], guid[6],
3642                                 guid[8], guid[9],
3643                                 guid[10], guid[11], guid[12], guid[13], guid[14], guid[15]);
3644 }
3645
3646 static MonoClass**
3647 get_constraints (MonoImage *image, int owner, MonoGenericContext *context)
3648 {
3649         MonoTableInfo *tdef  = &image->tables [MONO_TABLE_GENERICPARAMCONSTRAINT];
3650         guint32 cols [MONO_GENPARCONSTRAINT_SIZE];
3651         guint32 i, token, found;
3652         MonoClass *klass, **res;
3653         GList *cons = NULL, *tmp;
3654         
3655
3656         found = 0;
3657         for (i = 0; i < tdef->rows; ++i) {
3658                 mono_metadata_decode_row (tdef, i, cols, MONO_GENPARCONSTRAINT_SIZE);
3659                 if (cols [MONO_GENPARCONSTRAINT_GENERICPAR] == owner) {
3660                         token = mono_metadata_token_from_dor (cols [MONO_GENPARCONSTRAINT_CONSTRAINT]);
3661                         klass = mono_class_get_full (image, token, context);
3662                         cons = g_list_append (cons, klass);
3663                         ++found;
3664                 } else {
3665                         /* contiguous list finished */
3666                         if (found)
3667                                 break;
3668                 }
3669         }
3670         if (!found)
3671                 return NULL;
3672         res = g_new0 (MonoClass*, found + 1);
3673         for (i = 0, tmp = cons; i < found; ++i, tmp = tmp->next) {
3674                 res [i] = tmp->data;
3675         }
3676         g_list_free (cons);
3677         return res;
3678 }
3679
3680 MonoGenericContainer *
3681 mono_metadata_load_generic_params (MonoImage *image, guint32 token)
3682 {
3683         MonoTableInfo *tdef  = &image->tables [MONO_TABLE_GENERICPARAM];
3684         guint32 cols [MONO_GENERICPARAM_SIZE];
3685         guint32 i, owner = 0, last_num, n;
3686         MonoGenericContainer *container;
3687         MonoGenericParam *params;
3688
3689         if (mono_metadata_token_table (token) == MONO_TABLE_TYPEDEF)
3690                 owner = MONO_TYPEORMETHOD_TYPE;
3691         else if (mono_metadata_token_table (token) == MONO_TABLE_METHOD)
3692                 owner = MONO_TYPEORMETHOD_METHOD;
3693         else {
3694                 g_error ("wrong token %x to load_generics_params", token);
3695                 return NULL;
3696         }
3697         owner |= mono_metadata_token_index (token) << MONO_TYPEORMETHOD_BITS;
3698         if (!tdef->base)
3699                 return NULL;
3700
3701         for (i = 0; i < tdef->rows; ++i) {
3702                 mono_metadata_decode_row (tdef, i, cols, MONO_GENERICPARAM_SIZE);
3703                 if (cols [MONO_GENERICPARAM_OWNER] == owner)
3704                         break;
3705         }
3706         last_num = 0;
3707         if (i >= tdef->rows)
3708                 return NULL;
3709         params = NULL;
3710         n = 0;
3711         container = g_new0 (MonoGenericContainer, 1);
3712         do {
3713                 n++;
3714                 params = g_realloc (params, sizeof (MonoGenericParam) * n);
3715                 params [n - 1].owner = container;
3716                 params [n - 1].pklass = NULL;
3717                 params [n - 1].method = NULL;
3718                 params [n - 1].flags = cols [MONO_GENERICPARAM_FLAGS];
3719                 params [n - 1].num = cols [MONO_GENERICPARAM_NUMBER];
3720                 params [n - 1].name = mono_metadata_string_heap (image, cols [MONO_GENERICPARAM_NAME]);
3721                 if (++i >= tdef->rows)
3722                         break;
3723                 mono_metadata_decode_row (tdef, i, cols, MONO_GENERICPARAM_SIZE);
3724         } while (cols [MONO_GENERICPARAM_OWNER] == owner);
3725
3726         container->type_argc = n;
3727         container->type_params = params;
3728
3729         container->context = g_new0 (MonoGenericContext, 1);
3730         container->context->container = container;
3731
3732         for (i = 0; i < n; i++)
3733                 params [i].constraints = get_constraints (image, i + 1, container->context);
3734
3735         return container;
3736 }
3737
3738 gboolean
3739 mono_type_is_byref (MonoType *type)
3740 {
3741         return type->byref;
3742 }
3743
3744 int
3745 mono_type_get_type (MonoType *type)
3746 {
3747         return type->type;
3748 }
3749
3750 /* For MONO_TYPE_FNPTR */
3751 MonoMethodSignature*
3752 mono_type_get_signature (MonoType *type)
3753 {
3754         return type->data.method;
3755 }
3756
3757 /* For MONO_TYPE_CLASS, VALUETYPE */
3758 MonoClass*
3759 mono_type_get_class (MonoType *type)
3760 {
3761         return type->data.klass;
3762 }
3763
3764 /* For MONO_TYPE_ARRAY */
3765 MonoArrayType*
3766 mono_type_get_array_type (MonoType *type)
3767 {
3768         return type->data.array;
3769 }
3770
3771 MonoClass*
3772 mono_type_get_modifiers (MonoType *type, gboolean *is_required, gpointer *iter)
3773 {
3774         /* FIXME: implement */
3775         return NULL;
3776 }
3777
3778 MonoType*
3779 mono_signature_get_return_type (MonoMethodSignature *sig)
3780 {
3781         return sig->ret;
3782 }
3783
3784 MonoType*
3785 mono_signature_get_params (MonoMethodSignature *sig, gpointer *iter)
3786 {
3787         MonoType** type;
3788         if (!iter)
3789                 return NULL;
3790         if (!*iter) {
3791                 /* start from the first */
3792                 if (sig->param_count) {
3793                         *iter = &sig->params [0];
3794                         return sig->params [0];
3795                 } else {
3796                         /* no method */
3797                         return NULL;
3798                 }
3799         }
3800         type = *iter;
3801         type++;
3802         if (type < &sig->params [sig->param_count]) {
3803                 *iter = type;
3804                 return *type;
3805         }
3806         return NULL;
3807 }
3808
3809 guint32
3810 mono_signature_get_param_count (MonoMethodSignature *sig)
3811 {
3812         return sig->param_count;
3813 }
3814
3815 guint32
3816 mono_signature_get_call_conv (MonoMethodSignature *sig)
3817 {
3818         return sig->call_convention;
3819 }
3820
3821 int
3822 mono_signature_vararg_start (MonoMethodSignature *sig)
3823 {
3824         return sig->sentinelpos;
3825 }
3826
3827 gboolean
3828 mono_signature_is_instance (MonoMethodSignature *sig)
3829 {
3830         return sig->hasthis;
3831 }
3832
3833 gboolean
3834 mono_signature_explicit_this (MonoMethodSignature *sig)
3835 {
3836         return sig->explicit_this;
3837 }
3838