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