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