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