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