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