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