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