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