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