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