c5c4723acab4564f6d54df97376cf99ed5a6cffa
[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 gboolean do_mono_metadata_parse_type (MonoType *type, MonoImage *m, MonoGenericContainer *container,
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  * mono_metadata_decode_value:
1005  * @ptr: pointer to decode from
1006  * @rptr: the new position of the pointer
1007  *
1008  * This routine decompresses 32-bit values as specified in the "Blob and
1009  * Signature" section (22.2)
1010  *
1011  * Returns: the decoded value
1012  */
1013 guint32
1014 mono_metadata_decode_value (const char *_ptr, const char **rptr)
1015 {
1016         const unsigned char *ptr = (const unsigned char *) _ptr;
1017         unsigned char b = *ptr;
1018         guint32 len;
1019         
1020         if ((b & 0x80) == 0){
1021                 len = b;
1022                 ++ptr;
1023         } else if ((b & 0x40) == 0){
1024                 len = ((b & 0x3f) << 8 | ptr [1]);
1025                 ptr += 2;
1026         } else {
1027                 len = ((b & 0x1f) << 24) |
1028                         (ptr [1] << 16) |
1029                         (ptr [2] << 8) |
1030                         ptr [3];
1031                 ptr += 4;
1032         }
1033         if (rptr)
1034                 *rptr = ptr;
1035         
1036         return len;
1037 }
1038
1039 /**
1040  * mono_metadata_decode_signed_value:
1041  * @ptr: pointer to decode from
1042  * @rptr: the new position of the pointer
1043  *
1044  * This routine decompresses 32-bit signed values
1045  * (not specified in the spec)
1046  *
1047  * Returns: the decoded value
1048  */
1049 gint32
1050 mono_metadata_decode_signed_value (const char *ptr, const char **rptr)
1051 {
1052         guint32 uval = mono_metadata_decode_value (ptr, rptr);
1053         gint32 ival = uval >> 1;
1054         if (!(uval & 1))
1055                 return ival;
1056         /* ival is a truncated 2's complement negative number.  */
1057         if (ival < 0x40)
1058                 /* 6 bits = 7 bits for compressed representation (top bit is '0') - 1 sign bit */
1059                 return ival - 0x40;
1060         if (ival < 0x2000)
1061                 /* 13 bits = 14 bits for compressed representation (top bits are '10') - 1 sign bit */
1062                 return ival - 0x2000;
1063         if (ival < 0x10000000)
1064                 /* 28 bits = 29 bits for compressed representation (top bits are '110') - 1 sign bit */
1065                 return ival - 0x10000000;
1066         g_assert (ival < 0x20000000);
1067         g_warning ("compressed signed value appears to use 29 bits for compressed representation: %x (raw: %8x)", ival, uval);
1068         return ival - 0x20000000;
1069 }
1070
1071 /*
1072  * mono_metadata_parse_typedef_or_ref:
1073  * @m: a metadata context.
1074  * @ptr: a pointer to an encoded TypedefOrRef in @m
1075  * @rptr: pointer updated to match the end of the decoded stream
1076  *
1077  * Returns: a token valid in the @m metadata decoded from
1078  * the compressed representation.
1079  */
1080 guint32
1081 mono_metadata_parse_typedef_or_ref (MonoImage *m, const char *ptr, const char **rptr)
1082 {
1083         guint32 token;
1084         token = mono_metadata_decode_value (ptr, &ptr);
1085         if (rptr)
1086                 *rptr = ptr;
1087         return mono_metadata_token_from_dor (token);
1088 }
1089
1090 /*
1091  * mono_metadata_parse_custom_mod:
1092  * @m: a metadata context.
1093  * @dest: storage where the info about the custom modifier is stored (may be NULL)
1094  * @ptr: a pointer to (possibly) the start of a custom modifier list
1095  * @rptr: pointer updated to match the end of the decoded stream
1096  *
1097  * Checks if @ptr points to a type custom modifier compressed representation.
1098  *
1099  * Returns: #TRUE if a custom modifier was found, #FALSE if not.
1100  */
1101 int
1102 mono_metadata_parse_custom_mod (MonoImage *m, MonoCustomMod *dest, const char *ptr, const char **rptr)
1103 {
1104         MonoCustomMod local;
1105         if ((*ptr == MONO_TYPE_CMOD_OPT) || (*ptr == MONO_TYPE_CMOD_REQD)) {
1106                 if (!dest)
1107                         dest = &local;
1108                 dest->required = *ptr == MONO_TYPE_CMOD_REQD ? 1 : 0;
1109                 dest->token = mono_metadata_parse_typedef_or_ref (m, ptr + 1, rptr);
1110                 return TRUE;
1111         }
1112         return FALSE;
1113 }
1114
1115 /*
1116  * mono_metadata_parse_array:
1117  * @m: a metadata context.
1118  * @ptr: a pointer to an encoded array description.
1119  * @rptr: pointer updated to match the end of the decoded stream
1120  *
1121  * Decodes the compressed array description found in the metadata @m at @ptr.
1122  *
1123  * Returns: a #MonoArrayType structure describing the array type
1124  * and dimensions.
1125  */
1126 MonoArrayType *
1127 mono_metadata_parse_array_full (MonoImage *m, MonoGenericContainer *container,
1128                                 const char *ptr, const char **rptr)
1129 {
1130         int i;
1131         MonoArrayType *array = g_new0 (MonoArrayType, 1);
1132         MonoType *etype;
1133         
1134         etype = mono_metadata_parse_type_full (m, container, MONO_PARSE_TYPE, 0, ptr, &ptr);
1135         if (!etype)
1136                 return NULL;
1137         array->eklass = mono_class_from_mono_type (etype);
1138         array->rank = mono_metadata_decode_value (ptr, &ptr);
1139
1140         array->numsizes = mono_metadata_decode_value (ptr, &ptr);
1141         if (array->numsizes)
1142                 array->sizes = g_new0 (int, array->numsizes);
1143         for (i = 0; i < array->numsizes; ++i)
1144                 array->sizes [i] = mono_metadata_decode_value (ptr, &ptr);
1145
1146         array->numlobounds = mono_metadata_decode_value (ptr, &ptr);
1147         if (array->numlobounds)
1148                 array->lobounds = g_new0 (int, array->numlobounds);
1149         for (i = 0; i < array->numlobounds; ++i)
1150                 array->lobounds [i] = mono_metadata_decode_signed_value (ptr, &ptr);
1151
1152         if (rptr)
1153                 *rptr = ptr;
1154         return array;
1155 }
1156
1157 MonoArrayType *
1158 mono_metadata_parse_array (MonoImage *m, const char *ptr, const char **rptr)
1159 {
1160         return mono_metadata_parse_array_full (m, NULL, ptr, rptr);
1161 }
1162
1163 /*
1164  * mono_metadata_free_array:
1165  * @array: array description
1166  *
1167  * Frees the array description returned from mono_metadata_parse_array().
1168  */
1169 void
1170 mono_metadata_free_array (MonoArrayType *array)
1171 {
1172         g_free (array->sizes);
1173         g_free (array->lobounds);
1174         g_free (array);
1175 }
1176
1177 /*
1178  * need to add common field and param attributes combinations:
1179  * [out] param
1180  * public static
1181  * public static literal
1182  * private
1183  * private static
1184  * private static literal
1185  */
1186 static const MonoType
1187 builtin_types[] = {
1188         /* data, attrs, type,              nmods, byref, pinned */
1189         {{NULL}, 0,     MONO_TYPE_VOID,    0,     0,     0},
1190         {{NULL}, 0,     MONO_TYPE_BOOLEAN, 0,     0,     0},
1191         {{NULL}, 0,     MONO_TYPE_BOOLEAN, 0,     1,     0},
1192         {{NULL}, 0,     MONO_TYPE_CHAR,    0,     0,     0},
1193         {{NULL}, 0,     MONO_TYPE_CHAR,    0,     1,     0},
1194         {{NULL}, 0,     MONO_TYPE_I1,      0,     0,     0},
1195         {{NULL}, 0,     MONO_TYPE_I1,      0,     1,     0},
1196         {{NULL}, 0,     MONO_TYPE_U1,      0,     0,     0},
1197         {{NULL}, 0,     MONO_TYPE_U1,      0,     1,     0},
1198         {{NULL}, 0,     MONO_TYPE_I2,      0,     0,     0},
1199         {{NULL}, 0,     MONO_TYPE_I2,      0,     1,     0},
1200         {{NULL}, 0,     MONO_TYPE_U2,      0,     0,     0},
1201         {{NULL}, 0,     MONO_TYPE_U2,      0,     1,     0},
1202         {{NULL}, 0,     MONO_TYPE_I4,      0,     0,     0},
1203         {{NULL}, 0,     MONO_TYPE_I4,      0,     1,     0},
1204         {{NULL}, 0,     MONO_TYPE_U4,      0,     0,     0},
1205         {{NULL}, 0,     MONO_TYPE_U4,      0,     1,     0},
1206         {{NULL}, 0,     MONO_TYPE_I8,      0,     0,     0},
1207         {{NULL}, 0,     MONO_TYPE_I8,      0,     1,     0},
1208         {{NULL}, 0,     MONO_TYPE_U8,      0,     0,     0},
1209         {{NULL}, 0,     MONO_TYPE_U8,      0,     1,     0},
1210         {{NULL}, 0,     MONO_TYPE_R4,      0,     0,     0},
1211         {{NULL}, 0,     MONO_TYPE_R4,      0,     1,     0},
1212         {{NULL}, 0,     MONO_TYPE_R8,      0,     0,     0},
1213         {{NULL}, 0,     MONO_TYPE_R8,      0,     1,     0},
1214         {{NULL}, 0,     MONO_TYPE_STRING,  0,     0,     0},
1215         {{NULL}, 0,     MONO_TYPE_STRING,  0,     1,     0},
1216         {{NULL}, 0,     MONO_TYPE_OBJECT,  0,     0,     0},
1217         {{NULL}, 0,     MONO_TYPE_OBJECT,  0,     1,     0},
1218         {{NULL}, 0,     MONO_TYPE_TYPEDBYREF,  0,     0,     0},
1219         {{NULL}, 0,     MONO_TYPE_I,       0,     0,     0},
1220         {{NULL}, 0,     MONO_TYPE_I,       0,     1,     0},
1221         {{NULL}, 0,     MONO_TYPE_U,       0,     0,     0},
1222         {{NULL}, 0,     MONO_TYPE_U,       0,     1,     0},
1223 };
1224
1225 #define NBUILTIN_TYPES() (sizeof (builtin_types) / sizeof (builtin_types [0]))
1226
1227 static GHashTable *type_cache = NULL;
1228 static GHashTable *generic_inst_cache = NULL;
1229 static GHashTable *generic_class_cache = NULL;
1230 static int next_generic_inst_id = 0;
1231
1232 static guint mono_generic_class_hash (gconstpointer data);
1233
1234 /*
1235  * MonoTypes with modifies are never cached, so we never check or use that field.
1236  */
1237 static guint
1238 mono_type_hash (gconstpointer data)
1239 {
1240         const MonoType *type = (const MonoType *) data;
1241         if (type->type == MONO_TYPE_GENERICINST)
1242                 return mono_generic_class_hash (type->data.generic_class);
1243         else
1244                 return type->type | (type->byref << 8) | (type->attrs << 9);
1245 }
1246
1247 static gint
1248 mono_type_equal (gconstpointer ka, gconstpointer kb)
1249 {
1250         const MonoType *a = (const MonoType *) ka;
1251         const MonoType *b = (const MonoType *) kb;
1252         
1253         if (a->type != b->type || a->byref != b->byref || a->attrs != b->attrs || a->pinned != b->pinned)
1254                 return 0;
1255         /* need other checks */
1256         return 1;
1257 }
1258
1259 static guint
1260 mono_generic_inst_hash (gconstpointer data)
1261 {
1262         const MonoGenericInst *ginst = (const MonoGenericInst *) data;
1263         guint hash = 0;
1264         int i;
1265         
1266         for (i = 0; i < ginst->type_argc; ++i) {
1267                 hash *= 13;
1268                 hash += mono_metadata_type_hash (ginst->type_argv [i]);
1269         }
1270
1271         return hash ^ (ginst->is_open << 8);
1272 }
1273
1274 static gboolean
1275 mono_generic_inst_equal (gconstpointer ka, gconstpointer kb)
1276 {
1277         const MonoGenericInst *a = (const MonoGenericInst *) ka;
1278         const MonoGenericInst *b = (const MonoGenericInst *) kb;
1279         int i;
1280
1281         if ((a->is_open != b->is_open) || (a->type_argc != b->type_argc) || (a->is_reference != b->is_reference))
1282                 return FALSE;
1283         for (i = 0; i < a->type_argc; ++i) {
1284                 if (!do_mono_metadata_type_equal (a->type_argv [i], b->type_argv [i], FALSE))
1285                         return FALSE;
1286         }
1287         return TRUE;
1288 }
1289
1290 static guint
1291 mono_generic_class_hash (gconstpointer data)
1292 {
1293         const MonoGenericClass *gclass = (const MonoGenericClass *) data;
1294         guint hash = mono_metadata_type_hash (&gclass->container_class->byval_arg);
1295
1296         hash *= 13;
1297         hash += mono_generic_inst_hash (gclass->inst);
1298
1299         return hash;
1300 }
1301
1302 static gboolean
1303 mono_generic_class_equal (gconstpointer ka, gconstpointer kb)
1304 {
1305         const MonoGenericClass *a = (const MonoGenericClass *) ka;
1306         const MonoGenericClass *b = (const MonoGenericClass *) kb;
1307
1308         return _mono_metadata_generic_class_equal (a, b, FALSE);
1309 }
1310
1311 /**
1312  * mono_metadata_init:
1313  *
1314  * Initialize the global variables of this module.
1315  * This is a Mono runtime internal function.
1316  */
1317 void
1318 mono_metadata_init (void)
1319 {
1320         int i;
1321
1322         type_cache = g_hash_table_new (mono_type_hash, mono_type_equal);
1323         generic_inst_cache = g_hash_table_new (mono_generic_inst_hash, mono_generic_inst_equal);
1324         generic_class_cache = g_hash_table_new (mono_generic_class_hash, mono_generic_class_equal);
1325
1326         for (i = 0; i < NBUILTIN_TYPES (); ++i)
1327                 g_hash_table_insert (type_cache, (gpointer) &builtin_types [i], (gpointer) &builtin_types [i]);
1328 }
1329
1330 /**
1331  * mono_metadata_parse_type:
1332  * @m: metadata context
1333  * @mode: king of type that may be found at @ptr
1334  * @opt_attrs: optional attributes to store in the returned type
1335  * @ptr: pointer to the type representation
1336  * @rptr: pointer updated to match the end of the decoded stream
1337  * 
1338  * Decode a compressed type description found at @ptr in @m.
1339  * @mode can be one of MONO_PARSE_MOD_TYPE, MONO_PARSE_PARAM, MONO_PARSE_RET,
1340  * MONO_PARSE_FIELD, MONO_PARSE_LOCAL, MONO_PARSE_TYPE.
1341  * This function can be used to decode type descriptions in method signatures,
1342  * field signatures, locals signatures etc.
1343  *
1344  * To parse a generic type, `generic_container' points to the current class'es
1345  * (the `generic_container' field in the MonoClass) or the current generic method's
1346  * (the `generic_container' field in the MonoMethodNormal) generic container.
1347  * When we encounter any MONO_TYPE_VAR or MONO_TYPE_MVAR's, they're looked up in
1348  * this MonoGenericContainer.
1349  * This is a Mono runtime internal function.
1350  *
1351  * Returns: a #MonoType structure representing the decoded type.
1352  */
1353 MonoType*
1354 mono_metadata_parse_type_full (MonoImage *m, MonoGenericContainer *container, MonoParseTypeMode mode,
1355                                short opt_attrs, const char *ptr, const char **rptr)
1356 {
1357         MonoType *type, *cached;
1358         MonoType stype;
1359         gboolean byref = FALSE;
1360         gboolean pinned = FALSE;
1361         const char *tmp_ptr;
1362         int count = 0;
1363         gboolean found;
1364
1365         /*
1366          * According to the spec, custom modifiers should come before the byref
1367          * flag, but the IL produced by ilasm from the following signature:
1368          *   object modopt(...) &
1369          * starts with a byref flag, followed by the modifiers. (bug #49802)
1370          * Also, this type seems to be different from 'object & modopt(...)'. Maybe
1371          * it would be better to treat byref as real type constructor instead of
1372          * a modifier...
1373          * Also, pinned should come before anything else, but some MSV++ produced
1374          * assemblies violate this (#bug 61990).
1375          */
1376
1377         /* Count the modifiers first */
1378         tmp_ptr = ptr;
1379         found = TRUE;
1380         while (found) {
1381                 switch (*tmp_ptr) {
1382                 case MONO_TYPE_PINNED:
1383                 case MONO_TYPE_BYREF:
1384                         ++tmp_ptr;
1385                         break;
1386                 case MONO_TYPE_CMOD_REQD:
1387                 case MONO_TYPE_CMOD_OPT:
1388                         count ++;
1389                         mono_metadata_parse_custom_mod (m, NULL, tmp_ptr, &tmp_ptr);
1390                         break;
1391                 default:
1392                         found = FALSE;
1393                 }
1394         }
1395
1396         if (count) {
1397                 type = g_malloc0 (sizeof (MonoType) + ((gint32)count - MONO_ZERO_LEN_ARRAY) * sizeof (MonoCustomMod));
1398                 type->num_mods = count;
1399                 if (count > 64)
1400                         g_warning ("got more than 64 modifiers in type");
1401         } else {
1402                 type = &stype;
1403                 memset (type, 0, sizeof (MonoType));
1404         }
1405
1406         /* Parse pinned, byref and custom modifiers */
1407         found = TRUE;
1408         count = 0;
1409         while (found) {
1410                 switch (*ptr) {
1411                 case MONO_TYPE_PINNED:
1412                         pinned = TRUE;
1413                         ++ptr;
1414                         break;
1415                 case MONO_TYPE_BYREF:
1416                         byref = TRUE;
1417                         ++ptr;
1418                         break;
1419                 case MONO_TYPE_CMOD_REQD:
1420                 case MONO_TYPE_CMOD_OPT:
1421                         mono_metadata_parse_custom_mod (m, &(type->modifiers [count]), ptr, &ptr);
1422                         count ++;
1423                         break;
1424                 default:
1425                         found = FALSE;
1426                 }
1427         }
1428         
1429         type->attrs = opt_attrs;
1430         type->byref = byref;
1431         type->pinned = pinned ? 1 : 0;
1432
1433         if (!do_mono_metadata_parse_type (type, m, container, ptr, &ptr)) {
1434                 if (type != &stype)
1435                         g_free (type);
1436                 return NULL;
1437         }
1438
1439         if (rptr)
1440                 *rptr = ptr;
1441
1442         
1443         /* FIXME: remove the != MONO_PARSE_PARAM condition, this accounts for
1444          * almost 10k (about 2/3rds) of all MonoType's we create.
1445          */
1446         if (mode != MONO_PARSE_PARAM && !type->num_mods) {
1447                 /* no need to free type here, because it is on the stack */
1448                 if ((type->type == MONO_TYPE_CLASS || type->type == MONO_TYPE_VALUETYPE) && !type->pinned && !type->attrs) {
1449                         if (type->byref)
1450                                 return &type->data.klass->this_arg;
1451                         else
1452                                 return &type->data.klass->byval_arg;
1453                 }
1454                 /* No need to use locking since nobody is modifying the hash table */
1455                 if ((cached = g_hash_table_lookup (type_cache, type)))
1456                         return cached;
1457         }
1458         
1459         /*printf ("%x%c %s\n", type->attrs, type->pinned ? 'p' : ' ', mono_type_full_name (type));*/
1460         
1461         if (type == &stype)
1462                 type = g_memdup (&stype, sizeof (MonoType));
1463         return type;
1464 }
1465
1466 MonoType*
1467 mono_metadata_parse_type (MonoImage *m, MonoParseTypeMode mode, short opt_attrs,
1468                           const char *ptr, const char **rptr)
1469 {
1470         return mono_metadata_parse_type_full (m, NULL, mode, opt_attrs, ptr, rptr);
1471 }
1472
1473 /*
1474  * mono_metadata_parse_signature_full:
1475  * @image: metadata context
1476  * @generic_container: generic container
1477  * @toke: metadata token
1478  *
1479  * Decode a method signature stored in the STANDALONESIG table
1480  *
1481  * Returns: a MonoMethodSignature describing the signature.
1482  */
1483 MonoMethodSignature*
1484 mono_metadata_parse_signature_full (MonoImage *image, MonoGenericContainer *generic_container, guint32 token)
1485 {
1486         MonoTableInfo *tables = image->tables;
1487         guint32 idx = mono_metadata_token_index (token);
1488         guint32 sig;
1489         const char *ptr;
1490
1491         if (image->dynamic)
1492                 return mono_lookup_dynamic_token (image, token);
1493
1494         g_assert (mono_metadata_token_table(token) == MONO_TABLE_STANDALONESIG);
1495                 
1496         sig = mono_metadata_decode_row_col (&tables [MONO_TABLE_STANDALONESIG], idx - 1, 0);
1497
1498         ptr = mono_metadata_blob_heap (image, sig);
1499         mono_metadata_decode_blob_size (ptr, &ptr);
1500
1501         return mono_metadata_parse_method_signature_full (image, generic_container, FALSE, ptr, NULL); 
1502 }
1503
1504 /*
1505  * mono_metadata_parse_signature:
1506  * @image: metadata context
1507  * @toke: metadata token
1508  *
1509  * Decode a method signature stored in the STANDALONESIG table
1510  *
1511  * Returns: a MonoMethodSignature describing the signature.
1512  */
1513 MonoMethodSignature*
1514 mono_metadata_parse_signature (MonoImage *image, guint32 token)
1515 {
1516         return mono_metadata_parse_signature_full (image, NULL, token);
1517 }
1518
1519 /*
1520  * mono_metadata_signature_alloc:
1521  * @image: metadata context
1522  * @nparmas: number of parameters in the signature
1523  *
1524  * Allocate a MonoMethodSignature structure with the specified number of params.
1525  * The return type and the params types need to be filled later.
1526  * This is a Mono runtime internal function.
1527  *
1528  * Returns: the new MonoMethodSignature structure.
1529  */
1530 MonoMethodSignature*
1531 mono_metadata_signature_alloc (MonoImage *m, guint32 nparams)
1532 {
1533         MonoMethodSignature *sig;
1534
1535         /* later we want to allocate signatures with mempools */
1536         sig = g_malloc0 (sizeof (MonoMethodSignature) + ((gint32)nparams - MONO_ZERO_LEN_ARRAY) * sizeof (MonoType*));
1537         sig->param_count = nparams;
1538         sig->sentinelpos = -1;
1539
1540         return sig;
1541 }
1542
1543 /*
1544  * mono_metadata_signature_dup:
1545  * @sig: method signature
1546  *
1547  * Duplicate an existing MonoMethodSignature so it can be modified.
1548  * This is a Mono runtime internal function.
1549  *
1550  * Returns: the new MonoMethodSignature structure.
1551  */
1552 MonoMethodSignature*
1553 mono_metadata_signature_dup (MonoMethodSignature *sig)
1554 {
1555         int sigsize;
1556
1557         sigsize = sizeof (MonoMethodSignature) + (sig->param_count - MONO_ZERO_LEN_ARRAY) * sizeof (MonoType *);
1558         return g_memdup (sig, sigsize);
1559 }
1560
1561 /*
1562  * mono_metadata_parse_method_signature:
1563  * @m: metadata context
1564  * @generic_container: generics container
1565  * @def: the MethodDef index or 0 for Ref signatures.
1566  * @ptr: pointer to the signature metadata representation
1567  * @rptr: pointer updated to match the end of the decoded stream
1568  *
1569  * Decode a method signature stored at @ptr.
1570  * This is a Mono runtime internal function.
1571  *
1572  * Returns: a MonoMethodSignature describing the signature.
1573  */
1574 MonoMethodSignature *
1575 mono_metadata_parse_method_signature_full (MonoImage *m, MonoGenericContainer *container,
1576                                            int def, const char *ptr, const char **rptr)
1577 {
1578         MonoMethodSignature *method;
1579         int i, *pattrs = NULL;
1580         guint32 hasthis = 0, explicit_this = 0, call_convention, param_count;
1581         guint32 gen_param_count = 0;
1582         gboolean is_open = FALSE;
1583
1584         if (*ptr & 0x10)
1585                 gen_param_count = 1;
1586         if (*ptr & 0x20)
1587                 hasthis = 1;
1588         if (*ptr & 0x40)
1589                 explicit_this = 1;
1590         call_convention = *ptr & 0x0F;
1591         ptr++;
1592         if (gen_param_count)
1593                 gen_param_count = mono_metadata_decode_value (ptr, &ptr);
1594         param_count = mono_metadata_decode_value (ptr, &ptr);
1595
1596         if (def) {
1597                 MonoTableInfo *paramt = &m->tables [MONO_TABLE_PARAM];
1598                 MonoTableInfo *methodt = &m->tables [MONO_TABLE_METHOD];
1599                 guint32 cols [MONO_PARAM_SIZE];
1600                 guint lastp, param_index = mono_metadata_decode_row_col (methodt, def - 1, MONO_METHOD_PARAMLIST);
1601
1602                 if (def < methodt->rows)
1603                         lastp = mono_metadata_decode_row_col (methodt, def, MONO_METHOD_PARAMLIST);
1604                 else
1605                         lastp = paramt->rows + 1;
1606
1607                 pattrs = g_new0 (int, 1 + param_count);
1608                 for (i = param_index; i < lastp; ++i) {
1609                         mono_metadata_decode_row (paramt, i - 1, cols, MONO_PARAM_SIZE);
1610                         pattrs [cols [MONO_PARAM_SEQUENCE]] = cols [MONO_PARAM_FLAGS];
1611                 }
1612         }
1613         method = mono_metadata_signature_alloc (m, param_count);
1614         method->hasthis = hasthis;
1615         method->explicit_this = explicit_this;
1616         method->call_convention = call_convention;
1617         method->generic_param_count = gen_param_count;
1618
1619         if (call_convention != 0xa) {
1620                 method->ret = mono_metadata_parse_type_full (m, container, MONO_PARSE_RET, pattrs ? pattrs [0] : 0, ptr, &ptr);
1621                 if (!method->ret) {
1622                         mono_metadata_free_method_signature (method);
1623                         g_free (pattrs);
1624                         return NULL;
1625                 }
1626                 is_open = mono_class_is_open_constructed_type (method->ret);
1627         }
1628
1629         for (i = 0; i < method->param_count; ++i) {
1630                 if (*ptr == MONO_TYPE_SENTINEL) {
1631                         if (method->call_convention != MONO_CALL_VARARG || def)
1632                                 g_error ("found sentinel for methoddef or no vararg method");
1633                         method->sentinelpos = i;
1634                         ptr++;
1635                 }
1636                 method->params [i] = mono_metadata_parse_type_full (m, container, MONO_PARSE_PARAM, pattrs ? pattrs [i+1] : 0, ptr, &ptr);
1637                 if (!method->params [i]) {
1638                         mono_metadata_free_method_signature (method);
1639                         g_free (pattrs);
1640                         return NULL;
1641                 }
1642                 if (!is_open)
1643                         is_open = mono_class_is_open_constructed_type (method->params [i]);
1644         }
1645
1646         method->has_type_parameters = is_open;
1647
1648         if (def && (method->call_convention == MONO_CALL_VARARG))
1649                 method->sentinelpos = method->param_count;
1650
1651         g_free (pattrs);
1652
1653         if (rptr)
1654                 *rptr = ptr;
1655         /*
1656          * Add signature to a cache and increase ref count...
1657          */
1658
1659         return method;
1660 }
1661
1662 /*
1663  * mono_metadata_parse_method_signature:
1664  * @m: metadata context
1665  * @def: the MethodDef index or 0 for Ref signatures.
1666  * @ptr: pointer to the signature metadata representation
1667  * @rptr: pointer updated to match the end of the decoded stream
1668  *
1669  * Decode a method signature stored at @ptr.
1670  * This is a Mono runtime internal function.
1671  *
1672  * Returns: a MonoMethodSignature describing the signature.
1673  */
1674 MonoMethodSignature *
1675 mono_metadata_parse_method_signature (MonoImage *m, int def, const char *ptr, const char **rptr)
1676 {
1677         return mono_metadata_parse_method_signature_full (m, NULL, def, ptr, rptr);
1678 }
1679
1680 /*
1681  * mono_metadata_free_method_signature:
1682  * @sig: signature to destroy
1683  *
1684  * Free the memory allocated in the signature @sig.
1685  * This method needs to be robust and work also on partially-built
1686  * signatures, so it does extra checks.
1687  */
1688 void
1689 mono_metadata_free_method_signature (MonoMethodSignature *sig)
1690 {
1691         int i;
1692         if (sig->ret)
1693                 mono_metadata_free_type (sig->ret);
1694         for (i = 0; i < sig->param_count; ++i) {
1695                 if (sig->params [i])
1696                         mono_metadata_free_type (sig->params [i]);
1697         }
1698
1699         g_free (sig);
1700 }
1701
1702 /*
1703  * mono_metadata_lookup_generic_inst:
1704  *
1705  * Check whether the newly created generic instantiation @ginst already exists
1706  * in the cache and return the cached value in this case.  Otherwise insert
1707  * it into the cache.
1708  *
1709  * Use this method each time you create a new `MonoGenericInst' to ensure
1710  * proper caching.  Only use the returned value as the argument passed to this
1711  * method may be freed.
1712  *
1713  */
1714 MonoGenericInst *
1715 mono_metadata_lookup_generic_inst (MonoGenericInst *ginst)
1716 {
1717         MonoGenericInst *cached;
1718         int i;
1719
1720         cached = g_hash_table_lookup (generic_inst_cache, ginst);
1721         if (cached) {
1722                 for (i = 0; i < ginst->type_argc; i++)
1723                         mono_metadata_free_type (ginst->type_argv [i]);
1724                 g_free (ginst->type_argv);
1725                 g_free (ginst);
1726                 return cached;
1727         }
1728
1729         ginst->id = ++next_generic_inst_id;
1730         g_hash_table_insert (generic_inst_cache, ginst, ginst);
1731
1732         return ginst;
1733 }
1734
1735 /*
1736  * mono_metadata_lookup_generic_class:
1737  *
1738  * Check whether the newly created generic class @gclass already exists
1739  * in the cache and return the cached value in this case.  Otherwise insert
1740  * it into the cache and return NULL.
1741  *
1742  * Returns: the previosly cached generic class or NULL if it has been newly
1743  *          inserted into the cache.
1744  *
1745  */
1746 MonoGenericClass *
1747 mono_metadata_lookup_generic_class (MonoGenericClass *gclass)
1748 {
1749         MonoGenericClass *cached;
1750
1751         cached = g_hash_table_lookup (generic_class_cache, gclass);
1752         if (cached)
1753                 return cached;
1754
1755         g_hash_table_insert (generic_class_cache, gclass, gclass);
1756         return NULL;
1757 }
1758
1759 /*
1760  * mono_metadata_inflate_generic_inst:
1761  *
1762  * Instantiate the generic instance @ginst with the context @context.
1763  *
1764  */
1765 MonoGenericInst *
1766 mono_metadata_inflate_generic_inst (MonoGenericInst *ginst, MonoGenericContext *context)
1767 {
1768         MonoGenericInst *nginst;
1769         int i;
1770
1771         nginst = g_new0 (MonoGenericInst, 1);
1772         nginst->type_argc = ginst->type_argc;
1773         nginst->type_argv = g_new0 (MonoType*, nginst->type_argc);
1774         nginst->is_reference = 1;
1775
1776         for (i = 0; i < nginst->type_argc; i++) {
1777                 MonoType *t = mono_class_inflate_generic_type (ginst->type_argv [i], context);
1778
1779                 if (!nginst->is_open)
1780                         nginst->is_open = mono_class_is_open_constructed_type (t);
1781                 if (nginst->is_reference)
1782                         nginst->is_reference = MONO_TYPE_IS_REFERENCE (t);
1783
1784                 nginst->type_argv [i] = t;
1785         }
1786
1787         return mono_metadata_lookup_generic_inst (nginst);
1788 }
1789
1790 MonoGenericInst *
1791 mono_metadata_parse_generic_inst (MonoImage *m, MonoGenericContainer *container,
1792                                   int count, const char *ptr, const char **rptr)
1793 {
1794         MonoGenericInst *ginst;
1795         int i;
1796
1797         ginst = g_new0 (MonoGenericInst, 1);
1798         ginst->type_argc = count;
1799         ginst->type_argv = g_new0 (MonoType*, count);
1800         ginst->is_reference = 1;
1801
1802         for (i = 0; i < ginst->type_argc; i++) {
1803                 MonoType *t = mono_metadata_parse_type_full (m, container, MONO_PARSE_TYPE, 0, ptr, &ptr);
1804
1805                 if (!t) {
1806                         g_free (ginst->type_argv);
1807                         g_free (ginst);
1808                         return NULL;
1809                 }
1810                 ginst->type_argv [i] = t;
1811                 if (!ginst->is_open)
1812                         ginst->is_open = mono_class_is_open_constructed_type (t);
1813                 if (ginst->is_reference)
1814                         ginst->is_reference = MONO_TYPE_IS_REFERENCE (t);
1815         }
1816
1817         if (rptr)
1818                 *rptr = ptr;
1819
1820         return mono_metadata_lookup_generic_inst (ginst);
1821 }
1822
1823 static void
1824 do_mono_metadata_parse_generic_class (MonoType *type, MonoImage *m, MonoGenericContainer *container,
1825                                       const char *ptr, const char **rptr)
1826 {
1827         MonoInflatedGenericClass *igclass;
1828         MonoGenericClass *gclass, *cached;
1829         MonoClass *gklass;
1830         MonoType *gtype;
1831         int count;
1832
1833         igclass = g_new0 (MonoInflatedGenericClass, 1);
1834         gclass = &igclass->generic_class;
1835         gclass->is_inflated = TRUE;
1836
1837         type->data.generic_class = gclass;
1838
1839         gclass->context = g_new0 (MonoGenericContext, 1);
1840         gclass->context->gclass = gclass;
1841
1842         /*
1843          * Create the klass before parsing the type arguments.
1844          * This is required to support "recursive" definitions.
1845          * See mcs/tests/gen-23.cs for an example.
1846          */
1847         igclass->klass = g_new0 (MonoClass, 1);
1848
1849         gtype = mono_metadata_parse_type (m, MONO_PARSE_TYPE, 0, ptr, &ptr);
1850         gclass->container_class = gklass = mono_class_from_mono_type (gtype);
1851
1852         g_assert (gklass->generic_container);
1853         gclass->context->container = gklass->generic_container;
1854
1855         count = mono_metadata_decode_value (ptr, &ptr);
1856
1857         gclass->inst = mono_metadata_parse_generic_inst (m, container, count, ptr, &ptr);
1858
1859         if (rptr)
1860                 *rptr = ptr;
1861
1862         /*
1863          * We may be called multiple times on different metadata to create the same
1864          * instantiated type.  This happens for instance if we're part of a method or
1865          * local variable signature.
1866          *
1867          * It's important to return the same MonoGenericClass * for each particualar
1868          * instantiation of a generic type (ie "Stack<Int32>") to make static fields
1869          * work.
1870          *
1871          * According to the spec ($26.1.5), a static variable in a generic class
1872          * declaration is shared amongst all instances of the same closed constructed
1873          * type.
1874          */
1875
1876         cached = g_hash_table_lookup (generic_class_cache, gclass);
1877         if (cached) {
1878                 g_free (igclass->klass);
1879                 g_free (gclass);
1880
1881                 type->data.generic_class = cached;
1882                 return;
1883         } else {
1884                 g_hash_table_insert (generic_class_cache, gclass, gclass);
1885
1886                 mono_stats.generic_instance_count++;
1887                 mono_stats.generics_metadata_size += sizeof (MonoGenericClass) +
1888                         sizeof (MonoGenericContext) +
1889                         gclass->inst->type_argc * sizeof (MonoType);
1890         }
1891 }
1892
1893 /*
1894  * select_container:
1895  * @gc: The generic container to normalize
1896  * @type: The kind of generic parameters the resulting generic-container should contain
1897  */
1898
1899 static MonoGenericContainer *
1900 select_container (MonoGenericContainer *gc, MonoTypeEnum type)
1901 {
1902         gboolean is_var = (type == MONO_TYPE_VAR);
1903         if (!gc)
1904                 return NULL;
1905
1906         g_assert (is_var || type == MONO_TYPE_MVAR);
1907
1908         if (is_var && gc->parent)
1909                 /*
1910                  * The current MonoGenericContainer is a generic method -> its `parent'
1911                  * points to the containing class'es container.
1912                  */
1913                 gc = gc->parent;
1914
1915         /*
1916          * Ensure that we have the correct type of GenericContainer.
1917          */
1918         g_assert (is_var == !gc->is_method);
1919
1920         return gc;
1921 }
1922
1923 /* 
1924  * mono_metadata_parse_generic_param:
1925  * @generic_container: Our MonoClass's or MonoMethodNormal's MonoGenericContainer;
1926  *                     see mono_metadata_parse_type_full() for details.
1927  * Internal routine to parse a generic type parameter.
1928  */
1929 static MonoGenericParam *
1930 mono_metadata_parse_generic_param (MonoImage *m, MonoGenericContainer *generic_container,
1931                                    MonoTypeEnum type, const char *ptr, const char **rptr)
1932 {
1933         int index = mono_metadata_decode_value (ptr, &ptr);
1934         if (rptr)
1935                 *rptr = ptr;
1936
1937         generic_container = select_container (generic_container, type);
1938         if (!generic_container) {
1939                 /* Create dummy MonoGenericParam */
1940                 MonoGenericParam *param = g_new0 (MonoGenericParam, 1);
1941                 param->name = g_strdup_printf ("%d", index);
1942                 param->num = index;
1943
1944                 return param;
1945         }
1946
1947         g_assert (index < generic_container->type_argc);
1948         return &generic_container->type_params [index];
1949 }
1950
1951 /* 
1952  * do_mono_metadata_parse_type:
1953  * @type: MonoType to be filled in with the return value
1954  * @m: image context
1955  * @generic_context: generics_context
1956  * @ptr: pointer to the encoded type
1957  * @rptr: pointer where the end of the encoded type is saved
1958  * 
1959  * Internal routine used to "fill" the contents of @type from an 
1960  * allocated pointer.  This is done this way to avoid doing too
1961  * many mini-allocations (particularly for the MonoFieldType which
1962  * most of the time is just a MonoType, but sometimes might be augmented).
1963  *
1964  * This routine is used by mono_metadata_parse_type and
1965  * mono_metadata_parse_field_type
1966  *
1967  * This extracts a Type as specified in Partition II (22.2.12) 
1968  *
1969  * Returns: FALSE if the type could not be loaded
1970  */
1971 static gboolean
1972 do_mono_metadata_parse_type (MonoType *type, MonoImage *m, MonoGenericContainer *container,
1973                              const char *ptr, const char **rptr)
1974 {
1975         type->type = mono_metadata_decode_value (ptr, &ptr);
1976         
1977         switch (type->type){
1978         case MONO_TYPE_VOID:
1979         case MONO_TYPE_BOOLEAN:
1980         case MONO_TYPE_CHAR:
1981         case MONO_TYPE_I1:
1982         case MONO_TYPE_U1:
1983         case MONO_TYPE_I2:
1984         case MONO_TYPE_U2:
1985         case MONO_TYPE_I4:
1986         case MONO_TYPE_U4:
1987         case MONO_TYPE_I8:
1988         case MONO_TYPE_U8:
1989         case MONO_TYPE_R4:
1990         case MONO_TYPE_R8:
1991         case MONO_TYPE_I:
1992         case MONO_TYPE_U:
1993         case MONO_TYPE_STRING:
1994         case MONO_TYPE_OBJECT:
1995         case MONO_TYPE_TYPEDBYREF:
1996                 break;
1997         case MONO_TYPE_VALUETYPE:
1998         case MONO_TYPE_CLASS: {
1999                 guint32 token;
2000                 token = mono_metadata_parse_typedef_or_ref (m, ptr, &ptr);
2001                 type->data.klass = mono_class_get (m, token);
2002                 if (!type->data.klass)
2003                         return FALSE;
2004                 break;
2005         }
2006         case MONO_TYPE_SZARRAY: {
2007                 MonoType *etype = mono_metadata_parse_type_full (m, container, MONO_PARSE_MOD_TYPE, 0, ptr, &ptr);
2008                 if (!etype)
2009                         return FALSE;
2010                 type->data.klass = mono_class_from_mono_type (etype);
2011                 mono_metadata_free_type (etype);
2012                 break;
2013         }
2014         case MONO_TYPE_PTR:
2015                 type->data.type = mono_metadata_parse_type_full (m, container, MONO_PARSE_MOD_TYPE, 0, ptr, &ptr);
2016                 if (!type->data.type)
2017                         return FALSE;
2018                 break;
2019         case MONO_TYPE_FNPTR:
2020                 type->data.method = mono_metadata_parse_method_signature_full (m, container, 0, ptr, &ptr);
2021                 break;
2022         case MONO_TYPE_ARRAY:
2023                 type->data.array = mono_metadata_parse_array_full (m, container, ptr, &ptr);
2024                 break;
2025         case MONO_TYPE_MVAR:
2026         case MONO_TYPE_VAR:
2027                 type->data.generic_param = mono_metadata_parse_generic_param (m, container, type->type, ptr, &ptr);
2028                 break;
2029         case MONO_TYPE_GENERICINST:
2030                 do_mono_metadata_parse_generic_class (type, m, container, ptr, &ptr);
2031                 break;
2032         default:
2033                 g_error ("type 0x%02x not handled in do_mono_metadata_parse_type", type->type);
2034         }
2035         
2036         if (rptr)
2037                 *rptr = ptr;
2038         return TRUE;
2039 }
2040
2041 /*
2042  * mono_metadata_free_type:
2043  * @type: type to free
2044  *
2045  * Free the memory allocated for type @type.
2046  */
2047 void
2048 mono_metadata_free_type (MonoType *type)
2049 {
2050         if (type >= builtin_types && type < builtin_types + NBUILTIN_TYPES ())
2051                 return;
2052         
2053         switch (type->type){
2054         case MONO_TYPE_OBJECT:
2055         case MONO_TYPE_STRING:
2056                 if (!type->data.klass)
2057                         break;
2058                 /* fall through */
2059         case MONO_TYPE_CLASS:
2060         case MONO_TYPE_VALUETYPE:
2061                 if (type == &type->data.klass->byval_arg || type == &type->data.klass->this_arg)
2062                         return;
2063                 break;
2064         case MONO_TYPE_PTR:
2065                 mono_metadata_free_type (type->data.type);
2066                 break;
2067         case MONO_TYPE_FNPTR:
2068                 mono_metadata_free_method_signature (type->data.method);
2069                 break;
2070         case MONO_TYPE_ARRAY:
2071                 mono_metadata_free_array (type->data.array);
2072                 break;
2073         }
2074         g_free (type);
2075 }
2076
2077 #if 0
2078 static void
2079 hex_dump (const char *buffer, int base, int count)
2080 {
2081         int show_header = 1;
2082         int i;
2083
2084         if (count < 0){
2085                 count = -count;
2086                 show_header = 0;
2087         }
2088         
2089         for (i = 0; i < count; i++){
2090                 if (show_header)
2091                         if ((i % 16) == 0)
2092                                 printf ("\n0x%08x: ", (unsigned char) base + i);
2093
2094                 printf ("%02x ", (unsigned char) (buffer [i]));
2095         }
2096         fflush (stdout);
2097 }
2098 #endif
2099
2100 /** 
2101  * @mh: The Method header
2102  * @ptr: Points to the beginning of the Section Data (25.3)
2103  */
2104 static void
2105 parse_section_data (MonoImage *m, MonoMethodHeader *mh, const unsigned char *ptr)
2106 {
2107         unsigned char sect_data_flags;
2108         const unsigned char *sptr;
2109         int is_fat;
2110         guint32 sect_data_len;
2111         
2112         while (1) {
2113                 /* align on 32-bit boundary */
2114                 /* FIXME: not 64-bit clean code */
2115                 sptr = ptr = dword_align (ptr); 
2116                 sect_data_flags = *ptr;
2117                 ptr++;
2118                 
2119                 is_fat = sect_data_flags & METHOD_HEADER_SECTION_FAT_FORMAT;
2120                 if (is_fat) {
2121                         sect_data_len = (ptr [2] << 16) | (ptr [1] << 8) | ptr [0];
2122                         ptr += 3;
2123                 } else {
2124                         sect_data_len = ptr [0];
2125                         ++ptr;
2126                 }
2127                 /*
2128                 g_print ("flags: %02x, len: %d\n", sect_data_flags, sect_data_len);
2129                 hex_dump (sptr, 0, sect_data_len+8);
2130                 g_print ("\nheader: ");
2131                 hex_dump (sptr-4, 0, 4);
2132                 g_print ("\n");
2133                 */
2134                 
2135                 if (sect_data_flags & METHOD_HEADER_SECTION_EHTABLE) {
2136                         const unsigned char *p = dword_align (ptr);
2137                         int i;
2138                         mh->num_clauses = is_fat ? sect_data_len / 24: sect_data_len / 12;
2139                         /* we could just store a pointer if we don't need to byteswap */
2140                         mh->clauses = g_new0 (MonoExceptionClause, mh->num_clauses);
2141                         for (i = 0; i < mh->num_clauses; ++i) {
2142                                 MonoExceptionClause *ec = &mh->clauses [i];
2143                                 guint32 tof_value;
2144                                 if (is_fat) {
2145                                         ec->flags = read32 (p);
2146                                         ec->try_offset = read32 (p + 4);
2147                                         ec->try_len = read32 (p + 8);
2148                                         ec->handler_offset = read32 (p + 12);
2149                                         ec->handler_len = read32 (p + 16);
2150                                         tof_value = read32 (p + 20);
2151                                         p += 24;
2152                                 } else {
2153                                         ec->flags = read16 (p);
2154                                         ec->try_offset = read16 (p + 2);
2155                                         ec->try_len = *(p + 4);
2156                                         ec->handler_offset = read16 (p + 5);
2157                                         ec->handler_len = *(p + 7);
2158                                         tof_value = read32 (p + 8);
2159                                         p += 12;
2160                                 }
2161                                 if (ec->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
2162                                         ec->data.filter_offset = tof_value;
2163                                 } else if (ec->flags == MONO_EXCEPTION_CLAUSE_NONE) {
2164                                         ec->data.catch_class = tof_value? mono_class_get (m, tof_value): 0;
2165                                 } else {
2166                                         ec->data.catch_class = NULL;
2167                                 }
2168                                 /* g_print ("try %d: %x %04x-%04x %04x\n", i, ec->flags, ec->try_offset, ec->try_offset+ec->try_len, ec->try_len); */
2169                         }
2170
2171                 }
2172                 if (sect_data_flags & METHOD_HEADER_SECTION_MORE_SECTS)
2173                         ptr += sect_data_len - 4; /* LAMESPEC: it seems the size includes the header */
2174                 else
2175                         return;
2176         }
2177 }
2178
2179 /*
2180  * mono_metadata_parse_mh_full:
2181  * @m: metadata context
2182  * @generic_context: generics context
2183  * @ptr: pointer to the method header.
2184  *
2185  * Decode the method header at @ptr, including pointer to the IL code,
2186  * info about local variables and optional exception tables.
2187  * This is a Mono runtime internal function.
2188  *
2189  * Returns: a MonoMethodHeader.
2190  */
2191 MonoMethodHeader *
2192 mono_metadata_parse_mh_full (MonoImage *m, MonoGenericContainer *container, const char *ptr)
2193 {
2194         MonoMethodHeader *mh;
2195         unsigned char flags = *(const unsigned char *) ptr;
2196         unsigned char format = flags & METHOD_HEADER_FORMAT_MASK;
2197         guint16 fat_flags;
2198         guint32 local_var_sig_tok, max_stack, code_size, init_locals;
2199         const unsigned char *code;
2200         int hsize;
2201         
2202         g_return_val_if_fail (ptr != NULL, NULL);
2203
2204         switch (format) {
2205         case METHOD_HEADER_TINY_FORMAT:
2206                 mh = g_new0 (MonoMethodHeader, 1);
2207                 ptr++;
2208                 mh->max_stack = 8;
2209                 local_var_sig_tok = 0;
2210                 mh->code_size = flags >> 2;
2211                 mh->code = ptr;
2212                 return mh;
2213         case METHOD_HEADER_TINY_FORMAT1:
2214                 mh = g_new0 (MonoMethodHeader, 1);
2215                 ptr++;
2216                 mh->max_stack = 8;
2217                 local_var_sig_tok = 0;
2218
2219                 /*
2220                  * The spec claims 3 bits, but the Beta2 is
2221                  * incorrect
2222                  */
2223                 mh->code_size = flags >> 2;
2224                 mh->code = ptr;
2225                 return mh;
2226         case METHOD_HEADER_FAT_FORMAT:
2227                 fat_flags = read16 (ptr);
2228                 ptr += 2;
2229                 hsize = (fat_flags >> 12) & 0xf;
2230                 max_stack = read16 (ptr);
2231                 ptr += 2;
2232                 code_size = read32 (ptr);
2233                 ptr += 4;
2234                 local_var_sig_tok = read32 (ptr);
2235                 ptr += 4;
2236
2237                 if (fat_flags & METHOD_HEADER_INIT_LOCALS)
2238                         init_locals = 1;
2239                 else
2240                         init_locals = 0;
2241
2242                 code = ptr;
2243
2244                 if (!(fat_flags & METHOD_HEADER_MORE_SECTS))
2245                         break;
2246
2247                 /*
2248                  * There are more sections
2249                  */
2250                 ptr = code + code_size;
2251                 break;
2252         default:
2253                 return NULL;
2254         }
2255                        
2256         if (local_var_sig_tok) {
2257                 MonoTableInfo *t = &m->tables [MONO_TABLE_STANDALONESIG];
2258                 const char *locals_ptr;
2259                 guint32 cols [MONO_STAND_ALONE_SIGNATURE_SIZE];
2260                 int len=0, i, bsize;
2261
2262                 mono_metadata_decode_row (t, (local_var_sig_tok & 0xffffff)-1, cols, 1);
2263                 locals_ptr = mono_metadata_blob_heap (m, cols [MONO_STAND_ALONE_SIGNATURE]);
2264                 bsize = mono_metadata_decode_blob_size (locals_ptr, &locals_ptr);
2265                 if (*locals_ptr != 0x07)
2266                         g_warning ("wrong signature for locals blob");
2267                 locals_ptr++;
2268                 len = mono_metadata_decode_value (locals_ptr, &locals_ptr);
2269                 mh = g_malloc0 (sizeof (MonoMethodHeader) + (len - MONO_ZERO_LEN_ARRAY) * sizeof (MonoType*));
2270                 mh->num_locals = len;
2271                 for (i = 0; i < len; ++i) {
2272                         mh->locals [i] = mono_metadata_parse_type_full (
2273                                 m, container, MONO_PARSE_LOCAL, 0, locals_ptr, &locals_ptr);
2274                         if (!mh->locals [i]) {
2275                                 g_free (mh);
2276                                 return NULL;
2277                         }
2278                 }
2279         } else {
2280                 mh = g_new0 (MonoMethodHeader, 1);
2281         }
2282         mh->code = code;
2283         mh->code_size = code_size;
2284         mh->max_stack = max_stack;
2285         mh->init_locals = init_locals;
2286         if (fat_flags & METHOD_HEADER_MORE_SECTS)
2287                 parse_section_data (m, mh, (const unsigned char*)ptr);
2288         return mh;
2289 }
2290
2291 /*
2292  * mono_metadata_parse_mh:
2293  * @generic_context: generics context
2294  * @ptr: pointer to the method header.
2295  *
2296  * Decode the method header at @ptr, including pointer to the IL code,
2297  * info about local variables and optional exception tables.
2298  * This is a Mono runtime internal function.
2299  *
2300  * Returns: a MonoMethodHeader.
2301  */
2302 MonoMethodHeader *
2303 mono_metadata_parse_mh (MonoImage *m, const char *ptr)
2304 {
2305         return mono_metadata_parse_mh_full (m, NULL, ptr);
2306 }
2307
2308 /*
2309  * mono_metadata_free_mh:
2310  * @mh: a method header
2311  *
2312  * Free the memory allocated for the method header.
2313  * This is a Mono runtime internal function.
2314  */
2315 void
2316 mono_metadata_free_mh (MonoMethodHeader *mh)
2317 {
2318         int i;
2319         for (i = 0; i < mh->num_locals; ++i)
2320                 mono_metadata_free_type (mh->locals[i]);
2321         g_free (mh->clauses);
2322         g_free (mh);
2323 }
2324
2325 /*
2326  * mono_method_header_get_code:
2327  * @header: a MonoMethodHeader pointer
2328  * @code_size: memory location for returning the code size
2329  * @max_stack: memory location for returning the max stack
2330  *
2331  * Method header accessor to retreive info about the IL code properties:
2332  * a pointer to the IL code itself, the size of the code and the max number
2333  * of stack slots used by the code.
2334  *
2335  * Returns: pointer to the IL code represented by the method header.
2336  */
2337 const unsigned char*
2338 mono_method_header_get_code (MonoMethodHeader *header, guint32* code_size, guint32* max_stack)
2339 {
2340         if (code_size)
2341                 *code_size = header->code_size;
2342         if (max_stack)
2343                 *max_stack = header->max_stack;
2344         return header->code;
2345 }
2346
2347 /*
2348  * mono_method_header_get_locals:
2349  * @header: a MonoMethodHeader pointer
2350  * @num_locals: memory location for returning the number of local variables
2351  * @init_locals: memory location for returning the init_locals flag
2352  *
2353  * Method header accessor to retreive info about the local variables:
2354  * an array of local types, the number of locals and whether the locals
2355  * are supposed to be initialized to 0 on method entry
2356  *
2357  * Returns: pointer to an array of types of the local variables
2358  */
2359 MonoType**
2360 mono_method_header_get_locals (MonoMethodHeader *header, guint32* num_locals, gboolean *init_locals)
2361 {
2362         if (num_locals)
2363                 *num_locals = header->num_locals;
2364         if (init_locals)
2365                 *init_locals = header->init_locals;
2366         return header->locals;
2367 }
2368
2369 /*
2370  * mono_method_header_get_num_clauses:
2371  * @header: a MonoMethodHeader pointer
2372  *
2373  * Method header accessor to retreive the number of exception clauses.
2374  *
2375  * Returns: the number of exception clauses present
2376  */
2377 int
2378 mono_method_header_get_num_clauses (MonoMethodHeader *header)
2379 {
2380         return header->num_clauses;
2381 }
2382
2383 /*
2384  * mono_method_header_get_clauses:
2385  * @header: a MonoMethodHeader pointer
2386  * @method: MonoMethod the header belongs to
2387  * @iter: pointer to a iterator
2388  * @clause: pointer to a MonoExceptionClause structure which will be filled with the info
2389  *
2390  * Get the info about the exception clauses in the method. Set *iter to NULL to
2391  * initiate the iteration, then call the method repeatedly until it returns FALSE.
2392  * At each iteration, the structure pointed to by clause if filled with the
2393  * exception clause information.
2394  *
2395  * Returns: TRUE if clause was filled with info, FALSE if there are no more exception
2396  * clauses.
2397  */
2398 int
2399 mono_method_header_get_clauses (MonoMethodHeader *header, MonoMethod *method, gpointer *iter, MonoExceptionClause *clause)
2400 {
2401         MonoExceptionClause *sc;
2402         /* later we'll be able to use this interface to parse the clause info on demand,
2403          * without allocating anything.
2404          */
2405         if (!iter || !header->num_clauses)
2406                 return FALSE;
2407         if (!*iter) {
2408                 *iter = sc = header->clauses;
2409                 *clause = *sc;
2410                 return TRUE;
2411         }
2412         sc = *iter;
2413         sc++;
2414         if (sc < header->clauses + header->num_clauses) {
2415                 *iter = sc;
2416                 *clause = *sc;
2417                 return TRUE;
2418         }
2419         return FALSE;
2420 }
2421
2422 /**
2423  * mono_metadata_parse_field_type:
2424  * @m: metadata context to extract information from
2425  * @ptr: pointer to the field signature
2426  * @rptr: pointer updated to match the end of the decoded stream
2427  *
2428  * Parses the field signature, and returns the type information for it. 
2429  *
2430  * Returns: The MonoType that was extracted from @ptr.
2431  */
2432 MonoType *
2433 mono_metadata_parse_field_type (MonoImage *m, short field_flags, const char *ptr, const char **rptr)
2434 {
2435         return mono_metadata_parse_type (m, MONO_PARSE_FIELD, field_flags, ptr, rptr);
2436 }
2437
2438 /**
2439  * mono_metadata_parse_param:
2440  * @m: metadata context to extract information from
2441  * @ptr: pointer to the param signature
2442  * @rptr: pointer updated to match the end of the decoded stream
2443  *
2444  * Parses the param signature, and returns the type information for it. 
2445  *
2446  * Returns: The MonoType that was extracted from @ptr.
2447  */
2448 MonoType *
2449 mono_metadata_parse_param (MonoImage *m, const char *ptr, const char **rptr)
2450 {
2451         return mono_metadata_parse_type (m, MONO_PARSE_PARAM, 0, ptr, rptr);
2452 }
2453
2454 /*
2455  * mono_metadata_token_from_dor:
2456  * @dor_token: A TypeDefOrRef coded index
2457  *
2458  * dor_token is a TypeDefOrRef coded index: it contains either
2459  * a TypeDef, TypeRef or TypeSpec in the lower bits, and the upper
2460  * bits contain an index into the table.
2461  *
2462  * Returns: an expanded token
2463  */
2464 guint32
2465 mono_metadata_token_from_dor (guint32 dor_index)
2466 {
2467         guint32 table, idx;
2468
2469         table = dor_index & 0x03;
2470         idx = dor_index >> 2;
2471
2472         switch (table){
2473         case 0: /* TypeDef */
2474                 return MONO_TOKEN_TYPE_DEF | idx;
2475         case 1: /* TypeRef */
2476                 return MONO_TOKEN_TYPE_REF | idx;
2477         case 2: /* TypeSpec */
2478                 return MONO_TOKEN_TYPE_SPEC | idx;
2479         default:
2480                 g_assert_not_reached ();
2481         }
2482
2483         return 0;
2484 }
2485
2486 /*
2487  * We use this to pass context information to the row locator
2488  */
2489 typedef struct {
2490         int idx;                        /* The index that we are trying to locate */
2491         int col_idx;            /* The index in the row where idx may be stored */
2492         MonoTableInfo *t;       /* pointer to the table */
2493         guint32 result;
2494 } locator_t;
2495
2496 /*
2497  * How the row locator works.
2498  *
2499  *   Table A
2500  *   ___|___
2501  *   ___|___         Table B
2502  *   ___|___------>  _______
2503  *   ___|___         _______
2504  *   
2505  * A column in the rows of table A references an index in table B.
2506  * For example A may be the TYPEDEF table and B the METHODDEF table.
2507  * 
2508  * Given an index in table B we want to get the row in table A
2509  * where the column n references our index in B.
2510  *
2511  * In the locator_t structure:
2512  *      t is table A
2513  *      col_idx is the column number
2514  *      index is the index in table B
2515  *      result will be the index in table A
2516  *
2517  * Examples:
2518  * Table A              Table B         column (in table A)
2519  * TYPEDEF              METHODDEF   MONO_TYPEDEF_METHOD_LIST
2520  * TYPEDEF              FIELD           MONO_TYPEDEF_FIELD_LIST
2521  * PROPERTYMAP  PROPERTY        MONO_PROPERTY_MAP_PROPERTY_LIST
2522  * INTERFIMPL   TYPEDEF         MONO_INTERFACEIMPL_CLASS
2523  * METHODSEM    PROPERTY        ASSOCIATION (encoded index)
2524  *
2525  * Note that we still don't support encoded indexes.
2526  *
2527  */
2528 static int
2529 typedef_locator (const void *a, const void *b)
2530 {
2531         locator_t *loc = (locator_t *) a;
2532         const char *bb = (const char *) b;
2533         int typedef_index = (bb - loc->t->base) / loc->t->row_size;
2534         guint32 col, col_next;
2535
2536         col = mono_metadata_decode_row_col (loc->t, typedef_index, loc->col_idx);
2537
2538         if (loc->idx < col)
2539                 return -1;
2540
2541         /*
2542          * Need to check that the next row is valid.
2543          */
2544         if (typedef_index + 1 < loc->t->rows) {
2545                 col_next = mono_metadata_decode_row_col (loc->t, typedef_index + 1, loc->col_idx);
2546                 if (loc->idx >= col_next)
2547                         return 1;
2548
2549                 if (col == col_next)
2550                         return 1; 
2551         }
2552
2553         loc->result = typedef_index;
2554         
2555         return 0;
2556 }
2557
2558 static int
2559 table_locator (const void *a, const void *b)
2560 {
2561         locator_t *loc = (locator_t *) a;
2562         const char *bb = (const char *) b;
2563         guint32 table_index = (bb - loc->t->base) / loc->t->row_size;
2564         guint32 col;
2565         
2566         col = mono_metadata_decode_row_col (loc->t, table_index, loc->col_idx);
2567
2568         if (loc->idx == col) {
2569                 loc->result = table_index;
2570                 return 0;
2571         }
2572         if (loc->idx < col)
2573                 return -1;
2574         else 
2575                 return 1;
2576 }
2577
2578 static int
2579 declsec_locator (const void *a, const void *b)
2580 {
2581         locator_t *loc = (locator_t *) a;
2582         const char *bb = (const char *) b;
2583         guint32 table_index = (bb - loc->t->base) / loc->t->row_size;
2584         guint32 col;
2585
2586         col = mono_metadata_decode_row_col (loc->t, table_index, loc->col_idx);
2587
2588         if (loc->idx == col) {
2589                 loc->result = table_index;
2590                 return 0;
2591         }
2592         if (loc->idx < col)
2593                 return -1;
2594         else
2595                 return 1;
2596 }
2597
2598 /**
2599  * mono_metadata_typedef_from_field:
2600  * @meta: metadata context
2601  * @index: FieldDef token
2602  *
2603  * Returns: the 1-based index into the TypeDef table of the type that
2604  * declared the field described by @index, or 0 if not found.
2605  */
2606 guint32
2607 mono_metadata_typedef_from_field (MonoImage *meta, guint32 index)
2608 {
2609         MonoTableInfo *tdef = &meta->tables [MONO_TABLE_TYPEDEF];
2610         locator_t loc;
2611
2612         if (!tdef->base)
2613                 return 0;
2614
2615         loc.idx = mono_metadata_token_index (index);
2616         loc.col_idx = MONO_TYPEDEF_FIELD_LIST;
2617         loc.t = tdef;
2618
2619         if (!bsearch (&loc, tdef->base, tdef->rows, tdef->row_size, typedef_locator))
2620                 g_assert_not_reached ();
2621
2622         /* loc_result is 0..1, needs to be mapped to table index (that is +1) */
2623         return loc.result + 1;
2624 }
2625
2626 /*
2627  * mono_metadata_typedef_from_method:
2628  * @meta: metadata context
2629  * @index: MethodDef token
2630  *
2631  * Returns: the 1-based index into the TypeDef table of the type that
2632  * declared the method described by @index.  0 if not found.
2633  */
2634 guint32
2635 mono_metadata_typedef_from_method (MonoImage *meta, guint32 index)
2636 {
2637         MonoTableInfo *tdef = &meta->tables [MONO_TABLE_TYPEDEF];
2638         locator_t loc;
2639         
2640         if (!tdef->base)
2641                 return 0;
2642
2643         loc.idx = mono_metadata_token_index (index);
2644         loc.col_idx = MONO_TYPEDEF_METHOD_LIST;
2645         loc.t = tdef;
2646
2647         if (!bsearch (&loc, tdef->base, tdef->rows, tdef->row_size, typedef_locator))
2648                 g_assert_not_reached ();
2649
2650         /* loc_result is 0..1, needs to be mapped to table index (that is +1) */
2651         return loc.result + 1;
2652 }
2653
2654 /*
2655  * mono_metadata_interfaces_from_typedef_full:
2656  * @meta: metadata context
2657  * @index: typedef token
2658  * 
2659  * The array of interfaces that the @index typedef token implements is returned in
2660  * @interfaces. The number of elemnts in the array is returned in @count.
2661  *
2662  * Returns: TRUE on success, FALSE on failure.
2663  */
2664 gboolean
2665 mono_metadata_interfaces_from_typedef_full (MonoImage *meta, guint32 index, MonoClass ***interfaces, guint *count, MonoGenericContext *context)
2666 {
2667         MonoTableInfo *tdef = &meta->tables [MONO_TABLE_INTERFACEIMPL];
2668         locator_t loc;
2669         guint32 start, i;
2670         guint32 cols [MONO_INTERFACEIMPL_SIZE];
2671         MonoClass **result;
2672
2673         *interfaces = NULL;
2674         *count = 0;
2675
2676         if (!tdef->base)
2677                 return TRUE;
2678
2679         loc.idx = mono_metadata_token_index (index);
2680         loc.col_idx = MONO_INTERFACEIMPL_CLASS;
2681         loc.t = tdef;
2682
2683         if (!bsearch (&loc, tdef->base, tdef->rows, tdef->row_size, table_locator))
2684                 return TRUE;
2685
2686         start = loc.result;
2687         /*
2688          * We may end up in the middle of the rows... 
2689          */
2690         while (start > 0) {
2691                 if (loc.idx == mono_metadata_decode_row_col (tdef, start - 1, MONO_INTERFACEIMPL_CLASS))
2692                         start--;
2693                 else
2694                         break;
2695         }
2696         result = NULL;
2697         i = 0;
2698         while (start < tdef->rows) {
2699                 mono_metadata_decode_row (tdef, start, cols, MONO_INTERFACEIMPL_SIZE);
2700                 if (cols [MONO_INTERFACEIMPL_CLASS] != loc.idx)
2701                         break;
2702                 result = g_renew (MonoClass*, result, i + 1);
2703                 result [i] = mono_class_get_full (
2704                         meta, mono_metadata_token_from_dor (cols [MONO_INTERFACEIMPL_INTERFACE]), context);
2705                 *count = ++i;
2706                 ++start;
2707         }
2708         *interfaces = result;
2709         return TRUE;
2710 }
2711
2712 MonoClass**
2713 mono_metadata_interfaces_from_typedef (MonoImage *meta, guint32 index, guint *count)
2714 {
2715         MonoClass **interfaces;
2716         gboolean rv;
2717
2718         rv = mono_metadata_interfaces_from_typedef_full (meta, index, &interfaces, count, NULL);
2719         if (rv)
2720                 return interfaces;
2721         else
2722                 return NULL;
2723 }
2724
2725 /*
2726  * mono_metadata_nested_in_typedef:
2727  * @meta: metadata context
2728  * @index: typedef token
2729  * 
2730  * Returns: the 1-based index into the TypeDef table of the type
2731  * where the type described by @index is nested.
2732  * Retruns 0 if @index describes a non-nested type.
2733  */
2734 guint32
2735 mono_metadata_nested_in_typedef (MonoImage *meta, guint32 index)
2736 {
2737         MonoTableInfo *tdef = &meta->tables [MONO_TABLE_NESTEDCLASS];
2738         locator_t loc;
2739         
2740         if (!tdef->base)
2741                 return 0;
2742
2743         loc.idx = mono_metadata_token_index (index);
2744         loc.col_idx = MONO_NESTED_CLASS_NESTED;
2745         loc.t = tdef;
2746
2747         if (!bsearch (&loc, tdef->base, tdef->rows, tdef->row_size, table_locator))
2748                 return 0;
2749
2750         /* loc_result is 0..1, needs to be mapped to table index (that is +1) */
2751         return mono_metadata_decode_row_col (tdef, loc.result, MONO_NESTED_CLASS_ENCLOSING) | MONO_TOKEN_TYPE_DEF;
2752 }
2753
2754 /*
2755  * mono_metadata_nesting_typedef:
2756  * @meta: metadata context
2757  * @index: typedef token
2758  * 
2759  * Returns: the 1-based index into the TypeDef table of the first type
2760  * that is nested inside the type described by @index. The search starts at
2761  * @start_index.  returns 0 if no such type is found.
2762  */
2763 guint32
2764 mono_metadata_nesting_typedef (MonoImage *meta, guint32 index, guint32 start_index)
2765 {
2766         MonoTableInfo *tdef = &meta->tables [MONO_TABLE_NESTEDCLASS];
2767         guint32 start;
2768         guint32 class_index = mono_metadata_token_index (index);
2769         
2770         if (!tdef->base)
2771                 return 0;
2772
2773         start = start_index;
2774
2775         while (start <= tdef->rows) {
2776                 if (class_index == mono_metadata_decode_row_col (tdef, start - 1, MONO_NESTED_CLASS_ENCLOSING))
2777                         break;
2778                 else
2779                         start++;
2780         }
2781
2782         if (start > tdef->rows)
2783                 return 0;
2784         else
2785                 return start;
2786 }
2787
2788 /*
2789  * mono_metadata_packing_from_typedef:
2790  * @meta: metadata context
2791  * @index: token representing a type
2792  * 
2793  * Returns: the info stored in the ClassLAyout table for the given typedef token
2794  * into the @packing and @size pointers.
2795  * Returns 0 if the info is not found.
2796  */
2797 guint32
2798 mono_metadata_packing_from_typedef (MonoImage *meta, guint32 index, guint32 *packing, guint32 *size)
2799 {
2800         MonoTableInfo *tdef = &meta->tables [MONO_TABLE_CLASSLAYOUT];
2801         locator_t loc;
2802         guint32 cols [MONO_CLASS_LAYOUT_SIZE];
2803         
2804         if (!tdef->base)
2805                 return 0;
2806
2807         loc.idx = mono_metadata_token_index (index);
2808         loc.col_idx = MONO_CLASS_LAYOUT_PARENT;
2809         loc.t = tdef;
2810
2811         if (!bsearch (&loc, tdef->base, tdef->rows, tdef->row_size, table_locator))
2812                 return 0;
2813
2814         mono_metadata_decode_row (tdef, loc.result, cols, MONO_CLASS_LAYOUT_SIZE);
2815         if (packing)
2816                 *packing = cols [MONO_CLASS_LAYOUT_PACKING_SIZE];
2817         if (size)
2818                 *size = cols [MONO_CLASS_LAYOUT_CLASS_SIZE];
2819
2820         /* loc_result is 0..1, needs to be mapped to table index (that is +1) */
2821         return loc.result + 1;
2822 }
2823
2824 /*
2825  * mono_metadata_custom_attrs_from_index:
2826  * @meta: metadata context
2827  * @index: token representing the parent
2828  * 
2829  * Returns: the 1-based index into the CustomAttribute table of the first 
2830  * attribute which belongs to the metadata object described by @index.
2831  * Returns 0 if no such attribute is found.
2832  */
2833 guint32
2834 mono_metadata_custom_attrs_from_index (MonoImage *meta, guint32 index)
2835 {
2836         MonoTableInfo *tdef = &meta->tables [MONO_TABLE_CUSTOMATTRIBUTE];
2837         locator_t loc;
2838         
2839         if (!tdef->base)
2840                 return 0;
2841
2842         loc.idx = index;
2843         loc.col_idx = MONO_CUSTOM_ATTR_PARENT;
2844         loc.t = tdef;
2845
2846         if (!bsearch (&loc, tdef->base, tdef->rows, tdef->row_size, table_locator))
2847                 return 0;
2848
2849         /* Find the first entry by searching backwards */
2850         while ((loc.result > 0) && (mono_metadata_decode_row_col (tdef, loc.result - 1, MONO_CUSTOM_ATTR_PARENT) == index))
2851                 loc.result --;
2852
2853         /* loc_result is 0..1, needs to be mapped to table index (that is +1) */
2854         return loc.result + 1;
2855 }
2856
2857 /*
2858  * mono_metadata_declsec_from_index:
2859  * @meta: metadata context
2860  * @index: token representing the parent
2861  * 
2862  * Returns: the 0-based index into the DeclarativeSecurity table of the first 
2863  * attribute which belongs to the metadata object described by @index.
2864  * Returns -1 if no such attribute is found.
2865  */
2866 guint32
2867 mono_metadata_declsec_from_index (MonoImage *meta, guint32 index)
2868 {
2869         MonoTableInfo *tdef = &meta->tables [MONO_TABLE_DECLSECURITY];
2870         locator_t loc;
2871
2872         if (!tdef->base)
2873                 return -1;
2874
2875         loc.idx = index;
2876         loc.col_idx = MONO_DECL_SECURITY_PARENT;
2877         loc.t = tdef;
2878
2879         if (!bsearch (&loc, tdef->base, tdef->rows, tdef->row_size, declsec_locator))
2880                 return -1;
2881
2882         /* Find the first entry by searching backwards */
2883         while ((loc.result > 0) && (mono_metadata_decode_row_col (tdef, loc.result - 1, MONO_DECL_SECURITY_PARENT) == index))
2884                 loc.result --;
2885
2886         return loc.result;
2887 }
2888
2889 #ifdef DEBUG
2890 static void
2891 mono_backtrace (int limit)
2892 {
2893         void *array[limit];
2894         char **names;
2895         int i;
2896         backtrace (array, limit);
2897         names = backtrace_symbols (array, limit);
2898         for (i =0; i < limit; ++i) {
2899                 g_print ("\t%s\n", names [i]);
2900         }
2901         g_free (names);
2902 }
2903 #endif
2904
2905 #ifndef __GNUC__
2906 /*#define __alignof__(a) sizeof(a)*/
2907 #define __alignof__(type) G_STRUCT_OFFSET(struct { char c; type x; }, x)
2908 #endif
2909
2910 /*
2911  * mono_type_size:
2912  * @t: the type to return the size of
2913  *
2914  * Returns: the number of bytes required to hold an instance of this
2915  * type in memory
2916  */
2917 int
2918 mono_type_size (MonoType *t, gint *align)
2919 {
2920         if (!t) {
2921                 *align = 1;
2922                 return 0;
2923         }
2924         if (t->byref) {
2925                 *align = __alignof__(gpointer);
2926                 return sizeof (gpointer);
2927         }
2928
2929         switch (t->type){
2930         case MONO_TYPE_VOID:
2931                 *align = 1;
2932                 return 0;
2933         case MONO_TYPE_BOOLEAN:
2934                 *align = __alignof__(gint8);
2935                 return 1;
2936         case MONO_TYPE_I1:
2937         case MONO_TYPE_U1:
2938                 *align = __alignof__(gint8);
2939                 return 1;
2940         case MONO_TYPE_CHAR:
2941         case MONO_TYPE_I2:
2942         case MONO_TYPE_U2:
2943                 *align = __alignof__(gint16);
2944                 return 2;               
2945         case MONO_TYPE_I4:
2946         case MONO_TYPE_U4:
2947                 *align = __alignof__(gint32);
2948                 return 4;
2949         case MONO_TYPE_R4:
2950                 *align = __alignof__(float);
2951                 return 4;
2952         case MONO_TYPE_I8:
2953         case MONO_TYPE_U8:
2954                 *align = __alignof__(gint64);
2955                 return 8;               
2956         case MONO_TYPE_R8:
2957                 *align = __alignof__(double);
2958                 return 8;               
2959         case MONO_TYPE_I:
2960         case MONO_TYPE_U:
2961                 *align = __alignof__(gpointer);
2962                 return sizeof (gpointer);
2963         case MONO_TYPE_STRING:
2964                 *align = __alignof__(gpointer);
2965                 return sizeof (gpointer);
2966         case MONO_TYPE_OBJECT:
2967                 *align = __alignof__(gpointer);
2968                 return sizeof (gpointer);
2969         case MONO_TYPE_VALUETYPE: {
2970                 if (t->data.klass->enumtype)
2971                         return mono_type_size (t->data.klass->enum_basetype, align);
2972                 else
2973                         return mono_class_value_size (t->data.klass, align);
2974         }
2975         case MONO_TYPE_CLASS:
2976         case MONO_TYPE_SZARRAY:
2977         case MONO_TYPE_PTR:
2978         case MONO_TYPE_FNPTR:
2979         case MONO_TYPE_ARRAY:
2980                 *align = __alignof__(gpointer);
2981                 return sizeof (gpointer);
2982         case MONO_TYPE_TYPEDBYREF:
2983                 return mono_class_value_size (mono_defaults.typed_reference_class, align);
2984         case MONO_TYPE_GENERICINST: {
2985                 MonoInflatedGenericClass *gclass;
2986                 MonoClass *container_class;
2987
2988                 gclass = mono_get_inflated_generic_class (t->data.generic_class);
2989                 g_assert (!gclass->generic_class.inst->is_open);
2990                 g_assert (!gclass->klass->generic_container);
2991
2992                 container_class = gclass->generic_class.container_class;
2993
2994                 if (container_class->valuetype) {
2995                         if (container_class->enumtype)
2996                                 return mono_type_size (container_class->enum_basetype, align);
2997                         else
2998                                 return mono_class_value_size (gclass->klass, align);
2999                 } else {
3000                         *align = __alignof__(gpointer);
3001                         return sizeof (gpointer);
3002                 }
3003         }
3004         case MONO_TYPE_VAR:
3005         case MONO_TYPE_MVAR:
3006                 /* FIXME: Martin, this is wrong. */
3007                 *align = __alignof__(gpointer);
3008                 return sizeof (gpointer);
3009         default:
3010                 g_error ("mono_type_size: type 0x%02x unknown", t->type);
3011         }
3012         return 0;
3013 }
3014
3015 /*
3016  * mono_type_stack_size:
3017  * @t: the type to return the size it uses on the stack
3018  *
3019  * Returns: the number of bytes required to hold an instance of this
3020  * type on the runtime stack
3021  */
3022 int
3023 mono_type_stack_size (MonoType *t, gint *align)
3024 {
3025         int tmp;
3026
3027         g_assert (t != NULL);
3028
3029         if (!align)
3030                 align = &tmp;
3031
3032         if (t->byref) {
3033                 *align = __alignof__(gpointer);
3034                 return sizeof (gpointer);
3035         }
3036
3037         switch (t->type){
3038         case MONO_TYPE_BOOLEAN:
3039         case MONO_TYPE_CHAR:
3040         case MONO_TYPE_I1:
3041         case MONO_TYPE_U1:
3042         case MONO_TYPE_I2:
3043         case MONO_TYPE_U2:
3044         case MONO_TYPE_I4:
3045         case MONO_TYPE_U4:
3046         case MONO_TYPE_I:
3047         case MONO_TYPE_U:
3048         case MONO_TYPE_STRING:
3049         case MONO_TYPE_OBJECT:
3050         case MONO_TYPE_CLASS:
3051         case MONO_TYPE_SZARRAY:
3052         case MONO_TYPE_PTR:
3053         case MONO_TYPE_FNPTR:
3054         case MONO_TYPE_ARRAY:
3055                 *align = __alignof__(gpointer);
3056                 return sizeof (gpointer);
3057         case MONO_TYPE_TYPEDBYREF:
3058                 *align = __alignof__(gpointer);
3059                 return sizeof (gpointer) * 3;
3060         case MONO_TYPE_R4:
3061                 *align = __alignof__(float);
3062                 return sizeof (float);          
3063         case MONO_TYPE_I8:
3064         case MONO_TYPE_U8:
3065                 *align = __alignof__(gint64);
3066                 return sizeof (gint64);         
3067         case MONO_TYPE_R8:
3068                 *align = __alignof__(double);
3069                 return sizeof (double);
3070         case MONO_TYPE_VALUETYPE: {
3071                 guint32 size;
3072
3073                 if (t->data.klass->enumtype)
3074                         return mono_type_stack_size (t->data.klass->enum_basetype, align);
3075                 else {
3076                         size = mono_class_value_size (t->data.klass, align);
3077
3078                         *align = *align + __alignof__(gpointer) - 1;
3079                         *align &= ~(__alignof__(gpointer) - 1);
3080
3081                         size += sizeof (gpointer) - 1;
3082                         size &= ~(sizeof (gpointer) - 1);
3083
3084                         return size;
3085                 }
3086         }
3087         case MONO_TYPE_GENERICINST: {
3088                 MonoInflatedGenericClass *gclass;
3089                 MonoClass *container_class;
3090
3091                 gclass = mono_get_inflated_generic_class (t->data.generic_class);
3092                 container_class = gclass->generic_class.container_class;
3093
3094                 g_assert (!gclass->generic_class.inst->is_open);
3095                 g_assert (!gclass->klass->generic_container);
3096
3097                 if (container_class->valuetype) {
3098                         if (container_class->enumtype)
3099                                 return mono_type_stack_size (container_class->enum_basetype, align);
3100                         else {
3101                                 guint32 size = mono_class_value_size (gclass->klass, align);
3102
3103                                 *align = *align + __alignof__(gpointer) - 1;
3104                                 *align &= ~(__alignof__(gpointer) - 1);
3105
3106                                 size += sizeof (gpointer) - 1;
3107                                 size &= ~(sizeof (gpointer) - 1);
3108
3109                                 return size;
3110                         }
3111                 } else {
3112                         *align = __alignof__(gpointer);
3113                         return sizeof (gpointer);
3114                 }
3115         }
3116         default:
3117                 g_error ("type 0x%02x unknown", t->type);
3118         }
3119         return 0;
3120 }
3121
3122 gboolean
3123 mono_type_generic_inst_is_valuetype (MonoType *type)
3124 {
3125         g_assert (type->type == MONO_TYPE_GENERICINST);
3126         return type->data.generic_class->container_class->valuetype;
3127 }
3128
3129 gboolean
3130 mono_metadata_generic_class_is_valuetype (MonoGenericClass *gclass)
3131 {
3132         return gclass->container_class->valuetype;
3133 }
3134
3135 static gboolean
3136 _mono_metadata_generic_class_equal (const MonoGenericClass *g1, const MonoGenericClass *g2, gboolean signature_only)
3137 {
3138         int i;
3139
3140         if ((g1->inst->type_argc != g2->inst->type_argc) || (g1->is_dynamic != g2->is_dynamic) ||
3141             (g1->inst->is_reference != g2->inst->is_reference))
3142                 return FALSE;
3143         if (!mono_metadata_class_equal (g1->container_class, g2->container_class, signature_only))
3144                 return FALSE;
3145         for (i = 0; i < g1->inst->type_argc; ++i) {
3146                 if (!do_mono_metadata_type_equal (g1->inst->type_argv [i], g2->inst->type_argv [i], signature_only))
3147                         return FALSE;
3148         }
3149         return TRUE;
3150 }
3151
3152 guint
3153 mono_metadata_generic_method_hash (MonoGenericMethod *gmethod)
3154 {
3155         return gmethod->inst->id;
3156 }
3157
3158 gboolean
3159 mono_metadata_generic_method_equal (MonoGenericMethod *g1, MonoGenericMethod *g2)
3160 {
3161         return (g1->container == g2->container) && (g1->generic_class == g2->generic_class) &&
3162                 (g1->inst == g2->inst);
3163 }
3164
3165
3166 /*
3167  * mono_metadata_type_hash:
3168  * @t1: a type
3169  *
3170  * Computes an hash value for @t1 to be used in GHashTable.
3171  */
3172 guint
3173 mono_metadata_type_hash (MonoType *t1)
3174 {
3175         guint hash = t1->type;
3176
3177         hash |= t1->byref << 6; /* do not collide with t1->type values */
3178         switch (t1->type) {
3179         case MONO_TYPE_VALUETYPE:
3180         case MONO_TYPE_CLASS:
3181         case MONO_TYPE_SZARRAY:
3182                 /* check if the distribution is good enough */
3183                 return ((hash << 5) - hash) ^ g_str_hash (t1->data.klass->name);
3184         case MONO_TYPE_PTR:
3185                 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
3186         case MONO_TYPE_ARRAY:
3187                 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
3188         case MONO_TYPE_GENERICINST:
3189                 return ((hash << 5) - hash) ^ mono_generic_class_hash (t1->data.generic_class);
3190         }
3191         return hash;
3192 }
3193
3194 static gboolean
3195 mono_metadata_generic_param_equal (MonoGenericParam *p1, MonoGenericParam *p2, gboolean signature_only)
3196 {
3197         if (p1 == p2)
3198                 return TRUE;
3199         if (p1->num != p2->num)
3200                 return FALSE;
3201
3202         if (p1->owner == p2->owner)
3203                 return TRUE;
3204
3205         /*
3206          * If `signature_only' is true, we're comparing two (method) signatures.
3207          * In this case, the owner of two type parameters doesn't need to match.
3208          */
3209
3210         return signature_only;
3211 }
3212
3213 static gboolean
3214 mono_metadata_class_equal (MonoClass *c1, MonoClass *c2, gboolean signature_only)
3215 {
3216         if (c1 == c2)
3217                 return TRUE;
3218         if (c1->generic_class && c2->generic_class)
3219                 return _mono_metadata_generic_class_equal (c1->generic_class, c2->generic_class, signature_only);
3220         if ((c1->byval_arg.type == MONO_TYPE_VAR) && (c2->byval_arg.type == MONO_TYPE_VAR))
3221                 return mono_metadata_generic_param_equal (
3222                         c1->byval_arg.data.generic_param, c2->byval_arg.data.generic_param, signature_only);
3223         if ((c1->byval_arg.type == MONO_TYPE_MVAR) && (c2->byval_arg.type == MONO_TYPE_MVAR))
3224                 return mono_metadata_generic_param_equal (
3225                         c1->byval_arg.data.generic_param, c2->byval_arg.data.generic_param, signature_only);
3226         if (signature_only &&
3227             (c1->byval_arg.type == MONO_TYPE_SZARRAY) && (c2->byval_arg.type == MONO_TYPE_SZARRAY))
3228                 return mono_metadata_class_equal (c1->byval_arg.data.klass, c2->byval_arg.data.klass, signature_only);
3229         return FALSE;
3230 }
3231
3232 /*
3233  * mono_metadata_type_equal:
3234  * @t1: a type
3235  * @t2: another type
3236  *
3237  * Determine if @t1 and @t2 represent the same type.
3238  * Returns: #TRUE if @t1 and @t2 are equal.
3239  */
3240 static gboolean
3241 do_mono_metadata_type_equal (MonoType *t1, MonoType *t2, gboolean signature_only)
3242 {
3243         if (t1->type != t2->type || t1->byref != t2->byref)
3244                 return FALSE;
3245
3246         switch (t1->type) {
3247         case MONO_TYPE_VOID:
3248         case MONO_TYPE_BOOLEAN:
3249         case MONO_TYPE_CHAR:
3250         case MONO_TYPE_I1:
3251         case MONO_TYPE_U1:
3252         case MONO_TYPE_I2:
3253         case MONO_TYPE_U2:
3254         case MONO_TYPE_I4:
3255         case MONO_TYPE_U4:
3256         case MONO_TYPE_I8:
3257         case MONO_TYPE_U8:
3258         case MONO_TYPE_R4:
3259         case MONO_TYPE_R8:
3260         case MONO_TYPE_STRING:
3261         case MONO_TYPE_I:
3262         case MONO_TYPE_U:
3263         case MONO_TYPE_OBJECT:
3264         case MONO_TYPE_TYPEDBYREF:
3265                 return TRUE;
3266         case MONO_TYPE_VALUETYPE:
3267         case MONO_TYPE_CLASS:
3268         case MONO_TYPE_SZARRAY:
3269                 return mono_metadata_class_equal (t1->data.klass, t2->data.klass, signature_only);
3270         case MONO_TYPE_PTR:
3271                 return do_mono_metadata_type_equal (t1->data.type, t2->data.type, signature_only);
3272         case MONO_TYPE_ARRAY:
3273                 if (t1->data.array->rank != t2->data.array->rank)
3274                         return FALSE;
3275                 return mono_metadata_class_equal (t1->data.array->eklass, t2->data.array->eklass, signature_only);
3276         case MONO_TYPE_GENERICINST:
3277                 return _mono_metadata_generic_class_equal (
3278                         t1->data.generic_class, t2->data.generic_class, signature_only);
3279         case MONO_TYPE_VAR:
3280                 return mono_metadata_generic_param_equal (
3281                         t1->data.generic_param, t2->data.generic_param, signature_only);
3282         case MONO_TYPE_MVAR:
3283                 return mono_metadata_generic_param_equal (
3284                         t1->data.generic_param, t2->data.generic_param, signature_only);
3285         default:
3286                 g_error ("implement type compare for %0x!", t1->type);
3287                 return FALSE;
3288         }
3289
3290         return FALSE;
3291 }
3292
3293 gboolean
3294 mono_metadata_type_equal (MonoType *t1, MonoType *t2)
3295 {
3296         return do_mono_metadata_type_equal (t1, t2, FALSE);
3297 }
3298
3299 /**
3300  * mono_metadata_signature_equal:
3301  * @sig1: a signature
3302  * @sig2: another signature
3303  *
3304  * Determine if @sig1 and @sig2 represent the same signature, with the
3305  * same number of arguments and the same types.
3306  * Returns: #TRUE if @sig1 and @sig2 are equal.
3307  */
3308 gboolean
3309 mono_metadata_signature_equal (MonoMethodSignature *sig1, MonoMethodSignature *sig2)
3310 {
3311         int i;
3312
3313         if (sig1->hasthis != sig2->hasthis || sig1->param_count != sig2->param_count)
3314                 return FALSE;
3315
3316         /*
3317          * We're just comparing the signatures of two methods here:
3318          *
3319          * If we have two generic methods `void Foo<U> (U u)' and `void Bar<V> (V v)',
3320          * U and V are equal here.
3321          *
3322          * That's what the `signature_only' argument of do_mono_metadata_type_equal() is for.
3323          */
3324
3325         for (i = 0; i < sig1->param_count; i++) { 
3326                 MonoType *p1 = sig1->params[i];
3327                 MonoType *p2 = sig2->params[i];
3328                 
3329                 /* if (p1->attrs != p2->attrs)
3330                         return FALSE;
3331                 */
3332                 if (!do_mono_metadata_type_equal (p1, p2, TRUE))
3333                         return FALSE;
3334         }
3335
3336         if (!do_mono_metadata_type_equal (sig1->ret, sig2->ret, TRUE))
3337                 return FALSE;
3338         return TRUE;
3339 }
3340
3341 guint
3342 mono_signature_hash (MonoMethodSignature *sig)
3343 {
3344         guint i, res = sig->ret->type;
3345
3346         for (i = 0; i < sig->param_count; i++)
3347                 res = (res << 5) - res + mono_type_hash (sig->params[i]);
3348
3349         return res;
3350 }
3351
3352 /*
3353  * mono_metadata_encode_value:
3354  * @value: value to encode
3355  * @buf: buffer where to write the compressed representation
3356  * @endbuf: pointer updated to point at the end of the encoded output
3357  *
3358  * Encodes the value @value in the compressed representation used
3359  * in metadata and stores the result in @buf. @buf needs to be big
3360  * enough to hold the data (4 bytes).
3361  */
3362 void
3363 mono_metadata_encode_value (guint32 value, char *buf, char **endbuf)
3364 {
3365         char *p = buf;
3366         
3367         if (value < 0x80)
3368                 *p++ = value;
3369         else if (value < 0x4000) {
3370                 p [0] = 0x80 | (value >> 8);
3371                 p [1] = value & 0xff;
3372                 p += 2;
3373         } else {
3374                 p [0] = (value >> 24) | 0xc0;
3375                 p [1] = (value >> 16) & 0xff;
3376                 p [2] = (value >> 8) & 0xff;
3377                 p [3] = value & 0xff;
3378                 p += 4;
3379         }
3380         if (endbuf)
3381                 *endbuf = p;
3382 }
3383
3384 /*
3385  * mono_metadata_field_info:
3386  * @meta: the Image the field is defined in
3387  * @index: the index in the field table representing the field
3388  * @offset: a pointer to an integer where to store the offset that 
3389  * may have been specified for the field in a FieldLayout table
3390  * @rva: a pointer to the RVA of the field data in the image that
3391  * may have been defined in a FieldRVA table
3392  * @marshal_spec: a pointer to the marshal spec that may have been 
3393  * defined for the field in a FieldMarshal table.
3394  *
3395  * Gather info for field @index that may have been defined in the FieldLayout, 
3396  * FieldRVA and FieldMarshal tables.
3397  * Either of offset, rva and marshal_spec can be NULL if you're not interested 
3398  * in the data.
3399  */
3400 void
3401 mono_metadata_field_info (MonoImage *meta, guint32 index, guint32 *offset, guint32 *rva, 
3402                           MonoMarshalSpec **marshal_spec)
3403 {
3404         MonoTableInfo *tdef;
3405         locator_t loc;
3406
3407         loc.idx = index + 1;
3408         if (offset) {
3409                 tdef = &meta->tables [MONO_TABLE_FIELDLAYOUT];
3410
3411                 loc.col_idx = MONO_FIELD_LAYOUT_FIELD;
3412                 loc.t = tdef;
3413
3414                 if (tdef->base && bsearch (&loc, tdef->base, tdef->rows, tdef->row_size, table_locator)) {
3415                         *offset = mono_metadata_decode_row_col (tdef, loc.result, MONO_FIELD_LAYOUT_OFFSET);
3416                 } else {
3417                         *offset = (guint32)-1;
3418                 }
3419         }
3420         if (rva) {
3421                 tdef = &meta->tables [MONO_TABLE_FIELDRVA];
3422
3423                 loc.col_idx = MONO_FIELD_RVA_FIELD;
3424                 loc.t = tdef;
3425                 
3426                 if (tdef->base && bsearch (&loc, tdef->base, tdef->rows, tdef->row_size, table_locator)) {
3427                         /*
3428                          * LAMESPEC: There is no signature, no nothing, just the raw data.
3429                          */
3430                         *rva = mono_metadata_decode_row_col (tdef, loc.result, MONO_FIELD_RVA_RVA);
3431                 } else {
3432                         *rva = 0;
3433                 }
3434         }
3435         if (marshal_spec) {
3436                 const char *p;
3437                 
3438                 if ((p = mono_metadata_get_marshal_info (meta, index, TRUE))) {
3439                         *marshal_spec = mono_metadata_parse_marshal_spec (meta, p);
3440                 }
3441         }
3442
3443 }
3444
3445 /*
3446  * mono_metadata_get_constant_index:
3447  * @meta: the Image the field is defined in
3448  * @index: the token that may have a row defined in the constants table
3449  * @hint: possible position for the row
3450  *
3451  * @token must be a FieldDef, ParamDef or PropertyDef token.
3452  *
3453  * Returns: the index into the Constants table or 0 if not found.
3454  */
3455 guint32
3456 mono_metadata_get_constant_index (MonoImage *meta, guint32 token, guint32 hint)
3457 {
3458         MonoTableInfo *tdef;
3459         locator_t loc;
3460         guint32 index = mono_metadata_token_index (token);
3461
3462         tdef = &meta->tables [MONO_TABLE_CONSTANT];
3463         index <<= MONO_HASCONSTANT_BITS;
3464         switch (mono_metadata_token_table (token)) {
3465         case MONO_TABLE_FIELD:
3466                 index |= MONO_HASCONSTANT_FIEDDEF;
3467                 break;
3468         case MONO_TABLE_PARAM:
3469                 index |= MONO_HASCONSTANT_PARAM;
3470                 break;
3471         case MONO_TABLE_PROPERTY:
3472                 index |= MONO_HASCONSTANT_PROPERTY;
3473                 break;
3474         default:
3475                 g_warning ("Not a valid token for the constant table: 0x%08x", token);
3476                 return 0;
3477         }
3478         loc.idx = index;
3479         loc.col_idx = MONO_CONSTANT_PARENT;
3480         loc.t = tdef;
3481
3482         if ((hint > 0) && (hint < tdef->rows) && (mono_metadata_decode_row_col (tdef, hint - 1, MONO_CONSTANT_PARENT) == index))
3483                 return hint;
3484
3485         if (tdef->base && bsearch (&loc, tdef->base, tdef->rows, tdef->row_size, table_locator)) {
3486                 return loc.result + 1;
3487         }
3488         return 0;
3489 }
3490
3491 /*
3492  * mono_metadata_events_from_typedef:
3493  * @meta: metadata context
3494  * @index: 0-based index (in the TypeDef table) describing a type
3495  *
3496  * Returns: the 0-based index in the Event table for the events in the
3497  * type. The last event that belongs to the type (plus 1) is stored
3498  * in the @end_idx pointer.
3499  */
3500 guint32
3501 mono_metadata_events_from_typedef (MonoImage *meta, guint32 index, guint *end_idx)
3502 {
3503         locator_t loc;
3504         guint32 start, end;
3505         MonoTableInfo *tdef  = &meta->tables [MONO_TABLE_EVENTMAP];
3506
3507         *end_idx = 0;
3508         
3509         if (!tdef->base)
3510                 return 0;
3511
3512         loc.t = tdef;
3513         loc.col_idx = MONO_EVENT_MAP_PARENT;
3514         loc.idx = index + 1;
3515
3516         if (!bsearch (&loc, tdef->base, tdef->rows, tdef->row_size, table_locator))
3517                 return 0;
3518         
3519         start = mono_metadata_decode_row_col (tdef, loc.result, MONO_EVENT_MAP_EVENTLIST);
3520         if (loc.result + 1 < tdef->rows) {
3521                 end = mono_metadata_decode_row_col (tdef, loc.result + 1, MONO_EVENT_MAP_EVENTLIST) - 1;
3522         } else {
3523                 end = meta->tables [MONO_TABLE_EVENT].rows;
3524         }
3525
3526         *end_idx = end;
3527         return start - 1;
3528 }
3529
3530 /*
3531  * mono_metadata_methods_from_event:
3532  * @meta: metadata context
3533  * @index: 0-based index (in the Event table) describing a event
3534  *
3535  * Returns: the 0-based index in the MethodDef table for the methods in the
3536  * event. The last method that belongs to the event (plus 1) is stored
3537  * in the @end_idx pointer.
3538  */
3539 guint32
3540 mono_metadata_methods_from_event   (MonoImage *meta, guint32 index, guint *end_idx)
3541 {
3542         locator_t loc;
3543         guint start, end;
3544         guint32 cols [MONO_METHOD_SEMA_SIZE];
3545         MonoTableInfo *msemt = &meta->tables [MONO_TABLE_METHODSEMANTICS];
3546
3547         *end_idx = 0;
3548         if (!msemt->base)
3549                 return 0;
3550
3551         loc.t = msemt;
3552         loc.col_idx = MONO_METHOD_SEMA_ASSOCIATION;
3553         loc.idx = ((index + 1) << MONO_HAS_SEMANTICS_BITS) | MONO_HAS_SEMANTICS_EVENT; /* Method association coded index */
3554
3555         if (!bsearch (&loc, msemt->base, msemt->rows, msemt->row_size, table_locator))
3556                 return 0;
3557
3558         start = loc.result;
3559         /*
3560          * We may end up in the middle of the rows... 
3561          */
3562         while (start > 0) {
3563                 if (loc.idx == mono_metadata_decode_row_col (msemt, start - 1, MONO_METHOD_SEMA_ASSOCIATION))
3564                         start--;
3565                 else
3566                         break;
3567         }
3568         end = start + 1;
3569         while (end < msemt->rows) {
3570                 mono_metadata_decode_row (msemt, end, cols, MONO_METHOD_SEMA_SIZE);
3571                 if (cols [MONO_METHOD_SEMA_ASSOCIATION] != loc.idx)
3572                         break;
3573                 ++end;
3574         }
3575         *end_idx = end;
3576         return start;
3577 }
3578
3579 /*
3580  * mono_metadata_properties_from_typedef:
3581  * @meta: metadata context
3582  * @index: 0-based index (in the TypeDef table) describing a type
3583  *
3584  * Returns: the 0-based index in the Property table for the properties in the
3585  * type. The last property that belongs to the type (plus 1) is stored
3586  * in the @end_idx pointer.
3587  */
3588 guint32
3589 mono_metadata_properties_from_typedef (MonoImage *meta, guint32 index, guint *end_idx)
3590 {
3591         locator_t loc;
3592         guint32 start, end;
3593         MonoTableInfo *tdef  = &meta->tables [MONO_TABLE_PROPERTYMAP];
3594
3595         *end_idx = 0;
3596         
3597         if (!tdef->base)
3598                 return 0;
3599
3600         loc.t = tdef;
3601         loc.col_idx = MONO_PROPERTY_MAP_PARENT;
3602         loc.idx = index + 1;
3603
3604         if (!bsearch (&loc, tdef->base, tdef->rows, tdef->row_size, table_locator))
3605                 return 0;
3606         
3607         start = mono_metadata_decode_row_col (tdef, loc.result, MONO_PROPERTY_MAP_PROPERTY_LIST);
3608         if (loc.result + 1 < tdef->rows) {
3609                 end = mono_metadata_decode_row_col (tdef, loc.result + 1, MONO_PROPERTY_MAP_PROPERTY_LIST) - 1;
3610         } else {
3611                 end = meta->tables [MONO_TABLE_PROPERTY].rows;
3612         }
3613
3614         *end_idx = end;
3615         return start - 1;
3616 }
3617
3618 /*
3619  * mono_metadata_methods_from_property:
3620  * @meta: metadata context
3621  * @index: 0-based index (in the PropertyDef table) describing a property
3622  *
3623  * Returns: the 0-based index in the MethodDef table for the methods in the
3624  * property. The last method that belongs to the property (plus 1) is stored
3625  * in the @end_idx pointer.
3626  */
3627 guint32
3628 mono_metadata_methods_from_property   (MonoImage *meta, guint32 index, guint *end_idx)
3629 {
3630         locator_t loc;
3631         guint start, end;
3632         guint32 cols [MONO_METHOD_SEMA_SIZE];
3633         MonoTableInfo *msemt = &meta->tables [MONO_TABLE_METHODSEMANTICS];
3634
3635         *end_idx = 0;
3636         if (!msemt->base)
3637                 return 0;
3638
3639         loc.t = msemt;
3640         loc.col_idx = MONO_METHOD_SEMA_ASSOCIATION;
3641         loc.idx = ((index + 1) << MONO_HAS_SEMANTICS_BITS) | MONO_HAS_SEMANTICS_PROPERTY; /* Method association coded index */
3642
3643         if (!bsearch (&loc, msemt->base, msemt->rows, msemt->row_size, table_locator))
3644                 return 0;
3645
3646         start = loc.result;
3647         /*
3648          * We may end up in the middle of the rows... 
3649          */
3650         while (start > 0) {
3651                 if (loc.idx == mono_metadata_decode_row_col (msemt, start - 1, MONO_METHOD_SEMA_ASSOCIATION))
3652                         start--;
3653                 else
3654                         break;
3655         }
3656         end = start + 1;
3657         while (end < msemt->rows) {
3658                 mono_metadata_decode_row (msemt, end, cols, MONO_METHOD_SEMA_SIZE);
3659                 if (cols [MONO_METHOD_SEMA_ASSOCIATION] != loc.idx)
3660                         break;
3661                 ++end;
3662         }
3663         *end_idx = end;
3664         return start;
3665 }
3666
3667 guint32
3668 mono_metadata_implmap_from_method (MonoImage *meta, guint32 method_idx)
3669 {
3670         locator_t loc;
3671         MonoTableInfo *tdef  = &meta->tables [MONO_TABLE_IMPLMAP];
3672
3673         if (!tdef->base)
3674                 return 0;
3675
3676         loc.t = tdef;
3677         loc.col_idx = MONO_IMPLMAP_MEMBER;
3678         loc.idx = ((method_idx + 1) << MONO_MEMBERFORWD_BITS) | MONO_MEMBERFORWD_METHODDEF;
3679
3680         if (!bsearch (&loc, tdef->base, tdef->rows, tdef->row_size, table_locator))
3681                 return 0;
3682
3683         return loc.result + 1;
3684 }
3685
3686 /**
3687  * @image: context where the image is created
3688  * @type_spec:  typespec token
3689  *
3690  * Creates a MonoType representing the TypeSpec indexed by the @type_spec
3691  * token.
3692  */
3693 MonoType *
3694 mono_type_create_from_typespec (MonoImage *image, guint32 type_spec)
3695 {
3696         guint32 idx = mono_metadata_token_index (type_spec);
3697         MonoTableInfo *t;
3698         guint32 cols [MONO_TYPESPEC_SIZE];
3699         const char *ptr;
3700         guint32 len;
3701         MonoType *type;
3702
3703         mono_loader_lock ();
3704
3705         type = g_hash_table_lookup (image->typespec_cache, GUINT_TO_POINTER (type_spec));
3706         if (type) {
3707                 mono_loader_unlock ();
3708                 return type;
3709         }
3710
3711         t = &image->tables [MONO_TABLE_TYPESPEC];
3712
3713         mono_metadata_decode_row (t, idx-1, cols, MONO_TYPESPEC_SIZE);
3714         ptr = mono_metadata_blob_heap (image, cols [MONO_TYPESPEC_SIGNATURE]);
3715         len = mono_metadata_decode_value (ptr, &ptr);
3716
3717         type = g_new0 (MonoType, 1);
3718
3719         g_hash_table_insert (image->typespec_cache, GUINT_TO_POINTER (type_spec), type);
3720
3721         if (*ptr == MONO_TYPE_BYREF) {
3722                 type->byref = 1;
3723                 ptr++;
3724         }
3725
3726         if (!do_mono_metadata_parse_type (type, image, NULL, ptr, &ptr)) {
3727                 g_hash_table_remove (image->typespec_cache, GUINT_TO_POINTER (type_spec));
3728                 g_free (type);
3729                 mono_loader_unlock ();
3730                 return NULL;
3731         }
3732
3733         mono_loader_unlock ();
3734
3735         return type;
3736 }
3737
3738 MonoMarshalSpec *
3739 mono_metadata_parse_marshal_spec (MonoImage *image, const char *ptr)
3740 {
3741         MonoMarshalSpec *res;
3742         int len;
3743         const char *start = ptr;
3744
3745         /* fixme: this is incomplete, but I cant find more infos in the specs */
3746
3747         res = g_new0 (MonoMarshalSpec, 1);
3748         
3749         len = mono_metadata_decode_value (ptr, &ptr);
3750         res->native = *ptr++;
3751
3752         if (res->native == MONO_NATIVE_LPARRAY) {
3753                 res->data.array_data.param_num = -1;
3754                 res->data.array_data.num_elem = -1;
3755                 res->data.array_data.elem_mult = -1;
3756
3757                 if (ptr - start <= len)
3758                         res->data.array_data.elem_type = *ptr++;
3759                 if (ptr - start <= len)
3760                         res->data.array_data.param_num = mono_metadata_decode_value (ptr, &ptr);
3761                 if (ptr - start <= len)
3762                         res->data.array_data.num_elem = mono_metadata_decode_value (ptr, &ptr);
3763                 if (ptr - start <= len) {
3764                         /*
3765                          * LAMESPEC: Older spec versions say this parameter comes before 
3766                          * num_elem. Never spec versions don't talk about elem_mult at
3767                          * all, but csc still emits it, and it is used to distinguish
3768                          * between param_num being 0, and param_num being omitted.
3769                          * So if (param_num == 0) && (num_elem > 0), then
3770                          * elem_mult == 0 -> the array size is num_elem
3771                          * elem_mult == 1 -> the array size is @param_num + num_elem
3772                          */
3773                         res->data.array_data.elem_mult = mono_metadata_decode_value (ptr, &ptr);
3774                 }
3775         } 
3776
3777         if (res->native == MONO_NATIVE_BYVALTSTR) {
3778                 if (ptr - start <= len)
3779                         res->data.array_data.num_elem = mono_metadata_decode_value (ptr, &ptr);
3780         }
3781
3782         if (res->native == MONO_NATIVE_BYVALARRAY) {
3783                 if (ptr - start <= len)
3784                         res->data.array_data.num_elem = mono_metadata_decode_value (ptr, &ptr);
3785         }
3786         
3787         if (res->native == MONO_NATIVE_CUSTOM) {
3788                 /* skip unused type guid */
3789                 len = mono_metadata_decode_value (ptr, &ptr);
3790                 ptr += len;
3791                 /* skip unused native type name */
3792                 len = mono_metadata_decode_value (ptr, &ptr);
3793                 ptr += len;
3794                 /* read custom marshaler type name */
3795                 len = mono_metadata_decode_value (ptr, &ptr);
3796                 res->data.custom_data.custom_name = g_strndup (ptr, len);               
3797                 ptr += len;
3798                 /* read cookie string */
3799                 len = mono_metadata_decode_value (ptr, &ptr);
3800                 res->data.custom_data.cookie = g_strndup (ptr, len);
3801         }
3802
3803         if (res->native == MONO_NATIVE_SAFEARRAY) {
3804                 res->data.safearray_data.elem_type = 0;
3805                 res->data.safearray_data.num_elem = 0;
3806                 if (ptr - start <= len)
3807                         res->data.safearray_data.elem_type = *ptr++;
3808                 if (ptr - start <= len)
3809                         res->data.safearray_data.num_elem = *ptr++;
3810         }
3811         return res;
3812 }
3813
3814 void 
3815 mono_metadata_free_marshal_spec (MonoMarshalSpec *spec)
3816 {
3817         if (spec->native == MONO_NATIVE_CUSTOM) {
3818                 g_free (spec->data.custom_data.custom_name);
3819                 g_free (spec->data.custom_data.cookie);
3820         }
3821         g_free (spec);
3822 }
3823         
3824 guint32
3825 mono_type_to_unmanaged (MonoType *type, MonoMarshalSpec *mspec, gboolean as_field,
3826                         gboolean unicode, MonoMarshalConv *conv) 
3827 {
3828         MonoMarshalConv dummy_conv;
3829         int t = type->type;
3830
3831         if (!conv)
3832                 conv = &dummy_conv;
3833
3834         *conv = MONO_MARSHAL_CONV_NONE;
3835
3836         if (type->byref)
3837                 return MONO_NATIVE_UINT;
3838
3839 handle_enum:
3840         switch (t) {
3841         case MONO_TYPE_BOOLEAN: 
3842                 if (mspec) {
3843                         switch (mspec->native) {
3844                         case MONO_NATIVE_VARIANTBOOL:
3845                                 *conv = MONO_MARSHAL_CONV_BOOL_VARIANTBOOL;
3846                                 return MONO_NATIVE_VARIANTBOOL;
3847                         case MONO_NATIVE_BOOLEAN:
3848                                 *conv = MONO_MARSHAL_CONV_BOOL_I4;
3849                                 return MONO_NATIVE_BOOLEAN;
3850                         case MONO_NATIVE_I1:
3851                         case MONO_NATIVE_U1:
3852                                 return mspec->native;
3853                         default:
3854                                 g_error ("cant marshal bool to native type %02x", mspec->native);
3855                         }
3856                 }
3857                 *conv = MONO_MARSHAL_CONV_BOOL_I4;
3858                 return MONO_NATIVE_BOOLEAN;
3859         case MONO_TYPE_CHAR: return MONO_NATIVE_U2;
3860         case MONO_TYPE_I1: return MONO_NATIVE_I1;
3861         case MONO_TYPE_U1: return MONO_NATIVE_U1;
3862         case MONO_TYPE_I2: return MONO_NATIVE_I2;
3863         case MONO_TYPE_U2: return MONO_NATIVE_U2;
3864         case MONO_TYPE_I4: return MONO_NATIVE_I4;
3865         case MONO_TYPE_U4: return MONO_NATIVE_U4;
3866         case MONO_TYPE_I8: return MONO_NATIVE_I8;
3867         case MONO_TYPE_U8: return MONO_NATIVE_U8;
3868         case MONO_TYPE_R4: return MONO_NATIVE_R4;
3869         case MONO_TYPE_R8: return MONO_NATIVE_R8;
3870         case MONO_TYPE_STRING:
3871                 if (mspec) {
3872                         switch (mspec->native) {
3873                         case MONO_NATIVE_BSTR:
3874                                 *conv = MONO_MARSHAL_CONV_STR_BSTR;
3875                                 return MONO_NATIVE_BSTR;
3876                         case MONO_NATIVE_LPSTR:
3877                                 *conv = MONO_MARSHAL_CONV_STR_LPSTR;
3878                                 return MONO_NATIVE_LPSTR;
3879                         case MONO_NATIVE_LPWSTR:
3880                                 *conv = MONO_MARSHAL_CONV_STR_LPWSTR;
3881                                 return MONO_NATIVE_LPWSTR;
3882                         case MONO_NATIVE_LPTSTR:
3883                                 *conv = MONO_MARSHAL_CONV_STR_LPTSTR;
3884                                 return MONO_NATIVE_LPTSTR;
3885                         case MONO_NATIVE_ANSIBSTR:
3886                                 *conv = MONO_MARSHAL_CONV_STR_ANSIBSTR;
3887                                 return MONO_NATIVE_ANSIBSTR;
3888                         case MONO_NATIVE_TBSTR:
3889                                 *conv = MONO_MARSHAL_CONV_STR_TBSTR;
3890                                 return MONO_NATIVE_TBSTR;
3891                         case MONO_NATIVE_BYVALTSTR:
3892                                 if (unicode)
3893                                         *conv = MONO_MARSHAL_CONV_STR_BYVALWSTR;
3894                                 else
3895                                         *conv = MONO_MARSHAL_CONV_STR_BYVALSTR;
3896                                 return MONO_NATIVE_BYVALTSTR;
3897                         default:
3898                                 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);
3899                         }
3900                 }       
3901                 *conv = MONO_MARSHAL_CONV_STR_LPTSTR;
3902                 return MONO_NATIVE_LPTSTR; 
3903         case MONO_TYPE_PTR: return MONO_NATIVE_UINT;
3904         case MONO_TYPE_VALUETYPE: /*FIXME*/
3905                 if (type->data.klass->enumtype) {
3906                         t = type->data.klass->enum_basetype->type;
3907                         goto handle_enum;
3908                 }
3909                 return MONO_NATIVE_STRUCT;
3910         case MONO_TYPE_SZARRAY: 
3911         case MONO_TYPE_ARRAY: 
3912                 if (mspec) {
3913                         switch (mspec->native) {
3914                         case MONO_NATIVE_BYVALARRAY:
3915                                 *conv = MONO_MARSHAL_CONV_ARRAY_BYVALARRAY;
3916                                 return MONO_NATIVE_BYVALARRAY;
3917                         case MONO_NATIVE_SAFEARRAY:
3918                                 *conv = MONO_MARSHAL_CONV_ARRAY_SAVEARRAY;
3919                                 return MONO_NATIVE_SAFEARRAY;
3920                         case MONO_NATIVE_LPARRAY:                               
3921                                 *conv = MONO_MARSHAL_CONV_ARRAY_LPARRAY;
3922                                 return MONO_NATIVE_LPARRAY;
3923                         default:
3924                                 g_error ("cant marshal array as native type %02x", mspec->native);
3925                         }
3926                 }       
3927
3928                 *conv = MONO_MARSHAL_CONV_ARRAY_LPARRAY;
3929                 return MONO_NATIVE_LPARRAY;
3930         case MONO_TYPE_I: return MONO_NATIVE_INT;
3931         case MONO_TYPE_U: return MONO_NATIVE_UINT;
3932         case MONO_TYPE_CLASS: 
3933         case MONO_TYPE_OBJECT: {
3934                 /* FIXME : we need to handle ArrayList and StringBuilder here, probably */
3935                 if (mspec) {
3936                         switch (mspec->native) {
3937                         case MONO_NATIVE_STRUCT:
3938                                 return MONO_NATIVE_STRUCT;
3939                         case MONO_NATIVE_INTERFACE:
3940                                 *conv = MONO_MARSHAL_CONV_OBJECT_INTERFACE;
3941                                 return MONO_NATIVE_INTERFACE;
3942                         case MONO_NATIVE_IDISPATCH:
3943                                 *conv = MONO_MARSHAL_CONV_OBJECT_IDISPATCH;
3944                                 return MONO_NATIVE_IDISPATCH;
3945                         case MONO_NATIVE_IUNKNOWN:
3946                                 *conv = MONO_MARSHAL_CONV_OBJECT_IUNKNOWN;
3947                                 return MONO_NATIVE_IUNKNOWN;
3948                         case MONO_NATIVE_FUNC:
3949                                 if (t == MONO_TYPE_CLASS && (type->data.klass == mono_defaults.multicastdelegate_class ||
3950                                                                                          type->data.klass == mono_defaults.delegate_class || 
3951                                                                                          type->data.klass->parent == mono_defaults.multicastdelegate_class)) {
3952                                         *conv = MONO_MARSHAL_CONV_DEL_FTN;
3953                                         return MONO_NATIVE_FUNC;
3954                                 }
3955                                 /* Fall through */
3956                         default:
3957                                 g_error ("cant marshal object as native type %02x", mspec->native);
3958                         }
3959                 }
3960                 if (t == MONO_TYPE_CLASS && (type->data.klass == mono_defaults.multicastdelegate_class ||
3961                                              type->data.klass == mono_defaults.delegate_class || 
3962                                              type->data.klass->parent == mono_defaults.multicastdelegate_class)) {
3963                         *conv = MONO_MARSHAL_CONV_DEL_FTN;
3964                         return MONO_NATIVE_FUNC;
3965                 }
3966                 *conv = MONO_MARSHAL_CONV_OBJECT_STRUCT;
3967                 return MONO_NATIVE_STRUCT;
3968         }
3969         case MONO_TYPE_FNPTR: return MONO_NATIVE_FUNC;
3970         case MONO_TYPE_GENERICINST:
3971                 type = &type->data.generic_class->container_class->byval_arg;
3972                 t = type->type;
3973                 goto handle_enum;
3974         case MONO_TYPE_TYPEDBYREF:
3975         default:
3976                 g_error ("type 0x%02x not handled in marshal", t);
3977         }
3978         return MONO_NATIVE_MAX;
3979 }
3980
3981 const char*
3982 mono_metadata_get_marshal_info (MonoImage *meta, guint32 idx, gboolean is_field)
3983 {
3984         locator_t loc;
3985         MonoTableInfo *tdef  = &meta->tables [MONO_TABLE_FIELDMARSHAL];
3986
3987         if (!tdef->base)
3988                 return NULL;
3989
3990         loc.t = tdef;
3991         loc.col_idx = MONO_FIELD_MARSHAL_PARENT;
3992         loc.idx = ((idx + 1) << MONO_HAS_FIELD_MARSHAL_BITS) | (is_field? MONO_HAS_FIELD_MARSHAL_FIELDSREF: MONO_HAS_FIELD_MARSHAL_PARAMDEF);
3993
3994         if (!bsearch (&loc, tdef->base, tdef->rows, tdef->row_size, table_locator))
3995                 return NULL;
3996
3997         return mono_metadata_blob_heap (meta, mono_metadata_decode_row_col (tdef, loc.result, MONO_FIELD_MARSHAL_NATIVE_TYPE));
3998 }
3999
4000 static MonoMethod*
4001 method_from_method_def_or_ref (MonoImage *m, guint32 tok, MonoGenericContext *context)
4002 {
4003         guint32 idx = tok >> MONO_METHODDEFORREF_BITS;
4004         switch (tok & MONO_METHODDEFORREF_MASK) {
4005         case MONO_METHODDEFORREF_METHODDEF:
4006                 return mono_get_method_full (m, MONO_TOKEN_METHOD_DEF | idx, NULL, context);
4007         case MONO_METHODDEFORREF_METHODREF:
4008                 return mono_get_method_full (m, MONO_TOKEN_MEMBER_REF | idx, NULL, context);
4009         }
4010         g_assert_not_reached ();
4011         return NULL;
4012 }
4013
4014 /*
4015  * mono_class_get_overrides_full:
4016  *
4017  *   Return the method overrides belonging to class @type_token in @overrides, and
4018  * the number of overrides in @num_overrides.
4019  *
4020  * Returns: TRUE on success, FALSE on failure.
4021  */
4022 gboolean
4023 mono_class_get_overrides_full (MonoImage *image, guint32 type_token, MonoMethod ***overrides, gint32 *num_overrides,
4024                                MonoGenericContext *generic_context)
4025 {
4026         locator_t loc;
4027         MonoTableInfo *tdef  = &image->tables [MONO_TABLE_METHODIMPL];
4028         guint32 start, end;
4029         gint32 i, num;
4030         guint32 cols [MONO_METHODIMPL_SIZE];
4031         MonoMethod **result;
4032
4033         *overrides = NULL;
4034         if (num_overrides)
4035                 *num_overrides = 0;
4036
4037         if (!tdef->base)
4038                 return TRUE;
4039
4040         loc.t = tdef;
4041         loc.col_idx = MONO_METHODIMPL_CLASS;
4042         loc.idx = mono_metadata_token_index (type_token);
4043
4044         if (!bsearch (&loc, tdef->base, tdef->rows, tdef->row_size, table_locator))
4045                 return TRUE;
4046
4047         start = loc.result;
4048         end = start + 1;
4049         /*
4050          * We may end up in the middle of the rows... 
4051          */
4052         while (start > 0) {
4053                 if (loc.idx == mono_metadata_decode_row_col (tdef, start - 1, MONO_METHODIMPL_CLASS))
4054                         start--;
4055                 else
4056                         break;
4057         }
4058         while (end < tdef->rows) {
4059                 if (loc.idx == mono_metadata_decode_row_col (tdef, end, MONO_METHODIMPL_CLASS))
4060                         end++;
4061                 else
4062                         break;
4063         }
4064         num = end - start;
4065         result = g_new (MonoMethod*, num * 2);
4066         for (i = 0; i < num; ++i) {
4067                 mono_metadata_decode_row (tdef, start + i, cols, MONO_METHODIMPL_SIZE);
4068                 result [i * 2] = method_from_method_def_or_ref (
4069                         image, cols [MONO_METHODIMPL_DECLARATION], generic_context);
4070                 result [i * 2 + 1] = method_from_method_def_or_ref (
4071                         image, cols [MONO_METHODIMPL_BODY], generic_context);
4072         }
4073
4074         *overrides = result;
4075         if (num_overrides)
4076                 *num_overrides = num;
4077         return TRUE;
4078 }
4079
4080 /**
4081  * mono_guid_to_string:
4082  *
4083  * Converts a 16 byte Microsoft GUID to the standard string representation.
4084  */
4085 char *
4086 mono_guid_to_string (const guint8 *guid)
4087 {
4088         return g_strdup_printf ("%02X%02X%02X%02X-%02X%02X-%02X%02X-%02X%02X-%02X%02X%02X%02X%02X%02X", 
4089                                 guid[3], guid[2], guid[1], guid[0],
4090                                 guid[5], guid[4],
4091                                 guid[7], guid[6],
4092                                 guid[8], guid[9],
4093                                 guid[10], guid[11], guid[12], guid[13], guid[14], guid[15]);
4094 }
4095
4096 static gboolean
4097 get_constraints (MonoImage *image, int owner, MonoClass ***constraints, MonoGenericContainer *container)
4098 {
4099         MonoTableInfo *tdef  = &image->tables [MONO_TABLE_GENERICPARAMCONSTRAINT];
4100         guint32 cols [MONO_GENPARCONSTRAINT_SIZE];
4101         guint32 i, token, found;
4102         MonoClass *klass, **res;
4103         GList *cons = NULL, *tmp;
4104         MonoGenericContext *context = &container->context;
4105
4106         g_assert (context->gclass || context->gmethod);
4107
4108         *constraints = NULL;
4109         found = 0;
4110         for (i = 0; i < tdef->rows; ++i) {
4111                 mono_metadata_decode_row (tdef, i, cols, MONO_GENPARCONSTRAINT_SIZE);
4112                 if (cols [MONO_GENPARCONSTRAINT_GENERICPAR] == owner) {
4113                         token = mono_metadata_token_from_dor (cols [MONO_GENPARCONSTRAINT_CONSTRAINT]);
4114                         klass = mono_class_get_full (image, token, context);
4115                         cons = g_list_append (cons, klass);
4116                         ++found;
4117                 } else {
4118                         /* contiguous list finished */
4119                         if (found)
4120                                 break;
4121                 }
4122         }
4123         if (!found)
4124                 return TRUE;
4125         res = g_new0 (MonoClass*, found + 1);
4126         for (i = 0, tmp = cons; i < found; ++i, tmp = tmp->next) {
4127                 res [i] = tmp->data;
4128         }
4129         g_list_free (cons);
4130         *constraints = res;
4131         return TRUE;
4132 }
4133
4134 /*
4135  * mono_metadata_get_generic_param_row:
4136  *
4137  * @image:
4138  * @token: TypeOrMethodDef token, owner for GenericParam
4139  * @owner: coded token, set on return
4140  * 
4141  * Returns: 1-based row-id in the GenericParam table whose
4142  * owner is @token. 0 if not found.
4143  */
4144 guint32
4145 mono_metadata_get_generic_param_row (MonoImage *image, guint32 token, guint32 *owner)
4146 {
4147         MonoTableInfo *tdef  = &image->tables [MONO_TABLE_GENERICPARAM];
4148         guint32 cols [MONO_GENERICPARAM_SIZE];
4149         guint32 i;
4150
4151         g_assert (owner);
4152         if (!tdef->base)
4153                 return 0;
4154
4155         if (mono_metadata_token_table (token) == MONO_TABLE_TYPEDEF)
4156                 *owner = MONO_TYPEORMETHOD_TYPE;
4157         else if (mono_metadata_token_table (token) == MONO_TABLE_METHOD)
4158                 *owner = MONO_TYPEORMETHOD_METHOD;
4159         else {
4160                 g_error ("wrong token %x to get_generic_param_row", token);
4161                 return 0;
4162         }
4163         *owner |= mono_metadata_token_index (token) << MONO_TYPEORMETHOD_BITS;
4164
4165         for (i = 0; i < tdef->rows; ++i) {
4166                 mono_metadata_decode_row (tdef, i, cols, MONO_GENERICPARAM_SIZE);
4167                 if (cols [MONO_GENERICPARAM_OWNER] == *owner)
4168                         return i + 1;
4169         }
4170
4171         return 0;
4172 }
4173
4174 gboolean
4175 mono_metadata_has_generic_params (MonoImage *image, guint32 token)
4176 {
4177         guint32 owner;
4178         return mono_metadata_get_generic_param_row (image, token, &owner);
4179 }
4180
4181 /*
4182  * mono_metadata_load_generic_param_constraints:
4183  *
4184  * Load the generic parameter constraints for the newly created generic type or method
4185  * represented by @token and @container.  The @container is the new container which has
4186  * been returned by a call to mono_metadata_load_generic_params() with this @token.
4187  */
4188 void
4189 mono_metadata_load_generic_param_constraints (MonoImage *image, guint32 token,
4190                                               MonoGenericContainer *container)
4191 {
4192         guint32 start_row, i, owner;
4193         if (! (start_row = mono_metadata_get_generic_param_row (image, token, &owner)))
4194                 return;
4195         for (i = 0; i < container->type_argc; i++)
4196                 get_constraints (image, start_row + i, &container->type_params [i].constraints, container);
4197 }
4198
4199 /*
4200  * mono_metadata_load_generic_params:
4201  *
4202  * Load the type parameters from the type or method definition @token.
4203  *
4204  * Use this method after parsing a type or method definition to figure out whether it's a generic
4205  * type / method.  When parsing a method definition, @parent_container points to the generic container
4206  * of the current class, if any.
4207  *
4208  * Note: This method does not load the constraints: for typedefs, this has to be done after fully
4209  *       creating the type.
4210  *
4211  * Returns: NULL if @token is not a generic type or method definition or the new generic container.
4212  *
4213  */
4214 MonoGenericContainer *
4215 mono_metadata_load_generic_params (MonoImage *image, guint32 token, MonoGenericContainer *parent_container)
4216 {
4217         MonoTableInfo *tdef  = &image->tables [MONO_TABLE_GENERICPARAM];
4218         guint32 cols [MONO_GENERICPARAM_SIZE];
4219         guint32 i, owner = 0, n;
4220         MonoGenericContainer *container;
4221         MonoGenericParam *params;
4222
4223         if (!(i = mono_metadata_get_generic_param_row (image, token, &owner)))
4224                 return NULL;
4225         mono_metadata_decode_row (tdef, i - 1, cols, MONO_GENERICPARAM_SIZE);
4226         params = NULL;
4227         n = 0;
4228         container = g_new0 (MonoGenericContainer, 1);
4229         do {
4230                 n++;
4231                 params = g_realloc (params, sizeof (MonoGenericParam) * n);
4232                 params [n - 1].owner = container;
4233                 params [n - 1].pklass = NULL;
4234                 params [n - 1].method = NULL;
4235                 params [n - 1].flags = cols [MONO_GENERICPARAM_FLAGS];
4236                 params [n - 1].num = cols [MONO_GENERICPARAM_NUMBER];
4237                 params [n - 1].name = mono_metadata_string_heap (image, cols [MONO_GENERICPARAM_NAME]);
4238                 params [n - 1].constraints = NULL;
4239                 if (++i > tdef->rows)
4240                         break;
4241                 mono_metadata_decode_row (tdef, i - 1, cols, MONO_GENERICPARAM_SIZE);
4242         } while (cols [MONO_GENERICPARAM_OWNER] == owner);
4243
4244         container->type_argc = n;
4245         container->type_params = params;
4246         container->parent = parent_container;
4247
4248         if (mono_metadata_token_table (token) == MONO_TABLE_METHOD)
4249                 container->is_method = 1;
4250
4251         container->context.container = container;
4252
4253         return container;
4254 }
4255
4256 gboolean
4257 mono_type_is_byref (MonoType *type)
4258 {
4259         return type->byref;
4260 }
4261
4262 int
4263 mono_type_get_type (MonoType *type)
4264 {
4265         return type->type;
4266 }
4267
4268 /* For MONO_TYPE_FNPTR */
4269 MonoMethodSignature*
4270 mono_type_get_signature (MonoType *type)
4271 {
4272         return type->data.method;
4273 }
4274
4275 /* For MONO_TYPE_CLASS, VALUETYPE */
4276 MonoClass*
4277 mono_type_get_class (MonoType *type)
4278 {
4279         return type->data.klass;
4280 }
4281
4282 /* For MONO_TYPE_ARRAY */
4283 MonoArrayType*
4284 mono_type_get_array_type (MonoType *type)
4285 {
4286         return type->data.array;
4287 }
4288
4289 MonoClass*
4290 mono_type_get_modifiers (MonoType *type, gboolean *is_required, gpointer *iter)
4291 {
4292         /* FIXME: implement */
4293         return NULL;
4294 }
4295
4296 MonoType*
4297 mono_signature_get_return_type (MonoMethodSignature *sig)
4298 {
4299         return sig->ret;
4300 }
4301
4302 MonoType*
4303 mono_signature_get_params (MonoMethodSignature *sig, gpointer *iter)
4304 {
4305         MonoType** type;
4306         if (!iter)
4307                 return NULL;
4308         if (!*iter) {
4309                 /* start from the first */
4310                 if (sig->param_count) {
4311                         *iter = &sig->params [0];
4312                         return sig->params [0];
4313                 } else {
4314                         /* no method */
4315                         return NULL;
4316                 }
4317         }
4318         type = *iter;
4319         type++;
4320         if (type < &sig->params [sig->param_count]) {
4321                 *iter = type;
4322                 return *type;
4323         }
4324         return NULL;
4325 }
4326
4327 guint32
4328 mono_signature_get_param_count (MonoMethodSignature *sig)
4329 {
4330         return sig->param_count;
4331 }
4332
4333 guint32
4334 mono_signature_get_call_conv (MonoMethodSignature *sig)
4335 {
4336         return sig->call_convention;
4337 }
4338
4339 int
4340 mono_signature_vararg_start (MonoMethodSignature *sig)
4341 {
4342         return sig->sentinelpos;
4343 }
4344
4345 gboolean
4346 mono_signature_is_instance (MonoMethodSignature *sig)
4347 {
4348         return sig->hasthis;
4349 }
4350
4351 gboolean
4352 mono_signature_explicit_this (MonoMethodSignature *sig)
4353 {
4354         return sig->explicit_this;
4355 }
4356
4357 /* for use with allocated memory blocks (assumes alignment is to 8 bytes) */
4358 guint
4359 mono_aligned_addr_hash (gconstpointer ptr)
4360 {
4361         return GPOINTER_TO_UINT (ptr) >> 3;
4362 }
4363