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