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