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