2004-09-03 Zoltan Varga <vargaz@freemail.hu>
[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         gboolean pinned = FALSE;
1207         const char *tmp_ptr;
1208         int count = 0;
1209         gboolean found;
1210
1211         /*
1212          * According to the spec, custom modifiers should come before the byref
1213          * flag, but the IL produced by ilasm from the following signature:
1214          *   object modopt(...) &
1215          * starts with a byref flag, followed by the modifiers. (bug #49802)
1216          * Also, this type seems to be different from 'object & modopt(...)'. Maybe
1217          * it would be better to treat byref as real type constructor instead of
1218          * a modifier...
1219          * Also, pinned should come before anything else, but some MSV++ produced
1220          * assemblies violate this (#bug 61990).
1221          */
1222
1223         /* Count the modifiers first */
1224         tmp_ptr = ptr;
1225         found = TRUE;
1226         while (found) {
1227                 switch (*tmp_ptr) {
1228                 case MONO_TYPE_PINNED:
1229                 case MONO_TYPE_BYREF:
1230                         ++tmp_ptr;
1231                         break;
1232                 case MONO_TYPE_CMOD_REQD:
1233                 case MONO_TYPE_CMOD_OPT:
1234                         count ++;
1235                         mono_metadata_parse_custom_mod (m, NULL, tmp_ptr, &tmp_ptr);
1236                         break;
1237                 default:
1238                         found = FALSE;
1239                 }
1240         }
1241
1242         if (count) {
1243                 type = g_malloc0 (sizeof (MonoType) + ((gint32)count - MONO_ZERO_LEN_ARRAY) * sizeof (MonoCustomMod));
1244                 type->num_mods = count;
1245                 if (count > 64)
1246                         g_warning ("got more than 64 modifiers in type");
1247         }
1248         else
1249                 /*
1250                  * Later we can avoid doing this allocation.
1251                  */
1252                 type = g_new0 (MonoType, 1);
1253
1254         /* Parse pinned, byref and custom modifiers */
1255         found = TRUE;
1256         count = 0;
1257         while (found) {
1258                 switch (*ptr) {
1259                 case MONO_TYPE_PINNED:
1260                         pinned = TRUE;
1261                         ++ptr;
1262                         break;
1263                 case MONO_TYPE_BYREF:
1264                         byref = TRUE;
1265                         ++ptr;
1266                         break;
1267                 case MONO_TYPE_CMOD_REQD:
1268                 case MONO_TYPE_CMOD_OPT:
1269                         count ++;
1270                         mono_metadata_parse_custom_mod (m, &(type->modifiers [count]), ptr, &ptr);
1271                         break;
1272                 default:
1273                         found = FALSE;
1274                 }
1275         }
1276         
1277         type->attrs = opt_attrs;
1278         type->byref = byref;
1279         type->pinned = pinned ? 1 : 0;
1280
1281         do_mono_metadata_parse_type (type, m, ptr, &ptr);
1282
1283         if (rptr)
1284                 *rptr = ptr;
1285
1286         /* No need to use locking since nobody is modifying the hash table */
1287         if (mode != MONO_PARSE_PARAM && !type->num_mods && (cached = g_hash_table_lookup (type_cache, type))) {
1288                 mono_metadata_free_type (type);
1289                 return cached;
1290         } else {
1291                 return type;
1292         }
1293 }
1294
1295 /*
1296  * mono_metadata_parse_signature:
1297  * @image: metadata context
1298  * @toke: metadata token
1299  *
1300  * Decode a method signature stored in the STANDALONESIG table
1301  *
1302  * Returns: a MonoMethodSignature describing the signature.
1303  */
1304 MonoMethodSignature *
1305 mono_metadata_parse_signature (MonoImage *image, guint32 token)
1306 {
1307         MonoTableInfo *tables = image->tables;
1308         guint32 idx = mono_metadata_token_index (token);
1309         guint32 sig;
1310         const char *ptr;
1311
1312         if (image->dynamic)
1313                 return mono_lookup_dynamic_token (image, token);
1314
1315         g_assert (mono_metadata_token_table(token) == MONO_TABLE_STANDALONESIG);
1316                 
1317         sig = mono_metadata_decode_row_col (&tables [MONO_TABLE_STANDALONESIG], idx - 1, 0);
1318
1319         ptr = mono_metadata_blob_heap (image, sig);
1320         mono_metadata_decode_blob_size (ptr, &ptr);
1321
1322         return mono_metadata_parse_method_signature (image, FALSE, ptr, NULL); 
1323 }
1324
1325 MonoMethodSignature*
1326 mono_metadata_signature_alloc (MonoImage *m, guint32 nparams)
1327 {
1328         MonoMethodSignature *sig;
1329
1330         /* later we want to allocate signatures with mempools */
1331         sig = g_malloc0 (sizeof (MonoMethodSignature) + ((gint32)nparams - MONO_ZERO_LEN_ARRAY) * sizeof (MonoType*));
1332         sig->param_count = nparams;
1333         sig->sentinelpos = -1;
1334
1335         return sig;
1336 }
1337
1338 MonoMethodSignature*
1339 mono_metadata_signature_dup (MonoMethodSignature *sig)
1340 {
1341         int sigsize;
1342
1343         sigsize = sizeof (MonoMethodSignature) + sig->param_count * sizeof (MonoType *);
1344         return g_memdup (sig, sigsize);
1345 }
1346
1347 /*
1348  * mono_metadata_parse_method_signature:
1349  * @m: metadata context
1350  * @def: the MethodDef index or 0 for Ref signatures.
1351  * @ptr: pointer to the signature metadata representation
1352  * @rptr: pointer updated to match the end of the decoded stream
1353  *
1354  * Decode a method signature stored at @ptr.
1355  *
1356  * Returns: a MonoMethodSignature describing the signature.
1357  */
1358 MonoMethodSignature *
1359 mono_metadata_parse_method_signature (MonoImage *m, int def, const char *ptr, const char **rptr)
1360 {
1361         MonoMethodSignature *method;
1362         int i, ret_attrs = 0, *pattrs = NULL;
1363         guint32 hasthis = 0, explicit_this = 0, call_convention, param_count;
1364         guint32 gen_param_count = 0;
1365
1366         if (*ptr & 0x10)
1367                 gen_param_count = 1;
1368         if (*ptr & 0x20)
1369                 hasthis = 1;
1370         if (*ptr & 0x40)
1371                 explicit_this = 1;
1372         call_convention = *ptr & 0x0F;
1373         ptr++;
1374         if (gen_param_count)
1375                 gen_param_count = mono_metadata_decode_value (ptr, &ptr);
1376         param_count = mono_metadata_decode_value (ptr, &ptr);
1377         pattrs = g_new0 (int, param_count);
1378
1379         if (def) {
1380                 MonoTableInfo *paramt = &m->tables [MONO_TABLE_PARAM];
1381                 MonoTableInfo *methodt = &m->tables [MONO_TABLE_METHOD];
1382                 guint32 cols [MONO_PARAM_SIZE];
1383                 guint lastp, param_index = mono_metadata_decode_row_col (methodt, def - 1, MONO_METHOD_PARAMLIST);
1384
1385                 if (def < methodt->rows)
1386                         lastp = mono_metadata_decode_row_col (methodt, def, MONO_METHOD_PARAMLIST);
1387                 else
1388                         lastp = paramt->rows + 1;
1389                 for (i = param_index; i < lastp; ++i) {
1390                         mono_metadata_decode_row (paramt, i - 1, cols, MONO_PARAM_SIZE);
1391                         if (!cols [MONO_PARAM_SEQUENCE])
1392                                 ret_attrs = cols [MONO_PARAM_FLAGS];
1393                         else
1394                                 pattrs [cols [MONO_PARAM_SEQUENCE] - 1] = cols [MONO_PARAM_FLAGS];
1395                 }
1396         }
1397         method = mono_metadata_signature_alloc (m, param_count);
1398         method->hasthis = hasthis;
1399         method->explicit_this = explicit_this;
1400         method->call_convention = call_convention;
1401         method->generic_param_count = gen_param_count;
1402         if (call_convention != 0xa)
1403                 method->ret = mono_metadata_parse_type (m, MONO_PARSE_RET, ret_attrs, ptr, &ptr);
1404
1405         if (method->param_count) {
1406                 method->sentinelpos = -1;
1407                 
1408                 for (i = 0; i < method->param_count; ++i) {
1409                         if (*ptr == MONO_TYPE_SENTINEL) {
1410                                 if (method->call_convention != MONO_CALL_VARARG || def)
1411                                                 g_error ("found sentinel for methoddef or no vararg method");
1412                                 method->sentinelpos = i;
1413                                 ptr++;
1414                         }
1415                         method->params [i] = mono_metadata_parse_type (m, MONO_PARSE_PARAM, pattrs [i], ptr, &ptr);
1416                 }
1417         }
1418
1419         if (def && (method->call_convention == MONO_CALL_VARARG))
1420                 method->sentinelpos = method->param_count;
1421
1422         g_free (pattrs);
1423
1424         if (rptr)
1425                 *rptr = ptr;
1426         /*
1427          * Add signature to a cache and increase ref count...
1428          */
1429         return method;
1430 }
1431
1432 /*
1433  * mono_metadata_free_method_signature:
1434  * @sig: signature to destroy
1435  *
1436  * Free the memory allocated in the signature @sig.
1437  */
1438 void
1439 mono_metadata_free_method_signature (MonoMethodSignature *sig)
1440 {
1441         int i;
1442         mono_metadata_free_type (sig->ret);
1443         for (i = 0; i < sig->param_count; ++i)
1444                 mono_metadata_free_type (sig->params [i]);
1445
1446         g_free (sig);
1447 }
1448
1449 static void
1450 do_mono_metadata_parse_generic_inst (MonoType *type, MonoImage *m, const char *ptr, const char **rptr)
1451 {
1452         MonoGenericInst *ginst = g_new0 (MonoGenericInst, 1);
1453         MonoGenericInst *cached;
1454         int i, count;
1455
1456         type->data.generic_inst = ginst;
1457
1458         ginst->context = g_new0 (MonoGenericContext, 1);
1459         ginst->context->ginst = ginst;
1460
1461         ginst->klass = g_new0 (MonoClass, 1);
1462
1463         ginst->generic_type = mono_metadata_parse_type (m, MONO_PARSE_TYPE, 0, ptr, &ptr);
1464         ginst->type_argc = count = mono_metadata_decode_value (ptr, &ptr);
1465         ginst->type_argv = g_new0 (MonoType*, count);
1466
1467         /*
1468          * Create the klass before parsing the type arguments.
1469          * This is required to support "recursive" definitions.
1470          * See mcs/tests/gen-23.cs for an example.
1471          */
1472
1473         ginst->init_pending = TRUE;
1474
1475         mono_class_create_generic (ginst);
1476
1477         for (i = 0; i < ginst->type_argc; i++) {
1478                 MonoType *t = mono_metadata_parse_type (m, MONO_PARSE_TYPE, 0, ptr, &ptr);
1479
1480                 ginst->type_argv [i] = t;
1481                 if (!ginst->is_open)
1482                         ginst->is_open = mono_class_is_open_constructed_type (t);
1483         }
1484
1485
1486         if (rptr)
1487                 *rptr = ptr;
1488
1489         /*
1490          * We may be called multiple times on different metadata to create the same
1491          * instantiated type.  This happens for instance if we're part of a method or
1492          * local variable signature.
1493          *
1494          * It's important to return the same MonoGenericInst * for each particualar
1495          * instantiation of a generic type (ie "Stack<Int32>") to make static fields
1496          * work.
1497          *
1498          * According to the spec ($26.1.5), a static variable in a generic class
1499          * declaration is shared amongst all instances of the same closed constructed
1500          * type.
1501          */
1502
1503         cached = g_hash_table_lookup (m->generic_inst_cache, ginst);
1504         if (cached) {
1505                 g_free (ginst->klass);
1506                 g_free (ginst->type_argv);
1507                 g_free (ginst);
1508
1509                 type->data.generic_inst = cached;
1510                 return;
1511         } else {
1512                 g_hash_table_insert (m->generic_inst_cache, ginst, ginst);
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
2369                 g_assert (!ginst->is_open && !ginst->klass->gen_params);
2370
2371                 if (MONO_TYPE_ISSTRUCT (ginst->generic_type)) {
2372                         MonoClass *gklass = mono_class_from_mono_type (ginst->generic_type);
2373
2374                         if (gklass->enumtype)
2375                                 return mono_type_size (gklass->enum_basetype, align);
2376                         else
2377                                 return mono_class_value_size (ginst->klass, align);
2378                 } else {
2379                         *align = __alignof__(gpointer);
2380                         return sizeof (gpointer);
2381                 }
2382         }
2383         case MONO_TYPE_VAR:
2384         case MONO_TYPE_MVAR:
2385                 *align = __alignof__(gpointer);
2386                 return sizeof (gpointer);
2387         default:
2388                 g_error ("mono_type_size: type 0x%02x unknown", t->type);
2389         }
2390         return 0;
2391 }
2392
2393 /*
2394  * mono_type_stack_size:
2395  * @t: the type to return the size it uses on the stack
2396  *
2397  * Returns: the number of bytes required to hold an instance of this
2398  * type on the runtime stack
2399  */
2400 int
2401 mono_type_stack_size (MonoType *t, gint *align)
2402 {
2403         int tmp;
2404
2405         g_assert (t != NULL);
2406
2407         if (!align)
2408                 align = &tmp;
2409
2410         if (t->byref) {
2411                 *align = __alignof__(gpointer);
2412                 return sizeof (gpointer);
2413         }
2414
2415         switch (t->type){
2416         case MONO_TYPE_BOOLEAN:
2417         case MONO_TYPE_CHAR:
2418         case MONO_TYPE_I1:
2419         case MONO_TYPE_U1:
2420         case MONO_TYPE_I2:
2421         case MONO_TYPE_U2:
2422         case MONO_TYPE_I4:
2423         case MONO_TYPE_U4:
2424         case MONO_TYPE_I:
2425         case MONO_TYPE_U:
2426         case MONO_TYPE_STRING:
2427         case MONO_TYPE_OBJECT:
2428         case MONO_TYPE_CLASS:
2429         case MONO_TYPE_SZARRAY:
2430         case MONO_TYPE_PTR:
2431         case MONO_TYPE_FNPTR:
2432         case MONO_TYPE_ARRAY:
2433                 *align = __alignof__(gpointer);
2434                 return sizeof (gpointer);
2435         case MONO_TYPE_TYPEDBYREF:
2436                 *align = __alignof__(gpointer);
2437                 return sizeof (gpointer) * 3;
2438         case MONO_TYPE_R4:
2439                 *align = __alignof__(float);
2440                 return sizeof (float);          
2441         case MONO_TYPE_I8:
2442         case MONO_TYPE_U8:
2443                 *align = __alignof__(gint64);
2444                 return sizeof (gint64);         
2445         case MONO_TYPE_R8:
2446                 *align = __alignof__(double);
2447                 return sizeof (double);
2448         case MONO_TYPE_VALUETYPE: {
2449                 guint32 size;
2450
2451                 if (t->data.klass->enumtype)
2452                         return mono_type_stack_size (t->data.klass->enum_basetype, align);
2453                 else {
2454                         size = mono_class_value_size (t->data.klass, align);
2455
2456                         *align = *align + __alignof__(gpointer) - 1;
2457                         *align &= ~(__alignof__(gpointer) - 1);
2458
2459                         size += sizeof (gpointer) - 1;
2460                         size &= ~(sizeof (gpointer) - 1);
2461
2462                         return size;
2463                 }
2464         }
2465         case MONO_TYPE_GENERICINST: {
2466                 MonoGenericInst *ginst = t->data.generic_inst;
2467
2468                 g_assert (!ginst->is_open && !ginst->klass->gen_params);
2469
2470                 if (MONO_TYPE_ISSTRUCT (ginst->generic_type)) {
2471                         MonoClass *gklass = mono_class_from_mono_type (ginst->generic_type);
2472
2473                         if (gklass->enumtype)
2474                                 return mono_type_stack_size (gklass->enum_basetype, align);
2475                         else {
2476                                 guint32 size = mono_class_value_size (ginst->klass, align);
2477
2478                                 *align = *align + __alignof__(gpointer) - 1;
2479                                 *align &= ~(__alignof__(gpointer) - 1);
2480
2481                                 size += sizeof (gpointer) - 1;
2482                                 size &= ~(sizeof (gpointer) - 1);
2483
2484                                 return size;
2485                         }
2486                 } else {
2487                         *align = __alignof__(gpointer);
2488                         return sizeof (gpointer);
2489                 }
2490         }
2491         default:
2492                 g_error ("type 0x%02x unknown", t->type);
2493         }
2494         return 0;
2495 }
2496
2497 gboolean
2498 mono_metadata_generic_inst_is_valuetype (MonoGenericInst *ginst)
2499 {
2500         return MONO_TYPE_ISSTRUCT (ginst->generic_type);
2501 }
2502
2503 guint
2504 mono_metadata_generic_inst_hash (MonoGenericInst *ginst)
2505 {
2506         return mono_metadata_type_hash (ginst->generic_type);
2507 }
2508
2509 gboolean
2510 mono_metadata_generic_inst_equal (MonoGenericInst *g1, MonoGenericInst *g2)
2511 {
2512         int i;
2513
2514         if (g1->type_argc != g2->type_argc)
2515                 return FALSE;
2516         if (!mono_metadata_type_equal (g1->generic_type, g2->generic_type))
2517                 return FALSE;
2518         for (i = 0; i < g1->type_argc; ++i) {
2519                 if (!mono_metadata_type_equal (g1->type_argv [i], g2->type_argv [i]))
2520                         return FALSE;
2521         }
2522         return TRUE;
2523 }
2524
2525 /*
2526  * mono_metadata_type_hash:
2527  * @t1: a type
2528  *
2529  * Computes an hash value for @t1 to be used in GHashTable.
2530  */
2531 guint
2532 mono_metadata_type_hash (MonoType *t1)
2533 {
2534         guint hash = t1->type;
2535
2536         hash |= t1->byref << 6; /* do not collide with t1->type values */
2537         switch (t1->type) {
2538         case MONO_TYPE_VALUETYPE:
2539         case MONO_TYPE_CLASS:
2540         case MONO_TYPE_SZARRAY:
2541                 /* check if the distribution is good enough */
2542                 return ((hash << 5) - hash) ^ g_str_hash (t1->data.klass->name);
2543         case MONO_TYPE_PTR:
2544                 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
2545         case MONO_TYPE_ARRAY:
2546                 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
2547         case MONO_TYPE_GENERICINST:
2548                 return ((hash << 5) - hash) ^ mono_metadata_generic_inst_hash (t1->data.generic_inst);
2549         }
2550         return hash;
2551 }
2552
2553 static gboolean
2554 mono_metadata_class_equal (MonoClass *c1, MonoClass *c2)
2555 {
2556         if (c1 == c2)
2557                 return TRUE;
2558         if (c1->generic_inst && c2->generic_inst)
2559                 return mono_metadata_generic_inst_equal (c1->generic_inst, c2->generic_inst);
2560         if ((c1->byval_arg.type == MONO_TYPE_VAR) && (c2->byval_arg.type == MONO_TYPE_VAR))
2561                 return c1->byval_arg.data.generic_param->num == c2->byval_arg.data.generic_param->num;
2562         if ((c1->byval_arg.type == MONO_TYPE_MVAR) && (c2->byval_arg.type == MONO_TYPE_MVAR))
2563                 return c1->byval_arg.data.generic_param->num == c2->byval_arg.data.generic_param->num;
2564         return FALSE;
2565 }
2566
2567 /*
2568  * mono_metadata_type_equal:
2569  * @t1: a type
2570  * @t2: another type
2571  *
2572  * Determine if @t1 and @t2 represent the same type.
2573  * Returns: #TRUE if @t1 and @t2 are equal.
2574  */
2575 gboolean
2576 mono_metadata_type_equal (MonoType *t1, MonoType *t2)
2577 {
2578         if (t1->type != t2->type ||
2579             t1->byref != t2->byref)
2580                 return FALSE;
2581
2582         switch (t1->type) {
2583         case MONO_TYPE_VOID:
2584         case MONO_TYPE_BOOLEAN:
2585         case MONO_TYPE_CHAR:
2586         case MONO_TYPE_I1:
2587         case MONO_TYPE_U1:
2588         case MONO_TYPE_I2:
2589         case MONO_TYPE_U2:
2590         case MONO_TYPE_I4:
2591         case MONO_TYPE_U4:
2592         case MONO_TYPE_I8:
2593         case MONO_TYPE_U8:
2594         case MONO_TYPE_R4:
2595         case MONO_TYPE_R8:
2596         case MONO_TYPE_STRING:
2597         case MONO_TYPE_I:
2598         case MONO_TYPE_U:
2599         case MONO_TYPE_OBJECT:
2600         case MONO_TYPE_TYPEDBYREF:
2601                 return TRUE;
2602         case MONO_TYPE_VALUETYPE:
2603         case MONO_TYPE_CLASS:
2604         case MONO_TYPE_SZARRAY:
2605                 return mono_metadata_class_equal (t1->data.klass, t2->data.klass);
2606         case MONO_TYPE_PTR:
2607                 return mono_metadata_type_equal (t1->data.type, t2->data.type);
2608         case MONO_TYPE_ARRAY:
2609                 if (t1->data.array->rank != t2->data.array->rank)
2610                         return FALSE;
2611                 return mono_metadata_class_equal (t1->data.array->eklass, t2->data.array->eklass);
2612         case MONO_TYPE_GENERICINST:
2613                 return mono_metadata_generic_inst_equal (t1->data.generic_inst,
2614                                                          t2->data.generic_inst);
2615         case MONO_TYPE_VAR:
2616         case MONO_TYPE_MVAR:
2617                 return t1->data.generic_param->num == t2->data.generic_param->num;
2618         default:
2619                 g_error ("implement type compare for %0x!", t1->type);
2620                 return FALSE;
2621         }
2622
2623         return FALSE;
2624 }
2625
2626 /*
2627  * mono_metadata_signature_equal:
2628  * @sig1: a signature
2629  * @sig2: another signature
2630  *
2631  * Determine if @sig1 and @sig2 represent the same signature, with the
2632  * same number of arguments and the same types.
2633  * Returns: #TRUE if @sig1 and @sig2 are equal.
2634  */
2635 gboolean
2636 mono_metadata_signature_equal (MonoMethodSignature *sig1, MonoMethodSignature *sig2)
2637 {
2638         int i;
2639
2640         if (sig1->hasthis != sig2->hasthis ||
2641             sig1->param_count != sig2->param_count)
2642                 return FALSE;
2643
2644         for (i = 0; i < sig1->param_count; i++) { 
2645                 MonoType *p1 = sig1->params[i];
2646                 MonoType *p2 = sig2->params[i];
2647                 
2648                 /* if (p1->attrs != p2->attrs)
2649                         return FALSE;
2650                 */
2651                 if (!mono_metadata_type_equal (p1, p2))
2652                         return FALSE;
2653         }
2654
2655         if (!mono_metadata_type_equal (sig1->ret, sig2->ret))
2656                 return FALSE;
2657         return TRUE;
2658 }
2659
2660 guint
2661 mono_signature_hash (MonoMethodSignature *sig)
2662 {
2663         guint i, res = sig->ret->type;
2664
2665         for (i = 0; i < sig->param_count; i++)
2666                 res = (res << 5) - res + sig->params[i]->type;
2667
2668         return res;
2669 }
2670
2671 /*
2672  * mono_metadata_encode_value:
2673  * @value: value to encode
2674  * @buf: buffer where to write the compressed representation
2675  * @endbuf: pointer updated to point at the end of the encoded output
2676  *
2677  * Encodes the value @value in the compressed representation used
2678  * in metadata and stores the result in @buf. @buf needs to be big
2679  * enough to hold the data (4 bytes).
2680  */
2681 void
2682 mono_metadata_encode_value (guint32 value, char *buf, char **endbuf)
2683 {
2684         char *p = buf;
2685         
2686         if (value < 0x80)
2687                 *p++ = value;
2688         else if (value < 0x4000) {
2689                 p [0] = 0x80 | (value >> 8);
2690                 p [1] = value & 0xff;
2691                 p += 2;
2692         } else {
2693                 p [0] = (value >> 24) | 0xc0;
2694                 p [1] = (value >> 16) & 0xff;
2695                 p [2] = (value >> 8) & 0xff;
2696                 p [3] = value & 0xff;
2697                 p += 4;
2698         }
2699         if (endbuf)
2700                 *endbuf = p;
2701 }
2702
2703 /*
2704  * mono_metadata_field_info:
2705  * @meta: the Image the field is defined in
2706  * @index: the index in the field table representing the field
2707  * @offset: a pointer to an integer where to store the offset that 
2708  * may have been specified for the field in a FieldLayout table
2709  * @rva: a pointer to the RVA of the field data in the image that
2710  * may have been defined in a FieldRVA table
2711  * @marshal_spec: a pointer to the marshal spec that may have been 
2712  * defined for the field in a FieldMarshal table.
2713  *
2714  * Gather info for field @index that may have been defined in the FieldLayout, 
2715  * FieldRVA and FieldMarshal tables.
2716  * Either of offset, rva and marshal_spec can be NULL if you're not interested 
2717  * in the data.
2718  */
2719 void
2720 mono_metadata_field_info (MonoImage *meta, guint32 index, guint32 *offset, guint32 *rva, 
2721                           MonoMarshalSpec **marshal_spec)
2722 {
2723         MonoTableInfo *tdef;
2724         locator_t loc;
2725
2726         loc.idx = index + 1;
2727         if (offset) {
2728                 tdef = &meta->tables [MONO_TABLE_FIELDLAYOUT];
2729
2730                 loc.col_idx = MONO_FIELD_LAYOUT_FIELD;
2731                 loc.t = tdef;
2732
2733                 if (tdef->base && bsearch (&loc, tdef->base, tdef->rows, tdef->row_size, table_locator)) {
2734                         *offset = mono_metadata_decode_row_col (tdef, loc.result, MONO_FIELD_LAYOUT_OFFSET);
2735                 } else {
2736                         *offset = (guint32)-1;
2737                 }
2738         }
2739         if (rva) {
2740                 tdef = &meta->tables [MONO_TABLE_FIELDRVA];
2741
2742                 loc.col_idx = MONO_FIELD_RVA_FIELD;
2743                 loc.t = tdef;
2744                 
2745                 if (tdef->base && bsearch (&loc, tdef->base, tdef->rows, tdef->row_size, table_locator)) {
2746                         /*
2747                          * LAMESPEC: There is no signature, no nothing, just the raw data.
2748                          */
2749                         *rva = mono_metadata_decode_row_col (tdef, loc.result, MONO_FIELD_RVA_RVA);
2750                 } else {
2751                         *rva = 0;
2752                 }
2753         }
2754         if (marshal_spec) {
2755                 const char *p;
2756                 
2757                 if ((p = mono_metadata_get_marshal_info (meta, index, TRUE))) {
2758                         *marshal_spec = mono_metadata_parse_marshal_spec (meta, p);
2759                 }
2760         }
2761
2762 }
2763
2764 /*
2765  * mono_metadata_get_constant_index:
2766  * @meta: the Image the field is defined in
2767  * @index: the token that may have a row defined in the constants table
2768  * @hint: possible position for the row
2769  *
2770  * @token must be a FieldDef, ParamDef or PropertyDef token.
2771  *
2772  * Returns: the index into the Constants table or 0 if not found.
2773  */
2774 guint32
2775 mono_metadata_get_constant_index (MonoImage *meta, guint32 token, guint32 hint)
2776 {
2777         MonoTableInfo *tdef;
2778         locator_t loc;
2779         guint32 index = mono_metadata_token_index (token);
2780
2781         tdef = &meta->tables [MONO_TABLE_CONSTANT];
2782         index <<= MONO_HASCONSTANT_BITS;
2783         switch (mono_metadata_token_table (token)) {
2784         case MONO_TABLE_FIELD:
2785                 index |= MONO_HASCONSTANT_FIEDDEF;
2786                 break;
2787         case MONO_TABLE_PARAM:
2788                 index |= MONO_HASCONSTANT_PARAM;
2789                 break;
2790         case MONO_TABLE_PROPERTY:
2791                 index |= MONO_HASCONSTANT_PROPERTY;
2792                 break;
2793         default:
2794                 g_warning ("Not a valid token for the constant table: 0x%08x", token);
2795                 return 0;
2796         }
2797         loc.idx = index;
2798         loc.col_idx = MONO_CONSTANT_PARENT;
2799         loc.t = tdef;
2800
2801         if ((hint > 0) && (hint < tdef->rows) && (mono_metadata_decode_row_col (tdef, hint - 1, MONO_CONSTANT_PARENT) == index))
2802                 return hint;
2803
2804         if (tdef->base && bsearch (&loc, tdef->base, tdef->rows, tdef->row_size, table_locator)) {
2805                 return loc.result + 1;
2806         }
2807         return 0;
2808 }
2809
2810 /*
2811  * mono_metadata_events_from_typedef:
2812  * @meta: metadata context
2813  * @index: 0-based index (in the TypeDef table) describing a type
2814  *
2815  * Returns: the 0-based index in the Event table for the events in the
2816  * type. The last event that belongs to the type (plus 1) is stored
2817  * in the @end_idx pointer.
2818  */
2819 guint32
2820 mono_metadata_events_from_typedef (MonoImage *meta, guint32 index, guint *end_idx)
2821 {
2822         locator_t loc;
2823         guint32 start, end;
2824         MonoTableInfo *tdef  = &meta->tables [MONO_TABLE_EVENTMAP];
2825
2826         *end_idx = 0;
2827         
2828         if (!tdef->base)
2829                 return 0;
2830
2831         loc.t = tdef;
2832         loc.col_idx = MONO_EVENT_MAP_PARENT;
2833         loc.idx = index + 1;
2834
2835         if (!bsearch (&loc, tdef->base, tdef->rows, tdef->row_size, table_locator))
2836                 return 0;
2837         
2838         start = mono_metadata_decode_row_col (tdef, loc.result, MONO_EVENT_MAP_EVENTLIST);
2839         if (loc.result + 1 < tdef->rows) {
2840                 end = mono_metadata_decode_row_col (tdef, loc.result + 1, MONO_EVENT_MAP_EVENTLIST) - 1;
2841         } else {
2842                 end = meta->tables [MONO_TABLE_EVENT].rows;
2843         }
2844
2845         *end_idx = end;
2846         return start - 1;
2847 }
2848
2849 /*
2850  * mono_metadata_methods_from_event:
2851  * @meta: metadata context
2852  * @index: 0-based index (in the Event table) describing a event
2853  *
2854  * Returns: the 0-based index in the MethodDef table for the methods in the
2855  * event. The last method that belongs to the event (plus 1) is stored
2856  * in the @end_idx pointer.
2857  */
2858 guint32
2859 mono_metadata_methods_from_event   (MonoImage *meta, guint32 index, guint *end_idx)
2860 {
2861         locator_t loc;
2862         guint start, end;
2863         guint32 cols [MONO_METHOD_SEMA_SIZE];
2864         MonoTableInfo *msemt = &meta->tables [MONO_TABLE_METHODSEMANTICS];
2865
2866         *end_idx = 0;
2867         if (!msemt->base)
2868                 return 0;
2869
2870         loc.t = msemt;
2871         loc.col_idx = MONO_METHOD_SEMA_ASSOCIATION;
2872         loc.idx = ((index + 1) << MONO_HAS_SEMANTICS_BITS) | MONO_HAS_SEMANTICS_EVENT; /* Method association coded index */
2873
2874         if (!bsearch (&loc, msemt->base, msemt->rows, msemt->row_size, table_locator))
2875                 return 0;
2876
2877         start = loc.result;
2878         /*
2879          * We may end up in the middle of the rows... 
2880          */
2881         while (start > 0) {
2882                 if (loc.idx == mono_metadata_decode_row_col (msemt, start - 1, MONO_METHOD_SEMA_ASSOCIATION))
2883                         start--;
2884                 else
2885                         break;
2886         }
2887         end = start + 1;
2888         while (end < msemt->rows) {
2889                 mono_metadata_decode_row (msemt, end, cols, MONO_METHOD_SEMA_SIZE);
2890                 if (cols [MONO_METHOD_SEMA_ASSOCIATION] != loc.idx)
2891                         break;
2892                 ++end;
2893         }
2894         *end_idx = end;
2895         return start;
2896 }
2897
2898 /*
2899  * mono_metadata_properties_from_typedef:
2900  * @meta: metadata context
2901  * @index: 0-based index (in the TypeDef table) describing a type
2902  *
2903  * Returns: the 0-based index in the Property table for the properties in the
2904  * type. The last property that belongs to the type (plus 1) is stored
2905  * in the @end_idx pointer.
2906  */
2907 guint32
2908 mono_metadata_properties_from_typedef (MonoImage *meta, guint32 index, guint *end_idx)
2909 {
2910         locator_t loc;
2911         guint32 start, end;
2912         MonoTableInfo *tdef  = &meta->tables [MONO_TABLE_PROPERTYMAP];
2913
2914         *end_idx = 0;
2915         
2916         if (!tdef->base)
2917                 return 0;
2918
2919         loc.t = tdef;
2920         loc.col_idx = MONO_PROPERTY_MAP_PARENT;
2921         loc.idx = index + 1;
2922
2923         if (!bsearch (&loc, tdef->base, tdef->rows, tdef->row_size, table_locator))
2924                 return 0;
2925         
2926         start = mono_metadata_decode_row_col (tdef, loc.result, MONO_PROPERTY_MAP_PROPERTY_LIST);
2927         if (loc.result + 1 < tdef->rows) {
2928                 end = mono_metadata_decode_row_col (tdef, loc.result + 1, MONO_PROPERTY_MAP_PROPERTY_LIST) - 1;
2929         } else {
2930                 end = meta->tables [MONO_TABLE_PROPERTY].rows;
2931         }
2932
2933         *end_idx = end;
2934         return start - 1;
2935 }
2936
2937 /*
2938  * mono_metadata_methods_from_property:
2939  * @meta: metadata context
2940  * @index: 0-based index (in the PropertyDef table) describing a property
2941  *
2942  * Returns: the 0-based index in the MethodDef table for the methods in the
2943  * property. The last method that belongs to the property (plus 1) is stored
2944  * in the @end_idx pointer.
2945  */
2946 guint32
2947 mono_metadata_methods_from_property   (MonoImage *meta, guint32 index, guint *end_idx)
2948 {
2949         locator_t loc;
2950         guint start, end;
2951         guint32 cols [MONO_METHOD_SEMA_SIZE];
2952         MonoTableInfo *msemt = &meta->tables [MONO_TABLE_METHODSEMANTICS];
2953
2954         *end_idx = 0;
2955         if (!msemt->base)
2956                 return 0;
2957
2958         loc.t = msemt;
2959         loc.col_idx = MONO_METHOD_SEMA_ASSOCIATION;
2960         loc.idx = ((index + 1) << MONO_HAS_SEMANTICS_BITS) | MONO_HAS_SEMANTICS_PROPERTY; /* Method association coded index */
2961
2962         if (!bsearch (&loc, msemt->base, msemt->rows, msemt->row_size, table_locator))
2963                 return 0;
2964
2965         start = loc.result;
2966         /*
2967          * We may end up in the middle of the rows... 
2968          */
2969         while (start > 0) {
2970                 if (loc.idx == mono_metadata_decode_row_col (msemt, start - 1, MONO_METHOD_SEMA_ASSOCIATION))
2971                         start--;
2972                 else
2973                         break;
2974         }
2975         end = start + 1;
2976         while (end < msemt->rows) {
2977                 mono_metadata_decode_row (msemt, end, cols, MONO_METHOD_SEMA_SIZE);
2978                 if (cols [MONO_METHOD_SEMA_ASSOCIATION] != loc.idx)
2979                         break;
2980                 ++end;
2981         }
2982         *end_idx = end;
2983         return start;
2984 }
2985
2986 guint32
2987 mono_metadata_implmap_from_method (MonoImage *meta, guint32 method_idx)
2988 {
2989         locator_t loc;
2990         MonoTableInfo *tdef  = &meta->tables [MONO_TABLE_IMPLMAP];
2991
2992         if (!tdef->base)
2993                 return 0;
2994
2995         loc.t = tdef;
2996         loc.col_idx = MONO_IMPLMAP_MEMBER;
2997         loc.idx = ((method_idx + 1) << MONO_MEMBERFORWD_BITS) | MONO_MEMBERFORWD_METHODDEF;
2998
2999         if (!bsearch (&loc, tdef->base, tdef->rows, tdef->row_size, table_locator))
3000                 return 0;
3001
3002         return loc.result + 1;
3003 }
3004
3005 /**
3006  * @image: context where the image is created
3007  * @type_spec:  typespec token
3008  *
3009  * Creates a MonoType representing the TypeSpec indexed by the @type_spec
3010  * token.
3011  */
3012 MonoType *
3013 mono_type_create_from_typespec (MonoImage *image, guint32 type_spec)
3014 {
3015         guint32 idx = mono_metadata_token_index (type_spec);
3016         MonoTableInfo *t;
3017         guint32 cols [MONO_TYPESPEC_SIZE];       
3018         const char *ptr;
3019         guint32 len;
3020         MonoType *type;
3021
3022         mono_loader_lock ();
3023
3024         if ((type = g_hash_table_lookup (image->typespec_cache, GUINT_TO_POINTER (type_spec)))) {
3025                 mono_loader_unlock ();
3026                 return type;
3027         }
3028
3029         t = &image->tables [MONO_TABLE_TYPESPEC];
3030         
3031         mono_metadata_decode_row (t, idx-1, cols, MONO_TYPESPEC_SIZE);
3032         ptr = mono_metadata_blob_heap (image, cols [MONO_TYPESPEC_SIGNATURE]);
3033         len = mono_metadata_decode_value (ptr, &ptr);
3034
3035         type = g_new0 (MonoType, 1);
3036
3037         g_hash_table_insert (image->typespec_cache, GUINT_TO_POINTER (type_spec), type);
3038
3039         if (*ptr == MONO_TYPE_BYREF) {
3040                 type->byref = 1; 
3041                 ptr++;
3042         }
3043
3044         do_mono_metadata_parse_type (type, image, ptr, &ptr);
3045
3046         mono_loader_unlock ();
3047
3048         return type;
3049 }
3050
3051 MonoMarshalSpec *
3052 mono_metadata_parse_marshal_spec (MonoImage *image, const char *ptr)
3053 {
3054         MonoMarshalSpec *res;
3055         int len;
3056         const char *start = ptr;
3057
3058         /* fixme: this is incomplete, but I cant find more infos in the specs */
3059
3060         res = g_new0 (MonoMarshalSpec, 1);
3061         
3062         len = mono_metadata_decode_value (ptr, &ptr);
3063         res->native = *ptr++;
3064
3065         if (res->native == MONO_NATIVE_LPARRAY) {
3066                 if (ptr - start <= len)
3067                         res->data.array_data.elem_type = *ptr++;
3068                 if (ptr - start <= len)
3069                         res->data.array_data.param_num = mono_metadata_decode_value (ptr, &ptr);
3070                 if (ptr - start <= len)
3071                         res->data.array_data.num_elem = mono_metadata_decode_value (ptr, &ptr);
3072         } 
3073
3074         if (res->native == MONO_NATIVE_BYVALTSTR) {
3075                 if (ptr - start <= len)
3076                         res->data.array_data.num_elem = mono_metadata_decode_value (ptr, &ptr);
3077         }
3078
3079         if (res->native == MONO_NATIVE_BYVALARRAY) {
3080                 if (ptr - start <= len)
3081                         res->data.array_data.num_elem = mono_metadata_decode_value (ptr, &ptr);
3082         }
3083         
3084         if (res->native == MONO_NATIVE_CUSTOM) {
3085                 /* skip unused type guid */
3086                 len = mono_metadata_decode_value (ptr, &ptr);
3087                 ptr += len;
3088                 /* skip unused native type name */
3089                 len = mono_metadata_decode_value (ptr, &ptr);
3090                 ptr += len;
3091                 /* read custom marshaler type name */
3092                 len = mono_metadata_decode_value (ptr, &ptr);
3093                 res->data.custom_data.custom_name = g_strndup (ptr, len);               
3094                 ptr += len;
3095                 /* read cookie string */
3096                 len = mono_metadata_decode_value (ptr, &ptr);
3097                 res->data.custom_data.cookie = g_strndup (ptr, len);
3098         }
3099
3100         return res;
3101 }
3102
3103 void 
3104 mono_metadata_free_marshal_spec (MonoMarshalSpec *spec)
3105 {
3106         if (spec->native == MONO_NATIVE_CUSTOM) {
3107                 g_free (spec->data.custom_data.custom_name);
3108                 g_free (spec->data.custom_data.cookie);
3109         }
3110         g_free (spec);
3111 }
3112         
3113 guint32
3114 mono_type_to_unmanaged (MonoType *type, MonoMarshalSpec *mspec, gboolean as_field,
3115                         gboolean unicode, MonoMarshalConv *conv) 
3116 {
3117         MonoMarshalConv dummy_conv;
3118         int t = type->type;
3119
3120         if (!conv)
3121                 conv = &dummy_conv;
3122
3123         *conv = MONO_MARSHAL_CONV_NONE;
3124
3125         if (type->byref)
3126                 return MONO_NATIVE_UINT;
3127
3128 handle_enum:
3129         switch (t) {
3130         case MONO_TYPE_BOOLEAN: 
3131                 if (mspec) {
3132                         switch (mspec->native) {
3133                         case MONO_NATIVE_VARIANTBOOL:
3134                                 *conv = MONO_MARSHAL_CONV_BOOL_VARIANTBOOL;
3135                                 return MONO_NATIVE_VARIANTBOOL;
3136                         case MONO_NATIVE_BOOLEAN:
3137                                 *conv = MONO_MARSHAL_CONV_BOOL_I4;
3138                                 return MONO_NATIVE_BOOLEAN;
3139                         case MONO_NATIVE_I1:
3140                         case MONO_NATIVE_U1:
3141                                 return mspec->native;
3142                         default:
3143                                 g_error ("cant marshal bool to native type %02x", mspec->native);
3144                         }
3145                 }
3146                 *conv = MONO_MARSHAL_CONV_BOOL_I4;
3147                 return MONO_NATIVE_BOOLEAN;
3148         case MONO_TYPE_CHAR: return MONO_NATIVE_U2;
3149         case MONO_TYPE_I1: return MONO_NATIVE_I1;
3150         case MONO_TYPE_U1: return MONO_NATIVE_U1;
3151         case MONO_TYPE_I2: return MONO_NATIVE_I2;
3152         case MONO_TYPE_U2: return MONO_NATIVE_U2;
3153         case MONO_TYPE_I4: return MONO_NATIVE_I4;
3154         case MONO_TYPE_U4: return MONO_NATIVE_U4;
3155         case MONO_TYPE_I8: return MONO_NATIVE_I8;
3156         case MONO_TYPE_U8: return MONO_NATIVE_U8;
3157         case MONO_TYPE_R4: return MONO_NATIVE_R4;
3158         case MONO_TYPE_R8: return MONO_NATIVE_R8;
3159         case MONO_TYPE_STRING:
3160                 if (mspec) {
3161                         switch (mspec->native) {
3162                         case MONO_NATIVE_BSTR:
3163                                 *conv = MONO_MARSHAL_CONV_STR_BSTR;
3164                                 return MONO_NATIVE_BSTR;
3165                         case MONO_NATIVE_LPSTR:
3166                                 *conv = MONO_MARSHAL_CONV_STR_LPSTR;
3167                                 return MONO_NATIVE_LPSTR;
3168                         case MONO_NATIVE_LPWSTR:
3169                                 *conv = MONO_MARSHAL_CONV_STR_LPWSTR;
3170                                 return MONO_NATIVE_LPWSTR;
3171                         case MONO_NATIVE_LPTSTR:
3172                                 *conv = MONO_MARSHAL_CONV_STR_LPTSTR;
3173                                 return MONO_NATIVE_LPTSTR;
3174                         case MONO_NATIVE_ANSIBSTR:
3175                                 *conv = MONO_MARSHAL_CONV_STR_ANSIBSTR;
3176                                 return MONO_NATIVE_ANSIBSTR;
3177                         case MONO_NATIVE_TBSTR:
3178                                 *conv = MONO_MARSHAL_CONV_STR_TBSTR;
3179                                 return MONO_NATIVE_TBSTR;
3180                         case MONO_NATIVE_BYVALTSTR:
3181                                 if (unicode)
3182                                         *conv = MONO_MARSHAL_CONV_STR_BYVALWSTR;
3183                                 else
3184                                         *conv = MONO_MARSHAL_CONV_STR_BYVALSTR;
3185                                 return MONO_NATIVE_BYVALTSTR;
3186                         default:
3187                                 g_error ("cant marshal string to native type %02x", mspec->native);
3188                         }
3189                 }       
3190                 *conv = MONO_MARSHAL_CONV_STR_LPTSTR;
3191                 return MONO_NATIVE_LPTSTR; 
3192         case MONO_TYPE_PTR: return MONO_NATIVE_UINT;
3193         case MONO_TYPE_VALUETYPE: /*FIXME*/
3194                 if (type->data.klass->enumtype) {
3195                         t = type->data.klass->enum_basetype->type;
3196                         goto handle_enum;
3197                 }
3198                 return MONO_NATIVE_STRUCT;
3199         case MONO_TYPE_SZARRAY: 
3200         case MONO_TYPE_ARRAY: 
3201                 if (mspec) {
3202                         switch (mspec->native) {
3203                         case MONO_NATIVE_BYVALARRAY:
3204                                 *conv = MONO_MARSHAL_CONV_ARRAY_BYVALARRAY;
3205                                 return MONO_NATIVE_BYVALARRAY;
3206                         case MONO_NATIVE_SAFEARRAY:
3207                                 *conv = MONO_MARSHAL_CONV_ARRAY_SAVEARRAY;
3208                                 return MONO_NATIVE_SAFEARRAY;
3209                         case MONO_NATIVE_LPARRAY:                               
3210                                 *conv = MONO_MARSHAL_CONV_ARRAY_LPARRAY;
3211                                 return MONO_NATIVE_LPARRAY;
3212                         default:
3213                                 g_error ("cant marshal array as native type %02x", mspec->native);
3214                         }
3215                 }       
3216
3217                 *conv = MONO_MARSHAL_CONV_ARRAY_LPARRAY;
3218                 return MONO_NATIVE_LPARRAY;
3219         case MONO_TYPE_I: return MONO_NATIVE_INT;
3220         case MONO_TYPE_U: return MONO_NATIVE_UINT;
3221         case MONO_TYPE_CLASS: 
3222         case MONO_TYPE_OBJECT: {
3223                 /* FIXME : we need to handle ArrayList and StringBuilder here, probably */
3224                 if (mspec) {
3225                         switch (mspec->native) {
3226                         case MONO_NATIVE_STRUCT:
3227                                 return MONO_NATIVE_STRUCT;
3228                         case MONO_NATIVE_INTERFACE:
3229                                 *conv = MONO_MARSHAL_CONV_OBJECT_INTERFACE;
3230                                 return MONO_NATIVE_INTERFACE;
3231                         case MONO_NATIVE_IDISPATCH:
3232                                 *conv = MONO_MARSHAL_CONV_OBJECT_IDISPATCH;
3233                                 return MONO_NATIVE_IDISPATCH;
3234                         case MONO_NATIVE_IUNKNOWN:
3235                                 *conv = MONO_MARSHAL_CONV_OBJECT_IUNKNOWN;
3236                                 return MONO_NATIVE_IUNKNOWN;
3237                         case MONO_NATIVE_FUNC:
3238                                 if (t == MONO_TYPE_CLASS && (type->data.klass == mono_defaults.multicastdelegate_class ||
3239                                                                                          type->data.klass == mono_defaults.delegate_class || 
3240                                                                                          type->data.klass->parent == mono_defaults.multicastdelegate_class)) {
3241                                         *conv = MONO_MARSHAL_CONV_DEL_FTN;
3242                                         return MONO_NATIVE_FUNC;
3243                                 }
3244                                 else
3245                                         /* Fall through */
3246                                         ;
3247                         default:
3248                                 g_error ("cant marshal object as native type %02x", mspec->native);
3249                         }
3250                 }
3251                 if (t == MONO_TYPE_CLASS && (type->data.klass == mono_defaults.multicastdelegate_class ||
3252                                              type->data.klass == mono_defaults.delegate_class || 
3253                                              type->data.klass->parent == mono_defaults.multicastdelegate_class)) {
3254                         *conv = MONO_MARSHAL_CONV_DEL_FTN;
3255                         return MONO_NATIVE_FUNC;
3256                 }
3257                 *conv = MONO_MARSHAL_CONV_OBJECT_STRUCT;
3258                 return MONO_NATIVE_STRUCT;
3259         }
3260         case MONO_TYPE_FNPTR: return MONO_NATIVE_FUNC;
3261         case MONO_TYPE_TYPEDBYREF:
3262         default:
3263                 g_error ("type 0x%02x not handled in marshal", t);
3264         }
3265         return MONO_NATIVE_MAX;
3266 }
3267
3268 const char*
3269 mono_metadata_get_marshal_info (MonoImage *meta, guint32 idx, gboolean is_field)
3270 {
3271         locator_t loc;
3272         MonoTableInfo *tdef  = &meta->tables [MONO_TABLE_FIELDMARSHAL];
3273
3274         if (!tdef->base)
3275                 return NULL;
3276
3277         loc.t = tdef;
3278         loc.col_idx = MONO_FIELD_MARSHAL_PARENT;
3279         loc.idx = ((idx + 1) << MONO_HAS_FIELD_MARSHAL_BITS) | (is_field? MONO_HAS_FIELD_MARSHAL_FIELDSREF: MONO_HAS_FIELD_MARSHAL_PARAMDEF);
3280
3281         if (!bsearch (&loc, tdef->base, tdef->rows, tdef->row_size, table_locator))
3282                 return NULL;
3283
3284         return mono_metadata_blob_heap (meta, mono_metadata_decode_row_col (tdef, loc.result, MONO_FIELD_MARSHAL_NATIVE_TYPE));
3285 }
3286
3287 static MonoMethod*
3288 method_from_method_def_or_ref (MonoImage *m, guint32 tok)
3289 {
3290         guint32 idx = tok >> MONO_METHODDEFORREF_BITS;
3291         switch (tok & MONO_METHODDEFORREF_MASK) {
3292         case MONO_METHODDEFORREF_METHODDEF:
3293                 return mono_get_method (m, MONO_TOKEN_METHOD_DEF | idx, NULL);
3294         case MONO_METHODDEFORREF_METHODREF:
3295                 return mono_get_method (m, MONO_TOKEN_MEMBER_REF | idx, NULL);
3296         }
3297         g_assert_not_reached ();
3298         return NULL;
3299 }
3300
3301 MonoMethod**
3302 mono_class_get_overrides (MonoImage *image, guint32 type_token, gint32 *num_overrides)
3303 {
3304         locator_t loc;
3305         MonoTableInfo *tdef  = &image->tables [MONO_TABLE_METHODIMPL];
3306         guint32 start, end;
3307         gint32 i, num;
3308         guint32 cols [MONO_METHODIMPL_SIZE];
3309         MonoMethod **result;
3310
3311         if (num_overrides)
3312                 *num_overrides = 0;
3313
3314         if (!tdef->base)
3315                 return NULL;
3316
3317         loc.t = tdef;
3318         loc.col_idx = MONO_METHODIMPL_CLASS;
3319         loc.idx = mono_metadata_token_index (type_token);
3320
3321         if (!bsearch (&loc, tdef->base, tdef->rows, tdef->row_size, table_locator))
3322                 return NULL;
3323
3324         start = loc.result;
3325         end = start + 1;
3326         /*
3327          * We may end up in the middle of the rows... 
3328          */
3329         while (start > 0) {
3330                 if (loc.idx == mono_metadata_decode_row_col (tdef, start - 1, MONO_METHODIMPL_CLASS))
3331                         start--;
3332                 else
3333                         break;
3334         }
3335         while (end < tdef->rows) {
3336                 if (loc.idx == mono_metadata_decode_row_col (tdef, end, MONO_METHODIMPL_CLASS))
3337                         end++;
3338                 else
3339                         break;
3340         }
3341         num = end - start;
3342         result = g_new (MonoMethod*, num * 2);
3343         for (i = 0; i < num; ++i) {
3344                 mono_metadata_decode_row (tdef, start + i, cols, MONO_METHODIMPL_SIZE);
3345                 result [i * 2] = method_from_method_def_or_ref (image, cols [MONO_METHODIMPL_DECLARATION]);
3346                 result [i * 2 + 1] = method_from_method_def_or_ref (image, cols [MONO_METHODIMPL_BODY]);
3347         }
3348
3349         if (num_overrides)
3350                 *num_overrides = num;
3351         return result;
3352 }
3353
3354 /**
3355  * mono_guid_to_string:
3356  *
3357  * Converts a 16 byte Microsoft GUID to the standard string representation.
3358  */
3359 char *
3360 mono_guid_to_string (const guint8 *guid)
3361 {
3362         return g_strdup_printf ("%02X%02X%02X%02X-%02X%02X-%02X%02X-%02X%02X-%02X%02X%02X%02X%02X%02X", 
3363                                 guid[3], guid[2], guid[1], guid[0],
3364                                 guid[5], guid[4],
3365                                 guid[7], guid[6],
3366                                 guid[8], guid[9],
3367                                 guid[10], guid[11], guid[12], guid[13], guid[14], guid[15]);
3368 }
3369
3370 static MonoClass**
3371 get_constraints (MonoImage *image, int owner)
3372 {
3373         MonoTableInfo *tdef  = &image->tables [MONO_TABLE_GENERICPARAMCONSTRAINT];
3374         guint32 cols [MONO_GENPARCONSTRAINT_SIZE];
3375         guint32 i, token, found;
3376         MonoClass *klass, **res;
3377         GList *cons = NULL, *tmp;
3378         
3379
3380         found = 0;
3381         for (i = 0; i < tdef->rows; ++i) {
3382                 mono_metadata_decode_row (tdef, i, cols, MONO_GENPARCONSTRAINT_SIZE);
3383                 if (cols [MONO_GENPARCONSTRAINT_GENERICPAR] == owner) {
3384                         token = mono_metadata_token_from_dor (cols [MONO_GENPARCONSTRAINT_CONSTRAINT]);
3385                         klass = mono_class_get (image, token);
3386                         cons = g_list_append (cons, klass);
3387                         ++found;
3388                 } else {
3389                         /* contiguous list finished */
3390                         if (found)
3391                                 break;
3392                 }
3393         }
3394         if (!found)
3395                 return NULL;
3396         res = g_new0 (MonoClass*, found + 1);
3397         for (i = 0, tmp = cons; i < found; ++i, tmp = tmp->next) {
3398                 res [i] = tmp->data;
3399         }
3400         g_list_free (cons);
3401         return res;
3402 }
3403
3404 MonoGenericParam *
3405 mono_metadata_load_generic_params (MonoImage *image, guint32 token, guint32 *num)
3406 {
3407         MonoTableInfo *tdef  = &image->tables [MONO_TABLE_GENERICPARAM];
3408         guint32 cols [MONO_GENERICPARAM_SIZE];
3409         guint32 i, owner, last_num, n;
3410         MonoGenericParam *params;
3411
3412         if (mono_metadata_token_table (token) == MONO_TABLE_TYPEDEF)
3413                 owner = MONO_TYPEORMETHOD_TYPE;
3414         else if (mono_metadata_token_table (token) == MONO_TABLE_METHOD)
3415                 owner = MONO_TYPEORMETHOD_METHOD;
3416         else {
3417                 g_error ("wrong token %x to load_generics_params", token);
3418         }
3419         owner |= mono_metadata_token_index (token) << MONO_TYPEORMETHOD_BITS;
3420         if (num)
3421                 *num = 0;
3422         if (!tdef->base)
3423                 return NULL;
3424
3425         for (i = 0; i < tdef->rows; ++i) {
3426                 mono_metadata_decode_row (tdef, i, cols, MONO_GENERICPARAM_SIZE);
3427                 if (cols [MONO_GENERICPARAM_OWNER] == owner)
3428                         break;
3429         }
3430         last_num = 0;
3431         if (i >= tdef->rows)
3432                 return NULL;
3433         params = NULL;
3434         n = 0;
3435         do {
3436                 n++;
3437                 params = g_realloc (params, sizeof (MonoGenericParam) * n);
3438                 params [n - 1].pklass = NULL;
3439                 params [n - 1].method = NULL;
3440                 params [n - 1].flags = cols [MONO_GENERICPARAM_FLAGS];
3441                 params [n - 1].num = cols [MONO_GENERICPARAM_NUMBER];
3442                 params [n - 1].name = mono_metadata_string_heap (image, cols [MONO_GENERICPARAM_NAME]);
3443                 params [n - 1].constraints = get_constraints (image, i + 1);
3444                 if (++i >= tdef->rows)
3445                         break;
3446                 mono_metadata_decode_row (tdef, i, cols, MONO_GENERICPARAM_SIZE);
3447         } while (cols [MONO_GENERICPARAM_OWNER] == owner);
3448         
3449         if (num)
3450                 *num = n;
3451         return params;
3452 }
3453
3454 gboolean
3455 mono_type_is_byref (MonoType *type)
3456 {
3457         return type->byref;
3458 }
3459
3460 int
3461 mono_type_get_type (MonoType *type)
3462 {
3463         return type->type;
3464 }
3465
3466 /* For MONO_TYPE_FNPTR */
3467 MonoMethodSignature*
3468 mono_type_get_signature (MonoType *type)
3469 {
3470         return type->data.method;
3471 }
3472
3473 /* For MONO_TYPE_CLASS, VALUETYPE */
3474 MonoClass*
3475 mono_type_get_class (MonoType *type)
3476 {
3477         return type->data.klass;
3478 }
3479
3480 /* For MONO_TYPE_ARRAY */
3481 MonoArrayType*
3482 mono_type_get_array_type (MonoType *type)
3483 {
3484         return type->data.array;
3485 }
3486
3487 MonoClass*
3488 mono_type_get_modifiers (MonoType *type, gboolean *is_required, gpointer *iter)
3489 {
3490         /* FIXME: implement */
3491         return NULL;
3492 }
3493
3494 MonoType*
3495 mono_signature_get_return_type (MonoMethodSignature *sig)
3496 {
3497         return sig->ret;
3498 }
3499
3500 MonoType*
3501 mono_signature_get_params (MonoMethodSignature *sig, gpointer *iter)
3502 {
3503         MonoType** type;
3504         if (!iter)
3505                 return NULL;
3506         if (!*iter) {
3507                 /* start from the first */
3508                 if (sig->param_count) {
3509                         *iter = &sig->params [0];
3510                         return sig->params [0];
3511                 } else {
3512                         /* no method */
3513                         return NULL;
3514                 }
3515         }
3516         type = *iter;
3517         type++;
3518         if (type < &sig->params [sig->param_count]) {
3519                 *iter = type;
3520                 return *type;
3521         }
3522         return NULL;
3523 }
3524
3525 guint32
3526 mono_signature_get_param_count (MonoMethodSignature *sig)
3527 {
3528         return sig->param_count;
3529 }
3530
3531 guint32
3532 mono_signature_get_call_conv (MonoMethodSignature *sig)
3533 {
3534         return sig->call_convention;
3535 }
3536
3537 int
3538 mono_signature_vararg_start (MonoMethodSignature *sig)
3539 {
3540         return sig->sentinelpos;
3541 }
3542
3543 gboolean
3544 mono_signature_is_instance (MonoMethodSignature *sig)
3545 {
3546         return sig->hasthis;
3547 }
3548
3549 gboolean
3550 mono_signature_explicit_this (MonoMethodSignature *sig)
3551 {
3552         return sig->explicit_this;
3553 }
3554