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