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