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