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