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