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