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