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