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