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