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