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