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