Merge pull request #5303 from lambdageek/cattr-bcheck
[mono.git] / mono / metadata / metadata.c
1 /**
2  * \file
3  * Routines for accessing the metadata
4  *
5  * Authors:
6  *   Miguel de Icaza (miguel@ximian.com)
7  *   Paolo Molaro (lupus@ximian.com)
8  *
9  * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
10  * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
11  * Licensed under the MIT license. See LICENSE file in the project root for full license information.
12  */
13
14 #include <config.h>
15 #include <stdio.h>
16 #include <stdlib.h>
17 #include <string.h>
18 #include <glib.h>
19 #include "metadata.h"
20 #include "tabledefs.h"
21 #include "mono-endian.h"
22 #include "cil-coff.h"
23 #include "tokentype.h"
24 #include "class-internals.h"
25 #include "metadata-internals.h"
26 #include "verify-internals.h"
27 #include "class.h"
28 #include "marshal.h"
29 #include "debug-helpers.h"
30 #include "abi-details.h"
31 #include <mono/utils/mono-error-internals.h>
32 #include <mono/utils/bsearch.h>
33 #include <mono/utils/atomic.h>
34 #include <mono/utils/mono-counters.h>
35
36 static int img_set_cache_hit, img_set_cache_miss, img_set_count;
37
38
39 /* Auxiliary structure used for caching inflated signatures */
40 typedef struct {
41         MonoMethodSignature *sig;
42         MonoGenericContext context;
43 } MonoInflatedMethodSignature;
44
45 static gboolean do_mono_metadata_parse_type (MonoType *type, MonoImage *m, MonoGenericContainer *container, gboolean transient,
46                                          const char *ptr, const char **rptr, MonoError *error);
47
48 static gboolean do_mono_metadata_type_equal (MonoType *t1, MonoType *t2, gboolean signature_only);
49 static gboolean mono_metadata_class_equal (MonoClass *c1, MonoClass *c2, gboolean signature_only);
50 static gboolean mono_metadata_fnptr_equal (MonoMethodSignature *s1, MonoMethodSignature *s2, gboolean signature_only);
51 static gboolean _mono_metadata_generic_class_equal (const MonoGenericClass *g1, const MonoGenericClass *g2,
52                                                     gboolean signature_only);
53 static void free_generic_inst (MonoGenericInst *ginst);
54 static void free_generic_class (MonoGenericClass *ginst);
55 static void free_inflated_method (MonoMethodInflated *method);
56 static void free_inflated_signature (MonoInflatedMethodSignature *sig);
57 static void mono_metadata_field_info_full (MonoImage *meta, guint32 index, guint32 *offset, guint32 *rva, MonoMarshalSpec **marshal_spec, gboolean alloc_from_image);
58
59 /*
60  * This enumeration is used to describe the data types in the metadata
61  * tables
62  */
63 enum {
64         MONO_MT_END,
65
66         /* Sized elements */
67         MONO_MT_UINT32,
68         MONO_MT_UINT16,
69         MONO_MT_UINT8,
70
71         /* Index into Blob heap */
72         MONO_MT_BLOB_IDX,
73
74         /* Index into String heap */
75         MONO_MT_STRING_IDX,
76
77         /* GUID index */
78         MONO_MT_GUID_IDX,
79
80         /* Pointer into a table */
81         MONO_MT_TABLE_IDX,
82
83         /* HasConstant:Parent pointer (Param, Field or Property) */
84         MONO_MT_CONST_IDX,
85
86         /* HasCustomAttribute index.  Indexes any table except CustomAttribute */
87         MONO_MT_HASCAT_IDX,
88         
89         /* CustomAttributeType encoded index */
90         MONO_MT_CAT_IDX,
91
92         /* HasDeclSecurity index: TypeDef Method or Assembly */
93         MONO_MT_HASDEC_IDX,
94
95         /* Implementation coded index: File, Export AssemblyRef */
96         MONO_MT_IMPL_IDX,
97
98         /* HasFieldMarshal coded index: Field or Param table */
99         MONO_MT_HFM_IDX,
100
101         /* MemberForwardedIndex: Field or Method */
102         MONO_MT_MF_IDX,
103
104         /* TypeDefOrRef coded index: typedef, typeref, typespec */
105         MONO_MT_TDOR_IDX,
106
107         /* MemberRefParent coded index: typeref, moduleref, method, memberref, typesepc, typedef */
108         MONO_MT_MRP_IDX,
109
110         /* MethodDefOrRef coded index: Method or Member Ref table */
111         MONO_MT_MDOR_IDX,
112
113         /* HasSemantic coded index: Event or Property */
114         MONO_MT_HS_IDX,
115
116         /* ResolutionScope coded index: Module, ModuleRef, AssemblytRef, TypeRef */
117         MONO_MT_RS_IDX,
118
119         /* CustomDebugInformation parent encoded index */
120         MONO_MT_HASCUSTDEBUG_IDX
121 };
122
123 const static unsigned char TableSchemas [] = {
124 #define ASSEMBLY_SCHEMA_OFFSET 0
125         MONO_MT_UINT32,     /* "HashId" }, */
126         MONO_MT_UINT16,     /* "Major" },  */
127         MONO_MT_UINT16,     /* "Minor" }, */
128         MONO_MT_UINT16,     /* "BuildNumber" }, */
129         MONO_MT_UINT16,     /* "RevisionNumber" }, */
130         MONO_MT_UINT32,     /* "Flags" }, */
131         MONO_MT_BLOB_IDX,   /* "PublicKey" }, */
132         MONO_MT_STRING_IDX, /* "Name" }, */
133         MONO_MT_STRING_IDX, /* "Culture" }, */
134         MONO_MT_END,
135
136 #define ASSEMBLYOS_SCHEMA_OFFSET ASSEMBLY_SCHEMA_OFFSET + 10
137         MONO_MT_UINT32,     /* "OSPlatformID" }, */
138         MONO_MT_UINT32,     /* "OSMajor" }, */
139         MONO_MT_UINT32,     /* "OSMinor" }, */
140         MONO_MT_END,
141
142 #define ASSEMBLYPROC_SCHEMA_OFFSET ASSEMBLYOS_SCHEMA_OFFSET + 4
143         MONO_MT_UINT32,     /* "Processor" }, */
144         MONO_MT_END,
145
146 #define ASSEMBLYREF_SCHEMA_OFFSET ASSEMBLYPROC_SCHEMA_OFFSET + 2
147         MONO_MT_UINT16,     /* "Major" }, */
148         MONO_MT_UINT16,     /* "Minor" }, */
149         MONO_MT_UINT16,     /* "Build" }, */
150         MONO_MT_UINT16,     /* "Revision" }, */
151         MONO_MT_UINT32,     /* "Flags" }, */
152         MONO_MT_BLOB_IDX,   /* "PublicKeyOrToken" }, */
153         MONO_MT_STRING_IDX, /* "Name" }, */
154         MONO_MT_STRING_IDX, /* "Culture" }, */
155         MONO_MT_BLOB_IDX,   /* "HashValue" }, */
156         MONO_MT_END,
157
158 #define ASSEMBLYREFOS_SCHEMA_OFFSET ASSEMBLYREF_SCHEMA_OFFSET + 10
159         MONO_MT_UINT32,     /* "OSPlatformID" }, */
160         MONO_MT_UINT32,     /* "OSMajorVersion" }, */
161         MONO_MT_UINT32,     /* "OSMinorVersion" }, */
162         MONO_MT_TABLE_IDX,  /* "AssemblyRef:AssemblyRef" }, */
163         MONO_MT_END,
164
165 #define ASSEMBLYREFPROC_SCHEMA_OFFSET ASSEMBLYREFOS_SCHEMA_OFFSET + 5
166         MONO_MT_UINT32,     /* "Processor" }, */
167         MONO_MT_TABLE_IDX,  /* "AssemblyRef:AssemblyRef" }, */
168         MONO_MT_END,
169
170 #define CLASS_LAYOUT_SCHEMA_OFFSET ASSEMBLYREFPROC_SCHEMA_OFFSET + 3
171         MONO_MT_UINT16,     /* "PackingSize" }, */
172         MONO_MT_UINT32,     /* "ClassSize" }, */
173         MONO_MT_TABLE_IDX,  /* "Parent:TypeDef" }, */
174         MONO_MT_END,
175
176 #define CONSTANT_SCHEMA_OFFSET CLASS_LAYOUT_SCHEMA_OFFSET + 4
177         MONO_MT_UINT8,      /* "Type" }, */
178         MONO_MT_UINT8,      /* "PaddingZero" }, */
179         MONO_MT_CONST_IDX,  /* "Parent" }, */
180         MONO_MT_BLOB_IDX,   /* "Value" }, */
181         MONO_MT_END,
182
183 #define CUSTOM_ATTR_SCHEMA_OFFSET CONSTANT_SCHEMA_OFFSET + 5
184         MONO_MT_HASCAT_IDX, /* "Parent" }, */
185         MONO_MT_CAT_IDX,    /* "Type" }, */
186         MONO_MT_BLOB_IDX,   /* "Value" }, */
187         MONO_MT_END,
188
189 #define DECL_SEC_SCHEMA_OFFSET CUSTOM_ATTR_SCHEMA_OFFSET + 4
190         MONO_MT_UINT16,     /* "Action" }, */
191         MONO_MT_HASDEC_IDX, /* "Parent" }, */
192         MONO_MT_BLOB_IDX,   /* "PermissionSet" }, */
193         MONO_MT_END,
194
195 #define EVENTMAP_SCHEMA_OFFSET DECL_SEC_SCHEMA_OFFSET + 4
196         MONO_MT_TABLE_IDX,  /* "Parent:TypeDef" }, */
197         MONO_MT_TABLE_IDX,  /* "EventList:Event" }, */
198         MONO_MT_END,
199
200 #define EVENT_SCHEMA_OFFSET EVENTMAP_SCHEMA_OFFSET + 3
201         MONO_MT_UINT16,     /* "EventFlags#EventAttribute" }, */
202         MONO_MT_STRING_IDX, /* "Name" }, */
203         MONO_MT_TDOR_IDX,  /* "EventType" }, TypeDef or TypeRef or TypeSpec  */
204         MONO_MT_END,
205
206 #define EVENT_POINTER_SCHEMA_OFFSET EVENT_SCHEMA_OFFSET + 4
207         MONO_MT_TABLE_IDX,  /* "Event" }, */
208         MONO_MT_END,
209
210 #define EXPORTED_TYPE_SCHEMA_OFFSET EVENT_POINTER_SCHEMA_OFFSET + 2
211         MONO_MT_UINT32,     /* "Flags" }, */
212         MONO_MT_TABLE_IDX,  /* "TypeDefId" }, */
213         MONO_MT_STRING_IDX, /* "TypeName" }, */
214         MONO_MT_STRING_IDX, /* "TypeNameSpace" }, */
215         MONO_MT_IMPL_IDX,   /* "Implementation" }, */
216         MONO_MT_END,
217
218 #define FIELD_SCHEMA_OFFSET EXPORTED_TYPE_SCHEMA_OFFSET + 6
219         MONO_MT_UINT16,     /* "Flags" }, */
220         MONO_MT_STRING_IDX, /* "Name" }, */
221         MONO_MT_BLOB_IDX,   /* "Signature" }, */
222         MONO_MT_END,
223
224 #define FIELD_LAYOUT_SCHEMA_OFFSET FIELD_SCHEMA_OFFSET + 4
225         MONO_MT_UINT32,     /* "Offset" }, */
226         MONO_MT_TABLE_IDX,  /* "Field:Field" }, */
227         MONO_MT_END,
228
229 #define FIELD_MARSHAL_SCHEMA_OFFSET FIELD_LAYOUT_SCHEMA_OFFSET + 3
230         MONO_MT_HFM_IDX,    /* "Parent" }, */
231         MONO_MT_BLOB_IDX,   /* "NativeType" }, */
232         MONO_MT_END,
233
234 #define FIELD_RVA_SCHEMA_OFFSET FIELD_MARSHAL_SCHEMA_OFFSET + 3
235         MONO_MT_UINT32,     /* "RVA" }, */
236         MONO_MT_TABLE_IDX,  /* "Field:Field" }, */
237         MONO_MT_END,
238
239 #define FIELD_POINTER_SCHEMA_OFFSET FIELD_RVA_SCHEMA_OFFSET + 3
240         MONO_MT_TABLE_IDX,  /* "Field" }, */
241         MONO_MT_END,
242
243 #define FILE_SCHEMA_OFFSET FIELD_POINTER_SCHEMA_OFFSET + 2
244         MONO_MT_UINT32,     /* "Flags" }, */
245         MONO_MT_STRING_IDX, /* "Name" }, */
246         MONO_MT_BLOB_IDX,   /* "Value" },  */
247         MONO_MT_END,
248
249 #define IMPLMAP_SCHEMA_OFFSET FILE_SCHEMA_OFFSET + 4
250         MONO_MT_UINT16,     /* "MappingFlag" }, */
251         MONO_MT_MF_IDX,     /* "MemberForwarded" }, */
252         MONO_MT_STRING_IDX, /* "ImportName" }, */
253         MONO_MT_TABLE_IDX,  /* "ImportScope:ModuleRef" }, */
254         MONO_MT_END,
255
256 #define IFACEMAP_SCHEMA_OFFSET IMPLMAP_SCHEMA_OFFSET + 5
257         MONO_MT_TABLE_IDX,  /* "Class:TypeDef" },  */
258         MONO_MT_TDOR_IDX,  /* "Interface=TypeDefOrRef" }, */
259         MONO_MT_END,
260
261 #define MANIFEST_SCHEMA_OFFSET IFACEMAP_SCHEMA_OFFSET + 3
262         MONO_MT_UINT32,     /* "Offset" }, */
263         MONO_MT_UINT32,     /* "Flags" }, */
264         MONO_MT_STRING_IDX, /* "Name" }, */
265         MONO_MT_IMPL_IDX,   /* "Implementation" }, */
266         MONO_MT_END,
267
268 #define MEMBERREF_SCHEMA_OFFSET MANIFEST_SCHEMA_OFFSET + 5
269         MONO_MT_MRP_IDX,    /* "Class" }, */
270         MONO_MT_STRING_IDX, /* "Name" }, */
271         MONO_MT_BLOB_IDX,   /* "Signature" }, */
272         MONO_MT_END,
273
274 #define METHOD_SCHEMA_OFFSET MEMBERREF_SCHEMA_OFFSET + 4
275         MONO_MT_UINT32,     /* "RVA" }, */
276         MONO_MT_UINT16,     /* "ImplFlags#MethodImplAttributes" }, */
277         MONO_MT_UINT16,     /* "Flags#MethodAttribute" }, */
278         MONO_MT_STRING_IDX, /* "Name" }, */
279         MONO_MT_BLOB_IDX,   /* "Signature" }, */
280         MONO_MT_TABLE_IDX,  /* "ParamList:Param" }, */
281         MONO_MT_END,
282
283 #define METHOD_IMPL_SCHEMA_OFFSET METHOD_SCHEMA_OFFSET + 7
284         MONO_MT_TABLE_IDX,  /* "Class:TypeDef" }, */
285         MONO_MT_MDOR_IDX,   /* "MethodBody" }, */
286         MONO_MT_MDOR_IDX,   /* "MethodDeclaration" }, */
287         MONO_MT_END,
288
289 #define METHOD_SEMA_SCHEMA_OFFSET METHOD_IMPL_SCHEMA_OFFSET + 4
290         MONO_MT_UINT16,     /* "MethodSemantic" }, */
291         MONO_MT_TABLE_IDX,  /* "Method:Method" }, */
292         MONO_MT_HS_IDX,     /* "Association" }, */
293         MONO_MT_END,
294
295 #define METHOD_POINTER_SCHEMA_OFFSET METHOD_SEMA_SCHEMA_OFFSET + 4
296         MONO_MT_TABLE_IDX,  /* "Method" }, */
297         MONO_MT_END,
298
299 #define MODULE_SCHEMA_OFFSET METHOD_POINTER_SCHEMA_OFFSET + 2
300         MONO_MT_UINT16,     /* "Generation" }, */
301         MONO_MT_STRING_IDX, /* "Name" }, */
302         MONO_MT_GUID_IDX,   /* "MVID" }, */
303         MONO_MT_GUID_IDX,   /* "EncID" }, */
304         MONO_MT_GUID_IDX,   /* "EncBaseID" }, */
305         MONO_MT_END,
306
307 #define MODULEREF_SCHEMA_OFFSET MODULE_SCHEMA_OFFSET + 6
308         MONO_MT_STRING_IDX, /* "Name" }, */
309         MONO_MT_END,
310
311 #define NESTED_CLASS_SCHEMA_OFFSET MODULEREF_SCHEMA_OFFSET + 2
312         MONO_MT_TABLE_IDX,  /* "NestedClass:TypeDef" }, */
313         MONO_MT_TABLE_IDX,  /* "EnclosingClass:TypeDef" }, */
314         MONO_MT_END,
315
316 #define PARAM_SCHEMA_OFFSET NESTED_CLASS_SCHEMA_OFFSET + 3
317         MONO_MT_UINT16,     /* "Flags" }, */
318         MONO_MT_UINT16,     /* "Sequence" }, */
319         MONO_MT_STRING_IDX, /* "Name" }, */
320         MONO_MT_END,
321
322 #define PARAM_POINTER_SCHEMA_OFFSET PARAM_SCHEMA_OFFSET + 4
323         MONO_MT_TABLE_IDX,  /* "Param" }, */
324         MONO_MT_END,
325
326 #define PROPERTY_SCHEMA_OFFSET PARAM_POINTER_SCHEMA_OFFSET + 2
327         MONO_MT_UINT16,     /* "Flags" }, */
328         MONO_MT_STRING_IDX, /* "Name" }, */
329         MONO_MT_BLOB_IDX,   /* "Type" }, */
330         MONO_MT_END,
331
332 #define PROPERTY_POINTER_SCHEMA_OFFSET PROPERTY_SCHEMA_OFFSET + 4
333         MONO_MT_TABLE_IDX, /* "Property" }, */
334         MONO_MT_END,
335
336 #define PROPERTY_MAP_SCHEMA_OFFSET PROPERTY_POINTER_SCHEMA_OFFSET + 2
337         MONO_MT_TABLE_IDX,  /* "Parent:TypeDef" }, */
338         MONO_MT_TABLE_IDX,  /* "PropertyList:Property" }, */
339         MONO_MT_END,
340
341 #define STDALON_SIG_SCHEMA_OFFSET PROPERTY_MAP_SCHEMA_OFFSET + 3
342         MONO_MT_BLOB_IDX,   /* "Signature" }, */
343         MONO_MT_END,
344
345 #define TYPEDEF_SCHEMA_OFFSET STDALON_SIG_SCHEMA_OFFSET + 2
346         MONO_MT_UINT32,     /* "Flags" }, */
347         MONO_MT_STRING_IDX, /* "Name" }, */
348         MONO_MT_STRING_IDX, /* "Namespace" }, */
349         MONO_MT_TDOR_IDX,   /* "Extends" }, */
350         MONO_MT_TABLE_IDX,  /* "FieldList:Field" }, */
351         MONO_MT_TABLE_IDX,  /* "MethodList:Method" }, */
352         MONO_MT_END,
353
354 #define TYPEREF_SCHEMA_OFFSET TYPEDEF_SCHEMA_OFFSET + 7
355         MONO_MT_RS_IDX,     /* "ResolutionScope=ResolutionScope" }, */
356         MONO_MT_STRING_IDX, /* "Name" }, */
357         MONO_MT_STRING_IDX, /* "Namespace" }, */
358         MONO_MT_END,
359
360 #define TYPESPEC_SCHEMA_OFFSET TYPEREF_SCHEMA_OFFSET + 4
361         MONO_MT_BLOB_IDX,   /* "Signature" }, */
362         MONO_MT_END,
363
364 #define GENPARAM_SCHEMA_OFFSET TYPESPEC_SCHEMA_OFFSET + 2
365         MONO_MT_UINT16,     /* "Number" }, */
366         MONO_MT_UINT16,     /* "Flags" }, */
367         MONO_MT_TABLE_IDX,  /* "Owner" },  TypeDef or MethodDef */
368         MONO_MT_STRING_IDX, /* "Name" }, */
369         MONO_MT_END,
370
371 #define METHOD_SPEC_SCHEMA_OFFSET GENPARAM_SCHEMA_OFFSET + 5
372         MONO_MT_MDOR_IDX,   /* "Method" }, */
373         MONO_MT_BLOB_IDX,   /* "Signature" }, */
374         MONO_MT_END,
375
376 #define GEN_CONSTRAINT_SCHEMA_OFFSET METHOD_SPEC_SCHEMA_OFFSET + 3
377         MONO_MT_TABLE_IDX,  /* "GenericParam" }, */
378         MONO_MT_TDOR_IDX,   /* "Constraint" }, */
379         MONO_MT_END,
380
381 #define DOCUMENT_SCHEMA_OFFSET GEN_CONSTRAINT_SCHEMA_OFFSET + 3
382         MONO_MT_BLOB_IDX,   /* Name */
383         MONO_MT_GUID_IDX,   /* HashAlgorithm */
384         MONO_MT_BLOB_IDX,   /* Hash */
385         MONO_MT_GUID_IDX,   /* Language */
386         MONO_MT_END,
387
388 #define METHODBODY_SCHEMA_OFFSET DOCUMENT_SCHEMA_OFFSET + 5
389         MONO_MT_TABLE_IDX,   /* Document */
390         MONO_MT_BLOB_IDX,   /* SequencePoints */
391         MONO_MT_END,
392
393 #define LOCALSCOPE_SCHEMA_OFFSET METHODBODY_SCHEMA_OFFSET + 3
394         MONO_MT_TABLE_IDX,   /* Method */
395         MONO_MT_TABLE_IDX,   /* ImportScope */
396         MONO_MT_TABLE_IDX,   /* VariableList */
397         MONO_MT_TABLE_IDX,   /* ConstantList */
398         MONO_MT_UINT32,      /* StartOffset */
399         MONO_MT_UINT32,      /* Length */
400         MONO_MT_END,
401
402 #define LOCALVARIABLE_SCHEMA_OFFSET LOCALSCOPE_SCHEMA_OFFSET + 7
403         MONO_MT_UINT16,      /* Attributes */
404         MONO_MT_UINT16,      /* Index */
405         MONO_MT_STRING_IDX,  /* Name */
406         MONO_MT_END,
407
408 #define LOCALCONSTANT_SCHEMA_OFFSET LOCALVARIABLE_SCHEMA_OFFSET + 4
409         MONO_MT_STRING_IDX,  /* Name (String heap index) */
410         MONO_MT_BLOB_IDX,    /* Signature (Blob heap index, LocalConstantSig blob) */
411         MONO_MT_END,
412
413 #define IMPORTSCOPE_SCHEMA_OFFSET LOCALCONSTANT_SCHEMA_OFFSET + 3
414         MONO_MT_TABLE_IDX, /* Parent (ImportScope row id or nil) */
415         MONO_MT_BLOB_IDX,  /* Imports (Blob index, encoding: Imports blob) */
416         MONO_MT_END,
417
418 #define ASYNCMETHOD_SCHEMA_OFFSET IMPORTSCOPE_SCHEMA_OFFSET + 3
419         MONO_MT_TABLE_IDX, /* MoveNextMethod (MethodDef row id) */
420         MONO_MT_TABLE_IDX, /* KickoffMethod (MethodDef row id) */
421         MONO_MT_END,
422
423 #define CUSTOMDEBUGINFORMATION_SCHEMA_OFFSET ASYNCMETHOD_SCHEMA_OFFSET + 3
424         MONO_MT_HASCUSTDEBUG_IDX, /* Parent (HasCustomDebugInformation coded index) */
425         MONO_MT_GUID_IDX,  /* Kind (Guid heap index) */
426         MONO_MT_BLOB_IDX,  /* Value (Blob heap index) */
427         MONO_MT_END,
428
429 #define NULL_SCHEMA_OFFSET CUSTOMDEBUGINFORMATION_SCHEMA_OFFSET + 4
430         MONO_MT_END
431 };
432
433 /* Must be the same order as MONO_TABLE_* */
434 const static unsigned char
435 table_description [] = {
436         MODULE_SCHEMA_OFFSET,
437         TYPEREF_SCHEMA_OFFSET,
438         TYPEDEF_SCHEMA_OFFSET,
439         FIELD_POINTER_SCHEMA_OFFSET,
440         FIELD_SCHEMA_OFFSET,
441         METHOD_POINTER_SCHEMA_OFFSET,
442         METHOD_SCHEMA_OFFSET,
443         PARAM_POINTER_SCHEMA_OFFSET,
444         PARAM_SCHEMA_OFFSET,
445         IFACEMAP_SCHEMA_OFFSET,
446         MEMBERREF_SCHEMA_OFFSET, /* 0xa */
447         CONSTANT_SCHEMA_OFFSET,
448         CUSTOM_ATTR_SCHEMA_OFFSET,
449         FIELD_MARSHAL_SCHEMA_OFFSET,
450         DECL_SEC_SCHEMA_OFFSET,
451         CLASS_LAYOUT_SCHEMA_OFFSET,
452         FIELD_LAYOUT_SCHEMA_OFFSET, /* 0x10 */
453         STDALON_SIG_SCHEMA_OFFSET,
454         EVENTMAP_SCHEMA_OFFSET,
455         EVENT_POINTER_SCHEMA_OFFSET,
456         EVENT_SCHEMA_OFFSET,
457         PROPERTY_MAP_SCHEMA_OFFSET,
458         PROPERTY_POINTER_SCHEMA_OFFSET,
459         PROPERTY_SCHEMA_OFFSET,
460         METHOD_SEMA_SCHEMA_OFFSET,
461         METHOD_IMPL_SCHEMA_OFFSET,
462         MODULEREF_SCHEMA_OFFSET, /* 0x1a */
463         TYPESPEC_SCHEMA_OFFSET,
464         IMPLMAP_SCHEMA_OFFSET,
465         FIELD_RVA_SCHEMA_OFFSET,
466         NULL_SCHEMA_OFFSET,
467         NULL_SCHEMA_OFFSET,
468         ASSEMBLY_SCHEMA_OFFSET, /* 0x20 */
469         ASSEMBLYPROC_SCHEMA_OFFSET,
470         ASSEMBLYOS_SCHEMA_OFFSET,
471         ASSEMBLYREF_SCHEMA_OFFSET,
472         ASSEMBLYREFPROC_SCHEMA_OFFSET,
473         ASSEMBLYREFOS_SCHEMA_OFFSET,
474         FILE_SCHEMA_OFFSET,
475         EXPORTED_TYPE_SCHEMA_OFFSET,
476         MANIFEST_SCHEMA_OFFSET,
477         NESTED_CLASS_SCHEMA_OFFSET,
478         GENPARAM_SCHEMA_OFFSET, /* 0x2a */
479         METHOD_SPEC_SCHEMA_OFFSET,
480         GEN_CONSTRAINT_SCHEMA_OFFSET,
481         NULL_SCHEMA_OFFSET,
482         NULL_SCHEMA_OFFSET,
483         NULL_SCHEMA_OFFSET,
484         DOCUMENT_SCHEMA_OFFSET, /* 0x30 */
485         METHODBODY_SCHEMA_OFFSET,
486         LOCALSCOPE_SCHEMA_OFFSET,
487         LOCALVARIABLE_SCHEMA_OFFSET,
488         LOCALCONSTANT_SCHEMA_OFFSET,
489         IMPORTSCOPE_SCHEMA_OFFSET,
490         ASYNCMETHOD_SCHEMA_OFFSET,
491         CUSTOMDEBUGINFORMATION_SCHEMA_OFFSET
492 };
493
494 #ifdef HAVE_ARRAY_ELEM_INIT
495 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
496 #define MSGSTRFIELD1(line) str##line
497 static const struct msgstr_t {
498 #define TABLEDEF(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
499 #include "mono/cil/tables.def"
500 #undef TABLEDEF
501 } tablestr = {
502 #define TABLEDEF(a,b) b,
503 #include "mono/cil/tables.def"
504 #undef TABLEDEF
505 };
506 static const gint16 tableidx [] = {
507 #define TABLEDEF(a,b) [a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
508 #include "mono/cil/tables.def"
509 #undef TABLEDEF
510 };
511
512 #else
513 #define TABLEDEF(a,b) b,
514 static const char* const
515 mono_tables_names [] = {
516 #include "mono/cil/tables.def"
517         NULL
518 };
519
520 #endif
521
522 /* If TRUE (but also see DISABLE_STICT_STRONG_NAMES #define), Mono will check
523  * that the public key token, culture and version of a candidate assembly matches
524  * the requested strong name.  If FALSE, as long as the name matches, the candidate
525  * will be allowed.
526  */
527 static gboolean check_strong_names_strictly = FALSE;
528
529 // Amount initially reserved in each imageset's mempool.
530 // FIXME: This number is arbitrary, a more practical number should be found
531 #define INITIAL_IMAGE_SET_SIZE    1024
532
533 /**
534  * mono_meta_table_name:
535  * \param table table index
536  *
537  * Returns the name of the given ECMA metadata logical format table
538  * as described in ECMA 335, Partition II, Section 22.
539  * 
540  * \returns the name for the \p table index
541  */
542 const char *
543 mono_meta_table_name (int table)
544 {
545         if ((table < 0) || (table > MONO_TABLE_LAST))
546                 return "";
547
548 #ifdef HAVE_ARRAY_ELEM_INIT
549         return (const char*)&tablestr + tableidx [table];
550 #else
551         return mono_tables_names [table];
552 #endif
553 }
554
555 /* The guy who wrote the spec for this should not be allowed near a
556  * computer again.
557  
558 If  e is a coded token(see clause 23.1.7) that points into table ti out of n possible tables t0, .. tn-1, 
559 then it is stored as e << (log n) & tag{ t0, .. tn-1}[ ti] using 2 bytes if the maximum number of 
560 rows of tables t0, ..tn-1, is less than 2^16 - (log n), and using 4 bytes otherwise. The family of 
561 finite maps tag{ t0, ..tn-1} is defined below. Note that to decode a physical row, you need the 
562 inverse of this mapping.
563
564  */
565 #define rtsize(meta,s,b) (((s) < (1 << (b)) ? 2 : 4))
566
567 static inline int
568 idx_size (MonoImage *meta, int tableidx)
569 {
570         if (meta->referenced_tables && (meta->referenced_tables & ((guint64)1 << tableidx)))
571                 return meta->referenced_table_rows [tableidx] < 65536 ? 2 : 4;
572         else
573                 return meta->tables [tableidx].rows < 65536 ? 2 : 4;
574 }
575
576 static inline int
577 get_nrows (MonoImage *meta, int tableidx)
578 {
579         if (meta->referenced_tables && (meta->referenced_tables & ((guint64)1 << tableidx)))
580                 return meta->referenced_table_rows [tableidx];
581         else
582                 return meta->tables [tableidx].rows;
583 }
584
585 /* Reference: Partition II - 23.2.6 */
586 /**
587  * mono_metadata_compute_size:
588  * \param meta metadata context
589  * \param tableindex metadata table number
590  * \param result_bitfield pointer to \c guint32 where to store additional info
591  * 
592  * \c mono_metadata_compute_size computes the length in bytes of a single
593  * row in a metadata table. The size of each column is encoded in the
594  * \p result_bitfield return value along with the number of columns in the table.
595  * the resulting bitfield should be handed to the \c mono_metadata_table_size
596  * and \c mono_metadata_table_count macros.
597  * This is a Mono runtime internal only function.
598  */
599 int
600 mono_metadata_compute_size (MonoImage *meta, int tableindex, guint32 *result_bitfield)
601 {
602         guint32 bitfield = 0;
603         int size = 0, field_size = 0;
604         int i, n, code;
605         int shift = 0;
606         const unsigned char *description = TableSchemas + table_description [tableindex];
607
608         for (i = 0; (code = description [i]) != MONO_MT_END; i++){
609                 switch (code){
610                 case MONO_MT_UINT32:
611                         field_size = 4; break;
612                         
613                 case MONO_MT_UINT16:
614                         field_size = 2; break;
615                         
616                 case MONO_MT_UINT8:
617                         field_size = 1; break;
618                         
619                 case MONO_MT_BLOB_IDX:
620                         field_size = meta->idx_blob_wide ? 4 : 2; break;
621                         
622                 case MONO_MT_STRING_IDX:
623                         field_size = meta->idx_string_wide ? 4 : 2; break;
624                         
625                 case MONO_MT_GUID_IDX:
626                         field_size = meta->idx_guid_wide ? 4 : 2; break;
627
628                 case MONO_MT_TABLE_IDX:
629                         /* Uhm, a table index can point to other tables besides the current one
630                          * so, it's not correct to use the rowcount of the current table to
631                          * get the size for this column - lupus 
632                          */
633                         switch (tableindex) {
634                         case MONO_TABLE_ASSEMBLYREFOS:
635                                 g_assert (i == 3);
636                                 field_size = idx_size (meta, MONO_TABLE_ASSEMBLYREF); break;
637                         case MONO_TABLE_ASSEMBLYREFPROCESSOR:
638                                 g_assert (i == 1);
639                                 field_size = idx_size (meta, MONO_TABLE_ASSEMBLYREF); break;
640                         case MONO_TABLE_CLASSLAYOUT:
641                                 g_assert (i == 2);
642                                 field_size = idx_size (meta, MONO_TABLE_TYPEDEF); break;
643                         case MONO_TABLE_EVENTMAP:
644                                 g_assert (i == 0 || i == 1);
645                                 field_size = i ? idx_size (meta, MONO_TABLE_EVENT):
646                                         idx_size (meta, MONO_TABLE_TYPEDEF);
647                                 break;
648                         case MONO_TABLE_EVENT_POINTER:
649                                 g_assert (i == 0);
650                                 field_size = idx_size (meta, MONO_TABLE_EVENT); break;
651                         case MONO_TABLE_EXPORTEDTYPE:
652                                 g_assert (i == 1);
653                                 /* the index is in another metadata file, so it must be 4 */
654                                 field_size = 4; break;
655                         case MONO_TABLE_FIELDLAYOUT:
656                                 g_assert (i == 1);
657                                 field_size = idx_size (meta, MONO_TABLE_FIELD); break;
658                         case MONO_TABLE_FIELDRVA:
659                                 g_assert (i == 1);
660                                 field_size = idx_size (meta, MONO_TABLE_FIELD); break;
661                         case MONO_TABLE_FIELD_POINTER:
662                                 g_assert (i == 0);
663                                 field_size = idx_size (meta, MONO_TABLE_FIELD); break;
664                         case MONO_TABLE_IMPLMAP:
665                                 g_assert (i == 3);
666                                 field_size = idx_size (meta, MONO_TABLE_MODULEREF); break;
667                         case MONO_TABLE_INTERFACEIMPL:
668                                 g_assert (i == 0);
669                                 field_size = idx_size (meta, MONO_TABLE_TYPEDEF); break;
670                         case MONO_TABLE_METHOD:
671                                 g_assert (i == 5);
672                                 field_size = idx_size (meta, MONO_TABLE_PARAM); break;
673                         case MONO_TABLE_METHODIMPL:
674                                 g_assert (i == 0);
675                                 field_size = idx_size (meta, MONO_TABLE_TYPEDEF); break;
676                         case MONO_TABLE_METHODSEMANTICS:
677                                 g_assert (i == 1);
678                                 field_size = idx_size (meta, MONO_TABLE_METHOD); break;
679                         case MONO_TABLE_METHOD_POINTER:
680                                 g_assert (i == 0);
681                                 field_size = idx_size (meta, MONO_TABLE_METHOD); break;
682                         case MONO_TABLE_NESTEDCLASS:
683                                 g_assert (i == 0 || i == 1);
684                                 field_size = idx_size (meta, MONO_TABLE_TYPEDEF); break;
685                         case MONO_TABLE_PARAM_POINTER:
686                                 g_assert (i == 0);
687                                 field_size = idx_size (meta, MONO_TABLE_PARAM); break;
688                         case MONO_TABLE_PROPERTYMAP:
689                                 g_assert (i == 0 || i == 1);
690                                 field_size = i ? idx_size (meta, MONO_TABLE_PROPERTY):
691                                         idx_size (meta, MONO_TABLE_TYPEDEF);
692                                 break;
693                         case MONO_TABLE_PROPERTY_POINTER:
694                                 g_assert (i == 0);
695                                 field_size = idx_size (meta, MONO_TABLE_PROPERTY); break;
696                         case MONO_TABLE_TYPEDEF:
697                                 g_assert (i == 4 || i == 5);
698                                 field_size = i == 4 ? idx_size (meta, MONO_TABLE_FIELD):
699                                         idx_size (meta, MONO_TABLE_METHOD);
700                                 break;
701                         case MONO_TABLE_GENERICPARAM:
702                                 g_assert (i == 2);
703                                 n = MAX (get_nrows (meta, MONO_TABLE_METHOD), get_nrows (meta, MONO_TABLE_TYPEDEF));
704                                 /*This is a coded token for 2 tables, so takes 1 bit */
705                                 field_size = rtsize (meta, n, 16 - MONO_TYPEORMETHOD_BITS);
706                                 break;
707                         case MONO_TABLE_GENERICPARAMCONSTRAINT:
708                                 g_assert (i == 0);
709                                 field_size = idx_size (meta, MONO_TABLE_GENERICPARAM);
710                                 break;
711                         case MONO_TABLE_LOCALSCOPE:
712                                 switch (i) {
713                                 case 0:
714                                         // FIXME: This table is in another file
715                                         field_size = idx_size (meta, MONO_TABLE_METHOD);
716                                         break;
717                                 case 1:
718                                         field_size = idx_size (meta, MONO_TABLE_IMPORTSCOPE);
719                                         break;
720                                 case 2:
721                                         field_size = idx_size (meta, MONO_TABLE_LOCALVARIABLE);
722                                         break;
723                                 case 3:
724                                         field_size = idx_size (meta, MONO_TABLE_LOCALCONSTANT);
725                                         break;
726                                 default:
727                                         g_assert_not_reached ();
728                                         break;
729                                 }
730                                 break;
731                         case MONO_TABLE_METHODBODY:
732                                 g_assert (i == 0);
733                                 field_size = idx_size (meta, MONO_TABLE_DOCUMENT); break;
734                         case MONO_TABLE_IMPORTSCOPE:
735                                 g_assert(i == 0);
736                                 field_size = idx_size (meta, MONO_TABLE_IMPORTSCOPE); break;
737                         case MONO_TABLE_STATEMACHINEMETHOD:
738                                 g_assert(i == 0 || i == 1);
739                                 field_size = idx_size(meta, MONO_TABLE_METHOD); break;
740                         default:
741                                 g_error ("Can't handle MONO_MT_TABLE_IDX for table %d element %d", tableindex, i);
742                         }
743                         break;
744
745                         /*
746                          * HasConstant: ParamDef, FieldDef, Property
747                          */
748                 case MONO_MT_CONST_IDX:
749                         n = MAX (get_nrows (meta, MONO_TABLE_PARAM),
750                                  get_nrows (meta, MONO_TABLE_FIELD));
751                         n = MAX (n, get_nrows (meta, MONO_TABLE_PROPERTY));
752
753                         /* 2 bits to encode tag */
754                         field_size = rtsize (meta, n, 16-2);
755                         break;
756
757                         /*
758                          * HasCustomAttribute: points to any table but
759                          * itself.
760                          */
761                 case MONO_MT_HASCAT_IDX:
762                         /*
763                          * We believe that since the signature and
764                          * permission are indexing the Blob heap,
765                          * we should consider the blob size first
766                          */
767                         /* I'm not a believer - lupus
768                         if (meta->idx_blob_wide){
769                                 field_size = 4;
770                                 break;
771                         }*/
772                         
773                         n = MAX (get_nrows (meta, MONO_TABLE_METHOD),
774                                  get_nrows (meta, MONO_TABLE_FIELD));
775                         n = MAX (n, get_nrows (meta, MONO_TABLE_TYPEREF));
776                         n = MAX (n, get_nrows (meta, MONO_TABLE_TYPEDEF));
777                         n = MAX (n, get_nrows (meta, MONO_TABLE_PARAM));
778                         n = MAX (n, get_nrows (meta, MONO_TABLE_INTERFACEIMPL));
779                         n = MAX (n, get_nrows (meta, MONO_TABLE_MEMBERREF));
780                         n = MAX (n, get_nrows (meta, MONO_TABLE_MODULE));
781                         n = MAX (n, get_nrows (meta, MONO_TABLE_DECLSECURITY));
782                         n = MAX (n, get_nrows (meta, MONO_TABLE_PROPERTY));
783                         n = MAX (n, get_nrows (meta, MONO_TABLE_EVENT));
784                         n = MAX (n, get_nrows (meta, MONO_TABLE_STANDALONESIG));
785                         n = MAX (n, get_nrows (meta, MONO_TABLE_MODULEREF));
786                         n = MAX (n, get_nrows (meta, MONO_TABLE_TYPESPEC));
787                         n = MAX (n, get_nrows (meta, MONO_TABLE_ASSEMBLY));
788                         n = MAX (n, get_nrows (meta, MONO_TABLE_ASSEMBLYREF));
789                         n = MAX (n, get_nrows (meta, MONO_TABLE_FILE));
790                         n = MAX (n, get_nrows (meta, MONO_TABLE_EXPORTEDTYPE));
791                         n = MAX (n, get_nrows (meta, MONO_TABLE_MANIFESTRESOURCE));
792                         n = MAX (n, get_nrows (meta, MONO_TABLE_GENERICPARAM));
793                         n = MAX (n, get_nrows (meta, MONO_TABLE_GENERICPARAMCONSTRAINT));
794                         n = MAX (n, get_nrows (meta, MONO_TABLE_METHODSPEC));
795
796                         /* 5 bits to encode */
797                         field_size = rtsize (meta, n, 16-5);
798                         break;
799
800                         /*
801                         * HasCustomAttribute: points to any table but
802                         * itself.
803                         */
804
805                 case MONO_MT_HASCUSTDEBUG_IDX:
806                         n = MAX(get_nrows (meta, MONO_TABLE_METHOD),
807                                         get_nrows (meta, MONO_TABLE_FIELD));
808                         n = MAX(n, get_nrows (meta, MONO_TABLE_TYPEREF));
809                         n = MAX(n, get_nrows (meta, MONO_TABLE_TYPEDEF));
810                         n = MAX(n, get_nrows (meta, MONO_TABLE_PARAM));
811                         n = MAX(n, get_nrows (meta, MONO_TABLE_INTERFACEIMPL));
812                         n = MAX(n, get_nrows (meta, MONO_TABLE_MEMBERREF));
813                         n = MAX(n, get_nrows (meta, MONO_TABLE_MODULE));
814                         n = MAX(n, get_nrows (meta, MONO_TABLE_DECLSECURITY));
815                         n = MAX(n, get_nrows (meta, MONO_TABLE_PROPERTY));
816                         n = MAX(n, get_nrows (meta, MONO_TABLE_EVENT));
817                         n = MAX(n, get_nrows (meta, MONO_TABLE_STANDALONESIG));
818                         n = MAX(n, get_nrows (meta, MONO_TABLE_MODULEREF));
819                         n = MAX(n, get_nrows (meta, MONO_TABLE_TYPESPEC));
820                         n = MAX(n, get_nrows (meta, MONO_TABLE_ASSEMBLY));
821                         n = MAX(n, get_nrows (meta, MONO_TABLE_ASSEMBLYREF));
822                         n = MAX(n, get_nrows (meta, MONO_TABLE_FILE));
823                         n = MAX(n, get_nrows (meta, MONO_TABLE_EXPORTEDTYPE));
824                         n = MAX(n, get_nrows (meta, MONO_TABLE_MANIFESTRESOURCE));
825                         n = MAX(n, get_nrows (meta, MONO_TABLE_GENERICPARAM));
826                         n = MAX(n, get_nrows (meta, MONO_TABLE_GENERICPARAMCONSTRAINT));
827                         n = MAX(n, get_nrows (meta, MONO_TABLE_METHODSPEC));
828                         n = MAX(n, get_nrows (meta, MONO_TABLE_DOCUMENT));
829                         n = MAX(n, get_nrows (meta, MONO_TABLE_LOCALSCOPE));
830                         n = MAX(n, get_nrows (meta, MONO_TABLE_LOCALVARIABLE));
831                         n = MAX(n, get_nrows (meta, MONO_TABLE_LOCALCONSTANT));
832                         n = MAX(n, get_nrows (meta, MONO_TABLE_IMPORTSCOPE));
833
834                         /* 5 bits to encode */
835                         field_size = rtsize(meta, n, 16 - 5);
836                         break;
837
838                         /*
839                          * CustomAttributeType: MethodDef, MemberRef.
840                          */
841                 case MONO_MT_CAT_IDX:
842                         n = MAX (get_nrows (meta, MONO_TABLE_METHOD),
843                                          get_nrows (meta, MONO_TABLE_MEMBERREF));
844
845                         /* 3 bits to encode */
846                         field_size = rtsize (meta, n, 16-3);
847                         break;
848
849                         /*
850                          * HasDeclSecurity: Typedef, MethodDef, Assembly
851                          */
852                 case MONO_MT_HASDEC_IDX:
853                         n = MAX (get_nrows (meta, MONO_TABLE_TYPEDEF),
854                                  get_nrows (meta, MONO_TABLE_METHOD));
855                         n = MAX (n, get_nrows (meta, MONO_TABLE_ASSEMBLY));
856
857                         /* 2 bits to encode */
858                         field_size = rtsize (meta, n, 16-2);
859                         break;
860
861                         /*
862                          * Implementation: File, AssemblyRef, ExportedType
863                          */
864                 case MONO_MT_IMPL_IDX:
865                         n = MAX (get_nrows (meta, MONO_TABLE_FILE),
866                                  get_nrows (meta, MONO_TABLE_ASSEMBLYREF));
867                         n = MAX (n, get_nrows (meta, MONO_TABLE_EXPORTEDTYPE));
868
869                         /* 2 bits to encode tag */
870                         field_size = rtsize (meta, n, 16-2);
871                         break;
872
873                         /*
874                          * HasFieldMarshall: FieldDef, ParamDef
875                          */
876                 case MONO_MT_HFM_IDX:
877                         n = MAX (get_nrows (meta, MONO_TABLE_FIELD),
878                                  get_nrows (meta, MONO_TABLE_PARAM));
879
880                         /* 1 bit used to encode tag */
881                         field_size = rtsize (meta, n, 16-1);
882                         break;
883
884                         /*
885                          * MemberForwarded: FieldDef, MethodDef
886                          */
887                 case MONO_MT_MF_IDX:
888                         n = MAX (get_nrows (meta, MONO_TABLE_FIELD),
889                                  get_nrows (meta, MONO_TABLE_METHOD));
890
891                         /* 1 bit used to encode tag */
892                         field_size = rtsize (meta, n, 16-1);
893                         break;
894
895                         /*
896                          * TypeDefOrRef: TypeDef, ParamDef, TypeSpec
897                          * LAMESPEC
898                          * It is TypeDef, _TypeRef_, TypeSpec, instead.
899                          */
900                 case MONO_MT_TDOR_IDX:
901                         n = MAX (get_nrows (meta, MONO_TABLE_TYPEDEF),
902                                  get_nrows (meta, MONO_TABLE_TYPEREF));
903                         n = MAX (n, get_nrows (meta, MONO_TABLE_TYPESPEC));
904
905                         /* 2 bits to encode */
906                         field_size = rtsize (meta, n, 16-2);
907                         break;
908
909                         /*
910                          * MemberRefParent: TypeDef, TypeRef, MethodDef, ModuleRef, TypeSpec, MemberRef
911                          */
912                 case MONO_MT_MRP_IDX:
913                         n = MAX (get_nrows (meta, MONO_TABLE_TYPEDEF),
914                                  get_nrows (meta, MONO_TABLE_TYPEREF));
915                         n = MAX (n, get_nrows (meta, MONO_TABLE_METHOD));
916                         n = MAX (n, get_nrows (meta, MONO_TABLE_MODULEREF));
917                         n = MAX (n, get_nrows (meta, MONO_TABLE_TYPESPEC));
918
919                         /* 3 bits to encode */
920                         field_size = rtsize (meta, n, 16 - 3);
921                         break;
922                         
923                         /*
924                          * MethodDefOrRef: MethodDef, MemberRef
925                          */
926                 case MONO_MT_MDOR_IDX:
927                         n = MAX (get_nrows (meta, MONO_TABLE_METHOD),
928                                  get_nrows (meta, MONO_TABLE_MEMBERREF));
929
930                         /* 1 bit used to encode tag */
931                         field_size = rtsize (meta, n, 16-1);
932                         break;
933                         
934                         /*
935                          * HasSemantics: Property, Event
936                          */
937                 case MONO_MT_HS_IDX:
938                         n = MAX (get_nrows (meta, MONO_TABLE_PROPERTY),
939                                  get_nrows (meta, MONO_TABLE_EVENT));
940
941                         /* 1 bit used to encode tag */
942                         field_size = rtsize (meta, n, 16-1);
943                         break;
944
945                         /*
946                          * ResolutionScope: Module, ModuleRef, AssemblyRef, TypeRef
947                          */
948                 case MONO_MT_RS_IDX:
949                         n = MAX (get_nrows (meta, MONO_TABLE_MODULE),
950                                  get_nrows (meta, MONO_TABLE_MODULEREF));
951                         n = MAX (n, get_nrows (meta, MONO_TABLE_ASSEMBLYREF));
952                         n = MAX (n, get_nrows (meta, MONO_TABLE_TYPEREF));
953
954                         /* 2 bits used to encode tag (ECMA spec claims 3) */
955                         field_size = rtsize (meta, n, 16 - 2);
956                         break;
957                 }
958
959                 /*
960                  * encode field size as follows (we just need to
961                  * distinguish them).
962                  *
963                  * 4 -> 3
964                  * 2 -> 1
965                  * 1 -> 0
966                  */
967                 bitfield |= (field_size-1) << shift;
968                 shift += 2;
969                 size += field_size;
970                 /*g_print ("table %02x field %d size %d\n", tableindex, i, field_size);*/
971         }
972
973         *result_bitfield = (i << 24) | bitfield;
974         return size;
975 }
976
977 /**
978  * mono_metadata_compute_table_bases:
979  * \param meta metadata context to compute table values
980  *
981  * Computes the table bases for the metadata structure.
982  * This is an internal function used by the image loader code.
983  */
984 void
985 mono_metadata_compute_table_bases (MonoImage *meta)
986 {
987         int i;
988         const char *base = meta->tables_base;
989         
990         for (i = 0; i < MONO_TABLE_NUM; i++) {
991                 MonoTableInfo *table = &meta->tables [i];
992                 if (table->rows == 0)
993                         continue;
994
995                 table->row_size = mono_metadata_compute_size (meta, i, &table->size_bitfield);
996                 table->base = base;
997                 base += table->rows * table->row_size;
998         }
999 }
1000
1001 /**
1002  * mono_metadata_locate:
1003  * \param meta metadata context
1004  * \param table table code.
1005  * \param idx index of element to retrieve from \p table.
1006  *
1007  * \returns a pointer to the \p idx element in the metadata table
1008  * whose code is \p table.
1009  */
1010 const char *
1011 mono_metadata_locate (MonoImage *meta, int table, int idx)
1012 {
1013         /* idx == 0 refers always to NULL */
1014         g_return_val_if_fail (idx > 0 && idx <= meta->tables [table].rows, ""); /*FIXME shouldn't we return NULL here?*/
1015            
1016         return meta->tables [table].base + (meta->tables [table].row_size * (idx - 1));
1017 }
1018
1019 /**
1020  * mono_metadata_locate_token:
1021  * \param meta metadata context
1022  * \param token metadata token
1023  *
1024  * \returns a pointer to the data in the metadata represented by the
1025  * token \p token .
1026  */
1027 const char *
1028 mono_metadata_locate_token (MonoImage *meta, guint32 token)
1029 {
1030         return mono_metadata_locate (meta, token >> 24, token & 0xffffff);
1031 }
1032
1033 /**
1034  * mono_metadata_string_heap:
1035  * \param meta metadata context
1036  * \param index index into the string heap.
1037  * \returns an in-memory pointer to the \p index in the string heap.
1038  */
1039 const char *
1040 mono_metadata_string_heap (MonoImage *meta, guint32 index)
1041 {
1042         g_assert (index < meta->heap_strings.size);
1043         g_return_val_if_fail (index < meta->heap_strings.size, "");
1044         return meta->heap_strings.data + index;
1045 }
1046
1047 /**
1048  * mono_metadata_user_string:
1049  * \param meta metadata context
1050  * \param index index into the user string heap.
1051  * \returns an in-memory pointer to the \p index in the user string heap (<code>#US</code>).
1052  */
1053 const char *
1054 mono_metadata_user_string (MonoImage *meta, guint32 index)
1055 {
1056         g_assert (index < meta->heap_us.size);
1057         g_return_val_if_fail (index < meta->heap_us.size, "");
1058         return meta->heap_us.data + index;
1059 }
1060
1061 /**
1062  * mono_metadata_blob_heap:
1063  * \param meta metadata context
1064  * \param index index into the blob.
1065  * \returns an in-memory pointer to the \p index in the Blob heap.
1066  */
1067 const char *
1068 mono_metadata_blob_heap (MonoImage *meta, guint32 index)
1069 {
1070         g_assert (index < meta->heap_blob.size);
1071         g_return_val_if_fail (index < meta->heap_blob.size, "");/*FIXME shouldn't we return NULL and check for index == 0?*/
1072         return meta->heap_blob.data + index;
1073 }
1074
1075 /**
1076  * mono_metadata_guid_heap:
1077  * \param meta metadata context
1078  * \param index index into the guid heap.
1079  * \returns an in-memory pointer to the \p index in the guid heap.
1080  */
1081 const char *
1082 mono_metadata_guid_heap (MonoImage *meta, guint32 index)
1083 {
1084         --index;
1085         index *= 16; /* adjust for guid size and 1-based index */
1086         g_return_val_if_fail (index < meta->heap_guid.size, "");
1087         return meta->heap_guid.data + index;
1088 }
1089
1090 static const unsigned char *
1091 dword_align (const unsigned char *ptr)
1092 {
1093 #if SIZEOF_VOID_P == 8
1094         return (const unsigned char *) (((guint64) (ptr + 3)) & ~3);
1095 #else
1096         return (const unsigned char *) (((guint32) (ptr + 3)) & ~3);
1097 #endif
1098 }
1099
1100 /**
1101  * mono_metadata_decode_row:
1102  * \param t table to extract information from.
1103  * \param idx index in table.
1104  * \param res array of \p res_size cols to store the results in
1105  *
1106  * This decompresses the metadata element \p idx in table \p t
1107  * into the \c guint32 \p res array that has \p res_size elements
1108  */
1109 void
1110 mono_metadata_decode_row (const MonoTableInfo *t, int idx, guint32 *res, int res_size)
1111 {
1112         guint32 bitfield = t->size_bitfield;
1113         int i, count = mono_metadata_table_count (bitfield);
1114         const char *data;
1115
1116         g_assert (idx < t->rows);
1117         g_assert (idx >= 0);
1118         data = t->base + idx * t->row_size;
1119         
1120         g_assert (res_size == count);
1121
1122         for (i = 0; i < count; i++) {
1123                 int n = mono_metadata_table_size (bitfield, i);
1124
1125                 switch (n){
1126                 case 1:
1127                         res [i] = *data; break;
1128                 case 2:
1129                         res [i] = read16 (data); break;
1130                 case 4:
1131                         res [i] = read32 (data); break;
1132                 default:
1133                         g_assert_not_reached ();
1134                 }
1135                 data += n;
1136         }
1137 }
1138
1139 /**
1140  * mono_metadata_decode_row_col:
1141  * \param t table to extract information from.
1142  * \param idx index for row in table.
1143  * \param col column in the row.
1144  *
1145  * This function returns the value of column \p col from the \p idx
1146  * row in the table \p t .
1147  */
1148 guint32
1149 mono_metadata_decode_row_col (const MonoTableInfo *t, int idx, guint col)
1150 {
1151         guint32 bitfield = t->size_bitfield;
1152         int i;
1153         register const char *data; 
1154         register int n;
1155         
1156         g_assert (idx < t->rows);
1157         g_assert (col < mono_metadata_table_count (bitfield));
1158         data = t->base + idx * t->row_size;
1159
1160         n = mono_metadata_table_size (bitfield, 0);
1161         for (i = 0; i < col; ++i) {
1162                 data += n;
1163                 n = mono_metadata_table_size (bitfield, i + 1);
1164         }
1165         switch (n) {
1166         case 1:
1167                 return *data;
1168         case 2:
1169                 return read16 (data);
1170         case 4:
1171                 return read32 (data);
1172         default:
1173                 g_assert_not_reached ();
1174         }
1175         return 0;
1176 }
1177
1178 /**
1179  * mono_metadata_decode_blob_size:
1180  * \param ptr pointer to a blob object
1181  * \param rptr the new position of the pointer
1182  *
1183  * This decodes a compressed size as described by 24.2.4 (#US and #Blob a blob or user string object)
1184  *
1185  * \returns the size of the blob object
1186  */
1187 guint32
1188 mono_metadata_decode_blob_size (const char *xptr, const char **rptr)
1189 {
1190         const unsigned char *ptr = (const unsigned char *)xptr;
1191         guint32 size;
1192         
1193         if ((*ptr & 0x80) == 0){
1194                 size = ptr [0] & 0x7f;
1195                 ptr++;
1196         } else if ((*ptr & 0x40) == 0){
1197                 size = ((ptr [0] & 0x3f) << 8) + ptr [1];
1198                 ptr += 2;
1199         } else {
1200                 size = ((ptr [0] & 0x1f) << 24) +
1201                         (ptr [1] << 16) +
1202                         (ptr [2] << 8) +
1203                         ptr [3];
1204                 ptr += 4;
1205         }
1206         if (rptr)
1207                 *rptr = (char*)ptr;
1208         return size;
1209 }
1210
1211 /**
1212  * mono_metadata_decode_value:
1213  * \param ptr pointer to decode from
1214  * \param rptr the new position of the pointer
1215  *
1216  * This routine decompresses 32-bit values as specified in the "Blob and
1217  * Signature" section (23.2)
1218  *
1219  * \returns the decoded value
1220  */
1221 guint32
1222 mono_metadata_decode_value (const char *_ptr, const char **rptr)
1223 {
1224         const unsigned char *ptr = (const unsigned char *) _ptr;
1225         unsigned char b = *ptr;
1226         guint32 len;
1227         
1228         if ((b & 0x80) == 0){
1229                 len = b;
1230                 ++ptr;
1231         } else if ((b & 0x40) == 0){
1232                 len = ((b & 0x3f) << 8 | ptr [1]);
1233                 ptr += 2;
1234         } else {
1235                 len = ((b & 0x1f) << 24) |
1236                         (ptr [1] << 16) |
1237                         (ptr [2] << 8) |
1238                         ptr [3];
1239                 ptr += 4;
1240         }
1241         if (rptr)
1242                 *rptr = (char*)ptr;
1243         
1244         return len;
1245 }
1246
1247 /**
1248  * mono_metadata_decode_signed_value:
1249  * \param ptr pointer to decode from
1250  * \param rptr the new position of the pointer
1251  *
1252  * This routine decompresses 32-bit signed values
1253  * (not specified in the spec)
1254  *
1255  * \returns the decoded value
1256  */
1257 gint32
1258 mono_metadata_decode_signed_value (const char *ptr, const char **rptr)
1259 {
1260         guint32 uval = mono_metadata_decode_value (ptr, rptr);
1261         gint32 ival = uval >> 1;
1262         if (!(uval & 1))
1263                 return ival;
1264         /* ival is a truncated 2's complement negative number.  */
1265         if (ival < 0x40)
1266                 /* 6 bits = 7 bits for compressed representation (top bit is '0') - 1 sign bit */
1267                 return ival - 0x40;
1268         if (ival < 0x2000)
1269                 /* 13 bits = 14 bits for compressed representation (top bits are '10') - 1 sign bit */
1270                 return ival - 0x2000;
1271         if (ival < 0x10000000)
1272                 /* 28 bits = 29 bits for compressed representation (top bits are '110') - 1 sign bit */
1273                 return ival - 0x10000000;
1274         g_assert (ival < 0x20000000);
1275         g_warning ("compressed signed value appears to use 29 bits for compressed representation: %x (raw: %8x)", ival, uval);
1276         return ival - 0x20000000;
1277 }
1278
1279 /**
1280  * mono_metadata_translate_token_index:
1281  * Translates the given 1-based index into the \c Method, \c Field, \c Event, or \c Param tables
1282  * using the \c *Ptr tables in uncompressed metadata, if they are available.
1283  *
1284  * FIXME: The caller is not forced to call this function, which is error-prone, since 
1285  * forgetting to call it would only show up as a bug on uncompressed metadata.
1286  */
1287 guint32
1288 mono_metadata_translate_token_index (MonoImage *image, int table, guint32 idx)
1289 {
1290         if (!image->uncompressed_metadata)
1291                 return idx;
1292
1293         switch (table) {
1294         case MONO_TABLE_METHOD:
1295                 if (image->tables [MONO_TABLE_METHOD_POINTER].rows)
1296                         return mono_metadata_decode_row_col (&image->tables [MONO_TABLE_METHOD_POINTER], idx - 1, MONO_METHOD_POINTER_METHOD);
1297                 else
1298                         return idx;
1299         case MONO_TABLE_FIELD:
1300                 if (image->tables [MONO_TABLE_FIELD_POINTER].rows)
1301                         return mono_metadata_decode_row_col (&image->tables [MONO_TABLE_FIELD_POINTER], idx - 1, MONO_FIELD_POINTER_FIELD);
1302                 else
1303                         return idx;
1304         case MONO_TABLE_EVENT:
1305                 if (image->tables [MONO_TABLE_EVENT_POINTER].rows)
1306                         return mono_metadata_decode_row_col (&image->tables [MONO_TABLE_EVENT_POINTER], idx - 1, MONO_EVENT_POINTER_EVENT);
1307                 else
1308                         return idx;
1309         case MONO_TABLE_PROPERTY:
1310                 if (image->tables [MONO_TABLE_PROPERTY_POINTER].rows)
1311                         return mono_metadata_decode_row_col (&image->tables [MONO_TABLE_PROPERTY_POINTER], idx - 1, MONO_PROPERTY_POINTER_PROPERTY);
1312                 else
1313                         return idx;
1314         case MONO_TABLE_PARAM:
1315                 if (image->tables [MONO_TABLE_PARAM_POINTER].rows)
1316                         return mono_metadata_decode_row_col (&image->tables [MONO_TABLE_PARAM_POINTER], idx - 1, MONO_PARAM_POINTER_PARAM);
1317                 else
1318                         return idx;
1319         default:
1320                 return idx;
1321         }
1322 }
1323
1324 /**
1325  * mono_metadata_decode_table_row:
1326  *
1327  * Same as \c mono_metadata_decode_row, but takes an \p image + \p table ID pair, and takes
1328  * uncompressed metadata into account, so it should be used to access the
1329  * \c Method, \c Field, \c Param and \c Event tables when the access is made from metadata, i.e.
1330  * \p idx is retrieved from a metadata table, like \c MONO_TYPEDEF_FIELD_LIST.
1331  */
1332 void
1333 mono_metadata_decode_table_row (MonoImage *image, int table, int idx, guint32 *res, int res_size)
1334 {
1335         if (image->uncompressed_metadata)
1336                 idx = mono_metadata_translate_token_index (image, table, idx + 1) - 1;
1337
1338         mono_metadata_decode_row (&image->tables [table], idx, res, res_size);
1339 }
1340
1341 /**
1342  * mono_metadata_decode_table_row_col:
1343  *
1344  * Same as \c mono_metadata_decode_row_col, but takes an \p image + \p table ID pair, and takes
1345  * uncompressed metadata into account, so it should be used to access the
1346  * \c Method, \c Field, \c Param and \c Event tables.
1347  */
1348 guint32 mono_metadata_decode_table_row_col (MonoImage *image, int table, int idx, guint col)
1349 {
1350         if (image->uncompressed_metadata)
1351                 idx = mono_metadata_translate_token_index (image, table, idx + 1) - 1;
1352
1353         return mono_metadata_decode_row_col (&image->tables [table], idx, col);
1354 }
1355
1356 /**
1357  * mono_metadata_parse_typedef_or_ref:
1358  * \param m a metadata context.
1359  * \param ptr a pointer to an encoded TypedefOrRef in \p m
1360  * \param rptr pointer updated to match the end of the decoded stream
1361  * \returns a token valid in the \p m metadata decoded from
1362  * the compressed representation.
1363  */
1364 guint32
1365 mono_metadata_parse_typedef_or_ref (MonoImage *m, const char *ptr, const char **rptr)
1366 {
1367         guint32 token;
1368         token = mono_metadata_decode_value (ptr, &ptr);
1369         if (rptr)
1370                 *rptr = ptr;
1371         return mono_metadata_token_from_dor (token);
1372 }
1373
1374 /**
1375  * mono_metadata_parse_custom_mod:
1376  * \param m a metadata context.
1377  * \param dest storage where the info about the custom modifier is stored (may be NULL)
1378  * \param ptr a pointer to (possibly) the start of a custom modifier list
1379  * \param rptr pointer updated to match the end of the decoded stream
1380  *
1381  * Checks if \p ptr points to a type custom modifier compressed representation.
1382  *
1383  * \returns TRUE if a custom modifier was found, FALSE if not.
1384  */
1385 int
1386 mono_metadata_parse_custom_mod (MonoImage *m, MonoCustomMod *dest, const char *ptr, const char **rptr)
1387 {
1388         MonoCustomMod local;
1389         if ((*ptr == MONO_TYPE_CMOD_OPT) || (*ptr == MONO_TYPE_CMOD_REQD)) {
1390                 if (!dest)
1391                         dest = &local;
1392                 dest->required = *ptr == MONO_TYPE_CMOD_REQD ? 1 : 0;
1393                 dest->token = mono_metadata_parse_typedef_or_ref (m, ptr + 1, rptr);
1394                 return TRUE;
1395         }
1396         return FALSE;
1397 }
1398
1399 /*
1400  * mono_metadata_parse_array_internal:
1401  * @m: a metadata context.
1402  * @transient: whenever to allocate data from the heap
1403  * @ptr: a pointer to an encoded array description.
1404  * @rptr: pointer updated to match the end of the decoded stream
1405  *
1406  * Decodes the compressed array description found in the metadata @m at @ptr.
1407  *
1408  * Returns: a #MonoArrayType structure describing the array type
1409  * and dimensions. Memory is allocated from the heap or from the image mempool, depending
1410  * on the value of @transient.
1411  *
1412  * LOCKING: Acquires the loader lock
1413  */
1414 static MonoArrayType *
1415 mono_metadata_parse_array_internal (MonoImage *m, MonoGenericContainer *container,
1416                                                                         gboolean transient, const char *ptr, const char **rptr, MonoError *error)
1417 {
1418         int i;
1419         MonoArrayType *array;
1420         MonoType *etype;
1421         
1422         etype = mono_metadata_parse_type_checked (m, container, 0, FALSE, ptr, &ptr, error); //FIXME this doesn't respect @transient
1423         if (!etype)
1424                 return NULL;
1425
1426         array = transient ? (MonoArrayType *)g_malloc0 (sizeof (MonoArrayType)) : (MonoArrayType *)mono_image_alloc0 (m, sizeof (MonoArrayType));
1427         array->eklass = mono_class_from_mono_type (etype);
1428         array->rank = mono_metadata_decode_value (ptr, &ptr);
1429
1430         array->numsizes = mono_metadata_decode_value (ptr, &ptr);
1431         if (array->numsizes)
1432                 array->sizes = transient ? (int *)g_malloc0 (sizeof (int) * array->numsizes) : (int *)mono_image_alloc0 (m, sizeof (int) * array->numsizes);
1433         for (i = 0; i < array->numsizes; ++i)
1434                 array->sizes [i] = mono_metadata_decode_value (ptr, &ptr);
1435
1436         array->numlobounds = mono_metadata_decode_value (ptr, &ptr);
1437         if (array->numlobounds)
1438                 array->lobounds = transient ? (int *)g_malloc0 (sizeof (int) * array->numlobounds) : (int *)mono_image_alloc0 (m, sizeof (int) * array->numlobounds);
1439         for (i = 0; i < array->numlobounds; ++i)
1440                 array->lobounds [i] = mono_metadata_decode_signed_value (ptr, &ptr);
1441
1442         if (rptr)
1443                 *rptr = ptr;
1444         return array;
1445 }
1446
1447 /**
1448  * mono_metadata_parse_array:
1449  */
1450 MonoArrayType *
1451 mono_metadata_parse_array (MonoImage *m, const char *ptr, const char **rptr)
1452 {
1453         MonoError error;
1454         MonoArrayType *ret = mono_metadata_parse_array_internal (m, NULL, FALSE, ptr, rptr, &error);
1455         mono_error_cleanup (&error);
1456
1457         return ret;
1458 }
1459
1460 /**
1461  * mono_metadata_free_array:
1462  * \param array array description
1463  *
1464  * Frees the array description returned from \c mono_metadata_parse_array.
1465  */
1466 void
1467 mono_metadata_free_array (MonoArrayType *array)
1468 {
1469         g_free (array->sizes);
1470         g_free (array->lobounds);
1471         g_free (array);
1472 }
1473
1474 /*
1475  * need to add common field and param attributes combinations:
1476  * [out] param
1477  * public static
1478  * public static literal
1479  * private
1480  * private static
1481  * private static literal
1482  */
1483 static const MonoType
1484 builtin_types[] = {
1485         /* data, attrs, type,              nmods, byref, pinned */
1486         {{NULL}, 0,     MONO_TYPE_VOID,    0,     0,     0},
1487         {{NULL}, 0,     MONO_TYPE_BOOLEAN, 0,     0,     0},
1488         {{NULL}, 0,     MONO_TYPE_BOOLEAN, 0,     1,     0},
1489         {{NULL}, 0,     MONO_TYPE_CHAR,    0,     0,     0},
1490         {{NULL}, 0,     MONO_TYPE_CHAR,    0,     1,     0},
1491         {{NULL}, 0,     MONO_TYPE_I1,      0,     0,     0},
1492         {{NULL}, 0,     MONO_TYPE_I1,      0,     1,     0},
1493         {{NULL}, 0,     MONO_TYPE_U1,      0,     0,     0},
1494         {{NULL}, 0,     MONO_TYPE_U1,      0,     1,     0},
1495         {{NULL}, 0,     MONO_TYPE_I2,      0,     0,     0},
1496         {{NULL}, 0,     MONO_TYPE_I2,      0,     1,     0},
1497         {{NULL}, 0,     MONO_TYPE_U2,      0,     0,     0},
1498         {{NULL}, 0,     MONO_TYPE_U2,      0,     1,     0},
1499         {{NULL}, 0,     MONO_TYPE_I4,      0,     0,     0},
1500         {{NULL}, 0,     MONO_TYPE_I4,      0,     1,     0},
1501         {{NULL}, 0,     MONO_TYPE_U4,      0,     0,     0},
1502         {{NULL}, 0,     MONO_TYPE_U4,      0,     1,     0},
1503         {{NULL}, 0,     MONO_TYPE_I8,      0,     0,     0},
1504         {{NULL}, 0,     MONO_TYPE_I8,      0,     1,     0},
1505         {{NULL}, 0,     MONO_TYPE_U8,      0,     0,     0},
1506         {{NULL}, 0,     MONO_TYPE_U8,      0,     1,     0},
1507         {{NULL}, 0,     MONO_TYPE_R4,      0,     0,     0},
1508         {{NULL}, 0,     MONO_TYPE_R4,      0,     1,     0},
1509         {{NULL}, 0,     MONO_TYPE_R8,      0,     0,     0},
1510         {{NULL}, 0,     MONO_TYPE_R8,      0,     1,     0},
1511         {{NULL}, 0,     MONO_TYPE_STRING,  0,     0,     0},
1512         {{NULL}, 0,     MONO_TYPE_STRING,  0,     1,     0},
1513         {{NULL}, 0,     MONO_TYPE_OBJECT,  0,     0,     0},
1514         {{NULL}, 0,     MONO_TYPE_OBJECT,  0,     1,     0},
1515         {{NULL}, 0,     MONO_TYPE_TYPEDBYREF,  0,     0,     0},
1516         {{NULL}, 0,     MONO_TYPE_I,       0,     0,     0},
1517         {{NULL}, 0,     MONO_TYPE_I,       0,     1,     0},
1518         {{NULL}, 0,     MONO_TYPE_U,       0,     0,     0},
1519         {{NULL}, 0,     MONO_TYPE_U,       0,     1,     0},
1520 };
1521
1522 #define NBUILTIN_TYPES() (sizeof (builtin_types) / sizeof (builtin_types [0]))
1523
1524 static GHashTable *type_cache = NULL;
1525 static gint32 next_generic_inst_id = 0;
1526
1527 /* Protected by image_sets_mutex */
1528 static MonoImageSet *mscorlib_image_set;
1529 /* Protected by image_sets_mutex */
1530 static GPtrArray *image_sets;
1531 static mono_mutex_t image_sets_mutex;
1532
1533 static guint mono_generic_class_hash (gconstpointer data);
1534
1535 /*
1536  * MonoTypes with modifies are never cached, so we never check or use that field.
1537  */
1538 static guint
1539 mono_type_hash (gconstpointer data)
1540 {
1541         const MonoType *type = (const MonoType *) data;
1542         if (type->type == MONO_TYPE_GENERICINST)
1543                 return mono_generic_class_hash (type->data.generic_class);
1544         else
1545                 return type->type | (type->byref << 8) | (type->attrs << 9);
1546 }
1547
1548 static gint
1549 mono_type_equal (gconstpointer ka, gconstpointer kb)
1550 {
1551         const MonoType *a = (const MonoType *) ka;
1552         const MonoType *b = (const MonoType *) kb;
1553         
1554         if (a->type != b->type || a->byref != b->byref || a->attrs != b->attrs || a->pinned != b->pinned)
1555                 return 0;
1556         /* need other checks */
1557         return 1;
1558 }
1559
1560 guint
1561 mono_metadata_generic_inst_hash (gconstpointer data)
1562 {
1563         const MonoGenericInst *ginst = (const MonoGenericInst *) data;
1564         guint hash = 0;
1565         int i;
1566         
1567         for (i = 0; i < ginst->type_argc; ++i) {
1568                 hash *= 13;
1569                 hash += mono_metadata_type_hash (ginst->type_argv [i]);
1570         }
1571
1572         return hash ^ (ginst->is_open << 8);
1573 }
1574
1575 static gboolean
1576 mono_generic_inst_equal_full (const MonoGenericInst *a, const MonoGenericInst *b, gboolean signature_only)
1577 {
1578         int i;
1579
1580         // An optimization: if the ids of two insts are the same, we know they are the same inst and don't check contents.
1581         // Furthermore, because we perform early de-duping, if the ids differ, we know the contents differ.
1582 #ifndef MONO_SMALL_CONFIG // Optimization does not work in MONO_SMALL_CONFIG: There are no IDs
1583         if (a->id && b->id) { // "id 0" means "object has no id"-- de-duping hasn't been performed yet, must check contents.
1584                 if (a->id == b->id)
1585                         return TRUE;
1586                 // In signature-comparison mode id equality implies object equality, but this is not true for inequality.
1587                 // Two separate objects could have signature-equavalent contents.
1588                 if (!signature_only)
1589                         return FALSE;
1590         }
1591 #endif
1592
1593         if (a->is_open != b->is_open || a->type_argc != b->type_argc)
1594                 return FALSE;
1595         for (i = 0; i < a->type_argc; ++i) {
1596                 if (!do_mono_metadata_type_equal (a->type_argv [i], b->type_argv [i], signature_only))
1597                         return FALSE;
1598         }
1599         return TRUE;
1600 }
1601
1602 gboolean
1603 mono_metadata_generic_inst_equal (gconstpointer ka, gconstpointer kb)
1604 {
1605         const MonoGenericInst *a = (const MonoGenericInst *) ka;
1606         const MonoGenericInst *b = (const MonoGenericInst *) kb;
1607
1608         return mono_generic_inst_equal_full (a, b, FALSE);
1609 }
1610
1611 static guint
1612 mono_generic_class_hash (gconstpointer data)
1613 {
1614         const MonoGenericClass *gclass = (const MonoGenericClass *) data;
1615         guint hash = mono_metadata_type_hash (&gclass->container_class->byval_arg);
1616
1617         hash *= 13;
1618         hash += gclass->is_tb_open;
1619         hash += mono_metadata_generic_context_hash (&gclass->context);
1620
1621         return hash;
1622 }
1623
1624 static gboolean
1625 mono_generic_class_equal (gconstpointer ka, gconstpointer kb)
1626 {
1627         const MonoGenericClass *a = (const MonoGenericClass *) ka;
1628         const MonoGenericClass *b = (const MonoGenericClass *) kb;
1629
1630         return _mono_metadata_generic_class_equal (a, b, FALSE);
1631 }
1632
1633 /**
1634  * mono_metadata_init:
1635  *
1636  * Initialize the global variables of this module.
1637  * This is a Mono runtime internal function.
1638  */
1639 void
1640 mono_metadata_init (void)
1641 {
1642         int i;
1643
1644         type_cache = g_hash_table_new (mono_type_hash, mono_type_equal);
1645
1646         for (i = 0; i < NBUILTIN_TYPES (); ++i)
1647                 g_hash_table_insert (type_cache, (gpointer) &builtin_types [i], (gpointer) &builtin_types [i]);
1648
1649         mono_os_mutex_init_recursive (&image_sets_mutex);
1650
1651         mono_counters_register ("ImgSet Cache Hit", MONO_COUNTER_METADATA | MONO_COUNTER_INT, &img_set_cache_hit);
1652         mono_counters_register ("ImgSet Cache Miss", MONO_COUNTER_METADATA | MONO_COUNTER_INT, &img_set_cache_miss);
1653         mono_counters_register ("ImgSet Count", MONO_COUNTER_METADATA | MONO_COUNTER_INT, &img_set_count);
1654 }
1655
1656 /**
1657  * mono_metadata_cleanup:
1658  *
1659  * Free all resources used by this module.
1660  * This is a Mono runtime internal function.
1661  */
1662 void
1663 mono_metadata_cleanup (void)
1664 {
1665         g_hash_table_destroy (type_cache);
1666         type_cache = NULL;
1667         g_ptr_array_free (image_sets, TRUE);
1668         image_sets = NULL;
1669         mono_os_mutex_destroy (&image_sets_mutex);
1670 }
1671
1672 /**
1673  * mono_metadata_parse_type:
1674  * \param m metadata context
1675  * \param mode kind of type that may be found at \p ptr
1676  * \param opt_attrs optional attributes to store in the returned type
1677  * \param ptr pointer to the type representation
1678  * \param rptr pointer updated to match the end of the decoded stream
1679  * \param transient whenever to allocate the result from the heap or from a mempool
1680  * 
1681  * Decode a compressed type description found at \p ptr in \p m .
1682  * \p mode can be one of \c MONO_PARSE_MOD_TYPE, \c MONO_PARSE_PARAM, \c MONO_PARSE_RET,
1683  * \c MONO_PARSE_FIELD, \c MONO_PARSE_LOCAL, \c MONO_PARSE_TYPE.
1684  * This function can be used to decode type descriptions in method signatures,
1685  * field signatures, locals signatures etc.
1686  *
1687  * To parse a generic type, \c generic_container points to the current class'es
1688  * (the \c generic_container field in the <code>MonoClass</code>) or the current generic method's
1689  * (stored in <code>image->property_hash</code>) generic container.
1690  * When we encounter a \c MONO_TYPE_VAR or \c MONO_TYPE_MVAR, it's looked up in
1691  * this \c MonoGenericContainer.
1692  *
1693  * LOCKING: Acquires the loader lock.
1694  *
1695  * \returns a \c MonoType structure representing the decoded type.
1696  */
1697 static MonoType*
1698 mono_metadata_parse_type_internal (MonoImage *m, MonoGenericContainer *container,
1699                                                                    short opt_attrs, gboolean transient, const char *ptr, const char **rptr, MonoError *error)
1700 {
1701         MonoType *type, *cached;
1702         MonoType stype;
1703         gboolean byref = FALSE;
1704         gboolean pinned = FALSE;
1705         const char *tmp_ptr;
1706         int count = 0; // Number of mod arguments
1707         gboolean found;
1708
1709         error_init (error);
1710
1711         /*
1712          * According to the spec, custom modifiers should come before the byref
1713          * flag, but the IL produced by ilasm from the following signature:
1714          *   object modopt(...) &
1715          * starts with a byref flag, followed by the modifiers. (bug #49802)
1716          * Also, this type seems to be different from 'object & modopt(...)'. Maybe
1717          * it would be better to treat byref as real type constructor instead of
1718          * a modifier...
1719          * Also, pinned should come before anything else, but some MSV++ produced
1720          * assemblies violate this (#bug 61990).
1721          */
1722
1723         /* Count the modifiers first */
1724         tmp_ptr = ptr;
1725         found = TRUE;
1726         while (found) {
1727                 switch (*tmp_ptr) {
1728                 case MONO_TYPE_PINNED:
1729                 case MONO_TYPE_BYREF:
1730                         ++tmp_ptr;
1731                         break;
1732                 case MONO_TYPE_CMOD_REQD:
1733                 case MONO_TYPE_CMOD_OPT:
1734                         count ++;
1735                         mono_metadata_parse_custom_mod (m, NULL, tmp_ptr, &tmp_ptr);
1736                         break;
1737                 default:
1738                         found = FALSE;
1739                 }
1740         }
1741
1742         if (count) { // There are mods, so the MonoType will be of nonstandard size.
1743                 int size;
1744
1745                 size = MONO_SIZEOF_TYPE + ((gint32)count) * sizeof (MonoCustomMod);
1746                 type = transient ? (MonoType *)g_malloc0 (size) : (MonoType *)mono_image_alloc0 (m, size);
1747                 type->num_mods = count;
1748                 if (count > 64) {
1749                         mono_error_set_bad_image (error, m, "Invalid type with more than 64 modifiers");
1750                         return NULL;
1751                 }
1752         } else {     // The type is of standard size, so we can allocate it on the stack.
1753                 type = &stype;
1754                 memset (type, 0, MONO_SIZEOF_TYPE);
1755         }
1756
1757         /* Iterate again, but now parse pinned, byref and custom modifiers */
1758         found = TRUE;
1759         count = 0;
1760         while (found) {
1761                 switch (*ptr) {
1762                 case MONO_TYPE_PINNED:
1763                         pinned = TRUE;
1764                         ++ptr;
1765                         break;
1766                 case MONO_TYPE_BYREF:
1767                         byref = TRUE;
1768                         ++ptr;
1769                         break;
1770                 case MONO_TYPE_CMOD_REQD:
1771                 case MONO_TYPE_CMOD_OPT:
1772                         mono_metadata_parse_custom_mod (m, &(type->modifiers [count]), ptr, &ptr);
1773                         count ++;
1774                         break;
1775                 default:
1776                         found = FALSE;
1777                 }
1778         }
1779         
1780         type->attrs = opt_attrs;
1781         type->byref = byref;
1782         type->pinned = pinned ? 1 : 0;
1783
1784         if (!do_mono_metadata_parse_type (type, m, container, transient, ptr, &ptr, error))
1785                 return NULL;
1786
1787         if (rptr)
1788                 *rptr = ptr;
1789
1790         // Possibly we can return an already-allocated type instead of the one we decoded
1791         if (!type->num_mods && !transient) {
1792                 /* no need to free type here, because it is on the stack */
1793                 if ((type->type == MONO_TYPE_CLASS || type->type == MONO_TYPE_VALUETYPE) && !type->pinned && !type->attrs) {
1794                         MonoType *ret = type->byref ? &type->data.klass->this_arg : &type->data.klass->byval_arg;
1795
1796                         /* Consider the case:
1797
1798                              class Foo<T> { class Bar {} }
1799                              class Test : Foo<Test>.Bar {}
1800
1801                            When Foo<Test> is being expanded, 'Test' isn't yet initialized.  It's actually in
1802                            a really pristine state: it doesn't even know whether 'Test' is a reference or a value type.
1803
1804                            We ensure that the MonoClass is in a state that we can canonicalize to:
1805
1806                              klass->byval_arg.data.klass == klass
1807                              klass->this_arg.data.klass == klass
1808
1809                            If we can't canonicalize 'type', it doesn't matter, since later users of 'type' will do it.
1810
1811                            LOCKING: even though we don't explicitly hold a lock, in the problematic case 'ret' is a field
1812                                     of a MonoClass which currently holds the loader lock.  'type' is local.
1813                         */
1814                         if (ret->data.klass == type->data.klass) {
1815                                 return ret;
1816                         }
1817                 }
1818                 /* No need to use locking since nobody is modifying the hash table */
1819                 if ((cached = (MonoType *)g_hash_table_lookup (type_cache, type))) {
1820                         return cached;
1821                 }
1822         }
1823         
1824         /* printf ("%x %x %c %s\n", type->attrs, type->num_mods, type->pinned ? 'p' : ' ', mono_type_full_name (type)); */
1825         
1826         if (type == &stype) { // Type was allocated on the stack, so we need to copy it to safety
1827                 type = transient ? (MonoType *)g_malloc (MONO_SIZEOF_TYPE) : (MonoType *)mono_image_alloc (m, MONO_SIZEOF_TYPE);
1828                 memcpy (type, &stype, MONO_SIZEOF_TYPE);
1829         }
1830         return type;
1831 }
1832
1833
1834 MonoType*
1835 mono_metadata_parse_type_checked (MonoImage *m, MonoGenericContainer *container,
1836                                                            short opt_attrs, gboolean transient, const char *ptr, const char **rptr, MonoError *error)
1837 {
1838         return mono_metadata_parse_type_internal (m, container, opt_attrs, transient, ptr, rptr, error);
1839 }
1840
1841 /*
1842  * LOCKING: Acquires the loader lock.
1843  */
1844 MonoType*
1845 mono_metadata_parse_type (MonoImage *m, MonoParseTypeMode mode, short opt_attrs,
1846                           const char *ptr, const char **rptr)
1847 {
1848         MonoError error;
1849         MonoType * type = mono_metadata_parse_type_internal (m, NULL, opt_attrs, FALSE, ptr, rptr, &error);
1850         mono_error_cleanup (&error);
1851         return type;
1852 }
1853
1854 gboolean
1855 mono_metadata_method_has_param_attrs (MonoImage *m, int def)
1856 {
1857         MonoTableInfo *paramt = &m->tables [MONO_TABLE_PARAM];
1858         MonoTableInfo *methodt = &m->tables [MONO_TABLE_METHOD];
1859         guint lastp, i, param_index = mono_metadata_decode_row_col (methodt, def - 1, MONO_METHOD_PARAMLIST);
1860
1861         if (def < methodt->rows)
1862                 lastp = mono_metadata_decode_row_col (methodt, def, MONO_METHOD_PARAMLIST);
1863         else
1864                 lastp = m->tables [MONO_TABLE_PARAM].rows + 1;
1865
1866         for (i = param_index; i < lastp; ++i) {
1867                 guint32 flags = mono_metadata_decode_row_col (paramt, i - 1, MONO_PARAM_FLAGS);
1868                 if (flags)
1869                         return TRUE;
1870         }
1871
1872         return FALSE;
1873 }
1874
1875 /*
1876  * mono_metadata_get_param_attrs:
1877  *
1878  * @m The image to loader parameter attributes from
1879  * @def method def token (one based)
1880  * @param_count number of params to decode including the return value
1881  *
1882  *   Return the parameter attributes for the method whose MethodDef index is DEF. The 
1883  * returned memory needs to be freed by the caller. If all the param attributes are
1884  * 0, then NULL is returned.
1885  */
1886 int*
1887 mono_metadata_get_param_attrs (MonoImage *m, int def, int param_count)
1888 {
1889         MonoTableInfo *paramt = &m->tables [MONO_TABLE_PARAM];
1890         MonoTableInfo *methodt = &m->tables [MONO_TABLE_METHOD];
1891         guint32 cols [MONO_PARAM_SIZE];
1892         guint lastp, i, param_index = mono_metadata_decode_row_col (methodt, def - 1, MONO_METHOD_PARAMLIST);
1893         int *pattrs = NULL;
1894
1895         if (def < methodt->rows)
1896                 lastp = mono_metadata_decode_row_col (methodt, def, MONO_METHOD_PARAMLIST);
1897         else
1898                 lastp = paramt->rows + 1;
1899
1900         for (i = param_index; i < lastp; ++i) {
1901                 mono_metadata_decode_row (paramt, i - 1, cols, MONO_PARAM_SIZE);
1902                 if (cols [MONO_PARAM_FLAGS]) {
1903                         if (!pattrs)
1904                                 pattrs = g_new0 (int, param_count);
1905                         /* at runtime we just ignore this kind of malformed file:
1906                         * the verifier can signal the error to the user
1907                         */
1908                         if (cols [MONO_PARAM_SEQUENCE] >= param_count)
1909                                 continue;
1910                         pattrs [cols [MONO_PARAM_SEQUENCE]] = cols [MONO_PARAM_FLAGS];
1911                 }
1912         }
1913
1914         return pattrs;
1915 }
1916
1917
1918 /**
1919  * mono_metadata_parse_signature:
1920  * \param image metadata context
1921  * \param token metadata token
1922  *
1923  * Decode a method signature stored in the \c StandAloneSig table
1924  *
1925  * \returns a \c MonoMethodSignature describing the signature.
1926  */
1927 MonoMethodSignature*
1928 mono_metadata_parse_signature (MonoImage *image, guint32 token)
1929 {
1930         MonoError error;
1931         MonoMethodSignature *ret;
1932         ret = mono_metadata_parse_signature_checked (image, token, &error);
1933         mono_error_cleanup (&error);
1934         return ret;
1935 }
1936
1937 /*
1938  * mono_metadata_parse_signature_checked:
1939  * @image: metadata context
1940  * @token: metadata token
1941  * @error: set on error
1942  *
1943  * Decode a method signature stored in the STANDALONESIG table
1944  *
1945  * Returns: a MonoMethodSignature describing the signature. On failure
1946  * returns NULL and sets @error.
1947  */
1948 MonoMethodSignature*
1949 mono_metadata_parse_signature_checked (MonoImage *image, guint32 token, MonoError *error)
1950 {
1951
1952         error_init (error);
1953         MonoTableInfo *tables = image->tables;
1954         guint32 idx = mono_metadata_token_index (token);
1955         guint32 sig;
1956         const char *ptr;
1957
1958         if (image_is_dynamic (image)) {
1959                 return (MonoMethodSignature *)mono_lookup_dynamic_token (image, token, NULL, error);
1960         }
1961
1962         g_assert (mono_metadata_token_table(token) == MONO_TABLE_STANDALONESIG);
1963                 
1964         sig = mono_metadata_decode_row_col (&tables [MONO_TABLE_STANDALONESIG], idx - 1, 0);
1965
1966         ptr = mono_metadata_blob_heap (image, sig);
1967         mono_metadata_decode_blob_size (ptr, &ptr);
1968
1969         return mono_metadata_parse_method_signature_full (image, NULL, 0, ptr, NULL, error);
1970 }
1971
1972 /**
1973  * mono_metadata_signature_alloc:
1974  * \param image metadata context
1975  * \param nparams number of parameters in the signature
1976  *
1977  * Allocate a \c MonoMethodSignature structure with the specified number of params.
1978  * The return type and the params types need to be filled later.
1979  * This is a Mono runtime internal function.
1980  *
1981  * LOCKING: Assumes the loader lock is held.
1982  *
1983  * \returns the new \c MonoMethodSignature structure.
1984  */
1985 MonoMethodSignature*
1986 mono_metadata_signature_alloc (MonoImage *m, guint32 nparams)
1987 {
1988         MonoMethodSignature *sig;
1989
1990         sig = (MonoMethodSignature *)mono_image_alloc0 (m, MONO_SIZEOF_METHOD_SIGNATURE + ((gint32)nparams) * sizeof (MonoType*));
1991         sig->param_count = nparams;
1992         sig->sentinelpos = -1;
1993
1994         return sig;
1995 }
1996
1997 static MonoMethodSignature*
1998 mono_metadata_signature_dup_internal_with_padding (MonoImage *image, MonoMemPool *mp, MonoMethodSignature *sig, size_t padding)
1999 {
2000         int sigsize, sig_header_size;
2001         MonoMethodSignature *ret;
2002         sigsize = sig_header_size = MONO_SIZEOF_METHOD_SIGNATURE + sig->param_count * sizeof (MonoType *) + padding;
2003         if (sig->ret)
2004                 sigsize += MONO_SIZEOF_TYPE;
2005
2006         if (image) {
2007                 ret = (MonoMethodSignature *)mono_image_alloc (image, sigsize);
2008         } else if (mp) {
2009                 ret = (MonoMethodSignature *)mono_mempool_alloc (mp, sigsize);
2010         } else {
2011                 ret = (MonoMethodSignature *)g_malloc (sigsize);
2012         }
2013
2014         memcpy (ret, sig, sig_header_size - padding);
2015
2016         // Copy return value because of ownership semantics.
2017         if (sig->ret) {
2018                 // Danger! Do not alter padding use without changing the dup_add_this below
2019                 intptr_t end_of_header = (intptr_t)( (char*)(ret) + sig_header_size);
2020                 ret->ret = (MonoType *)end_of_header;
2021                 memcpy (ret->ret, sig->ret, MONO_SIZEOF_TYPE);
2022         }
2023
2024         return ret;
2025 }
2026
2027 static MonoMethodSignature*
2028 mono_metadata_signature_dup_internal (MonoImage *image, MonoMemPool *mp, MonoMethodSignature *sig)
2029 {
2030         return mono_metadata_signature_dup_internal_with_padding (image, mp, sig, 0);
2031 }
2032 /*
2033  * signature_dup_add_this:
2034  *
2035  *  Make a copy of @sig, adding an explicit this argument.
2036  */
2037 MonoMethodSignature*
2038 mono_metadata_signature_dup_add_this (MonoImage *image, MonoMethodSignature *sig, MonoClass *klass)
2039 {
2040         MonoMethodSignature *ret;
2041         ret = mono_metadata_signature_dup_internal_with_padding (image, NULL, sig, sizeof (MonoType *));
2042
2043         ret->param_count = sig->param_count + 1;
2044         ret->hasthis = FALSE;
2045
2046         for (int i = sig->param_count - 1; i >= 0; i --)
2047                 ret->params [i + 1] = sig->params [i];
2048         ret->params [0] = klass->valuetype ? &klass->this_arg : &klass->byval_arg;
2049
2050         for (int i = sig->param_count - 1; i >= 0; i --)
2051                 g_assert(ret->params [i + 1]->type == sig->params [i]->type && ret->params [i+1]->type != MONO_TYPE_END);
2052         g_assert (ret->ret->type == sig->ret->type && ret->ret->type != MONO_TYPE_END);
2053
2054         return ret;
2055 }
2056
2057
2058
2059 MonoMethodSignature*
2060 mono_metadata_signature_dup_full (MonoImage *image, MonoMethodSignature *sig)
2061 {
2062         MonoMethodSignature *ret = mono_metadata_signature_dup_internal (image, NULL, sig);
2063
2064         for (int i = 0 ; i < sig->param_count; i ++)
2065                 g_assert(ret->params [i]->type == sig->params [i]->type);
2066         g_assert (ret->ret->type == sig->ret->type);
2067
2068         return ret;
2069 }
2070
2071 /*The mempool is accessed without synchronization*/
2072 MonoMethodSignature*
2073 mono_metadata_signature_dup_mempool (MonoMemPool *mp, MonoMethodSignature *sig)
2074 {
2075         return mono_metadata_signature_dup_internal (NULL, mp, sig);
2076 }
2077
2078 /**
2079  * mono_metadata_signature_dup:
2080  * \param sig method signature
2081  *
2082  * Duplicate an existing \c MonoMethodSignature so it can be modified.
2083  * This is a Mono runtime internal function.
2084  *
2085  * \returns the new \c MonoMethodSignature structure.
2086  */
2087 MonoMethodSignature*
2088 mono_metadata_signature_dup (MonoMethodSignature *sig)
2089 {
2090         return mono_metadata_signature_dup_full (NULL, sig);
2091 }
2092
2093 /*
2094  * mono_metadata_signature_size:
2095  *
2096  *   Return the amount of memory allocated to SIG.
2097  */
2098 guint32
2099 mono_metadata_signature_size (MonoMethodSignature *sig)
2100 {
2101         return MONO_SIZEOF_METHOD_SIGNATURE + sig->param_count * sizeof (MonoType *);
2102 }
2103
2104 /*
2105  * mono_metadata_parse_method_signature:
2106  * @m: metadata context
2107  * @generic_container: generics container
2108  * @def: the MethodDef index or 0 for Ref signatures.
2109  * @ptr: pointer to the signature metadata representation
2110  * @rptr: pointer updated to match the end of the decoded stream
2111  *
2112  * Decode a method signature stored at @ptr.
2113  * This is a Mono runtime internal function.
2114  *
2115  * LOCKING: Assumes the loader lock is held.
2116  *
2117  * Returns: a MonoMethodSignature describing the signature.
2118  */
2119 MonoMethodSignature *
2120 mono_metadata_parse_method_signature_full (MonoImage *m, MonoGenericContainer *container,
2121                                            int def, const char *ptr, const char **rptr, MonoError *error)
2122 {
2123         MonoMethodSignature *method;
2124         int i, *pattrs = NULL;
2125         guint32 hasthis = 0, explicit_this = 0, call_convention, param_count;
2126         guint32 gen_param_count = 0;
2127         gboolean is_open = FALSE;
2128
2129         error_init (error);
2130
2131         if (*ptr & 0x10)
2132                 gen_param_count = 1;
2133         if (*ptr & 0x20)
2134                 hasthis = 1;
2135         if (*ptr & 0x40)
2136                 explicit_this = 1;
2137         call_convention = *ptr & 0x0F;
2138         ptr++;
2139         if (gen_param_count)
2140                 gen_param_count = mono_metadata_decode_value (ptr, &ptr);
2141         param_count = mono_metadata_decode_value (ptr, &ptr);
2142
2143         if (def)
2144                 pattrs = mono_metadata_get_param_attrs (m, def, param_count + 1); /*Must be + 1 since signature's param count doesn't account for the return value */
2145
2146         method = mono_metadata_signature_alloc (m, param_count);
2147         method->hasthis = hasthis;
2148         method->explicit_this = explicit_this;
2149         method->call_convention = call_convention;
2150         method->generic_param_count = gen_param_count;
2151
2152         if (call_convention != 0xa) {
2153                 method->ret = mono_metadata_parse_type_checked (m, container, pattrs ? pattrs [0] : 0, FALSE, ptr, &ptr, error);
2154                 if (!method->ret) {
2155                         mono_metadata_free_method_signature (method);
2156                         g_free (pattrs);
2157                         return NULL;
2158                 }
2159                 is_open = mono_class_is_open_constructed_type (method->ret);
2160         }
2161
2162         for (i = 0; i < method->param_count; ++i) {
2163                 if (*ptr == MONO_TYPE_SENTINEL) {
2164                         if (method->call_convention != MONO_CALL_VARARG || def) {
2165                                 mono_error_set_bad_image (error, m, "Found sentinel for methoddef or no vararg");
2166                                 g_free (pattrs);
2167                                 return NULL;
2168                         }
2169                         if (method->sentinelpos >= 0) {
2170                                 mono_error_set_bad_image (error, m, "Found sentinel twice in the same signature.");
2171                                 g_free (pattrs);
2172                                 return NULL;
2173                         }
2174                         method->sentinelpos = i;
2175                         ptr++;
2176                 }
2177                 method->params [i] = mono_metadata_parse_type_checked (m, container, pattrs ? pattrs [i+1] : 0, FALSE, ptr, &ptr, error);
2178                 if (!method->params [i]) {
2179                         mono_metadata_free_method_signature (method);
2180                         g_free (pattrs);
2181                         return NULL;
2182                 }
2183                 if (!is_open)
2184                         is_open = mono_class_is_open_constructed_type (method->params [i]);
2185         }
2186
2187         /* The sentinel could be missing if the caller does not pass any additional arguments */
2188         if (!def && method->call_convention == MONO_CALL_VARARG && method->sentinelpos < 0)
2189                 method->sentinelpos = method->param_count;
2190
2191         method->has_type_parameters = is_open;
2192
2193         if (def && (method->call_convention == MONO_CALL_VARARG))
2194                 method->sentinelpos = method->param_count;
2195
2196         g_free (pattrs);
2197
2198         if (rptr)
2199                 *rptr = ptr;
2200         /*
2201          * Add signature to a cache and increase ref count...
2202          */
2203
2204         return method;
2205 }
2206
2207 /**
2208  * mono_metadata_parse_method_signature:
2209  * \param m metadata context
2210  * \param def the \c MethodDef index or 0 for \c Ref signatures.
2211  * \param ptr pointer to the signature metadata representation
2212  * \param rptr pointer updated to match the end of the decoded stream
2213  *
2214  * Decode a method signature stored at \p ptr.
2215  * This is a Mono runtime internal function.
2216  *
2217  * LOCKING: Assumes the loader lock is held.
2218  *
2219  * \returns a \c MonoMethodSignature describing the signature.
2220  */
2221 MonoMethodSignature *
2222 mono_metadata_parse_method_signature (MonoImage *m, int def, const char *ptr, const char **rptr)
2223 {
2224         /*
2225          * This function MUST NOT be called by runtime code as it does error handling incorrectly.
2226          * Use mono_metadata_parse_method_signature_full instead.
2227          * It's ok to asser on failure as we no longer use it.
2228          */
2229         MonoError error;
2230         MonoMethodSignature *ret;
2231         ret = mono_metadata_parse_method_signature_full (m, NULL, def, ptr, rptr, &error);
2232         g_assert (mono_error_ok (&error));
2233
2234         return ret;
2235 }
2236
2237 /**
2238  * mono_metadata_free_method_signature:
2239  * \param sig signature to destroy
2240  *
2241  * Free the memory allocated in the signature \p sig.
2242  * This method needs to be robust and work also on partially-built
2243  * signatures, so it does extra checks.
2244  */
2245 void
2246 mono_metadata_free_method_signature (MonoMethodSignature *sig)
2247 {
2248         /* Everything is allocated from mempools */
2249         /*
2250         int i;
2251         if (sig->ret)
2252                 mono_metadata_free_type (sig->ret);
2253         for (i = 0; i < sig->param_count; ++i) {
2254                 if (sig->params [i])
2255                         mono_metadata_free_type (sig->params [i]);
2256         }
2257         */
2258 }
2259
2260 void
2261 mono_metadata_free_inflated_signature (MonoMethodSignature *sig)
2262 {
2263         int i;
2264
2265         /* Allocated in inflate_generic_signature () */
2266         if (sig->ret)
2267                 mono_metadata_free_type (sig->ret);
2268         for (i = 0; i < sig->param_count; ++i) {
2269                 if (sig->params [i])
2270                         mono_metadata_free_type (sig->params [i]);
2271         }
2272         g_free (sig);
2273 }
2274
2275 static gboolean
2276 inflated_method_equal (gconstpointer a, gconstpointer b)
2277 {
2278         const MonoMethodInflated *ma = (const MonoMethodInflated *)a;
2279         const MonoMethodInflated *mb = (const MonoMethodInflated *)b;
2280         if (ma->declaring != mb->declaring)
2281                 return FALSE;
2282         return mono_metadata_generic_context_equal (&ma->context, &mb->context);
2283 }
2284
2285 static guint
2286 inflated_method_hash (gconstpointer a)
2287 {
2288         const MonoMethodInflated *ma = (const MonoMethodInflated *)a;
2289         return (mono_metadata_generic_context_hash (&ma->context) ^ mono_aligned_addr_hash (ma->declaring));
2290 }
2291
2292 static gboolean
2293 inflated_signature_equal (gconstpointer a, gconstpointer b)
2294 {
2295         const MonoInflatedMethodSignature *sig1 = (const MonoInflatedMethodSignature *)a;
2296         const MonoInflatedMethodSignature *sig2 = (const MonoInflatedMethodSignature *)b;
2297
2298         /* sig->sig is assumed to be canonized */
2299         if (sig1->sig != sig2->sig)
2300                 return FALSE;
2301         /* The generic instances are canonized */
2302         return mono_metadata_generic_context_equal (&sig1->context, &sig2->context);
2303 }
2304
2305 static guint
2306 inflated_signature_hash (gconstpointer a)
2307 {
2308         const MonoInflatedMethodSignature *sig = (const MonoInflatedMethodSignature *)a;
2309
2310         /* sig->sig is assumed to be canonized */
2311         return mono_metadata_generic_context_hash (&sig->context) ^ mono_aligned_addr_hash (sig->sig);
2312 }
2313
2314 /*static void
2315 dump_ginst (MonoGenericInst *ginst)
2316 {
2317         int i;
2318         char *name;
2319
2320         g_print ("Ginst: <");
2321         for (i = 0; i < ginst->type_argc; ++i) {
2322                 if (i != 0)
2323                         g_print (", ");
2324                 name = mono_type_get_name (ginst->type_argv [i]);
2325                 g_print ("%s", name);
2326                 g_free (name);
2327         }
2328         g_print (">");
2329 }*/
2330
2331 static gboolean type_in_image (MonoType *type, MonoImage *image);
2332
2333 static gboolean
2334 signature_in_image (MonoMethodSignature *sig, MonoImage *image)
2335 {
2336         gpointer iter = NULL;
2337         MonoType *p;
2338
2339         while ((p = mono_signature_get_params (sig, &iter)) != NULL)
2340                 if (type_in_image (p, image))
2341                         return TRUE;
2342
2343         return type_in_image (mono_signature_get_return_type (sig), image);
2344 }
2345
2346 static gboolean
2347 ginst_in_image (MonoGenericInst *ginst, MonoImage *image)
2348 {
2349         int i;
2350
2351         for (i = 0; i < ginst->type_argc; ++i) {
2352                 if (type_in_image (ginst->type_argv [i], image))
2353                         return TRUE;
2354         }
2355
2356         return FALSE;
2357 }
2358
2359 static gboolean
2360 gclass_in_image (MonoGenericClass *gclass, MonoImage *image)
2361 {
2362         return gclass->container_class->image == image ||
2363                 ginst_in_image (gclass->context.class_inst, image);
2364 }
2365
2366 static gboolean
2367 type_in_image (MonoType *type, MonoImage *image)
2368 {
2369 retry:
2370         switch (type->type) {
2371         case MONO_TYPE_GENERICINST:
2372                 return gclass_in_image (type->data.generic_class, image);
2373         case MONO_TYPE_PTR:
2374                 type = type->data.type;
2375                 goto retry;
2376         case MONO_TYPE_SZARRAY:
2377                 type = &type->data.klass->byval_arg;
2378                 goto retry;
2379         case MONO_TYPE_ARRAY:
2380                 type = &type->data.array->eklass->byval_arg;
2381                 goto retry;
2382         case MONO_TYPE_FNPTR:
2383                 return signature_in_image (type->data.method, image);
2384         case MONO_TYPE_VAR:
2385         case MONO_TYPE_MVAR:
2386                 return image == get_image_for_generic_param (type->data.generic_param);
2387         default:
2388                 /* At this point, we should've avoided all potential allocations in mono_class_from_mono_type () */
2389                 return image == mono_class_from_mono_type (type)->image;
2390         }
2391 }
2392
2393 static inline void
2394 image_sets_lock (void)
2395 {
2396         mono_os_mutex_lock (&image_sets_mutex);
2397 }
2398
2399 static inline void
2400 image_sets_unlock (void)
2401 {
2402         mono_os_mutex_unlock (&image_sets_mutex);
2403 }
2404
2405 static int
2406 compare_pointers (const void *a, const void *b)
2407 {
2408         return (size_t)a - (size_t)b;
2409 }
2410
2411 //1103, 1327, 1597
2412 #define HASH_TABLE_SIZE 1103
2413 static MonoImageSet *img_set_cache [HASH_TABLE_SIZE];
2414
2415 static guint32
2416 mix_hash (uintptr_t source)
2417 {
2418         unsigned int hash = source;
2419
2420         // Actual hash
2421         hash = (((hash * 215497) >> 16) ^ ((hash * 1823231) + hash));
2422
2423         // Mix in highest bits on 64-bit systems only
2424         if (sizeof (source) > 4)
2425                 hash = hash ^ (source >> 32);
2426
2427         return hash;
2428 }
2429
2430 static guint32
2431 hash_images (MonoImage **images, int nimages)
2432 {
2433         guint32 res = 0;
2434         int i;
2435         for (i = 0; i < nimages; ++i)
2436                 res += mix_hash ((size_t)images [i]);
2437
2438         return res;
2439 }
2440
2441 static gboolean
2442 compare_img_set (MonoImageSet *set, MonoImage **images, int nimages)
2443 {
2444         int j, k;
2445
2446         if (set->nimages != nimages)
2447                 return FALSE;
2448
2449         for (j = 0; j < nimages; ++j) {
2450                 for (k = 0; k < nimages; ++k)
2451                         if (set->images [k] == images [j])
2452                                 break; // Break on match
2453
2454                 // If we iterated all the way through set->images, images[j] was *not* found.
2455                 if (k == nimages)
2456                         break; // Break on "image not found"
2457         }
2458
2459         // If we iterated all the way through images without breaking, all items in images were found in set->images
2460         return j == nimages;
2461 }
2462
2463
2464 static MonoImageSet*
2465 img_set_cache_get (MonoImage **images, int nimages)
2466 {
2467         guint32 hash_code = hash_images (images, nimages);
2468         int index = hash_code % HASH_TABLE_SIZE;
2469         MonoImageSet *img = img_set_cache [index];
2470         if (!img || !compare_img_set (img, images, nimages)) {
2471                 ++img_set_cache_miss;
2472                 return NULL;
2473         }
2474         ++img_set_cache_hit;
2475         return img;
2476 }
2477
2478 static void
2479 img_set_cache_add (MonoImageSet *set)
2480 {
2481         guint32 hash_code = hash_images (set->images, set->nimages);
2482         int index = hash_code % HASH_TABLE_SIZE;
2483         img_set_cache [index] = set;    
2484 }
2485
2486 static void
2487 img_set_cache_remove (MonoImageSet *is)
2488 {
2489         guint32 hash_code = hash_images (is->images, is->nimages);
2490         int index = hash_code % HASH_TABLE_SIZE;
2491         if (img_set_cache [index] == is)
2492                 img_set_cache [index] = NULL;
2493 }
2494 /*
2495  * get_image_set:
2496  *
2497  *   Return a MonoImageSet representing the set of images in IMAGES.
2498  */
2499 static MonoImageSet*
2500 get_image_set (MonoImage **images, int nimages)
2501 {
2502         int i, j, k;
2503         MonoImageSet *set;
2504         GSList *l;
2505
2506         /* Common case: Image set contains corlib only. If we've seen that case before, we cached the set. */
2507         if (nimages == 1 && images [0] == mono_defaults.corlib && mscorlib_image_set)
2508                 return mscorlib_image_set;
2509
2510         /* Happens with empty generic instances */
2511         // FIXME: Is corlib the correct thing to return here? If so, why? This may be an artifact of generic instances previously defaulting to allocating from corlib.
2512         if (nimages == 0)
2513                 return mscorlib_image_set;
2514
2515         set = img_set_cache_get (images, nimages);
2516         if (set)
2517                 return set;
2518
2519         image_sets_lock ();
2520
2521         if (!image_sets)
2522                 image_sets = g_ptr_array_new ();
2523
2524         // Before we go on, we should check to see whether a MonoImageSet with these images already exists.
2525         // We can search the referred-by imagesets of any one of our images to do this. Arbitrarily pick one here:
2526         if (images [0] == mono_defaults.corlib && nimages > 1)
2527                 l = images [1]->image_sets; // Prefer not to search the imagesets of corlib-- that will be a long list.
2528         else
2529                 l = images [0]->image_sets;
2530
2531         set = NULL;
2532         while (l) // Iterate over selected list, looking for an imageset with members equal to our target one
2533         {
2534                 set = (MonoImageSet *)l->data;
2535
2536                 if (set->nimages == nimages) { // Member count differs, this can't be it
2537                         // Compare all members to all members-- order might be different
2538                         for (j = 0; j < nimages; ++j) {
2539                                 for (k = 0; k < nimages; ++k)
2540                                         if (set->images [k] == images [j])
2541                                                 break; // Break on match
2542
2543                                 // If we iterated all the way through set->images, images[j] was *not* found.
2544                                 if (k == nimages)
2545                                         break; // Break on "image not found"
2546                         }
2547
2548                         // If we iterated all the way through images without breaking, all items in images were found in set->images
2549                         if (j == nimages) {
2550                                 // Break on "found a set with equal members".
2551                                 // This happens in case of a hash collision with a previously cached set.
2552                                 break;
2553                         }
2554                 }
2555
2556                 l = l->next;
2557         }
2558
2559         // If we iterated all the way through l without breaking, the imageset does not already exist and we shuold create it
2560         if (!l) {
2561                 set = g_new0 (MonoImageSet, 1);
2562                 set->nimages = nimages;
2563                 set->images = g_new0 (MonoImage*, nimages);
2564                 mono_os_mutex_init_recursive (&set->lock);
2565                 for (i = 0; i < nimages; ++i)
2566                         set->images [i] = images [i];
2567                 set->gclass_cache = mono_conc_hashtable_new_full (mono_generic_class_hash, mono_generic_class_equal, NULL, (GDestroyNotify)free_generic_class);
2568                 set->ginst_cache = g_hash_table_new_full (mono_metadata_generic_inst_hash, mono_metadata_generic_inst_equal, NULL, (GDestroyNotify)free_generic_inst);
2569                 set->gmethod_cache = g_hash_table_new_full (inflated_method_hash, inflated_method_equal, NULL, (GDestroyNotify)free_inflated_method);
2570                 set->gsignature_cache = g_hash_table_new_full (inflated_signature_hash, inflated_signature_equal, NULL, (GDestroyNotify)free_inflated_signature);
2571
2572                 for (i = 0; i < nimages; ++i)
2573                         set->images [i]->image_sets = g_slist_prepend (set->images [i]->image_sets, set);
2574
2575                 g_ptr_array_add (image_sets, set);
2576                 ++img_set_count;
2577         }
2578
2579         /* Cache the set. If there was a cache collision, the previously cached value will be replaced. */
2580         img_set_cache_add (set);
2581
2582         if (nimages == 1 && images [0] == mono_defaults.corlib) {
2583                 mono_memory_barrier ();
2584                 mscorlib_image_set = set;
2585         }
2586
2587         image_sets_unlock ();
2588
2589         return set;
2590 }
2591
2592 static void
2593 delete_image_set (MonoImageSet *set)
2594 {
2595         int i;
2596
2597         mono_conc_hashtable_destroy (set->gclass_cache);
2598         g_hash_table_destroy (set->ginst_cache);
2599         g_hash_table_destroy (set->gmethod_cache);
2600         g_hash_table_destroy (set->gsignature_cache);
2601
2602         mono_wrapper_caches_free (&set->wrapper_caches);
2603
2604         image_sets_lock ();
2605
2606         for (i = 0; i < set->nimages; ++i)
2607                 set->images [i]->image_sets = g_slist_remove (set->images [i]->image_sets, set);
2608
2609         g_ptr_array_remove (image_sets, set);
2610
2611         image_sets_unlock ();
2612
2613         img_set_cache_remove (set);
2614
2615         if (set->mempool)
2616                 mono_mempool_destroy (set->mempool);
2617         g_free (set->images);
2618         mono_os_mutex_destroy (&set->lock);
2619         g_free (set);
2620 }
2621
2622 void
2623 mono_image_set_lock (MonoImageSet *set)
2624 {
2625         mono_os_mutex_lock (&set->lock);
2626 }
2627
2628 void
2629 mono_image_set_unlock (MonoImageSet *set)
2630 {
2631         mono_os_mutex_unlock (&set->lock);
2632 }
2633
2634 gpointer
2635 mono_image_set_alloc (MonoImageSet *set, guint size)
2636 {
2637         gpointer res;
2638
2639         mono_image_set_lock (set);
2640         if (!set->mempool)
2641                 set->mempool = mono_mempool_new_size (INITIAL_IMAGE_SET_SIZE);
2642         res = mono_mempool_alloc (set->mempool, size);
2643         mono_image_set_unlock (set);
2644
2645         return res;
2646 }
2647
2648 gpointer
2649 mono_image_set_alloc0 (MonoImageSet *set, guint size)
2650 {
2651         gpointer res;
2652
2653         mono_image_set_lock (set);
2654         if (!set->mempool)
2655                 set->mempool = mono_mempool_new_size (INITIAL_IMAGE_SET_SIZE);
2656         res = mono_mempool_alloc0 (set->mempool, size);
2657         mono_image_set_unlock (set);
2658
2659         return res;
2660 }
2661
2662 char*
2663 mono_image_set_strdup (MonoImageSet *set, const char *s)
2664 {
2665         char *res;
2666
2667         mono_image_set_lock (set);
2668         if (!set->mempool)
2669                 set->mempool = mono_mempool_new_size (INITIAL_IMAGE_SET_SIZE);
2670         res = mono_mempool_strdup (set->mempool, s);
2671         mono_image_set_unlock (set);
2672
2673         return res;
2674 }
2675
2676 // Get a descriptive string for a MonoImageSet
2677 // Callers are obligated to free buffer with g_free after use
2678 char *
2679 mono_image_set_description (MonoImageSet *set)
2680 {
2681         GString *result = g_string_new (NULL);
2682         int img;
2683         g_string_append (result, "[");
2684         for (img = 0; img < set->nimages; img++)
2685         {
2686                 if (img > 0)
2687                         g_string_append (result, ", ");
2688                 g_string_append (result, set->images[img]->name);
2689         }
2690         g_string_append (result, "]");
2691         return g_string_free (result, FALSE);
2692 }
2693
2694 /* 
2695  * Structure used by the collect_..._images functions to store the image list.
2696  */
2697 typedef struct {
2698         MonoImage *image_buf [64];
2699         MonoImage **images;
2700         int nimages, images_len;
2701 } CollectData;
2702
2703 static void
2704 collect_data_init (CollectData *data)
2705 {
2706         data->images = data->image_buf;
2707         data->images_len = 64;
2708         data->nimages = 0;
2709 }
2710
2711 static void
2712 collect_data_free (CollectData *data)
2713 {
2714         if (data->images != data->image_buf)
2715                 g_free (data->images);
2716 }
2717
2718 static void
2719 enlarge_data (CollectData *data)
2720 {
2721         int new_len = data->images_len < 16 ? 16 : data->images_len * 2;
2722         MonoImage **d = g_new (MonoImage *, new_len);
2723
2724         // FIXME: test this
2725         g_assert_not_reached ();
2726         memcpy (d, data->images, data->images_len);
2727         if (data->images != data->image_buf)
2728                 g_free (data->images);
2729         data->images = d;
2730         data->images_len = new_len;
2731 }
2732
2733 static inline void
2734 add_image (MonoImage *image, CollectData *data)
2735 {
2736         int i;
2737
2738         /* The arrays are small, so use a linear search instead of a hash table */
2739         for (i = 0; i < data->nimages; ++i)
2740                 if (data->images [i] == image)
2741                         return;
2742
2743         if (data->nimages == data->images_len)
2744                 enlarge_data (data);
2745
2746         data->images [data->nimages ++] = image;
2747 }
2748
2749 static void
2750 collect_type_images (MonoType *type, CollectData *data);
2751
2752 static void
2753 collect_ginst_images (MonoGenericInst *ginst, CollectData *data)
2754 {
2755         int i;
2756
2757         for (i = 0; i < ginst->type_argc; ++i) {
2758                 collect_type_images (ginst->type_argv [i], data);
2759         }
2760 }
2761
2762 static void
2763 collect_gclass_images (MonoGenericClass *gclass, CollectData *data)
2764 {
2765         add_image (gclass->container_class->image, data);
2766         if (gclass->context.class_inst)
2767                 collect_ginst_images (gclass->context.class_inst, data);
2768 }
2769
2770 static void
2771 collect_signature_images (MonoMethodSignature *sig, CollectData *data)
2772 {
2773         gpointer iter = NULL;
2774         MonoType *p;
2775
2776         collect_type_images (mono_signature_get_return_type (sig), data);
2777         while ((p = mono_signature_get_params (sig, &iter)) != NULL)
2778                 collect_type_images (p, data);
2779 }
2780
2781 static void
2782 collect_inflated_signature_images (MonoInflatedMethodSignature *sig, CollectData *data)
2783 {
2784         collect_signature_images (sig->sig, data);
2785         if (sig->context.class_inst)
2786                 collect_ginst_images (sig->context.class_inst, data);
2787         if (sig->context.method_inst)
2788                 collect_ginst_images (sig->context.method_inst, data);
2789 }
2790
2791 static void
2792 collect_method_images (MonoMethodInflated *method, CollectData *data)
2793 {
2794         MonoMethod *m = method->declaring;
2795
2796         add_image (method->declaring->klass->image, data);
2797         if (method->context.class_inst)
2798                 collect_ginst_images (method->context.class_inst, data);
2799         if (method->context.method_inst)
2800                 collect_ginst_images (method->context.method_inst, data);
2801         /*
2802          * Dynamic assemblies have no references, so the images they depend on can be unloaded before them.
2803          */
2804         if (image_is_dynamic (m->klass->image))
2805                 collect_signature_images (mono_method_signature (m), data);
2806 }
2807
2808 static void
2809 collect_type_images (MonoType *type, CollectData *data)
2810 {
2811 retry:
2812         switch (type->type) {
2813         case MONO_TYPE_GENERICINST:
2814                 collect_gclass_images (type->data.generic_class, data);
2815                 break;
2816         case MONO_TYPE_PTR:
2817                 type = type->data.type;
2818                 goto retry;
2819         case MONO_TYPE_SZARRAY:
2820                 type = &type->data.klass->byval_arg;
2821                 goto retry;
2822         case MONO_TYPE_ARRAY:
2823                 type = &type->data.array->eklass->byval_arg;
2824                 goto retry;
2825         case MONO_TYPE_FNPTR:
2826                 //return signature_in_image (type->data.method, image);
2827                 g_assert_not_reached ();
2828         case MONO_TYPE_VAR:
2829         case MONO_TYPE_MVAR:
2830         {
2831                 MonoImage *image = get_image_for_generic_param (type->data.generic_param);
2832                 add_image (image, data);
2833                 break;
2834         }
2835         case MONO_TYPE_CLASS:
2836         case MONO_TYPE_VALUETYPE:
2837                 add_image (mono_class_from_mono_type (type)->image, data);
2838                 break;
2839         default:
2840                 add_image (mono_defaults.corlib, data);
2841         }
2842 }
2843
2844 typedef struct {
2845         MonoImage *image;
2846         GSList *list;
2847 } CleanForImageUserData;
2848
2849 static gboolean
2850 steal_gclass_in_image (gpointer key, gpointer value, gpointer data)
2851 {
2852         MonoGenericClass *gclass = (MonoGenericClass *)key;
2853         CleanForImageUserData *user_data = (CleanForImageUserData *)data;
2854
2855         g_assert (gclass_in_image (gclass, user_data->image));
2856
2857         user_data->list = g_slist_prepend (user_data->list, gclass);
2858         return TRUE;
2859 }
2860
2861 static gboolean
2862 steal_ginst_in_image (gpointer key, gpointer value, gpointer data)
2863 {
2864         MonoGenericInst *ginst = (MonoGenericInst *)key;
2865         CleanForImageUserData *user_data = (CleanForImageUserData *)data;
2866
2867         // This doesn't work during corlib compilation
2868         //g_assert (ginst_in_image (ginst, user_data->image));
2869
2870         user_data->list = g_slist_prepend (user_data->list, ginst);
2871         return TRUE;
2872 }
2873
2874 static gboolean
2875 inflated_method_in_image (gpointer key, gpointer value, gpointer data)
2876 {
2877         MonoImage *image = (MonoImage *)data;
2878         MonoMethodInflated *method = (MonoMethodInflated *)key;
2879
2880         // FIXME:
2881         // https://bugzilla.novell.com/show_bug.cgi?id=458168
2882         g_assert (method->declaring->klass->image == image ||
2883                 (method->context.class_inst && ginst_in_image (method->context.class_inst, image)) ||
2884                           (method->context.method_inst && ginst_in_image (method->context.method_inst, image)) || (((MonoMethod*)method)->signature && signature_in_image (mono_method_signature ((MonoMethod*)method), image)));
2885
2886         return TRUE;
2887 }
2888
2889 static gboolean
2890 inflated_signature_in_image (gpointer key, gpointer value, gpointer data)
2891 {
2892         MonoImage *image = (MonoImage *)data;
2893         MonoInflatedMethodSignature *sig = (MonoInflatedMethodSignature *)key;
2894
2895         return signature_in_image (sig->sig, image) ||
2896                 (sig->context.class_inst && ginst_in_image (sig->context.class_inst, image)) ||
2897                 (sig->context.method_inst && ginst_in_image (sig->context.method_inst, image));
2898 }       
2899
2900 static void
2901 check_gmethod (gpointer key, gpointer value, gpointer data)
2902 {
2903         MonoMethodInflated *method = (MonoMethodInflated *)key;
2904         MonoImage *image = (MonoImage *)data;
2905
2906         if (method->context.class_inst)
2907                 g_assert (!ginst_in_image (method->context.class_inst, image));
2908         if (method->context.method_inst)
2909                 g_assert (!ginst_in_image (method->context.method_inst, image));
2910         if (((MonoMethod*)method)->signature)
2911                 g_assert (!signature_in_image (mono_method_signature ((MonoMethod*)method), image));
2912 }
2913
2914 /*
2915  * check_image_sets:
2916  *
2917  *   Run a consistency check on the image set data structures.
2918  */
2919 static G_GNUC_UNUSED void
2920 check_image_sets (MonoImage *image)
2921 {
2922         int i;
2923         GSList *l = image->image_sets;
2924
2925         if (!image_sets)
2926                 return;
2927
2928         for (i = 0; i < image_sets->len; ++i) {
2929                 MonoImageSet *set = (MonoImageSet *)g_ptr_array_index (image_sets, i);
2930
2931                 if (!g_slist_find (l, set)) {
2932                         g_hash_table_foreach (set->gmethod_cache, check_gmethod, image);
2933                 }
2934         }
2935 }
2936
2937 void
2938 mono_metadata_clean_for_image (MonoImage *image)
2939 {
2940         CleanForImageUserData ginst_data, gclass_data;
2941         GSList *l, *set_list;
2942
2943         //check_image_sets (image);
2944
2945         /*
2946          * The data structures could reference each other so we delete them in two phases.
2947          * This is required because of the hashing functions in gclass/ginst_cache.
2948          */
2949         ginst_data.image = gclass_data.image = image;
2950         ginst_data.list = gclass_data.list = NULL;
2951
2952         /* Collect the items to delete */
2953         /* delete_image_set () modifies the lists so make a copy */
2954         for (l = image->image_sets; l; l = l->next) {
2955                 MonoImageSet *set = (MonoImageSet *)l->data;
2956
2957                 mono_image_set_lock (set);
2958                 mono_conc_hashtable_foreach_steal (set->gclass_cache, steal_gclass_in_image, &gclass_data);
2959                 g_hash_table_foreach_steal (set->ginst_cache, steal_ginst_in_image, &ginst_data);
2960                 g_hash_table_foreach_remove (set->gmethod_cache, inflated_method_in_image, image);
2961                 g_hash_table_foreach_remove (set->gsignature_cache, inflated_signature_in_image, image);
2962                 mono_image_set_unlock (set);
2963         }
2964
2965         /* Delete the removed items */
2966         for (l = ginst_data.list; l; l = l->next)
2967                 free_generic_inst ((MonoGenericInst *)l->data);
2968         for (l = gclass_data.list; l; l = l->next)
2969                 free_generic_class ((MonoGenericClass *)l->data);
2970         g_slist_free (ginst_data.list);
2971         g_slist_free (gclass_data.list);
2972         /* delete_image_set () modifies the lists so make a copy */
2973         set_list = g_slist_copy (image->image_sets);
2974         for (l = set_list; l; l = l->next) {
2975                 MonoImageSet *set = (MonoImageSet *)l->data;
2976
2977                 delete_image_set (set);
2978         }
2979         g_slist_free (set_list);
2980 }
2981
2982 static void
2983 free_inflated_method (MonoMethodInflated *imethod)
2984 {
2985         MonoMethod *method = (MonoMethod*)imethod;
2986
2987         if (method->signature)
2988                 mono_metadata_free_inflated_signature (method->signature);
2989
2990         if (method->wrapper_type)
2991                 g_free (((MonoMethodWrapper*)method)->method_data);
2992
2993         g_free (method);
2994 }
2995
2996 static void
2997 free_generic_inst (MonoGenericInst *ginst)
2998 {
2999         int i;
3000
3001         /* The ginst itself is allocated from the image set mempool */
3002         for (i = 0; i < ginst->type_argc; ++i)
3003                 mono_metadata_free_type (ginst->type_argv [i]);
3004 }
3005
3006 static void
3007 free_generic_class (MonoGenericClass *gclass)
3008 {
3009         /* The gclass itself is allocated from the image set mempool */
3010         if (gclass->cached_class && gclass->cached_class->interface_id)
3011                 mono_unload_interface_id (gclass->cached_class);
3012 }
3013
3014 static void
3015 free_inflated_signature (MonoInflatedMethodSignature *sig)
3016 {
3017         mono_metadata_free_inflated_signature (sig->sig);
3018         g_free (sig);
3019 }
3020
3021 /*
3022  * mono_metadata_get_inflated_signature:
3023  *
3024  *   Given an inflated signature and a generic context, return a canonical copy of the 
3025  * signature. The returned signature might be equal to SIG or it might be a cached copy.
3026  */
3027 MonoMethodSignature *
3028 mono_metadata_get_inflated_signature (MonoMethodSignature *sig, MonoGenericContext *context)
3029 {
3030         MonoInflatedMethodSignature helper;
3031         MonoInflatedMethodSignature *res;
3032         CollectData data;
3033         MonoImageSet *set;
3034
3035         helper.sig = sig;
3036         helper.context.class_inst = context->class_inst;
3037         helper.context.method_inst = context->method_inst;
3038
3039         collect_data_init (&data);
3040
3041         collect_inflated_signature_images (&helper, &data);
3042
3043         set = get_image_set (data.images, data.nimages);
3044
3045         collect_data_free (&data);
3046
3047         mono_image_set_lock (set);
3048
3049         res = (MonoInflatedMethodSignature *)g_hash_table_lookup (set->gsignature_cache, &helper);
3050         if (!res) {
3051                 res = g_new0 (MonoInflatedMethodSignature, 1);
3052                 res->sig = sig;
3053                 res->context.class_inst = context->class_inst;
3054                 res->context.method_inst = context->method_inst;
3055                 g_hash_table_insert (set->gsignature_cache, res, res);
3056         }
3057
3058         mono_image_set_unlock (set);
3059
3060         return res->sig;
3061 }
3062
3063 MonoImageSet *
3064 mono_metadata_get_image_set_for_method (MonoMethodInflated *method)
3065 {
3066         MonoImageSet *set;
3067         CollectData image_set_data;
3068
3069         collect_data_init (&image_set_data);
3070         collect_method_images (method, &image_set_data);
3071         set = get_image_set (image_set_data.images, image_set_data.nimages);
3072         collect_data_free (&image_set_data);
3073
3074         return set;
3075 }
3076
3077 static gboolean
3078 type_is_gtd (MonoType *type)
3079 {
3080         switch (type->type) {
3081         case MONO_TYPE_CLASS:
3082         case MONO_TYPE_VALUETYPE:
3083                 return mono_class_is_gtd (type->data.klass);
3084         default:
3085                 return FALSE;
3086         }
3087 }
3088
3089 /*
3090  * mono_metadata_get_generic_inst:
3091  *
3092  * Given a list of types, return a MonoGenericInst that represents that list.
3093  * The returned MonoGenericInst has its own copy of the list of types.  The list
3094  * passed in the argument can be freed, modified or disposed of.
3095  *
3096  */
3097 MonoGenericInst *
3098 mono_metadata_get_generic_inst (int type_argc, MonoType **type_argv)
3099 {
3100         MonoGenericInst *ginst;
3101         gboolean is_open;
3102         int i;
3103         int size = MONO_SIZEOF_GENERIC_INST + type_argc * sizeof (MonoType *);
3104
3105         for (i = 0; i < type_argc; ++i)
3106                 if (mono_class_is_open_constructed_type (type_argv [i]))
3107                         break;
3108         is_open = (i < type_argc);
3109
3110         ginst = (MonoGenericInst *)g_alloca (size);
3111         memset (ginst, 0, sizeof (MonoGenericInst));
3112         ginst->is_open = is_open;
3113         ginst->type_argc = type_argc;
3114         memcpy (ginst->type_argv, type_argv, type_argc * sizeof (MonoType *));
3115
3116         for (i = 0; i < type_argc; ++i) {
3117                 MonoType *t = ginst->type_argv [i];
3118                 if (type_is_gtd (t)) {
3119                         ginst->type_argv [i] = mono_class_gtd_get_canonical_inst (t->data.klass);
3120                 }
3121         }
3122
3123         return mono_metadata_get_canonical_generic_inst (ginst);
3124 }
3125
3126
3127 /**
3128  * mono_metadata_get_canonical_generic_inst:
3129  * \param candidate an arbitrary generic instantiation
3130  *
3131  * \returns the canonical generic instantiation that represents the given
3132  * candidate by identifying the image set for the candidate instantiation and
3133  * finding the instance in the image set or adding a copy of the given instance
3134  * to the image set.
3135  *
3136  * The returned MonoGenericInst has its own copy of the list of types.  The list
3137  * passed in the argument can be freed, modified or disposed of.
3138  *
3139  */
3140 MonoGenericInst *
3141 mono_metadata_get_canonical_generic_inst (MonoGenericInst *candidate)
3142 {
3143         CollectData data;
3144         int type_argc = candidate->type_argc;
3145         gboolean is_open = candidate->is_open;
3146         MonoImageSet *set;
3147
3148         collect_data_init (&data);
3149
3150         collect_ginst_images (candidate, &data);
3151
3152         set = get_image_set (data.images, data.nimages);
3153
3154         collect_data_free (&data);
3155
3156         mono_image_set_lock (set);
3157
3158         MonoGenericInst *ginst = (MonoGenericInst *)g_hash_table_lookup (set->ginst_cache, candidate);
3159         if (!ginst) {
3160                 int size = MONO_SIZEOF_GENERIC_INST + type_argc * sizeof (MonoType *);
3161                 ginst = (MonoGenericInst *)mono_image_set_alloc0 (set, size);
3162 #ifndef MONO_SMALL_CONFIG
3163                 ginst->id = InterlockedIncrement (&next_generic_inst_id);
3164 #endif
3165                 ginst->is_open = is_open;
3166                 ginst->type_argc = type_argc;
3167
3168                 for (int i = 0; i < type_argc; ++i)
3169                         ginst->type_argv [i] = mono_metadata_type_dup (NULL, candidate->type_argv [i]);
3170
3171                 g_hash_table_insert (set->ginst_cache, ginst, ginst);
3172         }
3173
3174         mono_image_set_unlock (set);
3175         return ginst;
3176 }
3177
3178 static gboolean
3179 mono_metadata_is_type_builder_generic_type_definition (MonoClass *container_class, MonoGenericInst *inst, gboolean is_dynamic)
3180 {
3181         MonoGenericContainer *container = mono_class_get_generic_container (container_class); 
3182
3183         if (!is_dynamic || container_class->wastypebuilder || container->type_argc != inst->type_argc)
3184                 return FALSE;
3185         return inst == container->context.class_inst;
3186 }
3187
3188 /*
3189  * mono_metadata_lookup_generic_class:
3190  *
3191  * Returns a MonoGenericClass with the given properties.
3192  *
3193  */
3194 MonoGenericClass *
3195 mono_metadata_lookup_generic_class (MonoClass *container_class, MonoGenericInst *inst, gboolean is_dynamic)
3196 {
3197         MonoGenericClass *gclass;
3198         MonoGenericClass helper;
3199         gboolean is_tb_open = mono_metadata_is_type_builder_generic_type_definition (container_class, inst, is_dynamic);
3200         MonoImageSet *set;
3201         CollectData data;
3202
3203         g_assert (mono_class_get_generic_container (container_class)->type_argc == inst->type_argc);
3204
3205         memset (&helper, 0, sizeof(helper)); // act like g_new0
3206         helper.container_class = container_class;
3207         helper.context.class_inst = inst;
3208         helper.is_dynamic = is_dynamic; /* We use this in a hash lookup, which does not attempt to downcast the pointer */
3209         helper.is_tb_open = is_tb_open;
3210
3211         collect_data_init (&data);
3212
3213         collect_gclass_images (&helper, &data);
3214
3215         set = get_image_set (data.images, data.nimages);
3216
3217         collect_data_free (&data);
3218
3219         gclass = (MonoGenericClass *)mono_conc_hashtable_lookup (set->gclass_cache, &helper);
3220
3221         /* A tripwire just to keep us honest */
3222         g_assert (!helper.cached_class);
3223
3224         if (gclass)
3225                 return gclass;
3226
3227         gclass = mono_image_set_new0 (set, MonoGenericClass, 1);
3228         if (is_dynamic)
3229                 gclass->is_dynamic = 1;
3230
3231         gclass->is_tb_open = is_tb_open;
3232         gclass->container_class = container_class;
3233         gclass->context.class_inst = inst;
3234         gclass->context.method_inst = NULL;
3235         gclass->owner = set;
3236         if (inst == mono_class_get_generic_container (container_class)->context.class_inst && !is_tb_open)
3237                 gclass->cached_class = container_class;
3238
3239         mono_image_set_lock (set);
3240
3241         MonoGenericClass *gclass2 = mono_conc_hashtable_insert (set->gclass_cache, gclass, gclass);
3242         if (!gclass2)
3243                 gclass2 = gclass;
3244
3245         // g_hash_table_insert (set->gclass_cache, gclass, gclass);
3246
3247         mono_image_set_unlock (set);
3248
3249         return gclass2;
3250 }
3251
3252 /*
3253  * mono_metadata_inflate_generic_inst:
3254  *
3255  * Instantiate the generic instance @ginst with the context @context.
3256  * Check @error for success.
3257  *
3258  */
3259 MonoGenericInst *
3260 mono_metadata_inflate_generic_inst (MonoGenericInst *ginst, MonoGenericContext *context, MonoError *error)
3261 {
3262         MonoType **type_argv;
3263         MonoGenericInst *nginst = NULL;
3264         int i, count = 0;
3265
3266         error_init (error);
3267
3268         if (!ginst->is_open)
3269                 return ginst;
3270
3271         type_argv = g_new0 (MonoType*, ginst->type_argc);
3272
3273         for (i = 0; i < ginst->type_argc; i++) {
3274                 type_argv [i] = mono_class_inflate_generic_type_checked (ginst->type_argv [i], context, error);
3275                 if (!mono_error_ok (error))
3276                         goto cleanup;
3277                 ++count;
3278         }
3279
3280         nginst = mono_metadata_get_generic_inst (ginst->type_argc, type_argv);
3281
3282 cleanup:
3283         for (i = 0; i < count; i++)
3284                 mono_metadata_free_type (type_argv [i]);
3285         g_free (type_argv);
3286
3287         return nginst;
3288 }
3289
3290 MonoGenericInst *
3291 mono_metadata_parse_generic_inst (MonoImage *m, MonoGenericContainer *container,
3292                                   int count, const char *ptr, const char **rptr, MonoError *error)
3293 {
3294         MonoType **type_argv;
3295         MonoGenericInst *ginst;
3296         int i;
3297
3298         error_init (error);
3299         type_argv = g_new0 (MonoType*, count);
3300
3301         for (i = 0; i < count; i++) {
3302                 MonoType *t = mono_metadata_parse_type_checked (m, container, 0, FALSE, ptr, &ptr, error);
3303                 if (!t) {
3304                         g_free (type_argv);
3305                         return NULL;
3306                 }
3307                 type_argv [i] = t;
3308         }
3309
3310         if (rptr)
3311                 *rptr = ptr;
3312
3313         ginst = mono_metadata_get_generic_inst (count, type_argv);
3314
3315         g_free (type_argv);
3316
3317         return ginst;
3318 }
3319
3320 static gboolean
3321 do_mono_metadata_parse_generic_class (MonoType *type, MonoImage *m, MonoGenericContainer *container,
3322                                       const char *ptr, const char **rptr, MonoError *error)
3323 {
3324         MonoGenericInst *inst;
3325         MonoClass *gklass;
3326         MonoType *gtype;
3327         int count;
3328
3329         error_init (error);
3330
3331         // XXX how about transient?
3332         gtype = mono_metadata_parse_type_checked (m, NULL, 0, FALSE, ptr, &ptr, error);
3333         if (gtype == NULL)
3334                 return FALSE;
3335
3336         gklass = mono_class_from_mono_type (gtype);
3337         if (!mono_class_is_gtd (gklass)) {
3338                 mono_error_set_bad_image (error, m, "Generic instance with non-generic definition");
3339                 return FALSE;
3340         }
3341
3342         count = mono_metadata_decode_value (ptr, &ptr);
3343         inst = mono_metadata_parse_generic_inst (m, container, count, ptr, &ptr, error);
3344         if (inst == NULL)
3345                 return FALSE;
3346
3347         if (rptr)
3348                 *rptr = ptr;
3349
3350         type->data.generic_class = mono_metadata_lookup_generic_class (gklass, inst, FALSE);
3351         return TRUE;
3352 }
3353
3354 /*
3355  * select_container:
3356  * @gc: The generic container to normalize
3357  * @type: The kind of generic parameters the resulting generic-container should contain
3358  */
3359
3360 static MonoGenericContainer *
3361 select_container (MonoGenericContainer *gc, MonoTypeEnum type)
3362 {
3363         gboolean is_var = (type == MONO_TYPE_VAR);
3364         if (!gc)
3365                 return NULL;
3366
3367         g_assert (is_var || type == MONO_TYPE_MVAR);
3368
3369         if (is_var) {
3370                 if (gc->is_method || gc->parent)
3371                         /*
3372                          * The current MonoGenericContainer is a generic method -> its `parent'
3373                          * points to the containing class'es container.
3374                          */
3375                         return gc->parent;
3376         }
3377
3378         return gc;
3379 }
3380
3381 MonoGenericContainer *
3382 get_anonymous_container_for_image (MonoImage *image, gboolean is_mvar)
3383 {
3384         MonoGenericContainer **container_pointer;
3385         if (is_mvar)
3386                 container_pointer = &image->anonymous_generic_method_container;
3387         else
3388                 container_pointer = &image->anonymous_generic_class_container;
3389         MonoGenericContainer *result = *container_pointer;
3390
3391         // This container has never been created; make it now.
3392         if (!result)
3393         {
3394                 // Note this is never deallocated anywhere-- it exists for the lifetime of the image it's allocated from
3395                 result = (MonoGenericContainer *)mono_image_alloc0 (image, sizeof (MonoGenericContainer));
3396                 result->owner.image = image;
3397                 result->is_anonymous = TRUE;
3398                 result->is_small_param = TRUE;
3399                 result->is_method = is_mvar;
3400
3401                 // If another thread already made a container, use that and leak this new one.
3402                 // (Technically it would currently be safe to just assign instead of CASing.)
3403                 MonoGenericContainer *exchange = (MonoGenericContainer *)InterlockedCompareExchangePointer ((volatile gpointer *)container_pointer, result, NULL);
3404                 if (exchange)
3405                         result = exchange;
3406         }
3407         return result;
3408 }
3409
3410 /*
3411  * mono_metadata_parse_generic_param:
3412  * @generic_container: Our MonoClass's or MonoMethod's MonoGenericContainer;
3413  *                     see mono_metadata_parse_type_checked() for details.
3414  * Internal routine to parse a generic type parameter.
3415  * LOCKING: Acquires the loader lock
3416  */
3417 static MonoGenericParam *
3418 mono_metadata_parse_generic_param (MonoImage *m, MonoGenericContainer *generic_container,
3419                                    MonoTypeEnum type, const char *ptr, const char **rptr, MonoError *error)
3420 {
3421         int index = mono_metadata_decode_value (ptr, &ptr);
3422         if (rptr)
3423                 *rptr = ptr;
3424
3425         error_init (error);
3426
3427         generic_container = select_container (generic_container, type);
3428         if (!generic_container) {
3429                 gboolean is_mvar = FALSE;
3430                 switch (type)
3431                 {
3432                         case MONO_TYPE_VAR:
3433                                 break;
3434                         case MONO_TYPE_MVAR:
3435                                 is_mvar = TRUE;
3436                                 break;
3437                         default:
3438                                 g_error ("Cerating generic param object with invalid MonoType"); // This is not a generic param
3439                 }
3440
3441                 /* Create dummy MonoGenericParam */
3442                 MonoGenericParam *param;
3443
3444                 param = (MonoGenericParam *)mono_image_alloc0 (m, sizeof (MonoGenericParam));
3445                 param->num = index;
3446                 param->owner = get_anonymous_container_for_image (m, is_mvar);
3447
3448                 return param;
3449         }
3450
3451         if (index >= generic_container->type_argc) {
3452                 mono_error_set_bad_image (error, m, "Invalid generic %s parameter index %d, max index is %d",
3453                         generic_container->is_method ? "method" : "type",
3454                         index, generic_container->type_argc);
3455                 return NULL;
3456         }
3457
3458         //This can't return NULL
3459         return mono_generic_container_get_param (generic_container, index);
3460 }
3461
3462 /*
3463  * mono_metadata_get_shared_type:
3464  *
3465  *   Return a shared instance of TYPE, if available, NULL otherwise.
3466  * Shared MonoType instances help save memory. Their contents should not be modified
3467  * by the caller. They do not need to be freed as their lifetime is bound by either
3468  * the lifetime of the runtime (builtin types), or the lifetime of the MonoClass
3469  * instance they are embedded in. If they are freed, they should be freed using
3470  * mono_metadata_free_type () instead of g_free ().
3471  */
3472 MonoType*
3473 mono_metadata_get_shared_type (MonoType *type)
3474 {
3475         MonoType *cached;
3476
3477         /* No need to use locking since nobody is modifying the hash table */
3478         if ((cached = (MonoType *)g_hash_table_lookup (type_cache, type)))
3479                 return cached;
3480
3481         switch (type->type){
3482         case MONO_TYPE_CLASS:
3483         case MONO_TYPE_VALUETYPE:
3484                 if (type == &type->data.klass->byval_arg)
3485                         return type;
3486                 if (type == &type->data.klass->this_arg)
3487                         return type;
3488                 break;
3489         default:
3490                 break;
3491         }
3492
3493         return NULL;
3494 }
3495
3496 static gboolean
3497 compare_type_literals (MonoImage *image, int class_type, int type_type, MonoError *error)
3498 {
3499         error_init (error);
3500
3501         /* byval_arg.type can be zero if we're decoding a type that references a class been loading.
3502          * See mcs/test/gtest-440. and #650936.
3503          * FIXME This better be moved to the metadata verifier as it can catch more cases.
3504          */
3505         if (!class_type)
3506                 return TRUE;
3507         /* NET 1.1 assemblies might encode string and object in a denormalized way.
3508          * See #675464.
3509          */
3510         if (class_type == type_type)
3511                 return TRUE;
3512
3513         if (type_type == MONO_TYPE_CLASS) {
3514                 if (class_type == MONO_TYPE_STRING || class_type == MONO_TYPE_OBJECT)
3515                         return TRUE;
3516                 //XXX stringify this argument
3517                 mono_error_set_bad_image (error, image, "Expected reference type but got type kind %d", class_type);
3518                 return FALSE;
3519         }
3520
3521         g_assert (type_type == MONO_TYPE_VALUETYPE);
3522         switch (class_type) {
3523         case MONO_TYPE_BOOLEAN:
3524         case MONO_TYPE_CHAR:
3525         case MONO_TYPE_I1:
3526         case MONO_TYPE_U1:
3527         case MONO_TYPE_I2:
3528         case MONO_TYPE_U2:
3529         case MONO_TYPE_I4:
3530         case MONO_TYPE_U4:
3531         case MONO_TYPE_I8:
3532         case MONO_TYPE_U8:
3533         case MONO_TYPE_R4:
3534         case MONO_TYPE_R8:
3535         case MONO_TYPE_I:
3536         case MONO_TYPE_U:
3537         case MONO_TYPE_CLASS:
3538                 return TRUE;
3539         default:
3540                 //XXX stringify this argument
3541                 mono_error_set_bad_image (error, image, "Expected value type but got type kind %d", class_type);
3542                 return FALSE;
3543         }
3544 }
3545
3546 static gboolean
3547 verify_var_type_and_container (MonoImage *image, int var_type, MonoGenericContainer *container, MonoError *error)
3548 {
3549         error_init (error);
3550         if (var_type == MONO_TYPE_MVAR) {
3551                 if (!container->is_method) { //MVAR and a method container
3552                         mono_error_set_bad_image (error, image, "MVAR parsed in a context without a method container");
3553                         return FALSE;
3554                 }
3555         } else {
3556                 if (!(!container->is_method || //VAR and class container
3557                         (container->is_method && container->parent))) { //VAR and method container with parent
3558                         mono_error_set_bad_image (error, image, "VAR parsed in a context without a class container");
3559                         return FALSE;
3560                 }
3561         }
3562         return TRUE;
3563 }
3564
3565 /* 
3566  * do_mono_metadata_parse_type:
3567  * @type: MonoType to be filled in with the return value
3568  * @m: image context
3569  * @generic_context: generics_context
3570  * @transient: whenever to allocate data from the heap
3571  * @ptr: pointer to the encoded type
3572  * @rptr: pointer where the end of the encoded type is saved
3573  * 
3574  * Internal routine used to "fill" the contents of @type from an 
3575  * allocated pointer.  This is done this way to avoid doing too
3576  * many mini-allocations (particularly for the MonoFieldType which
3577  * most of the time is just a MonoType, but sometimes might be augmented).
3578  *
3579  * This routine is used by mono_metadata_parse_type and
3580  * mono_metadata_parse_field_type
3581  *
3582  * This extracts a Type as specified in Partition II (22.2.12) 
3583  *
3584  * Returns: FALSE if the type could not be loaded
3585  */
3586 static gboolean
3587 do_mono_metadata_parse_type (MonoType *type, MonoImage *m, MonoGenericContainer *container,
3588                                                          gboolean transient, const char *ptr, const char **rptr, MonoError *error)
3589 {
3590         error_init (error);
3591
3592         type->type = (MonoTypeEnum)mono_metadata_decode_value (ptr, &ptr);
3593         
3594         switch (type->type){
3595         case MONO_TYPE_VOID:
3596         case MONO_TYPE_BOOLEAN:
3597         case MONO_TYPE_CHAR:
3598         case MONO_TYPE_I1:
3599         case MONO_TYPE_U1:
3600         case MONO_TYPE_I2:
3601         case MONO_TYPE_U2:
3602         case MONO_TYPE_I4:
3603         case MONO_TYPE_U4:
3604         case MONO_TYPE_I8:
3605         case MONO_TYPE_U8:
3606         case MONO_TYPE_R4:
3607         case MONO_TYPE_R8:
3608         case MONO_TYPE_I:
3609         case MONO_TYPE_U:
3610         case MONO_TYPE_STRING:
3611         case MONO_TYPE_OBJECT:
3612         case MONO_TYPE_TYPEDBYREF:
3613                 break;
3614         case MONO_TYPE_VALUETYPE:
3615         case MONO_TYPE_CLASS: {
3616                 guint32 token;
3617                 MonoClass *klass;
3618                 token = mono_metadata_parse_typedef_or_ref (m, ptr, &ptr);
3619                 klass = mono_class_get_checked (m, token, error);
3620                 type->data.klass = klass;
3621                 if (!klass)
3622                         return FALSE;
3623
3624                 if (!compare_type_literals (m, klass->byval_arg.type, type->type, error))
3625                         return FALSE;
3626
3627                 break;
3628         }
3629         case MONO_TYPE_SZARRAY: {
3630                 MonoType *etype = mono_metadata_parse_type_checked (m, container, 0, transient, ptr, &ptr, error);
3631                 if (!etype)
3632                         return FALSE;
3633
3634                 type->data.klass = mono_class_from_mono_type (etype);
3635
3636                 if (transient)
3637                         mono_metadata_free_type (etype);
3638
3639                 g_assert (type->data.klass); //This was previously a check for NULL, but mcfmt should never fail. It can return a borken MonoClass, but should return at least something.
3640                 break;
3641         }
3642         case MONO_TYPE_PTR: {
3643                 type->data.type = mono_metadata_parse_type_checked (m, container, 0, transient, ptr, &ptr, error);
3644                 if (!type->data.type)
3645                         return FALSE;
3646                 break;
3647         }
3648         case MONO_TYPE_FNPTR: {
3649                 type->data.method = mono_metadata_parse_method_signature_full (m, container, 0, ptr, &ptr, error);
3650                 if (!type->data.method)
3651                         return FALSE;
3652                 break;
3653         }
3654         case MONO_TYPE_ARRAY: {
3655                 type->data.array = mono_metadata_parse_array_internal (m, container, transient, ptr, &ptr, error);
3656                 if (!type->data.array)
3657                         return FALSE;
3658                 break;
3659         }
3660         case MONO_TYPE_MVAR:
3661         case MONO_TYPE_VAR: {
3662                 if (container && !verify_var_type_and_container (m, type->type, container, error))
3663                         return FALSE;
3664
3665                 type->data.generic_param = mono_metadata_parse_generic_param (m, container, type->type, ptr, &ptr, error);
3666                 if (!type->data.generic_param)
3667                         return FALSE;
3668
3669                 break;
3670         }
3671         case MONO_TYPE_GENERICINST: {
3672                 if (!do_mono_metadata_parse_generic_class (type, m, container, ptr, &ptr, error))
3673                         return FALSE;
3674                 break;
3675         }
3676         default:
3677                 mono_error_set_bad_image (error, m, "type 0x%02x not handled in do_mono_metadata_parse_type on image %s", type->type, m->name);
3678                 return FALSE;
3679         }
3680         
3681         if (rptr)
3682                 *rptr = ptr;
3683         return TRUE;
3684 }
3685
3686 /**
3687  * mono_metadata_free_type:
3688  * \param type type to free
3689  *
3690  * Free the memory allocated for type \p type which is allocated on the heap.
3691  */
3692 void
3693 mono_metadata_free_type (MonoType *type)
3694 {
3695         if (type >= builtin_types && type < builtin_types + NBUILTIN_TYPES ())
3696                 return;
3697         
3698         switch (type->type){
3699         case MONO_TYPE_OBJECT:
3700         case MONO_TYPE_STRING:
3701                 if (!type->data.klass)
3702                         break;
3703                 /* fall through */
3704         case MONO_TYPE_CLASS:
3705         case MONO_TYPE_VALUETYPE:
3706                 if (type == &type->data.klass->byval_arg || type == &type->data.klass->this_arg)
3707                         return;
3708                 break;
3709         case MONO_TYPE_PTR:
3710                 mono_metadata_free_type (type->data.type);
3711                 break;
3712         case MONO_TYPE_FNPTR:
3713                 mono_metadata_free_method_signature (type->data.method);
3714                 break;
3715         case MONO_TYPE_ARRAY:
3716                 mono_metadata_free_array (type->data.array);
3717                 break;
3718         default:
3719                 break;
3720         }
3721
3722         g_free (type);
3723 }
3724
3725 #if 0
3726 static void
3727 hex_dump (const char *buffer, int base, int count)
3728 {
3729         int show_header = 1;
3730         int i;
3731
3732         if (count < 0){
3733                 count = -count;
3734                 show_header = 0;
3735         }
3736         
3737         for (i = 0; i < count; i++){
3738                 if (show_header)
3739                         if ((i % 16) == 0)
3740                                 printf ("\n0x%08x: ", (unsigned char) base + i);
3741
3742                 printf ("%02x ", (unsigned char) (buffer [i]));
3743         }
3744         fflush (stdout);
3745 }
3746 #endif
3747
3748 /** 
3749  * @ptr: Points to the beginning of the Section Data (25.3)
3750  */
3751 static MonoExceptionClause*
3752 parse_section_data (MonoImage *m, int *num_clauses, const unsigned char *ptr, MonoError *error)
3753 {
3754         unsigned char sect_data_flags;
3755         int is_fat;
3756         guint32 sect_data_len;
3757         MonoExceptionClause* clauses = NULL;
3758
3759         error_init (error);
3760         
3761         while (1) {
3762                 /* align on 32-bit boundary */
3763                 ptr = dword_align (ptr); 
3764                 sect_data_flags = *ptr;
3765                 ptr++;
3766                 
3767                 is_fat = sect_data_flags & METHOD_HEADER_SECTION_FAT_FORMAT;
3768                 if (is_fat) {
3769                         sect_data_len = (ptr [2] << 16) | (ptr [1] << 8) | ptr [0];
3770                         ptr += 3;
3771                 } else {
3772                         sect_data_len = ptr [0];
3773                         ++ptr;
3774                 }
3775
3776                 if (sect_data_flags & METHOD_HEADER_SECTION_EHTABLE) {
3777                         const unsigned char *p = dword_align (ptr);
3778                         int i;
3779                         *num_clauses = is_fat ? sect_data_len / 24: sect_data_len / 12;
3780                         /* we could just store a pointer if we don't need to byteswap */
3781                         clauses = (MonoExceptionClause *)g_malloc0 (sizeof (MonoExceptionClause) * (*num_clauses));
3782                         for (i = 0; i < *num_clauses; ++i) {
3783                                 MonoExceptionClause *ec = &clauses [i];
3784                                 guint32 tof_value;
3785                                 if (is_fat) {
3786                                         ec->flags = read32 (p);
3787                                         ec->try_offset = read32 (p + 4);
3788                                         ec->try_len = read32 (p + 8);
3789                                         ec->handler_offset = read32 (p + 12);
3790                                         ec->handler_len = read32 (p + 16);
3791                                         tof_value = read32 (p + 20);
3792                                         p += 24;
3793                                 } else {
3794                                         ec->flags = read16 (p);
3795                                         ec->try_offset = read16 (p + 2);
3796                                         ec->try_len = *(p + 4);
3797                                         ec->handler_offset = read16 (p + 5);
3798                                         ec->handler_len = *(p + 7);
3799                                         tof_value = read32 (p + 8);
3800                                         p += 12;
3801                                 }
3802                                 if (ec->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
3803                                         ec->data.filter_offset = tof_value;
3804                                 } else if (ec->flags == MONO_EXCEPTION_CLAUSE_NONE) {
3805                                         ec->data.catch_class = NULL;
3806                                         if (tof_value) {
3807                                                 ec->data.catch_class = mono_class_get_checked (m, tof_value, error);
3808                                                 if (!is_ok (error)) {
3809                                                         g_free (clauses);
3810                                                         return NULL;
3811                                                 }
3812                                         }
3813                                 } else {
3814                                         ec->data.catch_class = NULL;
3815                                 }
3816                                 /* g_print ("try %d: %x %04x-%04x %04x\n", i, ec->flags, ec->try_offset, ec->try_offset+ec->try_len, ec->try_len); */
3817                         }
3818
3819                 }
3820                 if (sect_data_flags & METHOD_HEADER_SECTION_MORE_SECTS)
3821                         ptr += sect_data_len - 4; /* LAMESPEC: it seems the size includes the header */
3822                 else
3823                         return clauses;
3824         }
3825 }
3826
3827 /*
3828  * mono_method_get_header_summary:
3829  * @method: The method to get the header.
3830  * @summary: Where to store the header
3831  *
3832  *
3833  * Returns: TRUE if the header was properly decoded.
3834  */
3835 gboolean
3836 mono_method_get_header_summary (MonoMethod *method, MonoMethodHeaderSummary *summary)
3837 {
3838         int idx;
3839         guint32 rva;
3840         MonoImage* img;
3841         const char *ptr;
3842         unsigned char flags, format;
3843         guint16 fat_flags;
3844
3845         /*Only the GMD has a pointer to the metadata.*/
3846         while (method->is_inflated)
3847                 method = ((MonoMethodInflated*)method)->declaring;
3848
3849         summary->code_size = 0;
3850         summary->has_clauses = FALSE;
3851
3852         /*FIXME extract this into a MACRO and share it with mono_method_get_header*/
3853         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))
3854                 return FALSE;
3855
3856         if (method->wrapper_type != MONO_WRAPPER_NONE || method->sre_method) {
3857                 MonoMethodHeader *header =  ((MonoMethodWrapper *)method)->header;
3858                 if (!header)
3859                         return FALSE;
3860                 summary->code_size = header->code_size;
3861                 summary->has_clauses = header->num_clauses > 0;
3862                 return TRUE;
3863         }
3864
3865
3866         idx = mono_metadata_token_index (method->token);
3867         img = method->klass->image;
3868         rva = mono_metadata_decode_row_col (&img->tables [MONO_TABLE_METHOD], idx - 1, MONO_METHOD_RVA);
3869
3870         /*We must run the verifier since we'll be decoding it.*/
3871         if (!mono_verifier_verify_method_header (img, rva, NULL))
3872                 return FALSE;
3873
3874         ptr = mono_image_rva_map (img, rva);
3875         if (!ptr)
3876                 return FALSE;
3877
3878         flags = *(const unsigned char *)ptr;
3879         format = flags & METHOD_HEADER_FORMAT_MASK;
3880
3881         switch (format) {
3882         case METHOD_HEADER_TINY_FORMAT:
3883                 ptr++;
3884                 summary->code_size = flags >> 2;
3885                 break;
3886         case METHOD_HEADER_FAT_FORMAT:
3887                 fat_flags = read16 (ptr);
3888                 ptr += 4;
3889                 summary->code_size = read32 (ptr);
3890                 if (fat_flags & METHOD_HEADER_MORE_SECTS)
3891                         summary->has_clauses = TRUE;
3892                 break;
3893         default:
3894                 return FALSE;
3895         }
3896         return TRUE;
3897 }
3898
3899 /*
3900  * mono_metadata_parse_mh_full:
3901  * @m: metadata context
3902  * @generic_context: generics context
3903  * @ptr: pointer to the method header.
3904  *
3905  * Decode the method header at @ptr, including pointer to the IL code,
3906  * info about local variables and optional exception tables.
3907  * This is a Mono runtime internal function.
3908  *
3909  * LOCKING: Acquires the loader lock.
3910  *
3911  * Returns: a transient MonoMethodHeader allocated from the heap.
3912  */
3913 MonoMethodHeader *
3914 mono_metadata_parse_mh_full (MonoImage *m, MonoGenericContainer *container, const char *ptr, MonoError *error)
3915 {
3916         MonoMethodHeader *mh = NULL;
3917         unsigned char flags = *(const unsigned char *) ptr;
3918         unsigned char format = flags & METHOD_HEADER_FORMAT_MASK;
3919         guint16 fat_flags;
3920         guint32 local_var_sig_tok, max_stack, code_size, init_locals;
3921         const unsigned char *code;
3922         MonoExceptionClause* clauses = NULL;
3923         int num_clauses = 0;
3924         MonoTableInfo *t = &m->tables [MONO_TABLE_STANDALONESIG];
3925         guint32 cols [MONO_STAND_ALONE_SIGNATURE_SIZE];
3926
3927         error_init (error);
3928
3929         if (!ptr) {
3930                 mono_error_set_bad_image (error, m, "Method header with null pointer");
3931                 return NULL;
3932         }
3933
3934         switch (format) {
3935         case METHOD_HEADER_TINY_FORMAT:
3936                 mh = (MonoMethodHeader *)g_malloc0 (MONO_SIZEOF_METHOD_HEADER);
3937                 ptr++;
3938                 mh->max_stack = 8;
3939                 mh->is_transient = TRUE;
3940                 local_var_sig_tok = 0;
3941                 mh->code_size = flags >> 2;
3942                 mh->code = (unsigned char*)ptr;
3943                 return mh;
3944         case METHOD_HEADER_FAT_FORMAT:
3945                 fat_flags = read16 (ptr);
3946                 ptr += 2;
3947                 max_stack = read16 (ptr);
3948                 ptr += 2;
3949                 code_size = read32 (ptr);
3950                 ptr += 4;
3951                 local_var_sig_tok = read32 (ptr);
3952                 ptr += 4;
3953
3954                 if (fat_flags & METHOD_HEADER_INIT_LOCALS)
3955                         init_locals = 1;
3956                 else
3957                         init_locals = 0;
3958
3959                 code = (unsigned char*)ptr;
3960
3961                 if (!(fat_flags & METHOD_HEADER_MORE_SECTS))
3962                         break;
3963
3964                 /*
3965                  * There are more sections
3966                  */
3967                 ptr = (char*)code + code_size;
3968                 break;
3969         default:
3970                 mono_error_set_bad_image (error, m, "Invalid method header format %d", format);
3971                 return NULL;
3972         }
3973
3974         if (local_var_sig_tok) {
3975                 int idx = (local_var_sig_tok & 0xffffff)-1;
3976                 if (idx >= t->rows || idx < 0) {
3977                         mono_error_set_bad_image (error, m, "Invalid method header local vars signature token 0x%8x", idx);
3978                         goto fail;
3979                 }
3980                 mono_metadata_decode_row (t, idx, cols, 1);
3981
3982                 if (!mono_verifier_verify_standalone_signature (m, cols [MONO_STAND_ALONE_SIGNATURE], NULL)) {
3983                         mono_error_set_bad_image (error, m, "Method header locals signature 0x%8x verification failed", idx);
3984                         goto fail;
3985                 }
3986         }
3987         if (fat_flags & METHOD_HEADER_MORE_SECTS) {
3988                 clauses = parse_section_data (m, &num_clauses, (const unsigned char*)ptr, error);
3989                 if (!is_ok (error))
3990                         goto fail;
3991         }
3992         if (local_var_sig_tok) {
3993                 const char *locals_ptr;
3994                 int len=0, i;
3995
3996                 locals_ptr = mono_metadata_blob_heap (m, cols [MONO_STAND_ALONE_SIGNATURE]);
3997                 mono_metadata_decode_blob_size (locals_ptr, &locals_ptr);
3998                 if (*locals_ptr != 0x07)
3999                         g_warning ("wrong signature for locals blob");
4000                 locals_ptr++;
4001                 len = mono_metadata_decode_value (locals_ptr, &locals_ptr);
4002                 mh = (MonoMethodHeader *)g_malloc0 (MONO_SIZEOF_METHOD_HEADER + len * sizeof (MonoType*) + num_clauses * sizeof (MonoExceptionClause));
4003                 mh->num_locals = len;
4004                 for (i = 0; i < len; ++i) {
4005                         mh->locals [i] = mono_metadata_parse_type_internal (m, container, 0, TRUE, locals_ptr, &locals_ptr, error);
4006                         if (!is_ok (error))
4007                                 goto fail;
4008                 }
4009         } else {
4010                 mh = (MonoMethodHeader *)g_malloc0 (MONO_SIZEOF_METHOD_HEADER + num_clauses * sizeof (MonoExceptionClause));
4011         }
4012         mh->code = code;
4013         mh->code_size = code_size;
4014         mh->max_stack = max_stack;
4015         mh->is_transient = TRUE;
4016         mh->init_locals = init_locals;
4017         if (clauses) {
4018                 MonoExceptionClause* clausesp = (MonoExceptionClause*)&mh->locals [mh->num_locals];
4019                 memcpy (clausesp, clauses, num_clauses * sizeof (MonoExceptionClause));
4020                 g_free (clauses);
4021                 mh->clauses = clausesp;
4022                 mh->num_clauses = num_clauses;
4023         }
4024         return mh;
4025 fail:
4026         g_free (clauses);
4027         g_free (mh);
4028         return NULL;
4029
4030 }
4031
4032 /**
4033  * mono_metadata_parse_mh:
4034  * \param generic_context generics context
4035  * \param ptr pointer to the method header.
4036  *
4037  * Decode the method header at \p ptr, including pointer to the IL code,
4038  * info about local variables and optional exception tables.
4039  *
4040  * \returns a transient \c MonoMethodHeader allocated from the heap.
4041  */
4042 MonoMethodHeader *
4043 mono_metadata_parse_mh (MonoImage *m, const char *ptr)
4044 {
4045         MonoError error;
4046         MonoMethodHeader *header = mono_metadata_parse_mh_full (m, NULL, ptr, &error);
4047         mono_error_cleanup (&error);
4048         return header;
4049 }
4050
4051 /**
4052  * mono_metadata_free_mh:
4053  * \param mh a method header
4054  *
4055  * Free the memory allocated for the method header.
4056  */
4057 void
4058 mono_metadata_free_mh (MonoMethodHeader *mh)
4059 {
4060         int i;
4061
4062         /* If it is not transient it means it's part of a wrapper method,
4063          * or a SRE-generated method, so the lifetime in that case is
4064          * dictated by the method's own lifetime
4065          */
4066         if (mh->is_transient) {
4067                 for (i = 0; i < mh->num_locals; ++i)
4068                         mono_metadata_free_type (mh->locals [i]);
4069                 g_free (mh);
4070         }
4071 }
4072
4073 /**
4074  * mono_method_header_get_code:
4075  * \param header a \c MonoMethodHeader pointer
4076  * \param code_size memory location for returning the code size
4077  * \param max_stack memory location for returning the max stack
4078  *
4079  * Method header accessor to retreive info about the IL code properties:
4080  * a pointer to the IL code itself, the size of the code and the max number
4081  * of stack slots used by the code.
4082  *
4083  * \returns pointer to the IL code represented by the method header.
4084  */
4085 const unsigned char*
4086 mono_method_header_get_code (MonoMethodHeader *header, guint32* code_size, guint32* max_stack)
4087 {
4088         if (code_size)
4089                 *code_size = header->code_size;
4090         if (max_stack)
4091                 *max_stack = header->max_stack;
4092         return header->code;
4093 }
4094
4095 /**
4096  * mono_method_header_get_locals:
4097  * \param header a \c MonoMethodHeader pointer
4098  * \param num_locals memory location for returning the number of local variables
4099  * \param init_locals memory location for returning the init_locals flag
4100  *
4101  * Method header accessor to retreive info about the local variables:
4102  * an array of local types, the number of locals and whether the locals
4103  * are supposed to be initialized to 0 on method entry
4104  *
4105  * \returns pointer to an array of types of the local variables
4106  */
4107 MonoType**
4108 mono_method_header_get_locals (MonoMethodHeader *header, guint32* num_locals, gboolean *init_locals)
4109 {
4110         if (num_locals)
4111                 *num_locals = header->num_locals;
4112         if (init_locals)
4113                 *init_locals = header->init_locals;
4114         return header->locals;
4115 }
4116
4117 /*
4118  * mono_method_header_get_num_clauses:
4119  * @header: a MonoMethodHeader pointer
4120  *
4121  * Method header accessor to retreive the number of exception clauses.
4122  *
4123  * Returns: the number of exception clauses present
4124  */
4125 int
4126 mono_method_header_get_num_clauses (MonoMethodHeader *header)
4127 {
4128         return header->num_clauses;
4129 }
4130
4131 /**
4132  * mono_method_header_get_clauses:
4133  * \param header a \c MonoMethodHeader pointer
4134  * \param method \c MonoMethod the header belongs to
4135  * \param iter pointer to a iterator
4136  * \param clause pointer to a \c MonoExceptionClause structure which will be filled with the info
4137  *
4138  * Get the info about the exception clauses in the method. Set \c *iter to NULL to
4139  * initiate the iteration, then call the method repeatedly until it returns FALSE.
4140  * At each iteration, the structure pointed to by clause if filled with the
4141  * exception clause information.
4142  *
4143  * \returns TRUE if clause was filled with info, FALSE if there are no more exception
4144  * clauses.
4145  */
4146 int
4147 mono_method_header_get_clauses (MonoMethodHeader *header, MonoMethod *method, gpointer *iter, MonoExceptionClause *clause)
4148 {
4149         MonoExceptionClause *sc;
4150         /* later we'll be able to use this interface to parse the clause info on demand,
4151          * without allocating anything.
4152          */
4153         if (!iter || !header->num_clauses)
4154                 return FALSE;
4155         if (!*iter) {
4156                 *iter = sc = header->clauses;
4157                 *clause = *sc;
4158                 return TRUE;
4159         }
4160         sc = (MonoExceptionClause *)*iter;
4161         sc++;
4162         if (sc < header->clauses + header->num_clauses) {
4163                 *iter = sc;
4164                 *clause = *sc;
4165                 return TRUE;
4166         }
4167         return FALSE;
4168 }
4169
4170 /**
4171  * mono_metadata_parse_field_type:
4172  * \param m metadata context to extract information from
4173  * \param ptr pointer to the field signature
4174  * \param rptr pointer updated to match the end of the decoded stream
4175  *
4176  * Parses the field signature, and returns the type information for it. 
4177  *
4178  * \returns The \c MonoType that was extracted from \p ptr .
4179  */
4180 MonoType *
4181 mono_metadata_parse_field_type (MonoImage *m, short field_flags, const char *ptr, const char **rptr)
4182 {
4183         MonoError error;
4184         MonoType * type = mono_metadata_parse_type_internal (m, NULL, field_flags, FALSE, ptr, rptr, &error);
4185         mono_error_cleanup (&error);
4186         return type;
4187 }
4188
4189 /**
4190  * mono_metadata_parse_param:
4191  * \param m metadata context to extract information from
4192  * \param ptr pointer to the param signature
4193  * \param rptr pointer updated to match the end of the decoded stream
4194  *
4195  * Parses the param signature, and returns the type information for it. 
4196  *
4197  * \returns The \c MonoType that was extracted from \p ptr .
4198  */
4199 MonoType *
4200 mono_metadata_parse_param (MonoImage *m, const char *ptr, const char **rptr)
4201 {
4202         MonoError error;
4203         MonoType * type = mono_metadata_parse_type_internal (m, NULL, 0, FALSE, ptr, rptr, &error);
4204         mono_error_cleanup (&error);
4205         return type;
4206 }
4207
4208 /**
4209  * mono_metadata_token_from_dor:
4210  * \param dor_token A \c TypeDefOrRef coded index
4211  *
4212  * \p dor_token is a \c TypeDefOrRef coded index: it contains either
4213  * a \c TypeDef, \c TypeRef or \c TypeSpec in the lower bits, and the upper
4214  * bits contain an index into the table.
4215  *
4216  * \returns an expanded token
4217  */
4218 guint32
4219 mono_metadata_token_from_dor (guint32 dor_index)
4220 {
4221         guint32 table, idx;
4222
4223         table = dor_index & 0x03;
4224         idx = dor_index >> 2;
4225
4226         switch (table){
4227         case 0: /* TypeDef */
4228                 return MONO_TOKEN_TYPE_DEF | idx;
4229         case 1: /* TypeRef */
4230                 return MONO_TOKEN_TYPE_REF | idx;
4231         case 2: /* TypeSpec */
4232                 return MONO_TOKEN_TYPE_SPEC | idx;
4233         default:
4234                 g_assert_not_reached ();
4235         }
4236
4237         return 0;
4238 }
4239
4240 /*
4241  * We use this to pass context information to the row locator
4242  */
4243 typedef struct {
4244         int idx;                        /* The index that we are trying to locate */
4245         int col_idx;            /* The index in the row where idx may be stored */
4246         MonoTableInfo *t;       /* pointer to the table */
4247         guint32 result;
4248 } locator_t;
4249
4250 /*
4251  * How the row locator works.
4252  *
4253  *   Table A
4254  *   ___|___
4255  *   ___|___         Table B
4256  *   ___|___------>  _______
4257  *   ___|___         _______
4258  *   
4259  * A column in the rows of table A references an index in table B.
4260  * For example A may be the TYPEDEF table and B the METHODDEF table.
4261  * 
4262  * Given an index in table B we want to get the row in table A
4263  * where the column n references our index in B.
4264  *
4265  * In the locator_t structure:
4266  *      t is table A
4267  *      col_idx is the column number
4268  *      index is the index in table B
4269  *      result will be the index in table A
4270  *
4271  * Examples:
4272  * Table A              Table B         column (in table A)
4273  * TYPEDEF              METHODDEF   MONO_TYPEDEF_METHOD_LIST
4274  * TYPEDEF              FIELD           MONO_TYPEDEF_FIELD_LIST
4275  * PROPERTYMAP  PROPERTY        MONO_PROPERTY_MAP_PROPERTY_LIST
4276  * INTERFIMPL   TYPEDEF         MONO_INTERFACEIMPL_CLASS
4277  * METHODSEM    PROPERTY        ASSOCIATION (encoded index)
4278  *
4279  * Note that we still don't support encoded indexes.
4280  *
4281  */
4282 static int
4283 typedef_locator (const void *a, const void *b)
4284 {
4285         locator_t *loc = (locator_t *) a;
4286         const char *bb = (const char *) b;
4287         int typedef_index = (bb - loc->t->base) / loc->t->row_size;
4288         guint32 col, col_next;
4289
4290         col = mono_metadata_decode_row_col (loc->t, typedef_index, loc->col_idx);
4291
4292         if (loc->idx < col)
4293                 return -1;
4294
4295         /*
4296          * Need to check that the next row is valid.
4297          */
4298         if (typedef_index + 1 < loc->t->rows) {
4299                 col_next = mono_metadata_decode_row_col (loc->t, typedef_index + 1, loc->col_idx);
4300                 if (loc->idx >= col_next)
4301                         return 1;
4302
4303                 if (col == col_next)
4304                         return 1; 
4305         }
4306
4307         loc->result = typedef_index;
4308         
4309         return 0;
4310 }
4311
4312 static int
4313 table_locator (const void *a, const void *b)
4314 {
4315         locator_t *loc = (locator_t *) a;
4316         const char *bb = (const char *) b;
4317         guint32 table_index = (bb - loc->t->base) / loc->t->row_size;
4318         guint32 col;
4319         
4320         col = mono_metadata_decode_row_col (loc->t, table_index, loc->col_idx);
4321
4322         if (loc->idx == col) {
4323                 loc->result = table_index;
4324                 return 0;
4325         }
4326         if (loc->idx < col)
4327                 return -1;
4328         else 
4329                 return 1;
4330 }
4331
4332 static int
4333 declsec_locator (const void *a, const void *b)
4334 {
4335         locator_t *loc = (locator_t *) a;
4336         const char *bb = (const char *) b;
4337         guint32 table_index = (bb - loc->t->base) / loc->t->row_size;
4338         guint32 col;
4339
4340         col = mono_metadata_decode_row_col (loc->t, table_index, loc->col_idx);
4341
4342         if (loc->idx == col) {
4343                 loc->result = table_index;
4344                 return 0;
4345         }
4346         if (loc->idx < col)
4347                 return -1;
4348         else
4349                 return 1;
4350 }
4351
4352 /**
4353  * search_ptr_table:
4354  *
4355  *  Return the 1-based row index in TABLE, which must be one of the *Ptr tables, 
4356  * which contains IDX.
4357  */
4358 static guint32
4359 search_ptr_table (MonoImage *image, int table, int idx)
4360 {
4361         MonoTableInfo *ptrdef = &image->tables [table];
4362         int i;
4363
4364         /* Use a linear search to find our index in the table */
4365         for (i = 0; i < ptrdef->rows; i ++)
4366                 /* All the Ptr tables have the same structure */
4367                 if (mono_metadata_decode_row_col (ptrdef, i, 0) == idx)
4368                         break;
4369
4370         if (i < ptrdef->rows)
4371                 return i + 1;
4372         else
4373                 return idx;
4374 }
4375
4376 /**
4377  * mono_metadata_typedef_from_field:
4378  * \param meta metadata context
4379  * \param index FieldDef token
4380  *
4381  * \returns the 1-based index into the \c TypeDef table of the type that
4382  * declared the field described by \p index, or 0 if not found.
4383  */
4384 guint32
4385 mono_metadata_typedef_from_field (MonoImage *meta, guint32 index)
4386 {
4387         MonoTableInfo *tdef = &meta->tables [MONO_TABLE_TYPEDEF];
4388         locator_t loc;
4389
4390         if (!tdef->base)
4391                 return 0;
4392
4393         loc.idx = mono_metadata_token_index (index);
4394         loc.col_idx = MONO_TYPEDEF_FIELD_LIST;
4395         loc.t = tdef;
4396
4397         if (meta->uncompressed_metadata)
4398                 loc.idx = search_ptr_table (meta, MONO_TABLE_FIELD_POINTER, loc.idx);
4399
4400         if (!mono_binary_search (&loc, tdef->base, tdef->rows, tdef->row_size, typedef_locator))
4401                 return 0;
4402
4403         /* loc_result is 0..1, needs to be mapped to table index (that is +1) */
4404         return loc.result + 1;
4405 }
4406
4407 /**
4408  * mono_metadata_typedef_from_method:
4409  * \param meta metadata context
4410  * \param index \c MethodDef token
4411  * \returns the 1-based index into the \c TypeDef table of the type that
4412  * declared the method described by \p index.  0 if not found.
4413  */
4414 guint32
4415 mono_metadata_typedef_from_method (MonoImage *meta, guint32 index)
4416 {
4417         MonoTableInfo *tdef = &meta->tables [MONO_TABLE_TYPEDEF];
4418         locator_t loc;
4419         
4420         if (!tdef->base)
4421                 return 0;
4422
4423         loc.idx = mono_metadata_token_index (index);
4424         loc.col_idx = MONO_TYPEDEF_METHOD_LIST;
4425         loc.t = tdef;
4426
4427         if (meta->uncompressed_metadata)
4428                 loc.idx = search_ptr_table (meta, MONO_TABLE_METHOD_POINTER, loc.idx);
4429
4430         if (!mono_binary_search (&loc, tdef->base, tdef->rows, tdef->row_size, typedef_locator))
4431                 return 0;
4432
4433         /* loc_result is 0..1, needs to be mapped to table index (that is +1) */
4434         return loc.result + 1;
4435 }
4436
4437 /*
4438  * mono_metadata_interfaces_from_typedef_full:
4439  * @meta: metadata context
4440  * @index: typedef token
4441  * @interfaces: Out parameter used to store the interface array
4442  * @count: Out parameter used to store the number of interfaces
4443  * @heap_alloc_result: if TRUE the result array will be g_malloc'd
4444  * @context: The generic context
4445  * 
4446  * The array of interfaces that the @index typedef token implements is returned in
4447  * @interfaces. The number of elements in the array is returned in @count. 
4448  *
4449
4450  * Returns: TRUE on success, FALSE on failure.
4451  */
4452 gboolean
4453 mono_metadata_interfaces_from_typedef_full (MonoImage *meta, guint32 index, MonoClass ***interfaces, guint *count, gboolean heap_alloc_result, MonoGenericContext *context, MonoError *error)
4454 {
4455         MonoTableInfo *tdef = &meta->tables [MONO_TABLE_INTERFACEIMPL];
4456         locator_t loc;
4457         guint32 start, pos;
4458         guint32 cols [MONO_INTERFACEIMPL_SIZE];
4459         MonoClass **result;
4460
4461         *interfaces = NULL;
4462         *count = 0;
4463
4464         error_init (error);
4465
4466         if (!tdef->base)
4467                 return TRUE;
4468
4469         loc.idx = mono_metadata_token_index (index);
4470         loc.col_idx = MONO_INTERFACEIMPL_CLASS;
4471         loc.t = tdef;
4472
4473         if (!mono_binary_search (&loc, tdef->base, tdef->rows, tdef->row_size, table_locator))
4474                 return TRUE;
4475
4476         start = loc.result;
4477         /*
4478          * We may end up in the middle of the rows... 
4479          */
4480         while (start > 0) {
4481                 if (loc.idx == mono_metadata_decode_row_col (tdef, start - 1, MONO_INTERFACEIMPL_CLASS))
4482                         start--;
4483                 else
4484                         break;
4485         }
4486         pos = start;
4487         while (pos < tdef->rows) {
4488                 mono_metadata_decode_row (tdef, pos, cols, MONO_INTERFACEIMPL_SIZE);
4489                 if (cols [MONO_INTERFACEIMPL_CLASS] != loc.idx)
4490                         break;
4491                 ++pos;
4492         }
4493
4494         if (heap_alloc_result)
4495                 result = g_new0 (MonoClass*, pos - start);
4496         else
4497                 result = (MonoClass **)mono_image_alloc0 (meta, sizeof (MonoClass*) * (pos - start));
4498
4499         pos = start;
4500         while (pos < tdef->rows) {
4501                 MonoClass *iface;
4502                 
4503                 mono_metadata_decode_row (tdef, pos, cols, MONO_INTERFACEIMPL_SIZE);
4504                 if (cols [MONO_INTERFACEIMPL_CLASS] != loc.idx)
4505                         break;
4506                 iface = mono_class_get_and_inflate_typespec_checked (
4507                         meta, mono_metadata_token_from_dor (cols [MONO_INTERFACEIMPL_INTERFACE]), context, error);
4508                 if (iface == NULL)
4509                         return FALSE;
4510                 result [pos - start] = iface;
4511                 ++pos;
4512         }
4513         *count = pos - start;
4514         *interfaces = result;
4515         return TRUE;
4516 }
4517
4518 /**
4519  * mono_metadata_interfaces_from_typedef:
4520  * \param meta metadata context
4521  * \param index typedef token
4522  * \param count Out parameter used to store the number of interfaces
4523  * 
4524  * The array of interfaces that the \p index typedef token implements is returned in
4525  * \p interfaces. The number of elements in the array is returned in \p count. The returned
4526  * array is allocated with \c g_malloc and the caller must free it.
4527  *
4528  * LOCKING: Acquires the loader lock .
4529  *
4530  * \returns the interface array on success, NULL on failure.
4531  */
4532 MonoClass**
4533 mono_metadata_interfaces_from_typedef (MonoImage *meta, guint32 index, guint *count)
4534 {
4535         MonoError error;
4536         MonoClass **interfaces = NULL;
4537         gboolean rv;
4538
4539         rv = mono_metadata_interfaces_from_typedef_full (meta, index, &interfaces, count, TRUE, NULL, &error);
4540         g_assert (mono_error_ok (&error)); /* FIXME dont swallow the error */
4541         if (rv)
4542                 return interfaces;
4543         else
4544                 return NULL;
4545 }
4546
4547 /**
4548  * mono_metadata_nested_in_typedef:
4549  * \param meta metadata context
4550  * \param index typedef token
4551  * \returns the 1-based index into the TypeDef table of the type
4552  * where the type described by \p index is nested.
4553  * Returns 0 if \p index describes a non-nested type.
4554  */
4555 guint32
4556 mono_metadata_nested_in_typedef (MonoImage *meta, guint32 index)
4557 {
4558         MonoTableInfo *tdef = &meta->tables [MONO_TABLE_NESTEDCLASS];
4559         locator_t loc;
4560         
4561         if (!tdef->base)
4562                 return 0;
4563
4564         loc.idx = mono_metadata_token_index (index);
4565         loc.col_idx = MONO_NESTED_CLASS_NESTED;
4566         loc.t = tdef;
4567
4568         if (!mono_binary_search (&loc, tdef->base, tdef->rows, tdef->row_size, table_locator))
4569                 return 0;
4570
4571         /* loc_result is 0..1, needs to be mapped to table index (that is +1) */
4572         return mono_metadata_decode_row_col (tdef, loc.result, MONO_NESTED_CLASS_ENCLOSING) | MONO_TOKEN_TYPE_DEF;
4573 }
4574
4575 /**
4576  * mono_metadata_nesting_typedef:
4577  * \param meta metadata context
4578  * \param index typedef token
4579  * \returns the 1-based index into the \c TypeDef table of the first type
4580  * that is nested inside the type described by \p index. The search starts at
4581  * \p start_index. Returns 0 if no such type is found.
4582  */
4583 guint32
4584 mono_metadata_nesting_typedef (MonoImage *meta, guint32 index, guint32 start_index)
4585 {
4586         MonoTableInfo *tdef = &meta->tables [MONO_TABLE_NESTEDCLASS];
4587         guint32 start;
4588         guint32 class_index = mono_metadata_token_index (index);
4589         
4590         if (!tdef->base)
4591                 return 0;
4592
4593         start = start_index;
4594
4595         while (start <= tdef->rows) {
4596                 if (class_index == mono_metadata_decode_row_col (tdef, start - 1, MONO_NESTED_CLASS_ENCLOSING))
4597                         break;
4598                 else
4599                         start++;
4600         }
4601
4602         if (start > tdef->rows)
4603                 return 0;
4604         else
4605                 return start;
4606 }
4607
4608 /**
4609  * mono_metadata_packing_from_typedef:
4610  * \param meta metadata context
4611  * \param index token representing a type
4612  * \returns the info stored in the \c ClassLayout table for the given typedef token
4613  * into the \p packing and \p size pointers.
4614  * Returns 0 if the info is not found.
4615  */
4616 guint32
4617 mono_metadata_packing_from_typedef (MonoImage *meta, guint32 index, guint32 *packing, guint32 *size)
4618 {
4619         MonoTableInfo *tdef = &meta->tables [MONO_TABLE_CLASSLAYOUT];
4620         locator_t loc;
4621         guint32 cols [MONO_CLASS_LAYOUT_SIZE];
4622         
4623         if (!tdef->base)
4624                 return 0;
4625
4626         loc.idx = mono_metadata_token_index (index);
4627         loc.col_idx = MONO_CLASS_LAYOUT_PARENT;
4628         loc.t = tdef;
4629
4630         if (!mono_binary_search (&loc, tdef->base, tdef->rows, tdef->row_size, table_locator))
4631                 return 0;
4632
4633         mono_metadata_decode_row (tdef, loc.result, cols, MONO_CLASS_LAYOUT_SIZE);
4634         if (packing)
4635                 *packing = cols [MONO_CLASS_LAYOUT_PACKING_SIZE];
4636         if (size)
4637                 *size = cols [MONO_CLASS_LAYOUT_CLASS_SIZE];
4638
4639         /* loc_result is 0..1, needs to be mapped to table index (that is +1) */
4640         return loc.result + 1;
4641 }
4642
4643 /**
4644  * mono_metadata_custom_attrs_from_index:
4645  * \param meta metadata context
4646  * \param index token representing the parent
4647  * \returns: the 1-based index into the \c CustomAttribute table of the first 
4648  * attribute which belongs to the metadata object described by \p index.
4649  * Returns 0 if no such attribute is found.
4650  */
4651 guint32
4652 mono_metadata_custom_attrs_from_index (MonoImage *meta, guint32 index)
4653 {
4654         MonoTableInfo *tdef = &meta->tables [MONO_TABLE_CUSTOMATTRIBUTE];
4655         locator_t loc;
4656         
4657         if (!tdef->base)
4658                 return 0;
4659
4660         loc.idx = index;
4661         loc.col_idx = MONO_CUSTOM_ATTR_PARENT;
4662         loc.t = tdef;
4663
4664         /* FIXME: Index translation */
4665
4666         if (!mono_binary_search (&loc, tdef->base, tdef->rows, tdef->row_size, table_locator))
4667                 return 0;
4668
4669         /* Find the first entry by searching backwards */
4670         while ((loc.result > 0) && (mono_metadata_decode_row_col (tdef, loc.result - 1, MONO_CUSTOM_ATTR_PARENT) == index))
4671                 loc.result --;
4672
4673         /* loc_result is 0..1, needs to be mapped to table index (that is +1) */
4674         return loc.result + 1;
4675 }
4676
4677 /**
4678  * mono_metadata_declsec_from_index:
4679  * \param meta metadata context
4680  * \param index token representing the parent
4681  * \returns the 0-based index into the \c DeclarativeSecurity table of the first 
4682  * attribute which belongs to the metadata object described by \p index.
4683  * Returns \c -1 if no such attribute is found.
4684  */
4685 guint32
4686 mono_metadata_declsec_from_index (MonoImage *meta, guint32 index)
4687 {
4688         MonoTableInfo *tdef = &meta->tables [MONO_TABLE_DECLSECURITY];
4689         locator_t loc;
4690
4691         if (!tdef->base)
4692                 return -1;
4693
4694         loc.idx = index;
4695         loc.col_idx = MONO_DECL_SECURITY_PARENT;
4696         loc.t = tdef;
4697
4698         if (!mono_binary_search (&loc, tdef->base, tdef->rows, tdef->row_size, declsec_locator))
4699                 return -1;
4700
4701         /* Find the first entry by searching backwards */
4702         while ((loc.result > 0) && (mono_metadata_decode_row_col (tdef, loc.result - 1, MONO_DECL_SECURITY_PARENT) == index))
4703                 loc.result --;
4704
4705         return loc.result;
4706 }
4707
4708 /*
4709  * mono_metadata_localscope_from_methoddef:
4710  * @meta: metadata context
4711  * @index: methoddef index
4712  * 
4713  * Returns: the 1-based index into the LocalScope table of the first
4714  * scope which belongs to the method described by @index.
4715  * Returns 0 if no such row is found.
4716  */
4717 guint32
4718 mono_metadata_localscope_from_methoddef (MonoImage *meta, guint32 index)
4719 {
4720         MonoTableInfo *tdef = &meta->tables [MONO_TABLE_LOCALSCOPE];
4721         locator_t loc;
4722
4723         if (!tdef->base)
4724                 return 0;
4725
4726         loc.idx = index;
4727         loc.col_idx = MONO_LOCALSCOPE_METHOD;
4728         loc.t = tdef;
4729
4730         if (!mono_binary_search (&loc, tdef->base, tdef->rows, tdef->row_size, table_locator))
4731                 return 0;
4732
4733         /* Find the first entry by searching backwards */
4734         while ((loc.result > 0) && (mono_metadata_decode_row_col (tdef, loc.result - 1, MONO_LOCALSCOPE_METHOD) == index))
4735                 loc.result --;
4736
4737         return loc.result + 1;
4738 }
4739
4740 #ifdef DEBUG
4741 static void
4742 mono_backtrace (int limit)
4743 {
4744         void *array[limit];
4745         char **names;
4746         int i;
4747         backtrace (array, limit);
4748         names = backtrace_symbols (array, limit);
4749         for (i =0; i < limit; ++i) {
4750                 g_print ("\t%s\n", names [i]);
4751         }
4752         g_free (names);
4753 }
4754 #endif
4755
4756 static int i8_align;
4757
4758 /*
4759  * mono_type_set_alignment:
4760  *
4761  *   Set the alignment used by runtime to layout fields etc. of type TYPE to ALIGN.
4762  * This should only be used in AOT mode since the resulting layout will not match the
4763  * host abi layout.
4764  */
4765 void
4766 mono_type_set_alignment (MonoTypeEnum type, int align)
4767 {
4768         /* Support only a few types whose alignment is abi dependent */
4769         switch (type) {
4770         case MONO_TYPE_I8:
4771                 i8_align = align;
4772                 break;
4773         default:
4774                 g_assert_not_reached ();
4775                 break;
4776         }
4777 }
4778
4779 /**
4780  * mono_type_size:
4781  * \param t the type to return the size of
4782  * \returns The number of bytes required to hold an instance of this
4783  * type in memory
4784  */
4785 int
4786 mono_type_size (MonoType *t, int *align)
4787 {
4788         MonoTypeEnum simple_type;
4789
4790         if (!t) {
4791                 *align = 1;
4792                 return 0;
4793         }
4794         if (t->byref) {
4795                 *align = MONO_ABI_ALIGNOF (gpointer);
4796                 return MONO_ABI_SIZEOF (gpointer);
4797         }
4798
4799         simple_type = t->type;
4800  again:
4801         switch (simple_type) {
4802         case MONO_TYPE_VOID:
4803                 *align = 1;
4804                 return 0;
4805         case MONO_TYPE_BOOLEAN:
4806                 *align = MONO_ABI_ALIGNOF (gint8);
4807                 return 1;
4808         case MONO_TYPE_I1:
4809         case MONO_TYPE_U1:
4810                 *align = MONO_ABI_ALIGNOF (gint8);
4811                 return 1;
4812         case MONO_TYPE_CHAR:
4813         case MONO_TYPE_I2:
4814         case MONO_TYPE_U2:
4815                 *align = MONO_ABI_ALIGNOF (gint16);
4816                 return 2;               
4817         case MONO_TYPE_I4:
4818         case MONO_TYPE_U4:
4819                 *align = MONO_ABI_ALIGNOF (gint32);
4820                 return 4;
4821         case MONO_TYPE_R4:
4822                 *align = MONO_ABI_ALIGNOF (float);
4823                 return 4;
4824         case MONO_TYPE_I8:
4825         case MONO_TYPE_U8:
4826                 *align = MONO_ABI_ALIGNOF (gint64);
4827                 return 8;               
4828         case MONO_TYPE_R8:
4829                 *align = MONO_ABI_ALIGNOF (double);
4830                 return 8;               
4831         case MONO_TYPE_I:
4832         case MONO_TYPE_U:
4833                 *align = MONO_ABI_ALIGNOF (gpointer);
4834                 return MONO_ABI_SIZEOF (gpointer);
4835         case MONO_TYPE_VALUETYPE: {
4836                 if (t->data.klass->enumtype)
4837                         return mono_type_size (mono_class_enum_basetype (t->data.klass), align);
4838                 else
4839                         return mono_class_value_size (t->data.klass, (guint32*)align);
4840         }
4841         case MONO_TYPE_STRING:
4842         case MONO_TYPE_OBJECT:
4843         case MONO_TYPE_CLASS:
4844         case MONO_TYPE_SZARRAY:
4845         case MONO_TYPE_PTR:
4846         case MONO_TYPE_FNPTR:
4847         case MONO_TYPE_ARRAY:
4848                 *align = MONO_ABI_ALIGNOF (gpointer);
4849                 return MONO_ABI_SIZEOF (gpointer);
4850         case MONO_TYPE_TYPEDBYREF:
4851                 return mono_class_value_size (mono_defaults.typed_reference_class, (guint32*)align);
4852         case MONO_TYPE_GENERICINST: {
4853                 MonoGenericClass *gclass = t->data.generic_class;
4854                 MonoClass *container_class = gclass->container_class;
4855
4856                 // g_assert (!gclass->inst->is_open);
4857
4858                 if (container_class->valuetype) {
4859                         if (container_class->enumtype)
4860                                 return mono_type_size (mono_class_enum_basetype (container_class), align);
4861                         else
4862                                 return mono_class_value_size (mono_class_from_mono_type (t), (guint32*)align);
4863                 } else {
4864                         *align = MONO_ABI_ALIGNOF (gpointer);
4865                         return MONO_ABI_SIZEOF (gpointer);
4866                 }
4867         }
4868         case MONO_TYPE_VAR:
4869         case MONO_TYPE_MVAR:
4870                 if (!t->data.generic_param->gshared_constraint || t->data.generic_param->gshared_constraint->type == MONO_TYPE_VALUETYPE) {
4871                         *align = MONO_ABI_ALIGNOF (gpointer);
4872                         return MONO_ABI_SIZEOF (gpointer);
4873                 } else {
4874                         /* The gparam can only match types given by gshared_constraint */
4875                         return mono_type_size (t->data.generic_param->gshared_constraint, align);
4876                         goto again;
4877                 }
4878         default:
4879                 g_error ("mono_type_size: type 0x%02x unknown", t->type);
4880         }
4881         return 0;
4882 }
4883
4884 /**
4885  * mono_type_stack_size:
4886  * \param t the type to return the size it uses on the stack
4887  * \returns The number of bytes required to hold an instance of this
4888  * type on the runtime stack
4889  */
4890 int
4891 mono_type_stack_size (MonoType *t, int *align)
4892 {
4893         return mono_type_stack_size_internal (t, align, FALSE);
4894 }
4895
4896 int
4897 mono_type_stack_size_internal (MonoType *t, int *align, gboolean allow_open)
4898 {
4899         int tmp;
4900         MonoTypeEnum simple_type;
4901 #if SIZEOF_VOID_P == SIZEOF_REGISTER
4902         int stack_slot_size = MONO_ABI_SIZEOF (gpointer);
4903         int stack_slot_align = MONO_ABI_ALIGNOF (gpointer);
4904 #elif SIZEOF_VOID_P < SIZEOF_REGISTER
4905         int stack_slot_size = SIZEOF_REGISTER;
4906         int stack_slot_align = SIZEOF_REGISTER;
4907 #endif
4908
4909         g_assert (t != NULL);
4910
4911         if (!align)
4912                 align = &tmp;
4913
4914         if (t->byref) {
4915                 *align = stack_slot_align;
4916                 return stack_slot_size;
4917         }
4918
4919         simple_type = t->type;
4920         switch (simple_type) {
4921         case MONO_TYPE_BOOLEAN:
4922         case MONO_TYPE_CHAR:
4923         case MONO_TYPE_I1:
4924         case MONO_TYPE_U1:
4925         case MONO_TYPE_I2:
4926         case MONO_TYPE_U2:
4927         case MONO_TYPE_I4:
4928         case MONO_TYPE_U4:
4929         case MONO_TYPE_I:
4930         case MONO_TYPE_U:
4931         case MONO_TYPE_STRING:
4932         case MONO_TYPE_OBJECT:
4933         case MONO_TYPE_CLASS:
4934         case MONO_TYPE_SZARRAY:
4935         case MONO_TYPE_PTR:
4936         case MONO_TYPE_FNPTR:
4937         case MONO_TYPE_ARRAY:
4938                 *align = stack_slot_align;
4939                 return stack_slot_size;
4940         case MONO_TYPE_VAR:
4941         case MONO_TYPE_MVAR:
4942                 g_assert (allow_open);
4943                 if (!t->data.generic_param->gshared_constraint || t->data.generic_param->gshared_constraint->type == MONO_TYPE_VALUETYPE) {
4944                         *align = stack_slot_align;
4945                         return stack_slot_size;
4946                 } else {
4947                         /* The gparam can only match types given by gshared_constraint */
4948                         return mono_type_stack_size_internal (t->data.generic_param->gshared_constraint, align, allow_open);
4949                 }
4950         case MONO_TYPE_TYPEDBYREF:
4951                 *align = stack_slot_align;
4952                 return stack_slot_size * 3;
4953         case MONO_TYPE_R4:
4954                 *align = MONO_ABI_ALIGNOF (float);
4955                 return sizeof (float);          
4956         case MONO_TYPE_I8:
4957         case MONO_TYPE_U8:
4958                 *align = MONO_ABI_ALIGNOF (gint64);
4959                 return sizeof (gint64);         
4960         case MONO_TYPE_R8:
4961                 *align = MONO_ABI_ALIGNOF (double);
4962                 return sizeof (double);
4963         case MONO_TYPE_VALUETYPE: {
4964                 guint32 size;
4965
4966                 if (t->data.klass->enumtype)
4967                         return mono_type_stack_size_internal (mono_class_enum_basetype (t->data.klass), align, allow_open);
4968                 else {
4969                         size = mono_class_value_size (t->data.klass, (guint32*)align);
4970
4971                         *align = *align + stack_slot_align - 1;
4972                         *align &= ~(stack_slot_align - 1);
4973
4974                         size += stack_slot_size - 1;
4975                         size &= ~(stack_slot_size - 1);
4976
4977                         return size;
4978                 }
4979         }
4980         case MONO_TYPE_GENERICINST: {
4981                 MonoGenericClass *gclass = t->data.generic_class;
4982                 MonoClass *container_class = gclass->container_class;
4983
4984                 if (!allow_open)
4985                         g_assert (!gclass->context.class_inst->is_open);
4986
4987                 if (container_class->valuetype) {
4988                         if (container_class->enumtype)
4989                                 return mono_type_stack_size_internal (mono_class_enum_basetype (container_class), align, allow_open);
4990                         else {
4991                                 guint32 size = mono_class_value_size (mono_class_from_mono_type (t), (guint32*)align);
4992
4993                                 *align = *align + stack_slot_align - 1;
4994                                 *align &= ~(stack_slot_align - 1);
4995
4996                                 size += stack_slot_size - 1;
4997                                 size &= ~(stack_slot_size - 1);
4998
4999                                 return size;
5000                         }
5001                 } else {
5002                         *align = stack_slot_align;
5003                         return stack_slot_size;
5004                 }
5005         }
5006         default:
5007                 g_error ("type 0x%02x unknown", t->type);
5008         }
5009         return 0;
5010 }
5011
5012 gboolean
5013 mono_type_generic_inst_is_valuetype (MonoType *type)
5014 {
5015         g_assert (type->type == MONO_TYPE_GENERICINST);
5016         return type->data.generic_class->container_class->valuetype;
5017 }
5018
5019 /**
5020  * mono_metadata_generic_class_is_valuetype:
5021  */
5022 gboolean
5023 mono_metadata_generic_class_is_valuetype (MonoGenericClass *gclass)
5024 {
5025         return gclass->container_class->valuetype;
5026 }
5027
5028 static gboolean
5029 _mono_metadata_generic_class_equal (const MonoGenericClass *g1, const MonoGenericClass *g2, gboolean signature_only)
5030 {
5031         MonoGenericInst *i1 = g1->context.class_inst;
5032         MonoGenericInst *i2 = g2->context.class_inst;
5033
5034         if (g1->is_dynamic != g2->is_dynamic)
5035                 return FALSE;
5036         if (!mono_metadata_class_equal (g1->container_class, g2->container_class, signature_only))
5037                 return FALSE;
5038         if (!mono_generic_inst_equal_full (i1, i2, signature_only))
5039                 return FALSE;
5040         return g1->is_tb_open == g2->is_tb_open;
5041 }
5042
5043 static gboolean
5044 _mono_metadata_generic_class_container_equal (const MonoGenericClass *g1, MonoClass *c2, gboolean signature_only)
5045 {
5046         MonoGenericInst *i1 = g1->context.class_inst;
5047         MonoGenericInst *i2 = mono_class_get_generic_container (c2)->context.class_inst;
5048
5049         if (!mono_metadata_class_equal (g1->container_class, c2, signature_only))
5050                 return FALSE;
5051         if (!mono_generic_inst_equal_full (i1, i2, signature_only))
5052                 return FALSE;
5053         return !g1->is_tb_open;
5054 }
5055
5056 guint
5057 mono_metadata_generic_context_hash (const MonoGenericContext *context)
5058 {
5059         /* FIXME: check if this seed is good enough */
5060         guint hash = 0xc01dfee7;
5061         if (context->class_inst)
5062                 hash = ((hash << 5) - hash) ^ mono_metadata_generic_inst_hash (context->class_inst);
5063         if (context->method_inst)
5064                 hash = ((hash << 5) - hash) ^ mono_metadata_generic_inst_hash (context->method_inst);
5065         return hash;
5066 }
5067
5068 gboolean
5069 mono_metadata_generic_context_equal (const MonoGenericContext *g1, const MonoGenericContext *g2)
5070 {
5071         return g1->class_inst == g2->class_inst && g1->method_inst == g2->method_inst;
5072 }
5073
5074 /*
5075  * mono_metadata_str_hash:
5076  *
5077  *   This should be used instead of g_str_hash for computing hash codes visible
5078  * outside this module, since g_str_hash () is not guaranteed to be stable
5079  * (its not the same in eglib for example).
5080  */
5081 guint
5082 mono_metadata_str_hash (gconstpointer v1)
5083 {
5084         /* Same as g_str_hash () in glib */
5085         char *p = (char *) v1;
5086         guint hash = *p;
5087
5088         while (*p++) {
5089                 if (*p)
5090                         hash = (hash << 5) - hash + *p;
5091         }
5092
5093         return hash;
5094
5095
5096 /**
5097  * mono_metadata_type_hash:
5098  * \param t1 a type
5099  * Computes a hash value for \p t1 to be used in \c GHashTable.
5100  * The returned hash is guaranteed to be the same across executions.
5101  */
5102 guint
5103 mono_metadata_type_hash (MonoType *t1)
5104 {
5105         guint hash = t1->type;
5106
5107         hash |= t1->byref << 6; /* do not collide with t1->type values */
5108         switch (t1->type) {
5109         case MONO_TYPE_VALUETYPE:
5110         case MONO_TYPE_CLASS:
5111         case MONO_TYPE_SZARRAY: {
5112                 MonoClass *klass = t1->data.klass;
5113                 /*
5114                  * Dynamic classes must not be hashed on their type since it can change
5115                  * during runtime. For example, if we hash a reference type that is
5116                  * later made into a valuetype.
5117                  *
5118                  * This is specially problematic with generic instances since they are
5119                  * inserted in a bunch of hash tables before been finished.
5120                  */
5121                 if (image_is_dynamic (klass->image))
5122                         return (t1->byref << 6) | mono_metadata_str_hash (klass->name);
5123                 return ((hash << 5) - hash) ^ mono_metadata_str_hash (klass->name);
5124         }
5125         case MONO_TYPE_PTR:
5126                 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
5127         case MONO_TYPE_ARRAY:
5128                 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
5129         case MONO_TYPE_GENERICINST:
5130                 return ((hash << 5) - hash) ^ mono_generic_class_hash (t1->data.generic_class);
5131         case MONO_TYPE_VAR:
5132         case MONO_TYPE_MVAR:
5133                 return ((hash << 5) - hash) ^ mono_metadata_generic_param_hash (t1->data.generic_param);
5134         default:
5135                 return hash;
5136         }
5137 }
5138
5139 guint
5140 mono_metadata_generic_param_hash (MonoGenericParam *p)
5141 {
5142         guint hash;
5143         MonoGenericParamInfo *info;
5144
5145         hash = (mono_generic_param_num (p) << 2);
5146         if (p->gshared_constraint)
5147                 hash = ((hash << 5) - hash) ^ mono_metadata_type_hash (p->gshared_constraint);
5148         info = mono_generic_param_info (p);
5149         /* Can't hash on the owner klass/method, since those might not be set when this is called */
5150         if (info)
5151                 hash = ((hash << 5) - hash) ^ info->token;
5152         return hash;
5153 }
5154
5155 static gboolean
5156 mono_metadata_generic_param_equal_internal (MonoGenericParam *p1, MonoGenericParam *p2, gboolean signature_only)
5157 {
5158         if (p1 == p2)
5159                 return TRUE;
5160         if (mono_generic_param_num (p1) != mono_generic_param_num (p2))
5161                 return FALSE;
5162         if (p1->gshared_constraint && p2->gshared_constraint) {
5163                 if (!mono_metadata_type_equal (p1->gshared_constraint, p2->gshared_constraint))
5164                         return FALSE;
5165         } else {
5166                 if (p1->gshared_constraint != p2->gshared_constraint)
5167                         return FALSE;
5168         }
5169
5170         /*
5171          * We have to compare the image as well because if we didn't,
5172          * the generic_inst_cache lookup wouldn't care about the image
5173          * of generic params, so what could happen is that a generic
5174          * inst with params from image A is put into the cache, then
5175          * image B gets that generic inst from the cache, image A is
5176          * unloaded, so the inst is deleted, but image B still retains
5177          * a pointer to it.
5178          */
5179         if (mono_generic_param_owner (p1) == mono_generic_param_owner (p2))
5180                 return TRUE;
5181
5182         /*
5183          * If `signature_only' is true, we're comparing two (method) signatures.
5184          * In this case, the owner of two type parameters doesn't need to match.
5185          */
5186
5187         return signature_only;
5188 }
5189
5190 gboolean
5191 mono_metadata_generic_param_equal (MonoGenericParam *p1, MonoGenericParam *p2)
5192 {
5193         return mono_metadata_generic_param_equal_internal (p1, p2, TRUE);
5194 }
5195
5196 static gboolean
5197 mono_metadata_class_equal (MonoClass *c1, MonoClass *c2, gboolean signature_only)
5198 {
5199         if (c1 == c2)
5200                 return TRUE;
5201         if (mono_class_is_ginst (c1) && mono_class_is_ginst (c2))
5202                 return _mono_metadata_generic_class_equal (mono_class_get_generic_class (c1), mono_class_get_generic_class (c2), signature_only);
5203         if (mono_class_is_ginst (c1) && mono_class_is_gtd (c2))
5204                 return _mono_metadata_generic_class_container_equal (mono_class_get_generic_class (c1), c2, signature_only);
5205         if (mono_class_is_gtd (c1) && mono_class_is_ginst (c2))
5206                 return _mono_metadata_generic_class_container_equal (mono_class_get_generic_class (c2), c1, signature_only);
5207         if ((c1->byval_arg.type == MONO_TYPE_VAR) && (c2->byval_arg.type == MONO_TYPE_VAR))
5208                 return mono_metadata_generic_param_equal_internal (
5209                         c1->byval_arg.data.generic_param, c2->byval_arg.data.generic_param, signature_only);
5210         if ((c1->byval_arg.type == MONO_TYPE_MVAR) && (c2->byval_arg.type == MONO_TYPE_MVAR))
5211                 return mono_metadata_generic_param_equal_internal (
5212                         c1->byval_arg.data.generic_param, c2->byval_arg.data.generic_param, signature_only);
5213         if (signature_only &&
5214             (c1->byval_arg.type == MONO_TYPE_SZARRAY) && (c2->byval_arg.type == MONO_TYPE_SZARRAY))
5215                 return mono_metadata_class_equal (c1->byval_arg.data.klass, c2->byval_arg.data.klass, signature_only);
5216         if (signature_only &&
5217             (c1->byval_arg.type == MONO_TYPE_ARRAY) && (c2->byval_arg.type == MONO_TYPE_ARRAY))
5218                 return do_mono_metadata_type_equal (&c1->byval_arg, &c2->byval_arg, signature_only);
5219         return FALSE;
5220 }
5221
5222 static gboolean
5223 mono_metadata_fnptr_equal (MonoMethodSignature *s1, MonoMethodSignature *s2, gboolean signature_only)
5224 {
5225         gpointer iter1 = 0, iter2 = 0;
5226
5227         if (s1 == s2)
5228                 return TRUE;
5229         if (s1->call_convention != s2->call_convention)
5230                 return FALSE;
5231         if (s1->sentinelpos != s2->sentinelpos)
5232                 return FALSE;
5233         if (s1->hasthis != s2->hasthis)
5234                 return FALSE;
5235         if (s1->explicit_this != s2->explicit_this)
5236                 return FALSE;
5237         if (! do_mono_metadata_type_equal (s1->ret, s2->ret, signature_only))
5238                 return FALSE;
5239         if (s1->param_count != s2->param_count)
5240                 return FALSE;
5241
5242         while (TRUE) {
5243                 MonoType *t1 = mono_signature_get_params (s1, &iter1);
5244                 MonoType *t2 = mono_signature_get_params (s2, &iter2);
5245
5246                 if (t1 == NULL || t2 == NULL)
5247                         return (t1 == t2);
5248                 if (! do_mono_metadata_type_equal (t1, t2, signature_only))
5249                         return FALSE;
5250         }
5251 }
5252
5253 /*
5254  * mono_metadata_type_equal:
5255  * @t1: a type
5256  * @t2: another type
5257  * @signature_only: If true, treat ginsts as equal which are instantiated separately but have equal positional value
5258  *
5259  * Determine if @t1 and @t2 represent the same type.
5260  * Returns: #TRUE if @t1 and @t2 are equal.
5261  */
5262 static gboolean
5263 do_mono_metadata_type_equal (MonoType *t1, MonoType *t2, gboolean signature_only)
5264 {
5265         if (t1->type != t2->type || t1->byref != t2->byref)
5266                 return FALSE;
5267
5268         switch (t1->type) {
5269         case MONO_TYPE_VOID:
5270         case MONO_TYPE_BOOLEAN:
5271         case MONO_TYPE_CHAR:
5272         case MONO_TYPE_I1:
5273         case MONO_TYPE_U1:
5274         case MONO_TYPE_I2:
5275         case MONO_TYPE_U2:
5276         case MONO_TYPE_I4:
5277         case MONO_TYPE_U4:
5278         case MONO_TYPE_I8:
5279         case MONO_TYPE_U8:
5280         case MONO_TYPE_R4:
5281         case MONO_TYPE_R8:
5282         case MONO_TYPE_STRING:
5283         case MONO_TYPE_I:
5284         case MONO_TYPE_U:
5285         case MONO_TYPE_OBJECT:
5286         case MONO_TYPE_TYPEDBYREF:
5287                 return TRUE;
5288         case MONO_TYPE_VALUETYPE:
5289         case MONO_TYPE_CLASS:
5290         case MONO_TYPE_SZARRAY:
5291                 return mono_metadata_class_equal (t1->data.klass, t2->data.klass, signature_only);
5292         case MONO_TYPE_PTR:
5293                 return do_mono_metadata_type_equal (t1->data.type, t2->data.type, signature_only);
5294         case MONO_TYPE_ARRAY:
5295                 if (t1->data.array->rank != t2->data.array->rank)
5296                         return FALSE;
5297                 return mono_metadata_class_equal (t1->data.array->eklass, t2->data.array->eklass, signature_only);
5298         case MONO_TYPE_GENERICINST:
5299                 return _mono_metadata_generic_class_equal (
5300                         t1->data.generic_class, t2->data.generic_class, signature_only);
5301         case MONO_TYPE_VAR:
5302                 return mono_metadata_generic_param_equal_internal (
5303                         t1->data.generic_param, t2->data.generic_param, signature_only);
5304         case MONO_TYPE_MVAR:
5305                 return mono_metadata_generic_param_equal_internal (
5306                         t1->data.generic_param, t2->data.generic_param, signature_only);
5307         case MONO_TYPE_FNPTR:
5308                 return mono_metadata_fnptr_equal (t1->data.method, t2->data.method, signature_only);
5309         default:
5310                 g_error ("implement type compare for %0x!", t1->type);
5311                 return FALSE;
5312         }
5313
5314         return FALSE;
5315 }
5316
5317 /**
5318  * mono_metadata_type_equal:
5319  */
5320 gboolean
5321 mono_metadata_type_equal (MonoType *t1, MonoType *t2)
5322 {
5323         return do_mono_metadata_type_equal (t1, t2, FALSE);
5324 }
5325
5326 /**
5327  * mono_metadata_type_equal_full:
5328  * \param t1 a type
5329  * \param t2 another type
5330  * \param signature_only if signature only comparison should be made
5331  *
5332  * Determine if \p t1 and \p t2 are signature compatible if \p signature_only is TRUE, otherwise
5333  * behaves the same way as mono_metadata_type_equal.
5334  * The function mono_metadata_type_equal(a, b) is just a shortcut for mono_metadata_type_equal_full(a, b, FALSE).
5335  * \returns TRUE if \p t1 and \p t2 are equal taking \p signature_only into account.
5336  */
5337 gboolean
5338 mono_metadata_type_equal_full (MonoType *t1, MonoType *t2, gboolean signature_only)
5339 {
5340         return do_mono_metadata_type_equal (t1, t2, signature_only);
5341 }
5342
5343 /**
5344  * mono_metadata_signature_equal:
5345  * \param sig1 a signature
5346  * \param sig2 another signature
5347  *
5348  * Determine if \p sig1 and \p sig2 represent the same signature, with the
5349  * same number of arguments and the same types.
5350  * \returns TRUE if \p sig1 and \p sig2 are equal.
5351  */
5352 gboolean
5353 mono_metadata_signature_equal (MonoMethodSignature *sig1, MonoMethodSignature *sig2)
5354 {
5355         int i;
5356
5357         if (sig1->hasthis != sig2->hasthis || sig1->param_count != sig2->param_count)
5358                 return FALSE;
5359
5360         if (sig1->generic_param_count != sig2->generic_param_count)
5361                 return FALSE;
5362
5363         /*
5364          * We're just comparing the signatures of two methods here:
5365          *
5366          * If we have two generic methods `void Foo<U> (U u)' and `void Bar<V> (V v)',
5367          * U and V are equal here.
5368          *
5369          * That's what the `signature_only' argument of do_mono_metadata_type_equal() is for.
5370          */
5371
5372         for (i = 0; i < sig1->param_count; i++) { 
5373                 MonoType *p1 = sig1->params[i];
5374                 MonoType *p2 = sig2->params[i];
5375                 
5376                 /* if (p1->attrs != p2->attrs)
5377                         return FALSE;
5378                 */
5379                 if (!do_mono_metadata_type_equal (p1, p2, TRUE))
5380                         return FALSE;
5381         }
5382
5383         if (!do_mono_metadata_type_equal (sig1->ret, sig2->ret, TRUE))
5384                 return FALSE;
5385         return TRUE;
5386 }
5387
5388 /**
5389  * mono_metadata_type_dup:
5390  * \param image image to alloc memory from
5391  * \param original type to duplicate
5392  * \returns copy of type allocated from the image's mempool (or from the heap, if \p image is null).
5393  */
5394 MonoType *
5395 mono_metadata_type_dup (MonoImage *image, const MonoType *o)
5396 {
5397         MonoType *r = NULL;
5398         int sizeof_o = MONO_SIZEOF_TYPE;
5399         if (o->num_mods)
5400                 sizeof_o += o->num_mods  * sizeof (MonoCustomMod);
5401
5402         r = image ? (MonoType *)mono_image_alloc0 (image, sizeof_o) : (MonoType *)g_malloc (sizeof_o);
5403
5404         memcpy (r, o, sizeof_o);
5405
5406         if (o->type == MONO_TYPE_PTR) {
5407                 r->data.type = mono_metadata_type_dup (image, o->data.type);
5408         } else if (o->type == MONO_TYPE_ARRAY) {
5409                 r->data.array = mono_dup_array_type (image, o->data.array);
5410         } else if (o->type == MONO_TYPE_FNPTR) {
5411                 /*FIXME the dup'ed signature is leaked mono_metadata_free_type*/
5412                 r->data.method = mono_metadata_signature_deep_dup (image, o->data.method);
5413         }
5414         return r;
5415 }
5416
5417 /**
5418  * mono_signature_hash:
5419  */
5420 guint
5421 mono_signature_hash (MonoMethodSignature *sig)
5422 {
5423         guint i, res = sig->ret->type;
5424
5425         for (i = 0; i < sig->param_count; i++)
5426                 res = (res << 5) - res + mono_type_hash (sig->params[i]);
5427
5428         return res;
5429 }
5430
5431 /*
5432  * mono_metadata_encode_value:
5433  * @value: value to encode
5434  * @buf: buffer where to write the compressed representation
5435  * @endbuf: pointer updated to point at the end of the encoded output
5436  *
5437  * Encodes the value @value in the compressed representation used
5438  * in metadata and stores the result in @buf. @buf needs to be big
5439  * enough to hold the data (4 bytes).
5440  */
5441 void
5442 mono_metadata_encode_value (guint32 value, char *buf, char **endbuf)
5443 {
5444         char *p = buf;
5445         
5446         if (value < 0x80)
5447                 *p++ = value;
5448         else if (value < 0x4000) {
5449                 p [0] = 0x80 | (value >> 8);
5450                 p [1] = value & 0xff;
5451                 p += 2;
5452         } else {
5453                 p [0] = (value >> 24) | 0xc0;
5454                 p [1] = (value >> 16) & 0xff;
5455                 p [2] = (value >> 8) & 0xff;
5456                 p [3] = value & 0xff;
5457                 p += 4;
5458         }
5459         if (endbuf)
5460                 *endbuf = p;
5461 }
5462
5463 /**
5464  * mono_metadata_field_info:
5465  * \param meta the Image the field is defined in
5466  * \param index the index in the field table representing the field
5467  * \param offset a pointer to an integer where to store the offset that  may have been specified for the field in a FieldLayout table
5468  * \param rva a pointer to the RVA of the field data in the image that may have been defined in a \c FieldRVA table
5469  * \param marshal_spec a pointer to the marshal spec that may have been defined for the field in a \c FieldMarshal table.
5470  *
5471  * Gather info for field \p index that may have been defined in the \c FieldLayout, 
5472  * \c FieldRVA and \c FieldMarshal tables.
5473  * Either of \p offset, \p rva and \p marshal_spec can be NULL if you're not interested 
5474  * in the data.
5475  */
5476 void
5477 mono_metadata_field_info (MonoImage *meta, guint32 index, guint32 *offset, guint32 *rva, 
5478                           MonoMarshalSpec **marshal_spec)
5479 {
5480         mono_metadata_field_info_full (meta, index, offset, rva, marshal_spec, FALSE);
5481 }
5482
5483 void
5484 mono_metadata_field_info_with_mempool (MonoImage *meta, guint32 index, guint32 *offset, guint32 *rva, 
5485                           MonoMarshalSpec **marshal_spec)
5486 {
5487         mono_metadata_field_info_full (meta, index, offset, rva, marshal_spec, TRUE);
5488 }
5489
5490 static void
5491 mono_metadata_field_info_full (MonoImage *meta, guint32 index, guint32 *offset, guint32 *rva, 
5492                                        MonoMarshalSpec **marshal_spec, gboolean alloc_from_image)
5493 {
5494         MonoTableInfo *tdef;
5495         locator_t loc;
5496
5497         loc.idx = index + 1;
5498         if (meta->uncompressed_metadata)
5499                 loc.idx = search_ptr_table (meta, MONO_TABLE_FIELD_POINTER, loc.idx);
5500
5501         if (offset) {
5502                 tdef = &meta->tables [MONO_TABLE_FIELDLAYOUT];
5503
5504                 loc.col_idx = MONO_FIELD_LAYOUT_FIELD;
5505                 loc.t = tdef;
5506
5507                 if (tdef->base && mono_binary_search (&loc, tdef->base, tdef->rows, tdef->row_size, table_locator)) {
5508                         *offset = mono_metadata_decode_row_col (tdef, loc.result, MONO_FIELD_LAYOUT_OFFSET);
5509                 } else {
5510                         *offset = (guint32)-1;
5511                 }
5512         }
5513         if (rva) {
5514                 tdef = &meta->tables [MONO_TABLE_FIELDRVA];
5515
5516                 loc.col_idx = MONO_FIELD_RVA_FIELD;
5517                 loc.t = tdef;
5518                 
5519                 if (tdef->base && mono_binary_search (&loc, tdef->base, tdef->rows, tdef->row_size, table_locator)) {
5520                         /*
5521                          * LAMESPEC: There is no signature, no nothing, just the raw data.
5522                          */
5523                         *rva = mono_metadata_decode_row_col (tdef, loc.result, MONO_FIELD_RVA_RVA);
5524                 } else {
5525                         *rva = 0;
5526                 }
5527         }
5528         if (marshal_spec) {
5529                 const char *p;
5530                 
5531                 if ((p = mono_metadata_get_marshal_info (meta, index, TRUE))) {
5532                         *marshal_spec = mono_metadata_parse_marshal_spec_full (alloc_from_image ? meta : NULL, meta, p);
5533                 }
5534         }
5535
5536 }
5537
5538 /**
5539  * mono_metadata_get_constant_index:
5540  * \param meta the Image the field is defined in
5541  * \param index the token that may have a row defined in the constants table
5542  * \param hint possible position for the row
5543  *
5544  * \p token must be a \c FieldDef, \c ParamDef or \c PropertyDef token.
5545  *
5546  * \returns the index into the \c Constants table or 0 if not found.
5547  */
5548 guint32
5549 mono_metadata_get_constant_index (MonoImage *meta, guint32 token, guint32 hint)
5550 {
5551         MonoTableInfo *tdef;
5552         locator_t loc;
5553         guint32 index = mono_metadata_token_index (token);
5554
5555         tdef = &meta->tables [MONO_TABLE_CONSTANT];
5556         index <<= MONO_HASCONSTANT_BITS;
5557         switch (mono_metadata_token_table (token)) {
5558         case MONO_TABLE_FIELD:
5559                 index |= MONO_HASCONSTANT_FIEDDEF;
5560                 break;
5561         case MONO_TABLE_PARAM:
5562                 index |= MONO_HASCONSTANT_PARAM;
5563                 break;
5564         case MONO_TABLE_PROPERTY:
5565                 index |= MONO_HASCONSTANT_PROPERTY;
5566                 break;
5567         default:
5568                 g_warning ("Not a valid token for the constant table: 0x%08x", token);
5569                 return 0;
5570         }
5571         loc.idx = index;
5572         loc.col_idx = MONO_CONSTANT_PARENT;
5573         loc.t = tdef;
5574
5575         /* FIXME: Index translation */
5576
5577         if ((hint > 0) && (hint < tdef->rows) && (mono_metadata_decode_row_col (tdef, hint - 1, MONO_CONSTANT_PARENT) == index))
5578                 return hint;
5579
5580         if (tdef->base && mono_binary_search (&loc, tdef->base, tdef->rows, tdef->row_size, table_locator)) {
5581                 return loc.result + 1;
5582         }
5583         return 0;
5584 }
5585
5586 /**
5587  * mono_metadata_events_from_typedef:
5588  * \param meta metadata context
5589  * \param index 0-based index (in the \c TypeDef table) describing a type
5590  * \returns the 0-based index in the \c Event table for the events in the
5591  * type. The last event that belongs to the type (plus 1) is stored
5592  * in the \p end_idx pointer.
5593  */
5594 guint32
5595 mono_metadata_events_from_typedef (MonoImage *meta, guint32 index, guint *end_idx)
5596 {
5597         locator_t loc;
5598         guint32 start, end;
5599         MonoTableInfo *tdef  = &meta->tables [MONO_TABLE_EVENTMAP];
5600
5601         *end_idx = 0;
5602         
5603         if (!tdef->base)
5604                 return 0;
5605
5606         loc.t = tdef;
5607         loc.col_idx = MONO_EVENT_MAP_PARENT;
5608         loc.idx = index + 1;
5609
5610         if (!mono_binary_search (&loc, tdef->base, tdef->rows, tdef->row_size, table_locator))
5611                 return 0;
5612         
5613         start = mono_metadata_decode_row_col (tdef, loc.result, MONO_EVENT_MAP_EVENTLIST);
5614         if (loc.result + 1 < tdef->rows) {
5615                 end = mono_metadata_decode_row_col (tdef, loc.result + 1, MONO_EVENT_MAP_EVENTLIST) - 1;
5616         } else {
5617                 end = meta->tables [MONO_TABLE_EVENT].rows;
5618         }
5619
5620         *end_idx = end;
5621         return start - 1;
5622 }
5623
5624 /**
5625  * mono_metadata_methods_from_event:
5626  * \param meta metadata context
5627  * \param index 0-based index (in the \c Event table) describing a event
5628  * \returns the 0-based index in the \c MethodDef table for the methods in the
5629  * event. The last method that belongs to the event (plus 1) is stored
5630  * in the \p end_idx pointer.
5631  */
5632 guint32
5633 mono_metadata_methods_from_event   (MonoImage *meta, guint32 index, guint *end_idx)
5634 {
5635         locator_t loc;
5636         guint start, end;
5637         guint32 cols [MONO_METHOD_SEMA_SIZE];
5638         MonoTableInfo *msemt = &meta->tables [MONO_TABLE_METHODSEMANTICS];
5639
5640         *end_idx = 0;
5641         if (!msemt->base)
5642                 return 0;
5643
5644         if (meta->uncompressed_metadata)
5645             index = search_ptr_table (meta, MONO_TABLE_EVENT_POINTER, index + 1) - 1;
5646
5647         loc.t = msemt;
5648         loc.col_idx = MONO_METHOD_SEMA_ASSOCIATION;
5649         loc.idx = ((index + 1) << MONO_HAS_SEMANTICS_BITS) | MONO_HAS_SEMANTICS_EVENT; /* Method association coded index */
5650
5651         if (!mono_binary_search (&loc, msemt->base, msemt->rows, msemt->row_size, table_locator))
5652                 return 0;
5653
5654         start = loc.result;
5655         /*
5656          * We may end up in the middle of the rows... 
5657          */
5658         while (start > 0) {
5659                 if (loc.idx == mono_metadata_decode_row_col (msemt, start - 1, MONO_METHOD_SEMA_ASSOCIATION))
5660                         start--;
5661                 else
5662                         break;
5663         }
5664         end = start + 1;
5665         while (end < msemt->rows) {
5666                 mono_metadata_decode_row (msemt, end, cols, MONO_METHOD_SEMA_SIZE);
5667                 if (cols [MONO_METHOD_SEMA_ASSOCIATION] != loc.idx)
5668                         break;
5669                 ++end;
5670         }
5671         *end_idx = end;
5672         return start;
5673 }
5674
5675 /**
5676  * mono_metadata_properties_from_typedef:
5677  * \param meta metadata context
5678  * \param index 0-based index (in the \c TypeDef table) describing a type
5679  * \returns the 0-based index in the \c Property table for the properties in the
5680  * type. The last property that belongs to the type (plus 1) is stored
5681  * in the \p end_idx pointer.
5682  */
5683 guint32
5684 mono_metadata_properties_from_typedef (MonoImage *meta, guint32 index, guint *end_idx)
5685 {
5686         locator_t loc;
5687         guint32 start, end;
5688         MonoTableInfo *tdef  = &meta->tables [MONO_TABLE_PROPERTYMAP];
5689
5690         *end_idx = 0;
5691         
5692         if (!tdef->base)
5693                 return 0;
5694
5695         loc.t = tdef;
5696         loc.col_idx = MONO_PROPERTY_MAP_PARENT;
5697         loc.idx = index + 1;
5698
5699         if (!mono_binary_search (&loc, tdef->base, tdef->rows, tdef->row_size, table_locator))
5700                 return 0;
5701         
5702         start = mono_metadata_decode_row_col (tdef, loc.result, MONO_PROPERTY_MAP_PROPERTY_LIST);
5703         if (loc.result + 1 < tdef->rows) {
5704                 end = mono_metadata_decode_row_col (tdef, loc.result + 1, MONO_PROPERTY_MAP_PROPERTY_LIST) - 1;
5705         } else {
5706                 end = meta->tables [MONO_TABLE_PROPERTY].rows;
5707         }
5708
5709         *end_idx = end;
5710         return start - 1;
5711 }
5712
5713 /**
5714  * mono_metadata_methods_from_property:
5715  * \param meta metadata context
5716  * \param index 0-based index (in the \c PropertyDef table) describing a property
5717  * \returns the 0-based index in the \c MethodDef table for the methods in the
5718  * property. The last method that belongs to the property (plus 1) is stored
5719  * in the \p end_idx pointer.
5720  */
5721 guint32
5722 mono_metadata_methods_from_property   (MonoImage *meta, guint32 index, guint *end_idx)
5723 {
5724         locator_t loc;
5725         guint start, end;
5726         guint32 cols [MONO_METHOD_SEMA_SIZE];
5727         MonoTableInfo *msemt = &meta->tables [MONO_TABLE_METHODSEMANTICS];
5728
5729         *end_idx = 0;
5730         if (!msemt->base)
5731                 return 0;
5732
5733         if (meta->uncompressed_metadata)
5734             index = search_ptr_table (meta, MONO_TABLE_PROPERTY_POINTER, index + 1) - 1;
5735
5736         loc.t = msemt;
5737         loc.col_idx = MONO_METHOD_SEMA_ASSOCIATION;
5738         loc.idx = ((index + 1) << MONO_HAS_SEMANTICS_BITS) | MONO_HAS_SEMANTICS_PROPERTY; /* Method association coded index */
5739
5740         if (!mono_binary_search (&loc, msemt->base, msemt->rows, msemt->row_size, table_locator))
5741                 return 0;
5742
5743         start = loc.result;
5744         /*
5745          * We may end up in the middle of the rows... 
5746          */
5747         while (start > 0) {
5748                 if (loc.idx == mono_metadata_decode_row_col (msemt, start - 1, MONO_METHOD_SEMA_ASSOCIATION))
5749                         start--;
5750                 else
5751                         break;
5752         }
5753         end = start + 1;
5754         while (end < msemt->rows) {
5755                 mono_metadata_decode_row (msemt, end, cols, MONO_METHOD_SEMA_SIZE);
5756                 if (cols [MONO_METHOD_SEMA_ASSOCIATION] != loc.idx)
5757                         break;
5758                 ++end;
5759         }
5760         *end_idx = end;
5761         return start;
5762 }
5763
5764 /**
5765  * mono_metadata_implmap_from_method:
5766  */
5767 guint32
5768 mono_metadata_implmap_from_method (MonoImage *meta, guint32 method_idx)
5769 {
5770         locator_t loc;
5771         MonoTableInfo *tdef  = &meta->tables [MONO_TABLE_IMPLMAP];
5772
5773         if (!tdef->base)
5774                 return 0;
5775
5776         /* No index translation seems to be needed */
5777
5778         loc.t = tdef;
5779         loc.col_idx = MONO_IMPLMAP_MEMBER;
5780         loc.idx = ((method_idx + 1) << MONO_MEMBERFORWD_BITS) | MONO_MEMBERFORWD_METHODDEF;
5781
5782         if (!mono_binary_search (&loc, tdef->base, tdef->rows, tdef->row_size, table_locator))
5783                 return 0;
5784
5785         return loc.result + 1;
5786 }
5787
5788 /**
5789  * mono_type_create_from_typespec:
5790  * \param image context where the image is created
5791  * \param type_spec  typespec token
5792  * \deprecated use \c mono_type_create_from_typespec_checked that has proper error handling
5793  *
5794  * Creates a \c MonoType representing the \c TypeSpec indexed by the \p type_spec
5795  * token.
5796  */
5797 MonoType *
5798 mono_type_create_from_typespec (MonoImage *image, guint32 type_spec)
5799 {
5800         MonoError error;
5801         MonoType *type = mono_type_create_from_typespec_checked (image, type_spec, &error);
5802         if (!type)
5803                  g_error ("Could not create typespec %x due to %s", type_spec, mono_error_get_message (&error));
5804         return type;
5805 }
5806
5807 MonoType *
5808 mono_type_create_from_typespec_checked (MonoImage *image, guint32 type_spec, MonoError *error)
5809
5810 {
5811         guint32 idx = mono_metadata_token_index (type_spec);
5812         MonoTableInfo *t;
5813         guint32 cols [MONO_TYPESPEC_SIZE];
5814         const char *ptr;
5815         MonoType *type, *type2;
5816
5817         error_init (error);
5818
5819         type = (MonoType *)mono_conc_hashtable_lookup (image->typespec_cache, GUINT_TO_POINTER (type_spec));
5820         if (type)
5821                 return type;
5822
5823         t = &image->tables [MONO_TABLE_TYPESPEC];
5824
5825         mono_metadata_decode_row (t, idx-1, cols, MONO_TYPESPEC_SIZE);
5826         ptr = mono_metadata_blob_heap (image, cols [MONO_TYPESPEC_SIGNATURE]);
5827
5828         if (!mono_verifier_verify_typespec_signature (image, cols [MONO_TYPESPEC_SIGNATURE], type_spec, NULL)) {
5829                 mono_error_set_bad_image (error, image, "Could not verify type spec %08x.", type_spec);
5830                 return NULL;
5831         }
5832
5833         mono_metadata_decode_value (ptr, &ptr);
5834
5835         type = mono_metadata_parse_type_checked (image, NULL, 0, TRUE, ptr, &ptr, error);
5836         if (!type)
5837                 return NULL;
5838
5839         type2 = mono_metadata_type_dup (image, type);
5840         mono_metadata_free_type (type);
5841
5842         mono_image_lock (image);
5843
5844         /* We might leak some data in the image mempool if found */
5845         type = mono_conc_hashtable_insert (image->typespec_cache, GUINT_TO_POINTER (type_spec), type2);
5846         if (!type)
5847                 type = type2;
5848
5849         mono_image_unlock (image);
5850
5851         return type;
5852 }
5853
5854
5855 static char*
5856 mono_image_strndup (MonoImage *image, const char *data, guint len)
5857 {
5858         char *res;
5859         if (!image)
5860                 return g_strndup (data, len);
5861         res = (char *)mono_image_alloc (image, len + 1);
5862         memcpy (res, data, len);
5863         res [len] = 0;
5864         return res;
5865 }
5866
5867 /**
5868  * mono_metadata_parse_marshal_spec:
5869  */
5870 MonoMarshalSpec *
5871 mono_metadata_parse_marshal_spec (MonoImage *image, const char *ptr)
5872 {
5873         return mono_metadata_parse_marshal_spec_full (NULL, image, ptr);
5874 }
5875
5876 /*
5877  * If IMAGE is non-null, memory will be allocated from its mempool, otherwise it will be allocated using malloc.
5878  * PARENT_IMAGE is the image containing the marshal spec.
5879  */
5880 MonoMarshalSpec *
5881 mono_metadata_parse_marshal_spec_full (MonoImage *image, MonoImage *parent_image, const char *ptr)
5882 {
5883         MonoMarshalSpec *res;
5884         int len;
5885         const char *start = ptr;
5886
5887         /* fixme: this is incomplete, but I cant find more infos in the specs */
5888
5889         if (image)
5890                 res = (MonoMarshalSpec *)mono_image_alloc0 (image, sizeof (MonoMarshalSpec));
5891         else
5892                 res = g_new0 (MonoMarshalSpec, 1);
5893         
5894         len = mono_metadata_decode_value (ptr, &ptr);
5895         res->native = (MonoMarshalNative)*ptr++;
5896
5897         if (res->native == MONO_NATIVE_LPARRAY) {
5898                 res->data.array_data.param_num = -1;
5899                 res->data.array_data.num_elem = -1;
5900                 res->data.array_data.elem_mult = -1;
5901
5902                 if (ptr - start <= len)
5903                         res->data.array_data.elem_type = (MonoMarshalNative)*ptr++;
5904                 if (ptr - start <= len)
5905                         res->data.array_data.param_num = mono_metadata_decode_value (ptr, &ptr);
5906                 if (ptr - start <= len)
5907                         res->data.array_data.num_elem = mono_metadata_decode_value (ptr, &ptr);
5908                 if (ptr - start <= len) {
5909                         /*
5910                          * LAMESPEC: Older spec versions say this parameter comes before 
5911                          * num_elem. Never spec versions don't talk about elem_mult at
5912                          * all, but csc still emits it, and it is used to distinguish
5913                          * between param_num being 0, and param_num being omitted.
5914                          * So if (param_num == 0) && (num_elem > 0), then
5915                          * elem_mult == 0 -> the array size is num_elem
5916                          * elem_mult == 1 -> the array size is @param_num + num_elem
5917                          */
5918                         res->data.array_data.elem_mult = mono_metadata_decode_value (ptr, &ptr);
5919                 }
5920         } 
5921
5922         if (res->native == MONO_NATIVE_BYVALTSTR) {
5923                 if (ptr - start <= len)
5924                         res->data.array_data.num_elem = mono_metadata_decode_value (ptr, &ptr);
5925         }
5926
5927         if (res->native == MONO_NATIVE_BYVALARRAY) {
5928                 if (ptr - start <= len)
5929                         res->data.array_data.num_elem = mono_metadata_decode_value (ptr, &ptr);
5930         }
5931         
5932         if (res->native == MONO_NATIVE_CUSTOM) {
5933                 /* skip unused type guid */
5934                 len = mono_metadata_decode_value (ptr, &ptr);
5935                 ptr += len;
5936                 /* skip unused native type name */
5937                 len = mono_metadata_decode_value (ptr, &ptr);
5938                 ptr += len;
5939                 /* read custom marshaler type name */
5940                 len = mono_metadata_decode_value (ptr, &ptr);
5941                 res->data.custom_data.custom_name = mono_image_strndup (image, ptr, len);               
5942                 ptr += len;
5943                 /* read cookie string */
5944                 len = mono_metadata_decode_value (ptr, &ptr);
5945                 res->data.custom_data.cookie = mono_image_strndup (image, ptr, len);
5946                 res->data.custom_data.image = parent_image;
5947         }
5948
5949         if (res->native == MONO_NATIVE_SAFEARRAY) {
5950                 res->data.safearray_data.elem_type = (MonoMarshalVariant)0;
5951                 res->data.safearray_data.num_elem = 0;
5952                 if (ptr - start <= len)
5953                         res->data.safearray_data.elem_type = (MonoMarshalVariant)*ptr++;
5954                 if (ptr - start <= len)
5955                         res->data.safearray_data.num_elem = *ptr++;
5956         }
5957         return res;
5958 }
5959
5960 /**
5961  * mono_metadata_free_marshal_spec:
5962  */
5963 void 
5964 mono_metadata_free_marshal_spec (MonoMarshalSpec *spec)
5965 {
5966         if (spec->native == MONO_NATIVE_CUSTOM) {
5967                 g_free (spec->data.custom_data.custom_name);
5968                 g_free (spec->data.custom_data.cookie);
5969         }
5970         g_free (spec);
5971 }
5972
5973 /**
5974  * mono_type_to_unmanaged:
5975  * The value pointed to by \p conv will contain the kind of marshalling required for this
5976  * particular type one of the \c MONO_MARSHAL_CONV_ enumeration values.
5977  * \returns A \c MonoMarshalNative enumeration value (<code>MONO_NATIVE_</code>) value
5978  * describing the underlying native reprensetation of the type.
5979  */
5980 guint32
5981 mono_type_to_unmanaged (MonoType *type, MonoMarshalSpec *mspec, gboolean as_field,
5982                         gboolean unicode, MonoMarshalConv *conv) 
5983 {
5984         MonoMarshalConv dummy_conv;
5985         int t = type->type;
5986
5987         if (!conv)
5988                 conv = &dummy_conv;
5989
5990         *conv = MONO_MARSHAL_CONV_NONE;
5991
5992         if (type->byref)
5993                 return MONO_NATIVE_UINT;
5994
5995 handle_enum:
5996         switch (t) {
5997         case MONO_TYPE_BOOLEAN: 
5998                 if (mspec) {
5999                         switch (mspec->native) {
6000                         case MONO_NATIVE_VARIANTBOOL:
6001                                 *conv = MONO_MARSHAL_CONV_BOOL_VARIANTBOOL;
6002                                 return MONO_NATIVE_VARIANTBOOL;
6003                         case MONO_NATIVE_BOOLEAN:
6004                                 *conv = MONO_MARSHAL_CONV_BOOL_I4;
6005                                 return MONO_NATIVE_BOOLEAN;
6006                         case MONO_NATIVE_I1:
6007                         case MONO_NATIVE_U1:
6008                                 return mspec->native;
6009                         default:
6010                                 g_error ("cant marshal bool to native type %02x", mspec->native);
6011                         }
6012                 }
6013                 *conv = MONO_MARSHAL_CONV_BOOL_I4;
6014                 return MONO_NATIVE_BOOLEAN;
6015         case MONO_TYPE_CHAR:
6016                 if (mspec) {
6017                         switch (mspec->native) {
6018                         case MONO_NATIVE_U2:
6019                         case MONO_NATIVE_U1:
6020                                 return mspec->native;
6021                         default:
6022                                 g_error ("cant marshal char to native type %02x", mspec->native);
6023                         }
6024                 }
6025                 return unicode ? MONO_NATIVE_U2 : MONO_NATIVE_U1;
6026         case MONO_TYPE_I1: return MONO_NATIVE_I1;
6027         case MONO_TYPE_U1: return MONO_NATIVE_U1;
6028         case MONO_TYPE_I2: return MONO_NATIVE_I2;
6029         case MONO_TYPE_U2: return MONO_NATIVE_U2;
6030         case MONO_TYPE_I4: return MONO_NATIVE_I4;
6031         case MONO_TYPE_U4: return MONO_NATIVE_U4;
6032         case MONO_TYPE_I8: return MONO_NATIVE_I8;
6033         case MONO_TYPE_U8: return MONO_NATIVE_U8;
6034         case MONO_TYPE_R4: return MONO_NATIVE_R4;
6035         case MONO_TYPE_R8: return MONO_NATIVE_R8;
6036         case MONO_TYPE_STRING:
6037                 if (mspec) {
6038                         switch (mspec->native) {
6039                         case MONO_NATIVE_BSTR:
6040                                 *conv = MONO_MARSHAL_CONV_STR_BSTR;
6041                                 return MONO_NATIVE_BSTR;
6042                         case MONO_NATIVE_LPSTR:
6043                                 *conv = MONO_MARSHAL_CONV_STR_LPSTR;
6044                                 return MONO_NATIVE_LPSTR;
6045                         case MONO_NATIVE_LPWSTR:
6046                                 *conv = MONO_MARSHAL_CONV_STR_LPWSTR;
6047                                 return MONO_NATIVE_LPWSTR;
6048                         case MONO_NATIVE_LPTSTR:
6049                                 *conv = MONO_MARSHAL_CONV_STR_LPTSTR;
6050                                 return MONO_NATIVE_LPTSTR;
6051                         case MONO_NATIVE_ANSIBSTR:
6052                                 *conv = MONO_MARSHAL_CONV_STR_ANSIBSTR;
6053                                 return MONO_NATIVE_ANSIBSTR;
6054                         case MONO_NATIVE_TBSTR:
6055                                 *conv = MONO_MARSHAL_CONV_STR_TBSTR;
6056                                 return MONO_NATIVE_TBSTR;
6057                         case MONO_NATIVE_UTF8STR:
6058                                 *conv = MONO_MARSHAL_CONV_STR_UTF8STR;
6059                                 return MONO_NATIVE_UTF8STR;
6060                         case MONO_NATIVE_BYVALTSTR:
6061                                 if (unicode)
6062                                         *conv = MONO_MARSHAL_CONV_STR_BYVALWSTR;
6063                                 else
6064                                         *conv = MONO_MARSHAL_CONV_STR_BYVALSTR;
6065                                 return MONO_NATIVE_BYVALTSTR;
6066                         default:
6067                                 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);
6068                         }
6069                 }       
6070                 if (unicode) {
6071                         *conv = MONO_MARSHAL_CONV_STR_LPWSTR;
6072                         return MONO_NATIVE_LPWSTR; 
6073                 }
6074                 else {
6075                         *conv = MONO_MARSHAL_CONV_STR_LPSTR;
6076                         return MONO_NATIVE_LPSTR; 
6077                 }
6078         case MONO_TYPE_PTR: return MONO_NATIVE_UINT;
6079         case MONO_TYPE_VALUETYPE: /*FIXME*/
6080                 if (type->data.klass->enumtype) {
6081                         t = mono_class_enum_basetype (type->data.klass)->type;
6082                         goto handle_enum;
6083                 }
6084                 if (type->data.klass == mono_defaults.handleref_class){
6085                         *conv = MONO_MARSHAL_CONV_HANDLEREF;
6086                         return MONO_NATIVE_INT;
6087                 }
6088                 return MONO_NATIVE_STRUCT;
6089         case MONO_TYPE_SZARRAY: 
6090         case MONO_TYPE_ARRAY: 
6091                 if (mspec) {
6092                         switch (mspec->native) {
6093                         case MONO_NATIVE_BYVALARRAY:
6094                                 if ((type->data.klass->element_class == mono_defaults.char_class) && !unicode)
6095                                         *conv = MONO_MARSHAL_CONV_ARRAY_BYVALCHARARRAY;
6096                                 else
6097                                         *conv = MONO_MARSHAL_CONV_ARRAY_BYVALARRAY;
6098                                 return MONO_NATIVE_BYVALARRAY;
6099                         case MONO_NATIVE_SAFEARRAY:
6100                                 *conv = MONO_MARSHAL_CONV_ARRAY_SAVEARRAY;
6101                                 return MONO_NATIVE_SAFEARRAY;
6102                         case MONO_NATIVE_LPARRAY:                               
6103                                 *conv = MONO_MARSHAL_CONV_ARRAY_LPARRAY;
6104                                 return MONO_NATIVE_LPARRAY;
6105                         default:
6106                                 g_error ("cant marshal array as native type %02x", mspec->native);
6107                         }
6108                 }       
6109
6110                 *conv = MONO_MARSHAL_CONV_ARRAY_LPARRAY;
6111                 return MONO_NATIVE_LPARRAY;
6112         case MONO_TYPE_I: return MONO_NATIVE_INT;
6113         case MONO_TYPE_U: return MONO_NATIVE_UINT;
6114         case MONO_TYPE_CLASS: 
6115         case MONO_TYPE_OBJECT: {
6116                 /* FIXME : we need to handle ArrayList and StringBuilder here, probably */
6117                 if (mspec) {
6118                         switch (mspec->native) {
6119                         case MONO_NATIVE_STRUCT:
6120                                 return MONO_NATIVE_STRUCT;
6121                         case MONO_NATIVE_CUSTOM:
6122                                 return MONO_NATIVE_CUSTOM;
6123                         case MONO_NATIVE_INTERFACE:
6124                                 *conv = MONO_MARSHAL_CONV_OBJECT_INTERFACE;
6125                                 return MONO_NATIVE_INTERFACE;
6126                         case MONO_NATIVE_IDISPATCH:
6127                                 *conv = MONO_MARSHAL_CONV_OBJECT_IDISPATCH;
6128                                 return MONO_NATIVE_IDISPATCH;
6129                         case MONO_NATIVE_IUNKNOWN:
6130                                 *conv = MONO_MARSHAL_CONV_OBJECT_IUNKNOWN;
6131                                 return MONO_NATIVE_IUNKNOWN;
6132                         case MONO_NATIVE_FUNC:
6133                                 if (t == MONO_TYPE_CLASS && (type->data.klass == mono_defaults.multicastdelegate_class ||
6134                                                                                          type->data.klass == mono_defaults.delegate_class || 
6135                                                                                          type->data.klass->parent == mono_defaults.multicastdelegate_class)) {
6136                                         *conv = MONO_MARSHAL_CONV_DEL_FTN;
6137                                         return MONO_NATIVE_FUNC;
6138                                 }
6139                                 /* Fall through */
6140                         default:
6141                                 g_error ("cant marshal object as native type %02x", mspec->native);
6142                         }
6143                 }
6144                 if (t == MONO_TYPE_CLASS && (type->data.klass == mono_defaults.multicastdelegate_class ||
6145                                              type->data.klass == mono_defaults.delegate_class || 
6146                                              type->data.klass->parent == mono_defaults.multicastdelegate_class)) {
6147                         *conv = MONO_MARSHAL_CONV_DEL_FTN;
6148                         return MONO_NATIVE_FUNC;
6149                 }
6150                 if (mono_class_try_get_safehandle_class () && type->data.klass == mono_class_try_get_safehandle_class ()){
6151                         *conv = MONO_MARSHAL_CONV_SAFEHANDLE;
6152                         return MONO_NATIVE_INT;
6153                 }
6154                 *conv = MONO_MARSHAL_CONV_OBJECT_STRUCT;
6155                 return MONO_NATIVE_STRUCT;
6156         }
6157         case MONO_TYPE_FNPTR: return MONO_NATIVE_FUNC;
6158         case MONO_TYPE_GENERICINST:
6159                 type = &type->data.generic_class->container_class->byval_arg;
6160                 t = type->type;
6161                 goto handle_enum;
6162         case MONO_TYPE_TYPEDBYREF:
6163         default:
6164                 g_error ("type 0x%02x not handled in marshal", t);
6165         }
6166         return MONO_NATIVE_MAX;
6167 }
6168
6169 /**
6170  * mono_metadata_get_marshal_info:
6171  */
6172 const char*
6173 mono_metadata_get_marshal_info (MonoImage *meta, guint32 idx, gboolean is_field)
6174 {
6175         locator_t loc;
6176         MonoTableInfo *tdef  = &meta->tables [MONO_TABLE_FIELDMARSHAL];
6177
6178         if (!tdef->base)
6179                 return NULL;
6180
6181         loc.t = tdef;
6182         loc.col_idx = MONO_FIELD_MARSHAL_PARENT;
6183         loc.idx = ((idx + 1) << MONO_HAS_FIELD_MARSHAL_BITS) | (is_field? MONO_HAS_FIELD_MARSHAL_FIELDSREF: MONO_HAS_FIELD_MARSHAL_PARAMDEF);
6184
6185         /* FIXME: Index translation */
6186
6187         if (!mono_binary_search (&loc, tdef->base, tdef->rows, tdef->row_size, table_locator))
6188                 return NULL;
6189
6190         return mono_metadata_blob_heap (meta, mono_metadata_decode_row_col (tdef, loc.result, MONO_FIELD_MARSHAL_NATIVE_TYPE));
6191 }
6192
6193 MonoMethod*
6194 method_from_method_def_or_ref (MonoImage *m, guint32 tok, MonoGenericContext *context, MonoError *error)
6195 {
6196         MonoMethod *result = NULL;
6197         guint32 idx = tok >> MONO_METHODDEFORREF_BITS;
6198
6199         error_init (error);
6200
6201         switch (tok & MONO_METHODDEFORREF_MASK) {
6202         case MONO_METHODDEFORREF_METHODDEF:
6203                 result = mono_get_method_checked (m, MONO_TOKEN_METHOD_DEF | idx, NULL, context, error);
6204                 break;
6205         case MONO_METHODDEFORREF_METHODREF:
6206                 result = mono_get_method_checked (m, MONO_TOKEN_MEMBER_REF | idx, NULL, context, error);
6207                 break;
6208         default:
6209                 mono_error_set_bad_image (error, m, "Invalid MethodDefOfRef token %x", tok);
6210         }
6211
6212         return result;
6213 }
6214
6215 /*
6216  * mono_class_get_overrides_full:
6217  *
6218  *   Return the method overrides belonging to class @type_token in @overrides, and
6219  * the number of overrides in @num_overrides.
6220  *
6221  * Returns: TRUE on success, FALSE on failure.
6222  */
6223 gboolean
6224 mono_class_get_overrides_full (MonoImage *image, guint32 type_token, MonoMethod ***overrides, gint32 *num_overrides,
6225                                MonoGenericContext *generic_context)
6226 {
6227         MonoError error;
6228         locator_t loc;
6229         MonoTableInfo *tdef  = &image->tables [MONO_TABLE_METHODIMPL];
6230         guint32 start, end;
6231         gint32 i, num;
6232         guint32 cols [MONO_METHODIMPL_SIZE];
6233         MonoMethod **result;
6234         gint32 ok = TRUE;
6235         
6236         *overrides = NULL;
6237         if (num_overrides)
6238                 *num_overrides = 0;
6239
6240         if (!tdef->base)
6241                 return TRUE;
6242
6243         loc.t = tdef;
6244         loc.col_idx = MONO_METHODIMPL_CLASS;
6245         loc.idx = mono_metadata_token_index (type_token);
6246
6247         if (!mono_binary_search (&loc, tdef->base, tdef->rows, tdef->row_size, table_locator))
6248                 return TRUE;
6249
6250         start = loc.result;
6251         end = start + 1;
6252         /*
6253          * We may end up in the middle of the rows... 
6254          */
6255         while (start > 0) {
6256                 if (loc.idx == mono_metadata_decode_row_col (tdef, start - 1, MONO_METHODIMPL_CLASS))
6257                         start--;
6258                 else
6259                         break;
6260         }
6261         while (end < tdef->rows) {
6262                 if (loc.idx == mono_metadata_decode_row_col (tdef, end, MONO_METHODIMPL_CLASS))
6263                         end++;
6264                 else
6265                         break;
6266         }
6267         num = end - start;
6268         result = g_new (MonoMethod*, num * 2);
6269         for (i = 0; i < num; ++i) {
6270                 MonoMethod *method;
6271
6272                 if (!mono_verifier_verify_methodimpl_row (image, start + i, &error)) {
6273                         mono_error_cleanup (&error); /* FIXME don't swallow the error */
6274                         ok = FALSE;
6275                         break;
6276                 }
6277
6278                 mono_metadata_decode_row (tdef, start + i, cols, MONO_METHODIMPL_SIZE);
6279                 method = method_from_method_def_or_ref (
6280                         image, cols [MONO_METHODIMPL_DECLARATION], generic_context, &error);
6281                 if (method == NULL) {
6282                         mono_error_cleanup (&error); /* FIXME don't swallow the error */
6283                         ok = FALSE;
6284                 }
6285                 result [i * 2] = method;
6286                 method = method_from_method_def_or_ref (
6287                         image, cols [MONO_METHODIMPL_BODY], generic_context, &error);
6288                 if (method == NULL) {
6289                         mono_error_cleanup (&error); /* FIXME don't swallow the error */
6290                         ok = FALSE;
6291                 }
6292                 result [i * 2 + 1] = method;
6293         }
6294
6295         *overrides = result;
6296         if (num_overrides)
6297                 *num_overrides = num;
6298         return ok;
6299 }
6300
6301 /**
6302  * mono_guid_to_string:
6303  *
6304  * Converts a 16 byte Microsoft GUID to the standard string representation.
6305  */
6306 char *
6307 mono_guid_to_string (const guint8 *guid)
6308 {
6309         return g_strdup_printf ("%02X%02X%02X%02X-%02X%02X-%02X%02X-%02X%02X-%02X%02X%02X%02X%02X%02X", 
6310                                 guid[3], guid[2], guid[1], guid[0],
6311                                 guid[5], guid[4],
6312                                 guid[7], guid[6],
6313                                 guid[8], guid[9],
6314                                 guid[10], guid[11], guid[12], guid[13], guid[14], guid[15]);
6315 }
6316
6317 /**
6318  * mono_guid_to_string_minimal:
6319  *
6320  * Converts a 16 byte Microsoft GUID to lower case no '-' representation..
6321  */
6322 char *
6323 mono_guid_to_string_minimal (const guint8 *guid)
6324 {
6325         return g_strdup_printf ("%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
6326                                 guid[3], guid[2], guid[1], guid[0],
6327                                 guid[5], guid[4],
6328                                 guid[7], guid[6],
6329                                 guid[8], guid[9],
6330                                 guid[10], guid[11], guid[12], guid[13], guid[14], guid[15]);
6331 }
6332 static gboolean
6333 get_constraints (MonoImage *image, int owner, MonoClass ***constraints, MonoGenericContainer *container, MonoError *error)
6334 {
6335         MonoTableInfo *tdef  = &image->tables [MONO_TABLE_GENERICPARAMCONSTRAINT];
6336         guint32 cols [MONO_GENPARCONSTRAINT_SIZE];
6337         guint32 i, token, found;
6338         MonoClass *klass, **res;
6339         GSList *cons = NULL, *tmp;
6340         MonoGenericContext *context = &container->context;
6341
6342         error_init (error);
6343
6344         *constraints = NULL;
6345         found = 0;
6346         for (i = 0; i < tdef->rows; ++i) {
6347                 mono_metadata_decode_row (tdef, i, cols, MONO_GENPARCONSTRAINT_SIZE);
6348                 if (cols [MONO_GENPARCONSTRAINT_GENERICPAR] == owner) {
6349                         token = mono_metadata_token_from_dor (cols [MONO_GENPARCONSTRAINT_CONSTRAINT]);
6350                         klass = mono_class_get_and_inflate_typespec_checked (image, token, context, error);
6351                         if (!klass) {
6352                                 g_slist_free (cons);
6353                                 return FALSE;
6354                         }
6355                         cons = g_slist_append (cons, klass);
6356                         ++found;
6357                 } else {
6358                         /* contiguous list finished */
6359                         if (found)
6360                                 break;
6361                 }
6362         }
6363         if (!found)
6364                 return TRUE;
6365         res = (MonoClass **)mono_image_alloc0 (image, sizeof (MonoClass*) * (found + 1));
6366         for (i = 0, tmp = cons; i < found; ++i, tmp = tmp->next) {
6367                 res [i] = (MonoClass *)tmp->data;
6368         }
6369         g_slist_free (cons);
6370         *constraints = res;
6371         return TRUE;
6372 }
6373
6374 /*
6375  * mono_metadata_get_generic_param_row:
6376  *
6377  * @image:
6378  * @token: TypeOrMethodDef token, owner for GenericParam
6379  * @owner: coded token, set on return
6380  * 
6381  * Returns: 1-based row-id in the GenericParam table whose
6382  * owner is @token. 0 if not found.
6383  */
6384 guint32
6385 mono_metadata_get_generic_param_row (MonoImage *image, guint32 token, guint32 *owner)
6386 {
6387         MonoTableInfo *tdef  = &image->tables [MONO_TABLE_GENERICPARAM];
6388         locator_t loc;
6389
6390         g_assert (owner);
6391         if (!tdef->base)
6392                 return 0;
6393
6394         if (mono_metadata_token_table (token) == MONO_TABLE_TYPEDEF)
6395                 *owner = MONO_TYPEORMETHOD_TYPE;
6396         else if (mono_metadata_token_table (token) == MONO_TABLE_METHOD)
6397                 *owner = MONO_TYPEORMETHOD_METHOD;
6398         else {
6399                 g_error ("wrong token %x to get_generic_param_row", token);
6400                 return 0;
6401         }
6402         *owner |= mono_metadata_token_index (token) << MONO_TYPEORMETHOD_BITS;
6403
6404         loc.idx = *owner;
6405         loc.col_idx = MONO_GENERICPARAM_OWNER;
6406         loc.t = tdef;
6407
6408         if (!mono_binary_search (&loc, tdef->base, tdef->rows, tdef->row_size, table_locator))
6409                 return 0;
6410
6411         /* Find the first entry by searching backwards */
6412         while ((loc.result > 0) && (mono_metadata_decode_row_col (tdef, loc.result - 1, MONO_GENERICPARAM_OWNER) == loc.idx))
6413                 loc.result --;
6414
6415         return loc.result + 1;
6416 }
6417
6418 gboolean
6419 mono_metadata_has_generic_params (MonoImage *image, guint32 token)
6420 {
6421         guint32 owner;
6422         return mono_metadata_get_generic_param_row (image, token, &owner);
6423 }
6424
6425 /*
6426  * Memory is allocated from IMAGE's mempool.
6427  */
6428 gboolean
6429 mono_metadata_load_generic_param_constraints_checked (MonoImage *image, guint32 token,
6430                                               MonoGenericContainer *container, MonoError *error)
6431 {
6432
6433         guint32 start_row, i, owner;
6434         error_init (error);
6435
6436         if (! (start_row = mono_metadata_get_generic_param_row (image, token, &owner)))
6437                 return TRUE;
6438         for (i = 0; i < container->type_argc; i++) {
6439                 if (!get_constraints (image, start_row + i, &mono_generic_container_get_param_info (container, i)->constraints, container, error)) {
6440                         return FALSE;
6441                 }
6442         }
6443         return TRUE;
6444 }
6445
6446 /*
6447  * mono_metadata_load_generic_params:
6448  *
6449  * Load the type parameters from the type or method definition @token.
6450  *
6451  * Use this method after parsing a type or method definition to figure out whether it's a generic
6452  * type / method.  When parsing a method definition, @parent_container points to the generic container
6453  * of the current class, if any.
6454  *
6455  * Note: This method does not load the constraints: for typedefs, this has to be done after fully
6456  *       creating the type.
6457  *
6458  * Returns: NULL if @token is not a generic type or method definition or the new generic container.
6459  *
6460  * LOCKING: Acquires the loader lock
6461  *
6462  */
6463 MonoGenericContainer *
6464 mono_metadata_load_generic_params (MonoImage *image, guint32 token, MonoGenericContainer *parent_container)
6465 {
6466         MonoTableInfo *tdef  = &image->tables [MONO_TABLE_GENERICPARAM];
6467         guint32 cols [MONO_GENERICPARAM_SIZE];
6468         guint32 i, owner = 0, n;
6469         MonoGenericContainer *container;
6470         MonoGenericParamFull *params;
6471         MonoGenericContext *context;
6472
6473         if (!(i = mono_metadata_get_generic_param_row (image, token, &owner)))
6474                 return NULL;
6475         mono_metadata_decode_row (tdef, i - 1, cols, MONO_GENERICPARAM_SIZE);
6476         params = NULL;
6477         n = 0;
6478         container = (MonoGenericContainer *)mono_image_alloc0 (image, sizeof (MonoGenericContainer));
6479         container->owner.image = image; // Temporarily mark as anonymous, but this will be overriden by caller
6480         container->is_anonymous = TRUE;
6481         do {
6482                 n++;
6483                 params = (MonoGenericParamFull *)g_realloc (params, sizeof (MonoGenericParamFull) * n);
6484                 memset (&params [n - 1], 0, sizeof (MonoGenericParamFull));
6485                 params [n - 1].param.owner = container;
6486                 params [n - 1].param.num = cols [MONO_GENERICPARAM_NUMBER];
6487                 params [n - 1].info.token = i | MONO_TOKEN_GENERIC_PARAM;
6488                 params [n - 1].info.flags = cols [MONO_GENERICPARAM_FLAGS];
6489                 params [n - 1].info.name = mono_metadata_string_heap (image, cols [MONO_GENERICPARAM_NAME]);
6490                 if (params [n - 1].param.num != n - 1)
6491                         g_warning ("GenericParam table unsorted or hole in generic param sequence: token %d", i);
6492                 if (++i > tdef->rows)
6493                         break;
6494                 mono_metadata_decode_row (tdef, i - 1, cols, MONO_GENERICPARAM_SIZE);
6495         } while (cols [MONO_GENERICPARAM_OWNER] == owner);
6496
6497         container->type_argc = n;
6498         container->type_params = (MonoGenericParamFull *)mono_image_alloc0 (image, sizeof (MonoGenericParamFull) * n);
6499         memcpy (container->type_params, params, sizeof (MonoGenericParamFull) * n);
6500         g_free (params);
6501         container->parent = parent_container;
6502
6503         if (mono_metadata_token_table (token) == MONO_TABLE_METHOD)
6504                 container->is_method = 1;
6505
6506         g_assert (container->parent == NULL || container->is_method);
6507
6508         context = &container->context;
6509         if (container->is_method) {
6510                 context->class_inst = container->parent ? container->parent->context.class_inst : NULL;
6511                 context->method_inst = mono_get_shared_generic_inst (container);
6512         } else {
6513                 context->class_inst = mono_get_shared_generic_inst (container);
6514         }
6515
6516         return container;
6517 }
6518
6519 MonoGenericInst *
6520 mono_get_shared_generic_inst (MonoGenericContainer *container)
6521 {
6522         MonoType **type_argv;
6523         MonoType *helper;
6524         MonoGenericInst *nginst;
6525         int i;
6526
6527         type_argv = g_new0 (MonoType *, container->type_argc);
6528         helper = g_new0 (MonoType, container->type_argc);
6529
6530         for (i = 0; i < container->type_argc; i++) {
6531                 MonoType *t = &helper [i];
6532
6533                 t->type = container->is_method ? MONO_TYPE_MVAR : MONO_TYPE_VAR;
6534                 t->data.generic_param = mono_generic_container_get_param (container, i);
6535
6536                 type_argv [i] = t;
6537         }
6538
6539         nginst = mono_metadata_get_generic_inst (container->type_argc, type_argv);
6540
6541         g_free (type_argv);
6542         g_free (helper);
6543
6544         return nginst;
6545 }
6546
6547 /**
6548  * mono_type_is_byref:
6549  * \param type the \c MonoType operated on
6550  * \returns TRUE if \p type represents a type passed by reference,
6551  * FALSE otherwise.
6552  */
6553 gboolean
6554 mono_type_is_byref (MonoType *type)
6555 {
6556         return type->byref;
6557 }
6558
6559 /**
6560  * mono_type_get_type:
6561  * \param type the \c MonoType operated on
6562  * \returns the IL type value for \p type. This is one of the \c MonoTypeEnum
6563  * enum members like \c MONO_TYPE_I4 or \c MONO_TYPE_STRING.
6564  */
6565 int
6566 mono_type_get_type (MonoType *type)
6567 {
6568         return type->type;
6569 }
6570
6571 /**
6572  * mono_type_get_signature:
6573  * \param type the \c MonoType operated on
6574  * It is only valid to call this function if \p type is a \c MONO_TYPE_FNPTR .
6575  * \returns the \c MonoMethodSignature pointer that describes the signature
6576  * of the function pointer \p type represents.
6577  */
6578 MonoMethodSignature*
6579 mono_type_get_signature (MonoType *type)
6580 {
6581         g_assert (type->type == MONO_TYPE_FNPTR);
6582         return type->data.method;
6583 }
6584
6585 /**
6586  * mono_type_get_class:
6587  * \param type the \c MonoType operated on
6588  * It is only valid to call this function if \p type is a \c MONO_TYPE_CLASS or a
6589  * \c MONO_TYPE_VALUETYPE . For more general functionality, use \c mono_class_from_mono_type,
6590  * instead.
6591  * \returns the \c MonoClass pointer that describes the class that \p type represents.
6592  */
6593 MonoClass*
6594 mono_type_get_class (MonoType *type)
6595 {
6596         /* FIXME: review the runtime users before adding the assert here */
6597         return type->data.klass;
6598 }
6599
6600 /**
6601  * mono_type_get_array_type:
6602  * \param type the \c MonoType operated on
6603  * It is only valid to call this function if \p type is a \c MONO_TYPE_ARRAY .
6604  * \returns a \c MonoArrayType struct describing the array type that \p type
6605  * represents. The info includes details such as rank, array element type
6606  * and the sizes and bounds of multidimensional arrays.
6607  */
6608 MonoArrayType*
6609 mono_type_get_array_type (MonoType *type)
6610 {
6611         return type->data.array;
6612 }
6613
6614 /**
6615  * mono_type_get_ptr_type:
6616  * \pararm type the \c MonoType operated on
6617  * It is only valid to call this function if \p type is a \c MONO_TYPE_PTR .
6618  * \returns the \c MonoType pointer that describes the type that \p type
6619  * represents a pointer to.
6620  */
6621 MonoType*
6622 mono_type_get_ptr_type (MonoType *type)
6623 {
6624         g_assert (type->type == MONO_TYPE_PTR);
6625         return type->data.type;
6626 }
6627
6628 /**
6629  * mono_type_get_modifiers:
6630  */
6631 MonoClass*
6632 mono_type_get_modifiers (MonoType *type, gboolean *is_required, gpointer *iter)
6633 {
6634         /* FIXME: implement */
6635         return NULL;
6636 }
6637
6638 /**
6639  * mono_type_is_struct:
6640  * \param type the \c MonoType operated on
6641  * \returns TRUE if \p type is a struct, that is a \c ValueType but not an enum
6642  * or a basic type like \c System.Int32 . FALSE otherwise.
6643  */
6644 mono_bool
6645 mono_type_is_struct (MonoType *type)
6646 {
6647         return (!type->byref && ((type->type == MONO_TYPE_VALUETYPE &&
6648                 !type->data.klass->enumtype) || (type->type == MONO_TYPE_TYPEDBYREF) ||
6649                 ((type->type == MONO_TYPE_GENERICINST) && 
6650                 mono_metadata_generic_class_is_valuetype (type->data.generic_class) &&
6651                 !type->data.generic_class->container_class->enumtype)));
6652 }
6653
6654 /**
6655  * mono_type_is_void:
6656  * \param type the \c MonoType operated on
6657  * \returns TRUE if \p type is \c System.Void . FALSE otherwise.
6658  */
6659 mono_bool
6660 mono_type_is_void (MonoType *type)
6661 {
6662         return (type && (type->type == MONO_TYPE_VOID) && !type->byref);
6663 }
6664
6665 /**
6666  * mono_type_is_pointer:
6667  * \param type the \c MonoType operated on
6668  * \returns TRUE if \p type is a managed or unmanaged pointer type. FALSE otherwise.
6669  */
6670 mono_bool
6671 mono_type_is_pointer (MonoType *type)
6672 {
6673         return (type && ((type->byref || (type->type == MONO_TYPE_I) || type->type == MONO_TYPE_STRING)
6674                 || (type->type == MONO_TYPE_SZARRAY) || (type->type == MONO_TYPE_CLASS) ||
6675                 (type->type == MONO_TYPE_U) || (type->type == MONO_TYPE_OBJECT) ||
6676                 (type->type == MONO_TYPE_ARRAY) || (type->type == MONO_TYPE_PTR) ||
6677                 (type->type == MONO_TYPE_FNPTR)));
6678 }
6679
6680 /**
6681  * mono_type_is_reference:
6682  * \param type the \c MonoType operated on
6683  * \returns TRUE if \p type represents an object reference. FALSE otherwise.
6684  */
6685 mono_bool
6686 mono_type_is_reference (MonoType *type)
6687 {
6688         return (type && (((type->type == MONO_TYPE_STRING) ||
6689                 (type->type == MONO_TYPE_SZARRAY) || (type->type == MONO_TYPE_CLASS) ||
6690                 (type->type == MONO_TYPE_OBJECT) || (type->type == MONO_TYPE_ARRAY)) ||
6691                 ((type->type == MONO_TYPE_GENERICINST) &&
6692                 !mono_metadata_generic_class_is_valuetype (type->data.generic_class))));
6693 }
6694
6695 mono_bool
6696 mono_type_is_generic_parameter (MonoType *type)
6697 {
6698         return !type->byref && (type->type == MONO_TYPE_VAR || type->type == MONO_TYPE_MVAR);
6699 }
6700
6701 /**
6702  * mono_signature_get_return_type:
6703  * \param sig the method signature inspected
6704  * \returns the return type of the method signature \p sig
6705  */
6706 MonoType*
6707 mono_signature_get_return_type (MonoMethodSignature *sig)
6708 {
6709         return sig->ret;
6710 }
6711
6712 /**
6713  * mono_signature_get_params:
6714  * \param sig the method signature inspected
6715  * \param iter pointer to an iterator
6716  * Iterates over the parameters for the method signature \p sig.
6717  * A \c void* pointer must be initialized to NULL to start the iteration
6718  * and its address is passed to this function repeteadly until it returns
6719  * NULL.
6720  * \returns the next parameter type of the method signature \p sig,
6721  * NULL when finished.
6722  */
6723 MonoType*
6724 mono_signature_get_params (MonoMethodSignature *sig, gpointer *iter)
6725 {
6726         MonoType** type;
6727         if (!iter)
6728                 return NULL;
6729         if (!*iter) {
6730                 /* start from the first */
6731                 if (sig->param_count) {
6732                         *iter = &sig->params [0];
6733                         return sig->params [0];
6734                 } else {
6735                         /* no method */
6736                         return NULL;
6737                 }
6738         }
6739         type = (MonoType **)*iter;
6740         type++;
6741         if (type < &sig->params [sig->param_count]) {
6742                 *iter = type;
6743                 return *type;
6744         }
6745         return NULL;
6746 }
6747
6748 /**
6749  * mono_signature_get_param_count:
6750  * \param sig the method signature inspected
6751  * \returns the number of parameters in the method signature \p sig.
6752  */
6753 guint32
6754 mono_signature_get_param_count (MonoMethodSignature *sig)
6755 {
6756         return sig->param_count;
6757 }
6758
6759 /**
6760  * mono_signature_get_call_conv:
6761  * \param sig the method signature inspected
6762  * \returns the call convention of the method signature \p sig.
6763  */
6764 guint32
6765 mono_signature_get_call_conv (MonoMethodSignature *sig)
6766 {
6767         return sig->call_convention;
6768 }
6769
6770 /**
6771  * mono_signature_vararg_start:
6772  * \param sig the method signature inspected
6773  * \returns the number of the first vararg parameter in the
6774  * method signature \param sig. \c -1 if this is not a vararg signature.
6775  */
6776 int
6777 mono_signature_vararg_start (MonoMethodSignature *sig)
6778 {
6779         return sig->sentinelpos;
6780 }
6781
6782 /**
6783  * mono_signature_is_instance:
6784  * \param sig the method signature inspected
6785  * \returns TRUE if this the method signature \p sig has an implicit
6786  * first instance argument. FALSE otherwise.
6787  */
6788 gboolean
6789 mono_signature_is_instance (MonoMethodSignature *sig)
6790 {
6791         return sig->hasthis;
6792 }
6793
6794 /**
6795  * mono_signature_param_is_out
6796  * \param sig the method signature inspected
6797  * \param param_num the 0-based index of the inspected parameter
6798  * \returns TRUE if the parameter is an out parameter, FALSE
6799  * otherwise.
6800  */
6801 mono_bool
6802 mono_signature_param_is_out (MonoMethodSignature *sig, int param_num)
6803 {
6804         g_assert (param_num >= 0 && param_num < sig->param_count);
6805         return (sig->params [param_num]->attrs & PARAM_ATTRIBUTE_OUT) != 0;
6806 }
6807
6808 /**
6809  * mono_signature_explicit_this:
6810  * \param sig the method signature inspected
6811  * \returns TRUE if this the method signature \p sig has an explicit
6812  * instance argument. FALSE otherwise.
6813  */
6814 gboolean
6815 mono_signature_explicit_this (MonoMethodSignature *sig)
6816 {
6817         return sig->explicit_this;
6818 }
6819
6820 /* for use with allocated memory blocks (assumes alignment is to 8 bytes) */
6821 guint
6822 mono_aligned_addr_hash (gconstpointer ptr)
6823 {
6824         /* Same hashing we use for objects */
6825         return (GPOINTER_TO_UINT (ptr) >> 3) * 2654435761u;
6826 }
6827
6828 /*
6829  * If @field belongs to an inflated generic class, return the corresponding field of the
6830  * generic type definition class.
6831  */
6832 MonoClassField*
6833 mono_metadata_get_corresponding_field_from_generic_type_definition (MonoClassField *field)
6834 {
6835         MonoClass *gtd;
6836         int offset;
6837
6838         if (!mono_class_is_ginst (field->parent))
6839                 return field;
6840
6841         gtd = mono_class_get_generic_class (field->parent)->container_class;
6842         offset = field - field->parent->fields;
6843         return gtd->fields + offset;
6844 }
6845
6846 /*
6847  * If @event belongs to an inflated generic class, return the corresponding event of the
6848  * generic type definition class.
6849  */
6850 MonoEvent*
6851 mono_metadata_get_corresponding_event_from_generic_type_definition (MonoEvent *event)
6852 {
6853         MonoClass *gtd;
6854         int offset;
6855
6856         if (!mono_class_is_ginst (event->parent))
6857                 return event;
6858
6859         gtd = mono_class_get_generic_class (event->parent)->container_class;
6860         offset = event - mono_class_get_event_info (event->parent)->events;
6861         return mono_class_get_event_info (gtd)->events + offset;
6862 }
6863
6864 /*
6865  * If @property belongs to an inflated generic class, return the corresponding property of the
6866  * generic type definition class.
6867  */
6868 MonoProperty*
6869 mono_metadata_get_corresponding_property_from_generic_type_definition (MonoProperty *property)
6870 {
6871         MonoClassPropertyInfo *info;
6872         MonoClass *gtd;
6873         int offset;
6874
6875         if (!mono_class_is_ginst (property->parent))
6876                 return property;
6877
6878         info = mono_class_get_property_info (property->parent);
6879         gtd = mono_class_get_generic_class (property->parent)->container_class;
6880         offset = property - info->properties;
6881         return mono_class_get_property_info (gtd)->properties + offset;
6882 }
6883
6884 MonoWrapperCaches*
6885 mono_method_get_wrapper_cache (MonoMethod *method)
6886 {
6887         if (method->is_inflated) {
6888                 MonoMethodInflated *imethod = (MonoMethodInflated *)method;
6889                 return &imethod->owner->wrapper_caches;
6890         } else {
6891                 return &method->klass->image->wrapper_caches;
6892         }
6893 }
6894
6895 // This is support for the mempool reference tracking feature in checked-build, but lives in metadata.c due to use of static variables of this file.
6896
6897 /**
6898  * mono_find_image_set_owner:
6899  *
6900  * Find the imageset, if any, which a given pointer is located in the memory of.
6901  */
6902 MonoImageSet *
6903 mono_find_image_set_owner (void *ptr)
6904 {
6905         MonoImageSet *owner = NULL;
6906         int i;
6907
6908         image_sets_lock ();
6909
6910         if (image_sets)
6911         {
6912                 for (i = 0; !owner && i < image_sets->len; ++i) {
6913                         MonoImageSet *set = (MonoImageSet *)g_ptr_array_index (image_sets, i);
6914                         if (mono_mempool_contains_addr (set->mempool, ptr))
6915                                 owner = set;
6916                 }
6917         }
6918
6919         image_sets_unlock ();
6920
6921         return owner;
6922 }
6923
6924 void
6925 mono_loader_set_strict_strong_names (gboolean enabled)
6926 {
6927         check_strong_names_strictly = enabled;
6928 }
6929
6930 gboolean
6931 mono_loader_get_strict_strong_names (void)
6932 {
6933         return check_strong_names_strictly;
6934 }