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