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