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