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