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