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