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