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