* icall.c (ves_icall_MonoMethod_get_base_definition): Simplify
[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_cleanup:
1331  *
1332  * Free all resources used by this module.
1333  * This is a Mono runtime internal function.
1334  */
1335 void
1336 mono_metadata_cleanup (void)
1337 {
1338         g_hash_table_destroy (type_cache);
1339         g_hash_table_destroy (generic_inst_cache);
1340         g_hash_table_destroy (generic_class_cache);
1341 }
1342
1343 /**
1344  * mono_metadata_parse_type:
1345  * @m: metadata context
1346  * @mode: king of type that may be found at @ptr
1347  * @opt_attrs: optional attributes to store in the returned type
1348  * @ptr: pointer to the type representation
1349  * @rptr: pointer updated to match the end of the decoded stream
1350  * 
1351  * Decode a compressed type description found at @ptr in @m.
1352  * @mode can be one of MONO_PARSE_MOD_TYPE, MONO_PARSE_PARAM, MONO_PARSE_RET,
1353  * MONO_PARSE_FIELD, MONO_PARSE_LOCAL, MONO_PARSE_TYPE.
1354  * This function can be used to decode type descriptions in method signatures,
1355  * field signatures, locals signatures etc.
1356  *
1357  * To parse a generic type, `generic_container' points to the current class'es
1358  * (the `generic_container' field in the MonoClass) or the current generic method's
1359  * (the `generic_container' field in the MonoMethodNormal) generic container.
1360  * When we encounter any MONO_TYPE_VAR or MONO_TYPE_MVAR's, they're looked up in
1361  * this MonoGenericContainer.
1362  * This is a Mono runtime internal function.
1363  *
1364  * LOCKING: Assumes the loader lock is held.
1365  *
1366  * Returns: a #MonoType structure representing the decoded type.
1367  */
1368 MonoType*
1369 mono_metadata_parse_type_full (MonoImage *m, MonoGenericContainer *container, MonoParseTypeMode mode,
1370                                short opt_attrs, const char *ptr, const char **rptr)
1371 {
1372         MonoType *type, *cached;
1373         MonoType stype;
1374         gboolean byref = FALSE;
1375         gboolean pinned = FALSE;
1376         const char *tmp_ptr;
1377         int count = 0;
1378         gboolean found;
1379
1380         /*
1381          * According to the spec, custom modifiers should come before the byref
1382          * flag, but the IL produced by ilasm from the following signature:
1383          *   object modopt(...) &
1384          * starts with a byref flag, followed by the modifiers. (bug #49802)
1385          * Also, this type seems to be different from 'object & modopt(...)'. Maybe
1386          * it would be better to treat byref as real type constructor instead of
1387          * a modifier...
1388          * Also, pinned should come before anything else, but some MSV++ produced
1389          * assemblies violate this (#bug 61990).
1390          */
1391
1392         /* Count the modifiers first */
1393         tmp_ptr = ptr;
1394         found = TRUE;
1395         while (found) {
1396                 switch (*tmp_ptr) {
1397                 case MONO_TYPE_PINNED:
1398                 case MONO_TYPE_BYREF:
1399                         ++tmp_ptr;
1400                         break;
1401                 case MONO_TYPE_CMOD_REQD:
1402                 case MONO_TYPE_CMOD_OPT:
1403                         count ++;
1404                         mono_metadata_parse_custom_mod (m, NULL, tmp_ptr, &tmp_ptr);
1405                         break;
1406                 default:
1407                         found = FALSE;
1408                 }
1409         }
1410
1411         if (count) {
1412                 type = mono_mempool_alloc0 (m->mempool, sizeof (MonoType) + ((gint32)count - MONO_ZERO_LEN_ARRAY) * sizeof (MonoCustomMod));
1413                 type->num_mods = count;
1414                 if (count > 64)
1415                         g_warning ("got more than 64 modifiers in type");
1416         } else {
1417                 type = &stype;
1418                 memset (type, 0, sizeof (MonoType));
1419         }
1420
1421         /* Parse pinned, byref and custom modifiers */
1422         found = TRUE;
1423         count = 0;
1424         while (found) {
1425                 switch (*ptr) {
1426                 case MONO_TYPE_PINNED:
1427                         pinned = TRUE;
1428                         ++ptr;
1429                         break;
1430                 case MONO_TYPE_BYREF:
1431                         byref = TRUE;
1432                         ++ptr;
1433                         break;
1434                 case MONO_TYPE_CMOD_REQD:
1435                 case MONO_TYPE_CMOD_OPT:
1436                         mono_metadata_parse_custom_mod (m, &(type->modifiers [count]), ptr, &ptr);
1437                         count ++;
1438                         break;
1439                 default:
1440                         found = FALSE;
1441                 }
1442         }
1443         
1444         type->attrs = opt_attrs;
1445         type->byref = byref;
1446         type->pinned = pinned ? 1 : 0;
1447
1448         if (!do_mono_metadata_parse_type (type, m, container, ptr, &ptr)) {
1449                 if (type != &stype)
1450                         g_free (type);
1451                 return NULL;
1452         }
1453
1454         if (rptr)
1455                 *rptr = ptr;
1456
1457                 if (!type->num_mods) {
1458                 /* no need to free type here, because it is on the stack */
1459                 if ((type->type == MONO_TYPE_CLASS || type->type == MONO_TYPE_VALUETYPE) && !type->pinned && !type->attrs) {
1460                         MonoType *ret = type->byref ? &type->data.klass->this_arg : &type->data.klass->byval_arg;
1461
1462                         /* Consider the case:
1463
1464                              class Foo<T> { class Bar {} }
1465                              class Test : Foo<Test>.Bar {}
1466
1467                            When Foo<Test> is being expanded, 'Test' isn't yet initialized.  It's actually in
1468                            a really pristine state: it doesn't even know whether 'Test' is a reference or a value type.
1469
1470                            We ensure that the MonoClass is in a state that we can canonicalize to:
1471
1472                              klass->byval_arg.data.klass == klass
1473                              klass->this_arg.data.klass == klass
1474
1475                            If we can't canonicalize 'type', it doesn't matter, since later users of 'type' will do it.
1476
1477                            LOCKING: even though we don't explicitly hold a lock, in the problematic case 'ret' is a field
1478                                     of a MonoClass which currently holds the loader lock.  'type' is local.
1479                         */
1480                         if (ret->data.klass == type->data.klass)
1481                                 return ret;
1482                 }
1483                 /* No need to use locking since nobody is modifying the hash table */
1484                 if ((cached = g_hash_table_lookup (type_cache, type)))
1485                         return cached;
1486         }
1487         
1488         /* printf ("%x %x %c %s\n", type->attrs, type->num_mods, type->pinned ? 'p' : ' ', mono_type_full_name (type)); */
1489         
1490         if (type == &stype) {
1491                 type = mono_mempool_alloc (m->mempool, sizeof (MonoType));
1492                 memcpy (type, &stype, sizeof (MonoType));
1493         }
1494         return type;
1495 }
1496
1497 /*
1498  * LOCKING: Assumes the loader lock is held.
1499  */
1500 MonoType*
1501 mono_metadata_parse_type (MonoImage *m, MonoParseTypeMode mode, short opt_attrs,
1502                           const char *ptr, const char **rptr)
1503 {
1504         return mono_metadata_parse_type_full (m, NULL, mode, opt_attrs, ptr, rptr);
1505 }
1506
1507 /*
1508  * mono_metadata_get_param_attrs:
1509  *
1510  *   Return the parameter attributes for the method whose MethodDef index is DEF. The 
1511  * returned memory needs to be freed by the caller. If all the param attributes are
1512  * 0, then NULL is returned.
1513  */
1514 int*
1515 mono_metadata_get_param_attrs (MonoImage *m, int def)
1516 {
1517         MonoTableInfo *paramt = &m->tables [MONO_TABLE_PARAM];
1518         MonoTableInfo *methodt = &m->tables [MONO_TABLE_METHOD];
1519         guint32 cols [MONO_PARAM_SIZE];
1520         guint lastp, i, param_index = mono_metadata_decode_row_col (methodt, def - 1, MONO_METHOD_PARAMLIST);
1521         int *pattrs = NULL;
1522
1523         if (def < methodt->rows)
1524                 lastp = mono_metadata_decode_row_col (methodt, def, MONO_METHOD_PARAMLIST);
1525         else
1526                 lastp = paramt->rows + 1;
1527
1528         for (i = param_index; i < lastp; ++i) {
1529                 mono_metadata_decode_row (paramt, i - 1, cols, MONO_PARAM_SIZE);
1530                 if (cols [MONO_PARAM_FLAGS]) {
1531                         if (!pattrs)
1532                                 pattrs = g_new0 (int, 1 + (lastp - param_index));
1533                         pattrs [cols [MONO_PARAM_SEQUENCE]] = cols [MONO_PARAM_FLAGS];
1534                 }
1535         }
1536
1537         return pattrs;
1538 }
1539
1540 /*
1541  * mono_metadata_parse_signature_full:
1542  * @image: metadata context
1543  * @generic_container: generic container
1544  * @toke: metadata token
1545  *
1546  * Decode a method signature stored in the STANDALONESIG table
1547  *
1548  * LOCKING: Assumes the loader lock is held.
1549  *
1550  * Returns: a MonoMethodSignature describing the signature.
1551  */
1552 MonoMethodSignature*
1553 mono_metadata_parse_signature_full (MonoImage *image, MonoGenericContainer *generic_container, guint32 token)
1554 {
1555         MonoTableInfo *tables = image->tables;
1556         guint32 idx = mono_metadata_token_index (token);
1557         guint32 sig;
1558         const char *ptr;
1559
1560         if (image->dynamic)
1561                 return mono_lookup_dynamic_token (image, token);
1562
1563         g_assert (mono_metadata_token_table(token) == MONO_TABLE_STANDALONESIG);
1564                 
1565         sig = mono_metadata_decode_row_col (&tables [MONO_TABLE_STANDALONESIG], idx - 1, 0);
1566
1567         ptr = mono_metadata_blob_heap (image, sig);
1568         mono_metadata_decode_blob_size (ptr, &ptr);
1569
1570         return mono_metadata_parse_method_signature_full (image, generic_container, 0, ptr, NULL); 
1571 }
1572
1573 /*
1574  * mono_metadata_parse_signature:
1575  * @image: metadata context
1576  * @toke: metadata token
1577  *
1578  * Decode a method signature stored in the STANDALONESIG table
1579  *
1580  * Returns: a MonoMethodSignature describing the signature.
1581  */
1582 MonoMethodSignature*
1583 mono_metadata_parse_signature (MonoImage *image, guint32 token)
1584 {
1585         return mono_metadata_parse_signature_full (image, NULL, token);
1586 }
1587
1588 /*
1589  * mono_metadata_signature_alloc:
1590  * @image: metadata context
1591  * @nparmas: number of parameters in the signature
1592  *
1593  * Allocate a MonoMethodSignature structure with the specified number of params.
1594  * The return type and the params types need to be filled later.
1595  * This is a Mono runtime internal function.
1596  *
1597  * LOCKING: Assumes the loader lock is held.
1598  *
1599  * Returns: the new MonoMethodSignature structure.
1600  */
1601 MonoMethodSignature*
1602 mono_metadata_signature_alloc (MonoImage *m, guint32 nparams)
1603 {
1604         MonoMethodSignature *sig;
1605
1606         sig = mono_mempool_alloc0 (m->mempool, sizeof (MonoMethodSignature) + ((gint32)nparams - MONO_ZERO_LEN_ARRAY) * sizeof (MonoType*));
1607         sig->param_count = nparams;
1608         sig->sentinelpos = -1;
1609
1610         return sig;
1611 }
1612
1613 /*
1614  * mono_metadata_signature_dup:
1615  * @sig: method signature
1616  *
1617  * Duplicate an existing MonoMethodSignature so it can be modified.
1618  * This is a Mono runtime internal function.
1619  *
1620  * Returns: the new MonoMethodSignature structure.
1621  */
1622 MonoMethodSignature*
1623 mono_metadata_signature_dup (MonoMethodSignature *sig)
1624 {
1625         int sigsize;
1626
1627         sigsize = sizeof (MonoMethodSignature) + (sig->param_count - MONO_ZERO_LEN_ARRAY) * sizeof (MonoType *);
1628         return g_memdup (sig, sigsize);
1629 }
1630
1631 /*
1632  * mono_metadata_parse_method_signature:
1633  * @m: metadata context
1634  * @generic_container: generics container
1635  * @def: the MethodDef index or 0 for Ref signatures.
1636  * @ptr: pointer to the signature metadata representation
1637  * @rptr: pointer updated to match the end of the decoded stream
1638  *
1639  * Decode a method signature stored at @ptr.
1640  * This is a Mono runtime internal function.
1641  *
1642  * LOCKING: Assumes the loader lock is held.
1643  *
1644  * Returns: a MonoMethodSignature describing the signature.
1645  */
1646 MonoMethodSignature *
1647 mono_metadata_parse_method_signature_full (MonoImage *m, MonoGenericContainer *container,
1648                                            int def, const char *ptr, const char **rptr)
1649 {
1650         MonoMethodSignature *method;
1651         int i, *pattrs = NULL;
1652         guint32 hasthis = 0, explicit_this = 0, call_convention, param_count;
1653         guint32 gen_param_count = 0;
1654         gboolean is_open = FALSE;
1655
1656         if (*ptr & 0x10)
1657                 gen_param_count = 1;
1658         if (*ptr & 0x20)
1659                 hasthis = 1;
1660         if (*ptr & 0x40)
1661                 explicit_this = 1;
1662         call_convention = *ptr & 0x0F;
1663         ptr++;
1664         if (gen_param_count)
1665                 gen_param_count = mono_metadata_decode_value (ptr, &ptr);
1666         param_count = mono_metadata_decode_value (ptr, &ptr);
1667
1668         if (def)
1669                 pattrs = mono_metadata_get_param_attrs (m, def);
1670         method = mono_metadata_signature_alloc (m, param_count);
1671         method->hasthis = hasthis;
1672         method->explicit_this = explicit_this;
1673         method->call_convention = call_convention;
1674         method->generic_param_count = gen_param_count;
1675
1676         if (call_convention != 0xa) {
1677                 method->ret = mono_metadata_parse_type_full (m, container, MONO_PARSE_RET, pattrs ? pattrs [0] : 0, ptr, &ptr);
1678                 if (!method->ret) {
1679                         mono_metadata_free_method_signature (method);
1680                         g_free (pattrs);
1681                         return NULL;
1682                 }
1683                 is_open = mono_class_is_open_constructed_type (method->ret);
1684         }
1685
1686         for (i = 0; i < method->param_count; ++i) {
1687                 if (*ptr == MONO_TYPE_SENTINEL) {
1688                         if (method->call_convention != MONO_CALL_VARARG || def)
1689                                 g_error ("found sentinel for methoddef or no vararg method");
1690                         method->sentinelpos = i;
1691                         ptr++;
1692                 }
1693                 method->params [i] = mono_metadata_parse_type_full (m, container, MONO_PARSE_PARAM, pattrs ? pattrs [i+1] : 0, ptr, &ptr);
1694                 if (!method->params [i]) {
1695                         mono_metadata_free_method_signature (method);
1696                         g_free (pattrs);
1697                         return NULL;
1698                 }
1699                 if (!is_open)
1700                         is_open = mono_class_is_open_constructed_type (method->params [i]);
1701         }
1702
1703         method->has_type_parameters = is_open;
1704
1705         if (def && (method->call_convention == MONO_CALL_VARARG))
1706                 method->sentinelpos = method->param_count;
1707
1708         g_free (pattrs);
1709
1710         if (rptr)
1711                 *rptr = ptr;
1712         /*
1713          * Add signature to a cache and increase ref count...
1714          */
1715
1716         return method;
1717 }
1718
1719 /*
1720  * mono_metadata_parse_method_signature:
1721  * @m: metadata context
1722  * @def: the MethodDef index or 0 for Ref signatures.
1723  * @ptr: pointer to the signature metadata representation
1724  * @rptr: pointer updated to match the end of the decoded stream
1725  *
1726  * Decode a method signature stored at @ptr.
1727  * This is a Mono runtime internal function.
1728  *
1729  * LOCKING: Assumes the loader lock is held.
1730  *
1731  * Returns: a MonoMethodSignature describing the signature.
1732  */
1733 MonoMethodSignature *
1734 mono_metadata_parse_method_signature (MonoImage *m, int def, const char *ptr, const char **rptr)
1735 {
1736         return mono_metadata_parse_method_signature_full (m, NULL, def, ptr, rptr);
1737 }
1738
1739 /*
1740  * mono_metadata_free_method_signature:
1741  * @sig: signature to destroy
1742  *
1743  * Free the memory allocated in the signature @sig.
1744  * This method needs to be robust and work also on partially-built
1745  * signatures, so it does extra checks.
1746  */
1747 void
1748 mono_metadata_free_method_signature (MonoMethodSignature *sig)
1749 {
1750         int i;
1751         if (sig->ret)
1752                 mono_metadata_free_type (sig->ret);
1753         for (i = 0; i < sig->param_count; ++i) {
1754                 if (sig->params [i])
1755                         mono_metadata_free_type (sig->params [i]);
1756         }
1757 }
1758
1759 /*
1760  * mono_metadata_lookup_generic_inst:
1761  *
1762  * Check whether the newly created generic instantiation @ginst already exists
1763  * in the cache and return the cached value in this case.  Otherwise insert
1764  * it into the cache.
1765  *
1766  * Use this method each time you create a new `MonoGenericInst' to ensure
1767  * proper caching.  Only use the returned value as the argument passed to this
1768  * method may be freed.
1769  *
1770  */
1771 MonoGenericInst *
1772 mono_metadata_lookup_generic_inst (MonoGenericInst *ginst)
1773 {
1774         MonoGenericInst *cached;
1775         int i;
1776
1777         cached = g_hash_table_lookup (generic_inst_cache, ginst);
1778         if (cached) {
1779                 for (i = 0; i < ginst->type_argc; i++)
1780                         mono_metadata_free_type (ginst->type_argv [i]);
1781                 g_free (ginst->type_argv);
1782                 g_free (ginst);
1783                 return cached;
1784         }
1785
1786         ginst->id = ++next_generic_inst_id;
1787         g_hash_table_insert (generic_inst_cache, ginst, ginst);
1788
1789         return ginst;
1790 }
1791
1792 /*
1793  * mono_metadata_lookup_generic_class:
1794  *
1795  * Check whether the newly created generic class @gclass already exists
1796  * in the cache and return the cached value in this case.  Otherwise insert
1797  * it into the cache and return NULL.
1798  *
1799  * Returns: the previosly cached generic class or NULL if it has been newly
1800  *          inserted into the cache.
1801  *
1802  */
1803 MonoGenericClass *
1804 mono_metadata_lookup_generic_class (MonoGenericClass *gclass)
1805 {
1806         MonoGenericClass *cached;
1807
1808         cached = g_hash_table_lookup (generic_class_cache, gclass);
1809         if (cached)
1810                 return cached;
1811
1812         g_hash_table_insert (generic_class_cache, gclass, gclass);
1813         return NULL;
1814 }
1815
1816 /*
1817  * mono_metadata_inflate_generic_inst:
1818  *
1819  * Instantiate the generic instance @ginst with the context @context.
1820  *
1821  */
1822 MonoGenericInst *
1823 mono_metadata_inflate_generic_inst (MonoGenericInst *ginst, MonoGenericContext *context)
1824 {
1825         MonoGenericInst *nginst;
1826         int i;
1827
1828         if (!ginst->is_open)
1829                 return ginst;
1830
1831         nginst = g_new0 (MonoGenericInst, 1);
1832         nginst->type_argc = ginst->type_argc;
1833         nginst->type_argv = g_new0 (MonoType*, nginst->type_argc);
1834         nginst->is_reference = 1;
1835
1836         for (i = 0; i < nginst->type_argc; i++) {
1837                 MonoType *t = mono_class_inflate_generic_type (ginst->type_argv [i], context);
1838
1839                 if (!nginst->is_open)
1840                         nginst->is_open = mono_class_is_open_constructed_type (t);
1841                 if (nginst->is_reference)
1842                         nginst->is_reference = MONO_TYPE_IS_REFERENCE (t);
1843
1844                 nginst->type_argv [i] = t;
1845         }
1846
1847         return mono_metadata_lookup_generic_inst (nginst);
1848 }
1849
1850 MonoGenericInst *
1851 mono_metadata_parse_generic_inst (MonoImage *m, MonoGenericContainer *container,
1852                                   int count, const char *ptr, const char **rptr)
1853 {
1854         MonoGenericInst *ginst;
1855         int i;
1856
1857         ginst = g_new0 (MonoGenericInst, 1);
1858         ginst->type_argc = count;
1859         ginst->type_argv = g_new0 (MonoType*, count);
1860         ginst->is_reference = 1;
1861
1862         for (i = 0; i < ginst->type_argc; i++) {
1863                 MonoType *t = mono_metadata_parse_type_full (m, container, MONO_PARSE_TYPE, 0, ptr, &ptr);
1864
1865                 if (!t) {
1866                         g_free (ginst->type_argv);
1867                         g_free (ginst);
1868                         return NULL;
1869                 }
1870                 ginst->type_argv [i] = t;
1871                 if (!ginst->is_open)
1872                         ginst->is_open = mono_class_is_open_constructed_type (t);
1873                 if (ginst->is_reference)
1874                         ginst->is_reference = MONO_TYPE_IS_REFERENCE (t);
1875         }
1876
1877         if (rptr)
1878                 *rptr = ptr;
1879
1880         return mono_metadata_lookup_generic_inst (ginst);
1881 }
1882
1883 static gboolean
1884 do_mono_metadata_parse_generic_class (MonoType *type, MonoImage *m, MonoGenericContainer *container,
1885                                       const char *ptr, const char **rptr)
1886 {
1887         MonoInflatedGenericClass *igclass;
1888         MonoGenericClass *gclass, *cached;
1889         MonoClass *gklass;
1890         MonoType *gtype;
1891         int count;
1892
1893         igclass = g_new0 (MonoInflatedGenericClass, 1);
1894         gclass = &igclass->generic_class;
1895         gclass->is_inflated = TRUE;
1896
1897         type->data.generic_class = gclass;
1898
1899         gclass->context = g_new0 (MonoGenericContext, 1);
1900         gclass->context->gclass = gclass;
1901
1902         /*
1903          * Create the klass before parsing the type arguments.
1904          * This is required to support "recursive" definitions.
1905          * See mcs/tests/gen-23.cs for an example.
1906          */
1907         igclass->klass = g_new0 (MonoClass, 1);
1908
1909         gtype = mono_metadata_parse_type (m, MONO_PARSE_TYPE, 0, ptr, &ptr);
1910         gclass->container_class = gklass = mono_class_from_mono_type (gtype);
1911
1912         g_assert (gklass->generic_container);
1913         gclass->context->container = gklass->generic_container;
1914
1915         count = mono_metadata_decode_value (ptr, &ptr);
1916
1917         gclass->inst = mono_metadata_parse_generic_inst (m, container, count, ptr, &ptr);
1918
1919         if (rptr)
1920                 *rptr = ptr;
1921
1922         /* If we failed to parse, return, the error has been flagged. */
1923         if (gclass->inst == NULL)
1924                 return FALSE;
1925         
1926         /*
1927          * We may be called multiple times on different metadata to create the same
1928          * instantiated type.  This happens for instance if we're part of a method or
1929          * local variable signature.
1930          *
1931          * It's important to return the same MonoGenericClass * for each particualar
1932          * instantiation of a generic type (ie "Stack<Int32>") to make static fields
1933          * work.
1934          *
1935          * According to the spec ($26.1.5), a static variable in a generic class
1936          * declaration is shared amongst all instances of the same closed constructed
1937          * type.
1938          */
1939
1940         cached = g_hash_table_lookup (generic_class_cache, gclass);
1941         if (cached) {
1942                 g_free (igclass->klass);
1943                 g_free (gclass);
1944
1945                 type->data.generic_class = cached;
1946                 return TRUE;
1947         } else {
1948                 g_hash_table_insert (generic_class_cache, gclass, gclass);
1949
1950                 mono_stats.generic_instance_count++;
1951                 mono_stats.generics_metadata_size += sizeof (MonoGenericClass) +
1952                         sizeof (MonoGenericContext) +
1953                         gclass->inst->type_argc * sizeof (MonoType);
1954         }
1955         return TRUE;
1956 }
1957
1958 /*
1959  * select_container:
1960  * @gc: The generic container to normalize
1961  * @type: The kind of generic parameters the resulting generic-container should contain
1962  */
1963
1964 static MonoGenericContainer *
1965 select_container (MonoGenericContainer *gc, MonoTypeEnum type)
1966 {
1967         gboolean is_var = (type == MONO_TYPE_VAR);
1968         if (!gc)
1969                 return NULL;
1970
1971         g_assert (is_var || type == MONO_TYPE_MVAR);
1972
1973         if (is_var && gc->parent)
1974                 /*
1975                  * The current MonoGenericContainer is a generic method -> its `parent'
1976                  * points to the containing class'es container.
1977                  */
1978                 gc = gc->parent;
1979
1980         /*
1981          * Ensure that we have the correct type of GenericContainer.
1982          */
1983         g_assert (is_var == !gc->is_method);
1984
1985         return gc;
1986 }
1987
1988 /* 
1989  * mono_metadata_parse_generic_param:
1990  * @generic_container: Our MonoClass's or MonoMethodNormal's MonoGenericContainer;
1991  *                     see mono_metadata_parse_type_full() for details.
1992  * Internal routine to parse a generic type parameter.
1993  */
1994 static MonoGenericParam *
1995 mono_metadata_parse_generic_param (MonoImage *m, MonoGenericContainer *generic_container,
1996                                    MonoTypeEnum type, const char *ptr, const char **rptr)
1997 {
1998         int index = mono_metadata_decode_value (ptr, &ptr);
1999         if (rptr)
2000                 *rptr = ptr;
2001
2002         generic_container = select_container (generic_container, type);
2003         if (!generic_container) {
2004                 /* Create dummy MonoGenericParam */
2005                 MonoGenericParam *param = g_new0 (MonoGenericParam, 1);
2006                 param->name = g_strdup_printf ("%d", index);
2007                 param->num = index;
2008
2009                 return param;
2010         }
2011
2012         g_assert (index < generic_container->type_argc);
2013         return &generic_container->type_params [index];
2014 }
2015
2016 /* 
2017  * do_mono_metadata_parse_type:
2018  * @type: MonoType to be filled in with the return value
2019  * @m: image context
2020  * @generic_context: generics_context
2021  * @ptr: pointer to the encoded type
2022  * @rptr: pointer where the end of the encoded type is saved
2023  * 
2024  * Internal routine used to "fill" the contents of @type from an 
2025  * allocated pointer.  This is done this way to avoid doing too
2026  * many mini-allocations (particularly for the MonoFieldType which
2027  * most of the time is just a MonoType, but sometimes might be augmented).
2028  *
2029  * This routine is used by mono_metadata_parse_type and
2030  * mono_metadata_parse_field_type
2031  *
2032  * This extracts a Type as specified in Partition II (22.2.12) 
2033  *
2034  * Returns: FALSE if the type could not be loaded
2035  */
2036 static gboolean
2037 do_mono_metadata_parse_type (MonoType *type, MonoImage *m, MonoGenericContainer *container,
2038                              const char *ptr, const char **rptr)
2039 {
2040         gboolean ok = TRUE;
2041         type->type = mono_metadata_decode_value (ptr, &ptr);
2042         
2043         switch (type->type){
2044         case MONO_TYPE_VOID:
2045         case MONO_TYPE_BOOLEAN:
2046         case MONO_TYPE_CHAR:
2047         case MONO_TYPE_I1:
2048         case MONO_TYPE_U1:
2049         case MONO_TYPE_I2:
2050         case MONO_TYPE_U2:
2051         case MONO_TYPE_I4:
2052         case MONO_TYPE_U4:
2053         case MONO_TYPE_I8:
2054         case MONO_TYPE_U8:
2055         case MONO_TYPE_R4:
2056         case MONO_TYPE_R8:
2057         case MONO_TYPE_I:
2058         case MONO_TYPE_U:
2059         case MONO_TYPE_STRING:
2060         case MONO_TYPE_OBJECT:
2061         case MONO_TYPE_TYPEDBYREF:
2062                 break;
2063         case MONO_TYPE_VALUETYPE:
2064         case MONO_TYPE_CLASS: {
2065                 guint32 token;
2066                 token = mono_metadata_parse_typedef_or_ref (m, ptr, &ptr);
2067                 type->data.klass = mono_class_get (m, token);
2068                 if (!type->data.klass)
2069                         return FALSE;
2070                 break;
2071         }
2072         case MONO_TYPE_SZARRAY: {
2073                 MonoType *etype = mono_metadata_parse_type_full (m, container, MONO_PARSE_MOD_TYPE, 0, ptr, &ptr);
2074                 if (!etype)
2075                         return FALSE;
2076                 type->data.klass = mono_class_from_mono_type (etype);
2077                 mono_metadata_free_type (etype);
2078                 break;
2079         }
2080         case MONO_TYPE_PTR:
2081                 type->data.type = mono_metadata_parse_type_full (m, container, MONO_PARSE_MOD_TYPE, 0, ptr, &ptr);
2082                 if (!type->data.type)
2083                         return FALSE;
2084                 break;
2085         case MONO_TYPE_FNPTR:
2086                 type->data.method = mono_metadata_parse_method_signature_full (m, container, 0, ptr, &ptr);
2087                 break;
2088         case MONO_TYPE_ARRAY:
2089                 type->data.array = mono_metadata_parse_array_full (m, container, ptr, &ptr);
2090                 break;
2091         case MONO_TYPE_MVAR:
2092         case MONO_TYPE_VAR:
2093                 type->data.generic_param = mono_metadata_parse_generic_param (m, container, type->type, ptr, &ptr);
2094                 break;
2095         case MONO_TYPE_GENERICINST:
2096                 ok = do_mono_metadata_parse_generic_class (type, m, container, ptr, &ptr);
2097                 break;
2098         default:
2099                 g_error ("type 0x%02x not handled in do_mono_metadata_parse_type", type->type);
2100         }
2101         
2102         if (rptr)
2103                 *rptr = ptr;
2104         return ok;
2105 }
2106
2107 /*
2108  * mono_metadata_free_type:
2109  * @type: type to free
2110  *
2111  * Free the memory allocated for type @type which is assumed to be created by
2112  * mono_metadata_parse_type ().
2113  */
2114 void
2115 mono_metadata_free_type (MonoType *type)
2116 {
2117         if (type >= builtin_types && type < builtin_types + NBUILTIN_TYPES ())
2118                 return;
2119         
2120         switch (type->type){
2121         case MONO_TYPE_OBJECT:
2122         case MONO_TYPE_STRING:
2123                 if (!type->data.klass)
2124                         break;
2125                 /* fall through */
2126         case MONO_TYPE_CLASS:
2127         case MONO_TYPE_VALUETYPE:
2128                 if (type == &type->data.klass->byval_arg || type == &type->data.klass->this_arg)
2129                         return;
2130                 break;
2131         case MONO_TYPE_PTR:
2132                 mono_metadata_free_type (type->data.type);
2133                 break;
2134         case MONO_TYPE_FNPTR:
2135                 mono_metadata_free_method_signature (type->data.method);
2136                 break;
2137         case MONO_TYPE_ARRAY:
2138                 mono_metadata_free_array (type->data.array);
2139                 break;
2140         }
2141
2142         /* Allocated from a mempool, no need to free it */
2143 }
2144
2145 #if 0
2146 static void
2147 hex_dump (const char *buffer, int base, int count)
2148 {
2149         int show_header = 1;
2150         int i;
2151
2152         if (count < 0){
2153                 count = -count;
2154                 show_header = 0;
2155         }
2156         
2157         for (i = 0; i < count; i++){
2158                 if (show_header)
2159                         if ((i % 16) == 0)
2160                                 printf ("\n0x%08x: ", (unsigned char) base + i);
2161
2162                 printf ("%02x ", (unsigned char) (buffer [i]));
2163         }
2164         fflush (stdout);
2165 }
2166 #endif
2167
2168 /** 
2169  * @mh: The Method header
2170  * @ptr: Points to the beginning of the Section Data (25.3)
2171  */
2172 static void
2173 parse_section_data (MonoImage *m, MonoMethodHeader *mh, const unsigned char *ptr)
2174 {
2175         unsigned char sect_data_flags;
2176         const unsigned char *sptr;
2177         int is_fat;
2178         guint32 sect_data_len;
2179         
2180         while (1) {
2181                 /* align on 32-bit boundary */
2182                 /* FIXME: not 64-bit clean code */
2183                 sptr = ptr = dword_align (ptr); 
2184                 sect_data_flags = *ptr;
2185                 ptr++;
2186                 
2187                 is_fat = sect_data_flags & METHOD_HEADER_SECTION_FAT_FORMAT;
2188                 if (is_fat) {
2189                         sect_data_len = (ptr [2] << 16) | (ptr [1] << 8) | ptr [0];
2190                         ptr += 3;
2191                 } else {
2192                         sect_data_len = ptr [0];
2193                         ++ptr;
2194                 }
2195                 /*
2196                 g_print ("flags: %02x, len: %d\n", sect_data_flags, sect_data_len);
2197                 hex_dump (sptr, 0, sect_data_len+8);
2198                 g_print ("\nheader: ");
2199                 hex_dump (sptr-4, 0, 4);
2200                 g_print ("\n");
2201                 */
2202                 
2203                 if (sect_data_flags & METHOD_HEADER_SECTION_EHTABLE) {
2204                         const unsigned char *p = dword_align (ptr);
2205                         int i;
2206                         mh->num_clauses = is_fat ? sect_data_len / 24: sect_data_len / 12;
2207                         /* we could just store a pointer if we don't need to byteswap */
2208                         mh->clauses = mono_mempool_alloc0 (m->mempool, sizeof (MonoExceptionClause) * mh->num_clauses);
2209                         for (i = 0; i < mh->num_clauses; ++i) {
2210                                 MonoExceptionClause *ec = &mh->clauses [i];
2211                                 guint32 tof_value;
2212                                 if (is_fat) {
2213                                         ec->flags = read32 (p);
2214                                         ec->try_offset = read32 (p + 4);
2215                                         ec->try_len = read32 (p + 8);
2216                                         ec->handler_offset = read32 (p + 12);
2217                                         ec->handler_len = read32 (p + 16);
2218                                         tof_value = read32 (p + 20);
2219                                         p += 24;
2220                                 } else {
2221                                         ec->flags = read16 (p);
2222                                         ec->try_offset = read16 (p + 2);
2223                                         ec->try_len = *(p + 4);
2224                                         ec->handler_offset = read16 (p + 5);
2225                                         ec->handler_len = *(p + 7);
2226                                         tof_value = read32 (p + 8);
2227                                         p += 12;
2228                                 }
2229                                 if (ec->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
2230                                         ec->data.filter_offset = tof_value;
2231                                 } else if (ec->flags == MONO_EXCEPTION_CLAUSE_NONE) {
2232                                         ec->data.catch_class = tof_value? mono_class_get (m, tof_value): 0;
2233                                 } else {
2234                                         ec->data.catch_class = NULL;
2235                                 }
2236                                 /* g_print ("try %d: %x %04x-%04x %04x\n", i, ec->flags, ec->try_offset, ec->try_offset+ec->try_len, ec->try_len); */
2237                         }
2238
2239                 }
2240                 if (sect_data_flags & METHOD_HEADER_SECTION_MORE_SECTS)
2241                         ptr += sect_data_len - 4; /* LAMESPEC: it seems the size includes the header */
2242                 else
2243                         return;
2244         }
2245 }
2246
2247 /*
2248  * mono_metadata_parse_mh_full:
2249  * @m: metadata context
2250  * @generic_context: generics context
2251  * @ptr: pointer to the method header.
2252  *
2253  * Decode the method header at @ptr, including pointer to the IL code,
2254  * info about local variables and optional exception tables.
2255  * This is a Mono runtime internal function.
2256  *
2257  * LOCKING: Assumes the loader lock is held.
2258  *
2259  * Returns: a MonoMethodHeader allocated from the image mempool.
2260  */
2261 MonoMethodHeader *
2262 mono_metadata_parse_mh_full (MonoImage *m, MonoGenericContainer *container, const char *ptr)
2263 {
2264         MonoMethodHeader *mh;
2265         unsigned char flags = *(const unsigned char *) ptr;
2266         unsigned char format = flags & METHOD_HEADER_FORMAT_MASK;
2267         guint16 fat_flags;
2268         guint32 local_var_sig_tok, max_stack, code_size, init_locals;
2269         const unsigned char *code;
2270         int hsize;
2271         
2272         g_return_val_if_fail (ptr != NULL, NULL);
2273
2274         switch (format) {
2275         case METHOD_HEADER_TINY_FORMAT:
2276                 mh = mono_mempool_alloc0 (m->mempool, sizeof (MonoMethodHeader));
2277                 ptr++;
2278                 mh->max_stack = 8;
2279                 local_var_sig_tok = 0;
2280                 mh->code_size = flags >> 2;
2281                 mh->code = ptr;
2282                 return mh;
2283         case METHOD_HEADER_TINY_FORMAT1:
2284                 mh = mono_mempool_alloc0 (m->mempool, sizeof (MonoMethodHeader));
2285                 ptr++;
2286                 mh->max_stack = 8;
2287                 local_var_sig_tok = 0;
2288
2289                 /*
2290                  * The spec claims 3 bits, but the Beta2 is
2291                  * incorrect
2292                  */
2293                 mh->code_size = flags >> 2;
2294                 mh->code = ptr;
2295                 return mh;
2296         case METHOD_HEADER_FAT_FORMAT:
2297                 fat_flags = read16 (ptr);
2298                 ptr += 2;
2299                 hsize = (fat_flags >> 12) & 0xf;
2300                 max_stack = read16 (ptr);
2301                 ptr += 2;
2302                 code_size = read32 (ptr);
2303                 ptr += 4;
2304                 local_var_sig_tok = read32 (ptr);
2305                 ptr += 4;
2306
2307                 if (fat_flags & METHOD_HEADER_INIT_LOCALS)
2308                         init_locals = 1;
2309                 else
2310                         init_locals = 0;
2311
2312                 code = ptr;
2313
2314                 if (!(fat_flags & METHOD_HEADER_MORE_SECTS))
2315                         break;
2316
2317                 /*
2318                  * There are more sections
2319                  */
2320                 ptr = code + code_size;
2321                 break;
2322         default:
2323                 return NULL;
2324         }
2325                        
2326         if (local_var_sig_tok) {
2327                 MonoTableInfo *t = &m->tables [MONO_TABLE_STANDALONESIG];
2328                 const char *locals_ptr;
2329                 guint32 cols [MONO_STAND_ALONE_SIGNATURE_SIZE];
2330                 int len=0, i, bsize;
2331
2332                 mono_metadata_decode_row (t, (local_var_sig_tok & 0xffffff)-1, cols, 1);
2333                 locals_ptr = mono_metadata_blob_heap (m, cols [MONO_STAND_ALONE_SIGNATURE]);
2334                 bsize = mono_metadata_decode_blob_size (locals_ptr, &locals_ptr);
2335                 if (*locals_ptr != 0x07)
2336                         g_warning ("wrong signature for locals blob");
2337                 locals_ptr++;
2338                 len = mono_metadata_decode_value (locals_ptr, &locals_ptr);
2339                 mh = mono_mempool_alloc0 (m->mempool, sizeof (MonoMethodHeader) + (len - MONO_ZERO_LEN_ARRAY) * sizeof (MonoType*));
2340                 mh->num_locals = len;
2341                 for (i = 0; i < len; ++i) {
2342                         mh->locals [i] = mono_metadata_parse_type_full (
2343                                 m, container, MONO_PARSE_LOCAL, 0, locals_ptr, &locals_ptr);
2344                         if (!mh->locals [i]) {
2345                                 g_free (mh);
2346                                 return NULL;
2347                         }
2348                 }
2349         } else {
2350                 mh = mono_mempool_alloc0 (m->mempool, sizeof (MonoMethodHeader));
2351         }
2352         mh->code = code;
2353         mh->code_size = code_size;
2354         mh->max_stack = max_stack;
2355         mh->init_locals = init_locals;
2356         if (fat_flags & METHOD_HEADER_MORE_SECTS)
2357                 parse_section_data (m, mh, (const unsigned char*)ptr);
2358         return mh;
2359 }
2360
2361 /*
2362  * mono_metadata_parse_mh:
2363  * @generic_context: generics context
2364  * @ptr: pointer to the method header.
2365  *
2366  * Decode the method header at @ptr, including pointer to the IL code,
2367  * info about local variables and optional exception tables.
2368  * This is a Mono runtime internal function.
2369  *
2370  * Returns: a MonoMethodHeader.
2371  */
2372 MonoMethodHeader *
2373 mono_metadata_parse_mh (MonoImage *m, const char *ptr)
2374 {
2375         MonoMethodHeader *res;
2376
2377         mono_loader_lock ();
2378
2379         res = mono_metadata_parse_mh_full (m, NULL, ptr);
2380
2381         mono_loader_unlock ();
2382
2383         return res;
2384 }
2385
2386 /*
2387  * mono_metadata_free_mh:
2388  * @mh: a method header
2389  *
2390  * Free the memory allocated for the method header.
2391  * This is a Mono runtime internal function.
2392  */
2393 void
2394 mono_metadata_free_mh (MonoMethodHeader *mh)
2395 {
2396         /* Allocated from the mempool */
2397 }
2398
2399 /*
2400  * mono_method_header_get_code:
2401  * @header: a MonoMethodHeader pointer
2402  * @code_size: memory location for returning the code size
2403  * @max_stack: memory location for returning the max stack
2404  *
2405  * Method header accessor to retreive info about the IL code properties:
2406  * a pointer to the IL code itself, the size of the code and the max number
2407  * of stack slots used by the code.
2408  *
2409  * Returns: pointer to the IL code represented by the method header.
2410  */
2411 const unsigned char*
2412 mono_method_header_get_code (MonoMethodHeader *header, guint32* code_size, guint32* max_stack)
2413 {
2414         if (code_size)
2415                 *code_size = header->code_size;
2416         if (max_stack)
2417                 *max_stack = header->max_stack;
2418         return header->code;
2419 }
2420
2421 /*
2422  * mono_method_header_get_locals:
2423  * @header: a MonoMethodHeader pointer
2424  * @num_locals: memory location for returning the number of local variables
2425  * @init_locals: memory location for returning the init_locals flag
2426  *
2427  * Method header accessor to retreive info about the local variables:
2428  * an array of local types, the number of locals and whether the locals
2429  * are supposed to be initialized to 0 on method entry
2430  *
2431  * Returns: pointer to an array of types of the local variables
2432  */
2433 MonoType**
2434 mono_method_header_get_locals (MonoMethodHeader *header, guint32* num_locals, gboolean *init_locals)
2435 {
2436         if (num_locals)
2437                 *num_locals = header->num_locals;
2438         if (init_locals)
2439                 *init_locals = header->init_locals;
2440         return header->locals;
2441 }
2442
2443 /*
2444  * mono_method_header_get_num_clauses:
2445  * @header: a MonoMethodHeader pointer
2446  *
2447  * Method header accessor to retreive the number of exception clauses.
2448  *
2449  * Returns: the number of exception clauses present
2450  */
2451 int
2452 mono_method_header_get_num_clauses (MonoMethodHeader *header)
2453 {
2454         return header->num_clauses;
2455 }
2456
2457 /*
2458  * mono_method_header_get_clauses:
2459  * @header: a MonoMethodHeader pointer
2460  * @method: MonoMethod the header belongs to
2461  * @iter: pointer to a iterator
2462  * @clause: pointer to a MonoExceptionClause structure which will be filled with the info
2463  *
2464  * Get the info about the exception clauses in the method. Set *iter to NULL to
2465  * initiate the iteration, then call the method repeatedly until it returns FALSE.
2466  * At each iteration, the structure pointed to by clause if filled with the
2467  * exception clause information.
2468  *
2469  * Returns: TRUE if clause was filled with info, FALSE if there are no more exception
2470  * clauses.
2471  */
2472 int
2473 mono_method_header_get_clauses (MonoMethodHeader *header, MonoMethod *method, gpointer *iter, MonoExceptionClause *clause)
2474 {
2475         MonoExceptionClause *sc;
2476         /* later we'll be able to use this interface to parse the clause info on demand,
2477          * without allocating anything.
2478          */
2479         if (!iter || !header->num_clauses)
2480                 return FALSE;
2481         if (!*iter) {
2482                 *iter = sc = header->clauses;
2483                 *clause = *sc;
2484                 return TRUE;
2485         }
2486         sc = *iter;
2487         sc++;
2488         if (sc < header->clauses + header->num_clauses) {
2489                 *iter = sc;
2490                 *clause = *sc;
2491                 return TRUE;
2492         }
2493         return FALSE;
2494 }
2495
2496 /**
2497  * mono_metadata_parse_field_type:
2498  * @m: metadata context to extract information from
2499  * @ptr: pointer to the field signature
2500  * @rptr: pointer updated to match the end of the decoded stream
2501  *
2502  * Parses the field signature, and returns the type information for it. 
2503  *
2504  * Returns: The MonoType that was extracted from @ptr.
2505  */
2506 MonoType *
2507 mono_metadata_parse_field_type (MonoImage *m, short field_flags, const char *ptr, const char **rptr)
2508 {
2509         return mono_metadata_parse_type (m, MONO_PARSE_FIELD, field_flags, ptr, rptr);
2510 }
2511
2512 /**
2513  * mono_metadata_parse_param:
2514  * @m: metadata context to extract information from
2515  * @ptr: pointer to the param signature
2516  * @rptr: pointer updated to match the end of the decoded stream
2517  *
2518  * Parses the param signature, and returns the type information for it. 
2519  *
2520  * Returns: The MonoType that was extracted from @ptr.
2521  */
2522 MonoType *
2523 mono_metadata_parse_param (MonoImage *m, const char *ptr, const char **rptr)
2524 {
2525         return mono_metadata_parse_type (m, MONO_PARSE_PARAM, 0, ptr, rptr);
2526 }
2527
2528 /*
2529  * mono_metadata_token_from_dor:
2530  * @dor_token: A TypeDefOrRef coded index
2531  *
2532  * dor_token is a TypeDefOrRef coded index: it contains either
2533  * a TypeDef, TypeRef or TypeSpec in the lower bits, and the upper
2534  * bits contain an index into the table.
2535  *
2536  * Returns: an expanded token
2537  */
2538 guint32
2539 mono_metadata_token_from_dor (guint32 dor_index)
2540 {
2541         guint32 table, idx;
2542
2543         table = dor_index & 0x03;
2544         idx = dor_index >> 2;
2545
2546         switch (table){
2547         case 0: /* TypeDef */
2548                 return MONO_TOKEN_TYPE_DEF | idx;
2549         case 1: /* TypeRef */
2550                 return MONO_TOKEN_TYPE_REF | idx;
2551         case 2: /* TypeSpec */
2552                 return MONO_TOKEN_TYPE_SPEC | idx;
2553         default:
2554                 g_assert_not_reached ();
2555         }
2556
2557         return 0;
2558 }
2559
2560 /*
2561  * We use this to pass context information to the row locator
2562  */
2563 typedef struct {
2564         int idx;                        /* The index that we are trying to locate */
2565         int col_idx;            /* The index in the row where idx may be stored */
2566         MonoTableInfo *t;       /* pointer to the table */
2567         guint32 result;
2568 } locator_t;
2569
2570 /*
2571  * How the row locator works.
2572  *
2573  *   Table A
2574  *   ___|___
2575  *   ___|___         Table B
2576  *   ___|___------>  _______
2577  *   ___|___         _______
2578  *   
2579  * A column in the rows of table A references an index in table B.
2580  * For example A may be the TYPEDEF table and B the METHODDEF table.
2581  * 
2582  * Given an index in table B we want to get the row in table A
2583  * where the column n references our index in B.
2584  *
2585  * In the locator_t structure:
2586  *      t is table A
2587  *      col_idx is the column number
2588  *      index is the index in table B
2589  *      result will be the index in table A
2590  *
2591  * Examples:
2592  * Table A              Table B         column (in table A)
2593  * TYPEDEF              METHODDEF   MONO_TYPEDEF_METHOD_LIST
2594  * TYPEDEF              FIELD           MONO_TYPEDEF_FIELD_LIST
2595  * PROPERTYMAP  PROPERTY        MONO_PROPERTY_MAP_PROPERTY_LIST
2596  * INTERFIMPL   TYPEDEF         MONO_INTERFACEIMPL_CLASS
2597  * METHODSEM    PROPERTY        ASSOCIATION (encoded index)
2598  *
2599  * Note that we still don't support encoded indexes.
2600  *
2601  */
2602 static int
2603 typedef_locator (const void *a, const void *b)
2604 {
2605         locator_t *loc = (locator_t *) a;
2606         const char *bb = (const char *) b;
2607         int typedef_index = (bb - loc->t->base) / loc->t->row_size;
2608         guint32 col, col_next;
2609
2610         col = mono_metadata_decode_row_col (loc->t, typedef_index, loc->col_idx);
2611
2612         if (loc->idx < col)
2613                 return -1;
2614
2615         /*
2616          * Need to check that the next row is valid.
2617          */
2618         if (typedef_index + 1 < loc->t->rows) {
2619                 col_next = mono_metadata_decode_row_col (loc->t, typedef_index + 1, loc->col_idx);
2620                 if (loc->idx >= col_next)
2621                         return 1;
2622
2623                 if (col == col_next)
2624                         return 1; 
2625         }
2626
2627         loc->result = typedef_index;
2628         
2629         return 0;
2630 }
2631
2632 static int
2633 table_locator (const void *a, const void *b)
2634 {
2635         locator_t *loc = (locator_t *) a;
2636         const char *bb = (const char *) b;
2637         guint32 table_index = (bb - loc->t->base) / loc->t->row_size;
2638         guint32 col;
2639         
2640         col = mono_metadata_decode_row_col (loc->t, table_index, loc->col_idx);
2641
2642         if (loc->idx == col) {
2643                 loc->result = table_index;
2644                 return 0;
2645         }
2646         if (loc->idx < col)
2647                 return -1;
2648         else 
2649                 return 1;
2650 }
2651
2652 static int
2653 declsec_locator (const void *a, const void *b)
2654 {
2655         locator_t *loc = (locator_t *) a;
2656         const char *bb = (const char *) b;
2657         guint32 table_index = (bb - loc->t->base) / loc->t->row_size;
2658         guint32 col;
2659
2660         col = mono_metadata_decode_row_col (loc->t, table_index, loc->col_idx);
2661
2662         if (loc->idx == col) {
2663                 loc->result = table_index;
2664                 return 0;
2665         }
2666         if (loc->idx < col)
2667                 return -1;
2668         else
2669                 return 1;
2670 }
2671
2672 /**
2673  * mono_metadata_typedef_from_field:
2674  * @meta: metadata context
2675  * @index: FieldDef token
2676  *
2677  * Returns: the 1-based index into the TypeDef table of the type that
2678  * declared the field described by @index, or 0 if not found.
2679  */
2680 guint32
2681 mono_metadata_typedef_from_field (MonoImage *meta, guint32 index)
2682 {
2683         MonoTableInfo *tdef = &meta->tables [MONO_TABLE_TYPEDEF];
2684         locator_t loc;
2685
2686         if (!tdef->base)
2687                 return 0;
2688
2689         loc.idx = mono_metadata_token_index (index);
2690         loc.col_idx = MONO_TYPEDEF_FIELD_LIST;
2691         loc.t = tdef;
2692
2693         if (!bsearch (&loc, tdef->base, tdef->rows, tdef->row_size, typedef_locator))
2694                 g_assert_not_reached ();
2695
2696         /* loc_result is 0..1, needs to be mapped to table index (that is +1) */
2697         return loc.result + 1;
2698 }
2699
2700 /*
2701  * mono_metadata_typedef_from_method:
2702  * @meta: metadata context
2703  * @index: MethodDef token
2704  *
2705  * Returns: the 1-based index into the TypeDef table of the type that
2706  * declared the method described by @index.  0 if not found.
2707  */
2708 guint32
2709 mono_metadata_typedef_from_method (MonoImage *meta, guint32 index)
2710 {
2711         MonoTableInfo *tdef = &meta->tables [MONO_TABLE_TYPEDEF];
2712         locator_t loc;
2713         
2714         if (!tdef->base)
2715                 return 0;
2716
2717         loc.idx = mono_metadata_token_index (index);
2718         loc.col_idx = MONO_TYPEDEF_METHOD_LIST;
2719         loc.t = tdef;
2720
2721         if (!bsearch (&loc, tdef->base, tdef->rows, tdef->row_size, typedef_locator))
2722                 g_assert_not_reached ();
2723
2724         /* loc_result is 0..1, needs to be mapped to table index (that is +1) */
2725         return loc.result + 1;
2726 }
2727
2728 /*
2729  * mono_metadata_interfaces_from_typedef_full:
2730  * @meta: metadata context
2731  * @index: typedef token
2732  * 
2733  * The array of interfaces that the @index typedef token implements is returned in
2734  * @interfaces. The number of elemnts in the array is returned in @count.
2735  *
2736  * LOCKING: Assumes the loader lock is held.
2737  *
2738  * Returns: TRUE on success, FALSE on failure.
2739  */
2740 gboolean
2741 mono_metadata_interfaces_from_typedef_full (MonoImage *meta, guint32 index, MonoClass ***interfaces, guint *count, MonoGenericContext *context)
2742 {
2743         MonoTableInfo *tdef = &meta->tables [MONO_TABLE_INTERFACEIMPL];
2744         locator_t loc;
2745         guint32 start, pos;
2746         guint32 cols [MONO_INTERFACEIMPL_SIZE];
2747         MonoClass **result;
2748
2749         *interfaces = NULL;
2750         *count = 0;
2751
2752         if (!tdef->base)
2753                 return TRUE;
2754
2755         loc.idx = mono_metadata_token_index (index);
2756         loc.col_idx = MONO_INTERFACEIMPL_CLASS;
2757         loc.t = tdef;
2758
2759         if (!bsearch (&loc, tdef->base, tdef->rows, tdef->row_size, table_locator))
2760                 return TRUE;
2761
2762         start = loc.result;
2763         /*
2764          * We may end up in the middle of the rows... 
2765          */
2766         while (start > 0) {
2767                 if (loc.idx == mono_metadata_decode_row_col (tdef, start - 1, MONO_INTERFACEIMPL_CLASS))
2768                         start--;
2769                 else
2770                         break;
2771         }
2772         pos = start;
2773         while (pos < tdef->rows) {
2774                 mono_metadata_decode_row (tdef, pos, cols, MONO_INTERFACEIMPL_SIZE);
2775                 if (cols [MONO_INTERFACEIMPL_CLASS] != loc.idx)
2776                         break;
2777                 ++pos;
2778         }
2779
2780         result = mono_mempool_alloc0 (meta->mempool, sizeof (MonoClass*) * (pos - start));
2781
2782         pos = start;
2783         while (pos < tdef->rows) {
2784                 MonoClass *iface;
2785                 
2786                 mono_metadata_decode_row (tdef, pos, cols, MONO_INTERFACEIMPL_SIZE);
2787                 if (cols [MONO_INTERFACEIMPL_CLASS] != loc.idx)
2788                         break;
2789                 iface = mono_class_get_full (
2790                         meta, mono_metadata_token_from_dor (cols [MONO_INTERFACEIMPL_INTERFACE]), context);
2791                 if (iface == NULL)
2792                         return FALSE;
2793                 result [pos - start] = iface;
2794                 ++pos;
2795         }
2796         *count = pos - start;
2797         *interfaces = result;
2798         return TRUE;
2799 }
2800
2801 MonoClass**
2802 mono_metadata_interfaces_from_typedef (MonoImage *meta, guint32 index, guint *count)
2803 {
2804         MonoClass **interfaces;
2805         gboolean rv;
2806
2807         mono_loader_lock ();
2808         rv = mono_metadata_interfaces_from_typedef_full (meta, index, &interfaces, count, NULL);
2809         mono_loader_unlock ();
2810         if (rv)
2811                 return interfaces;
2812         else
2813                 return NULL;
2814 }
2815
2816 /*
2817  * mono_metadata_nested_in_typedef:
2818  * @meta: metadata context
2819  * @index: typedef token
2820  * 
2821  * Returns: the 1-based index into the TypeDef table of the type
2822  * where the type described by @index is nested.
2823  * Retruns 0 if @index describes a non-nested type.
2824  */
2825 guint32
2826 mono_metadata_nested_in_typedef (MonoImage *meta, guint32 index)
2827 {
2828         MonoTableInfo *tdef = &meta->tables [MONO_TABLE_NESTEDCLASS];
2829         locator_t loc;
2830         
2831         if (!tdef->base)
2832                 return 0;
2833
2834         loc.idx = mono_metadata_token_index (index);
2835         loc.col_idx = MONO_NESTED_CLASS_NESTED;
2836         loc.t = tdef;
2837
2838         if (!bsearch (&loc, tdef->base, tdef->rows, tdef->row_size, table_locator))
2839                 return 0;
2840
2841         /* loc_result is 0..1, needs to be mapped to table index (that is +1) */
2842         return mono_metadata_decode_row_col (tdef, loc.result, MONO_NESTED_CLASS_ENCLOSING) | MONO_TOKEN_TYPE_DEF;
2843 }
2844
2845 /*
2846  * mono_metadata_nesting_typedef:
2847  * @meta: metadata context
2848  * @index: typedef token
2849  * 
2850  * Returns: the 1-based index into the TypeDef table of the first type
2851  * that is nested inside the type described by @index. The search starts at
2852  * @start_index.  returns 0 if no such type is found.
2853  */
2854 guint32
2855 mono_metadata_nesting_typedef (MonoImage *meta, guint32 index, guint32 start_index)
2856 {
2857         MonoTableInfo *tdef = &meta->tables [MONO_TABLE_NESTEDCLASS];
2858         guint32 start;
2859         guint32 class_index = mono_metadata_token_index (index);
2860         
2861         if (!tdef->base)
2862                 return 0;
2863
2864         start = start_index;
2865
2866         while (start <= tdef->rows) {
2867                 if (class_index == mono_metadata_decode_row_col (tdef, start - 1, MONO_NESTED_CLASS_ENCLOSING))
2868                         break;
2869                 else
2870                         start++;
2871         }
2872
2873         if (start > tdef->rows)
2874                 return 0;
2875         else
2876                 return start;
2877 }
2878
2879 /*
2880  * mono_metadata_packing_from_typedef:
2881  * @meta: metadata context
2882  * @index: token representing a type
2883  * 
2884  * Returns: the info stored in the ClassLAyout table for the given typedef token
2885  * into the @packing and @size pointers.
2886  * Returns 0 if the info is not found.
2887  */
2888 guint32
2889 mono_metadata_packing_from_typedef (MonoImage *meta, guint32 index, guint32 *packing, guint32 *size)
2890 {
2891         MonoTableInfo *tdef = &meta->tables [MONO_TABLE_CLASSLAYOUT];
2892         locator_t loc;
2893         guint32 cols [MONO_CLASS_LAYOUT_SIZE];
2894         
2895         if (!tdef->base)
2896                 return 0;
2897
2898         loc.idx = mono_metadata_token_index (index);
2899         loc.col_idx = MONO_CLASS_LAYOUT_PARENT;
2900         loc.t = tdef;
2901
2902         if (!bsearch (&loc, tdef->base, tdef->rows, tdef->row_size, table_locator))
2903                 return 0;
2904
2905         mono_metadata_decode_row (tdef, loc.result, cols, MONO_CLASS_LAYOUT_SIZE);
2906         if (packing)
2907                 *packing = cols [MONO_CLASS_LAYOUT_PACKING_SIZE];
2908         if (size)
2909                 *size = cols [MONO_CLASS_LAYOUT_CLASS_SIZE];
2910
2911         /* loc_result is 0..1, needs to be mapped to table index (that is +1) */
2912         return loc.result + 1;
2913 }
2914
2915 /*
2916  * mono_metadata_custom_attrs_from_index:
2917  * @meta: metadata context
2918  * @index: token representing the parent
2919  * 
2920  * Returns: the 1-based index into the CustomAttribute table of the first 
2921  * attribute which belongs to the metadata object described by @index.
2922  * Returns 0 if no such attribute is found.
2923  */
2924 guint32
2925 mono_metadata_custom_attrs_from_index (MonoImage *meta, guint32 index)
2926 {
2927         MonoTableInfo *tdef = &meta->tables [MONO_TABLE_CUSTOMATTRIBUTE];
2928         locator_t loc;
2929         
2930         if (!tdef->base)
2931                 return 0;
2932
2933         loc.idx = index;
2934         loc.col_idx = MONO_CUSTOM_ATTR_PARENT;
2935         loc.t = tdef;
2936
2937         if (!bsearch (&loc, tdef->base, tdef->rows, tdef->row_size, table_locator))
2938                 return 0;
2939
2940         /* Find the first entry by searching backwards */
2941         while ((loc.result > 0) && (mono_metadata_decode_row_col (tdef, loc.result - 1, MONO_CUSTOM_ATTR_PARENT) == index))
2942                 loc.result --;
2943
2944         /* loc_result is 0..1, needs to be mapped to table index (that is +1) */
2945         return loc.result + 1;
2946 }
2947
2948 /*
2949  * mono_metadata_declsec_from_index:
2950  * @meta: metadata context
2951  * @index: token representing the parent
2952  * 
2953  * Returns: the 0-based index into the DeclarativeSecurity table of the first 
2954  * attribute which belongs to the metadata object described by @index.
2955  * Returns -1 if no such attribute is found.
2956  */
2957 guint32
2958 mono_metadata_declsec_from_index (MonoImage *meta, guint32 index)
2959 {
2960         MonoTableInfo *tdef = &meta->tables [MONO_TABLE_DECLSECURITY];
2961         locator_t loc;
2962
2963         if (!tdef->base)
2964                 return -1;
2965
2966         loc.idx = index;
2967         loc.col_idx = MONO_DECL_SECURITY_PARENT;
2968         loc.t = tdef;
2969
2970         if (!bsearch (&loc, tdef->base, tdef->rows, tdef->row_size, declsec_locator))
2971                 return -1;
2972
2973         /* Find the first entry by searching backwards */
2974         while ((loc.result > 0) && (mono_metadata_decode_row_col (tdef, loc.result - 1, MONO_DECL_SECURITY_PARENT) == index))
2975                 loc.result --;
2976
2977         return loc.result;
2978 }
2979
2980 #ifdef DEBUG
2981 static void
2982 mono_backtrace (int limit)
2983 {
2984         void *array[limit];
2985         char **names;
2986         int i;
2987         backtrace (array, limit);
2988         names = backtrace_symbols (array, limit);
2989         for (i =0; i < limit; ++i) {
2990                 g_print ("\t%s\n", names [i]);
2991         }
2992         g_free (names);
2993 }
2994 #endif
2995
2996 #ifndef __GNUC__
2997 /*#define __alignof__(a) sizeof(a)*/
2998 #define __alignof__(type) G_STRUCT_OFFSET(struct { char c; type x; }, x)
2999 #endif
3000
3001 /*
3002  * mono_type_size:
3003  * @t: the type to return the size of
3004  *
3005  * Returns: the number of bytes required to hold an instance of this
3006  * type in memory
3007  * FIXME: This should really use 'guint32*' for the align parameter.
3008  */
3009 int
3010 mono_type_size (MonoType *t, gint *align)
3011 {
3012         if (!t) {
3013                 *align = 1;
3014                 return 0;
3015         }
3016         if (t->byref) {
3017                 *align = __alignof__(gpointer);
3018                 return sizeof (gpointer);
3019         }
3020
3021         switch (t->type){
3022         case MONO_TYPE_VOID:
3023                 *align = 1;
3024                 return 0;
3025         case MONO_TYPE_BOOLEAN:
3026                 *align = __alignof__(gint8);
3027                 return 1;
3028         case MONO_TYPE_I1:
3029         case MONO_TYPE_U1:
3030                 *align = __alignof__(gint8);
3031                 return 1;
3032         case MONO_TYPE_CHAR:
3033         case MONO_TYPE_I2:
3034         case MONO_TYPE_U2:
3035                 *align = __alignof__(gint16);
3036                 return 2;               
3037         case MONO_TYPE_I4:
3038         case MONO_TYPE_U4:
3039                 *align = __alignof__(gint32);
3040                 return 4;
3041         case MONO_TYPE_R4:
3042                 *align = __alignof__(float);
3043                 return 4;
3044         case MONO_TYPE_I8:
3045         case MONO_TYPE_U8:
3046                 *align = __alignof__(gint64);
3047                 return 8;               
3048         case MONO_TYPE_R8:
3049                 *align = __alignof__(double);
3050                 return 8;               
3051         case MONO_TYPE_I:
3052         case MONO_TYPE_U:
3053                 *align = __alignof__(gpointer);
3054                 return sizeof (gpointer);
3055         case MONO_TYPE_STRING:
3056                 *align = __alignof__(gpointer);
3057                 return sizeof (gpointer);
3058         case MONO_TYPE_OBJECT:
3059                 *align = __alignof__(gpointer);
3060                 return sizeof (gpointer);
3061         case MONO_TYPE_VALUETYPE: {
3062                 if (t->data.klass->enumtype)
3063                         return mono_type_size (t->data.klass->enum_basetype, align);
3064                 else
3065                         return mono_class_value_size (t->data.klass, align);
3066         }
3067         case MONO_TYPE_CLASS:
3068         case MONO_TYPE_SZARRAY:
3069         case MONO_TYPE_PTR:
3070         case MONO_TYPE_FNPTR:
3071         case MONO_TYPE_ARRAY:
3072                 *align = __alignof__(gpointer);
3073                 return sizeof (gpointer);
3074         case MONO_TYPE_TYPEDBYREF:
3075                 return mono_class_value_size (mono_defaults.typed_reference_class, align);
3076         case MONO_TYPE_GENERICINST: {
3077                 MonoInflatedGenericClass *gclass;
3078                 MonoClass *container_class;
3079
3080                 gclass = mono_get_inflated_generic_class (t->data.generic_class);
3081                 // g_assert (!gclass->generic_class.inst->is_open);
3082                 // g_assert (!gclass->klass->generic_container);
3083
3084                 container_class = gclass->generic_class.container_class;
3085
3086                 if (container_class->valuetype) {
3087                         if (container_class->enumtype)
3088                                 return mono_type_size (container_class->enum_basetype, align);
3089                         else
3090                                 return mono_class_value_size (gclass->klass, align);
3091                 } else {
3092                         *align = __alignof__(gpointer);
3093                         return sizeof (gpointer);
3094                 }
3095         }
3096         case MONO_TYPE_VAR:
3097         case MONO_TYPE_MVAR:
3098                 /* FIXME: Martin, this is wrong. */
3099                 *align = __alignof__(gpointer);
3100                 return sizeof (gpointer);
3101         default:
3102                 g_error ("mono_type_size: type 0x%02x unknown", t->type);
3103         }
3104         return 0;
3105 }
3106
3107 /*
3108  * mono_type_stack_size:
3109  * @t: the type to return the size it uses on the stack
3110  *
3111  * Returns: the number of bytes required to hold an instance of this
3112  * type on the runtime stack
3113  * FIXME: This should really use 'guint32*' for the align parameter.
3114  */
3115 int
3116 mono_type_stack_size (MonoType *t, gint *align)
3117 {
3118         int tmp;
3119
3120         g_assert (t != NULL);
3121
3122         if (!align)
3123                 align = &tmp;
3124
3125         if (t->byref) {
3126                 *align = __alignof__(gpointer);
3127                 return sizeof (gpointer);
3128         }
3129
3130         switch (t->type){
3131         case MONO_TYPE_BOOLEAN:
3132         case MONO_TYPE_CHAR:
3133         case MONO_TYPE_I1:
3134         case MONO_TYPE_U1:
3135         case MONO_TYPE_I2:
3136         case MONO_TYPE_U2:
3137         case MONO_TYPE_I4:
3138         case MONO_TYPE_U4:
3139         case MONO_TYPE_I:
3140         case MONO_TYPE_U:
3141         case MONO_TYPE_STRING:
3142         case MONO_TYPE_OBJECT:
3143         case MONO_TYPE_CLASS:
3144         case MONO_TYPE_SZARRAY:
3145         case MONO_TYPE_PTR:
3146         case MONO_TYPE_FNPTR:
3147         case MONO_TYPE_ARRAY:
3148                 *align = __alignof__(gpointer);
3149                 return sizeof (gpointer);
3150         case MONO_TYPE_TYPEDBYREF:
3151                 *align = __alignof__(gpointer);
3152                 return sizeof (gpointer) * 3;
3153         case MONO_TYPE_R4:
3154                 *align = __alignof__(float);
3155                 return sizeof (float);          
3156         case MONO_TYPE_I8:
3157         case MONO_TYPE_U8:
3158                 *align = __alignof__(gint64);
3159                 return sizeof (gint64);         
3160         case MONO_TYPE_R8:
3161                 *align = __alignof__(double);
3162                 return sizeof (double);
3163         case MONO_TYPE_VALUETYPE: {
3164                 guint32 size;
3165
3166                 if (t->data.klass->enumtype)
3167                         return mono_type_stack_size (t->data.klass->enum_basetype, align);
3168                 else {
3169                         size = mono_class_value_size (t->data.klass, align);
3170
3171                         *align = *align + __alignof__(gpointer) - 1;
3172                         *align &= ~(__alignof__(gpointer) - 1);
3173
3174                         size += sizeof (gpointer) - 1;
3175                         size &= ~(sizeof (gpointer) - 1);
3176
3177                         return size;
3178                 }
3179         }
3180         case MONO_TYPE_GENERICINST: {
3181                 MonoInflatedGenericClass *gclass;
3182                 MonoClass *container_class;
3183
3184                 gclass = mono_get_inflated_generic_class (t->data.generic_class);
3185                 container_class = gclass->generic_class.container_class;
3186
3187                 g_assert (!gclass->generic_class.inst->is_open);
3188                 g_assert (!gclass->klass->generic_container);
3189
3190                 if (container_class->valuetype) {
3191                         if (container_class->enumtype)
3192                                 return mono_type_stack_size (container_class->enum_basetype, align);
3193                         else {
3194                                 guint32 size = mono_class_value_size (gclass->klass, align);
3195
3196                                 *align = *align + __alignof__(gpointer) - 1;
3197                                 *align &= ~(__alignof__(gpointer) - 1);
3198
3199                                 size += sizeof (gpointer) - 1;
3200                                 size &= ~(sizeof (gpointer) - 1);
3201
3202                                 return size;
3203                         }
3204                 } else {
3205                         *align = __alignof__(gpointer);
3206                         return sizeof (gpointer);
3207                 }
3208         }
3209         default:
3210                 g_error ("type 0x%02x unknown", t->type);
3211         }
3212         return 0;
3213 }
3214
3215 gboolean
3216 mono_type_generic_inst_is_valuetype (MonoType *type)
3217 {
3218         g_assert (type->type == MONO_TYPE_GENERICINST);
3219         return type->data.generic_class->container_class->valuetype;
3220 }
3221
3222 gboolean
3223 mono_metadata_generic_class_is_valuetype (MonoGenericClass *gclass)
3224 {
3225         return gclass->container_class->valuetype;
3226 }
3227
3228 static gboolean
3229 _mono_metadata_generic_class_equal (const MonoGenericClass *g1, const MonoGenericClass *g2, gboolean signature_only)
3230 {
3231         int i;
3232
3233         if ((g1->inst->type_argc != g2->inst->type_argc) || (g1->is_dynamic != g2->is_dynamic) ||
3234             (g1->inst->is_reference != g2->inst->is_reference))
3235                 return FALSE;
3236         if (!mono_metadata_class_equal (g1->container_class, g2->container_class, signature_only))
3237                 return FALSE;
3238         for (i = 0; i < g1->inst->type_argc; ++i) {
3239                 if (!do_mono_metadata_type_equal (g1->inst->type_argv [i], g2->inst->type_argv [i], signature_only))
3240                         return FALSE;
3241         }
3242         return TRUE;
3243 }
3244
3245 guint
3246 mono_metadata_generic_method_hash (MonoGenericMethod *gmethod)
3247 {
3248         return gmethod->inst->id;
3249 }
3250
3251 gboolean
3252 mono_metadata_generic_method_equal (MonoGenericMethod *g1, MonoGenericMethod *g2)
3253 {
3254         return (g1->container == g2->container) && (g1->generic_class == g2->generic_class) &&
3255                 (g1->inst == g2->inst);
3256 }
3257
3258
3259 /*
3260  * mono_metadata_type_hash:
3261  * @t1: a type
3262  *
3263  * Computes an hash value for @t1 to be used in GHashTable.
3264  */
3265 guint
3266 mono_metadata_type_hash (MonoType *t1)
3267 {
3268         guint hash = t1->type;
3269
3270         hash |= t1->byref << 6; /* do not collide with t1->type values */
3271         switch (t1->type) {
3272         case MONO_TYPE_VALUETYPE:
3273         case MONO_TYPE_CLASS:
3274         case MONO_TYPE_SZARRAY:
3275                 /* check if the distribution is good enough */
3276                 return ((hash << 5) - hash) ^ g_str_hash (t1->data.klass->name);
3277         case MONO_TYPE_PTR:
3278                 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
3279         case MONO_TYPE_ARRAY:
3280                 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
3281         case MONO_TYPE_GENERICINST:
3282                 return ((hash << 5) - hash) ^ mono_generic_class_hash (t1->data.generic_class);
3283         }
3284         return hash;
3285 }
3286
3287 static gboolean
3288 mono_metadata_generic_param_equal (MonoGenericParam *p1, MonoGenericParam *p2, gboolean signature_only)
3289 {
3290         if (p1 == p2)
3291                 return TRUE;
3292         if (p1->num != p2->num)
3293                 return FALSE;
3294
3295         if (p1->owner == p2->owner)
3296                 return TRUE;
3297
3298         /*
3299          * If `signature_only' is true, we're comparing two (method) signatures.
3300          * In this case, the owner of two type parameters doesn't need to match.
3301          */
3302
3303         return signature_only;
3304 }
3305
3306 static gboolean
3307 mono_metadata_class_equal (MonoClass *c1, MonoClass *c2, gboolean signature_only)
3308 {
3309         if (c1 == c2)
3310                 return TRUE;
3311         if (c1->generic_class && c2->generic_class)
3312                 return _mono_metadata_generic_class_equal (c1->generic_class, c2->generic_class, signature_only);
3313         if ((c1->byval_arg.type == MONO_TYPE_VAR) && (c2->byval_arg.type == MONO_TYPE_VAR))
3314                 return mono_metadata_generic_param_equal (
3315                         c1->byval_arg.data.generic_param, c2->byval_arg.data.generic_param, signature_only);
3316         if ((c1->byval_arg.type == MONO_TYPE_MVAR) && (c2->byval_arg.type == MONO_TYPE_MVAR))
3317                 return mono_metadata_generic_param_equal (
3318                         c1->byval_arg.data.generic_param, c2->byval_arg.data.generic_param, signature_only);
3319         if (signature_only &&
3320             (c1->byval_arg.type == MONO_TYPE_SZARRAY) && (c2->byval_arg.type == MONO_TYPE_SZARRAY))
3321                 return mono_metadata_class_equal (c1->byval_arg.data.klass, c2->byval_arg.data.klass, signature_only);
3322         return FALSE;
3323 }
3324
3325 /*
3326  * mono_metadata_type_equal:
3327  * @t1: a type
3328  * @t2: another type
3329  *
3330  * Determine if @t1 and @t2 represent the same type.
3331  * Returns: #TRUE if @t1 and @t2 are equal.
3332  */
3333 static gboolean
3334 do_mono_metadata_type_equal (MonoType *t1, MonoType *t2, gboolean signature_only)
3335 {
3336         if (t1->type != t2->type || t1->byref != t2->byref)
3337                 return FALSE;
3338
3339         switch (t1->type) {
3340         case MONO_TYPE_VOID:
3341         case MONO_TYPE_BOOLEAN:
3342         case MONO_TYPE_CHAR:
3343         case MONO_TYPE_I1:
3344         case MONO_TYPE_U1:
3345         case MONO_TYPE_I2:
3346         case MONO_TYPE_U2:
3347         case MONO_TYPE_I4:
3348         case MONO_TYPE_U4:
3349         case MONO_TYPE_I8:
3350         case MONO_TYPE_U8:
3351         case MONO_TYPE_R4:
3352         case MONO_TYPE_R8:
3353         case MONO_TYPE_STRING:
3354         case MONO_TYPE_I:
3355         case MONO_TYPE_U:
3356         case MONO_TYPE_OBJECT:
3357         case MONO_TYPE_TYPEDBYREF:
3358                 return TRUE;
3359         case MONO_TYPE_VALUETYPE:
3360         case MONO_TYPE_CLASS:
3361         case MONO_TYPE_SZARRAY:
3362                 return mono_metadata_class_equal (t1->data.klass, t2->data.klass, signature_only);
3363         case MONO_TYPE_PTR:
3364                 return do_mono_metadata_type_equal (t1->data.type, t2->data.type, signature_only);
3365         case MONO_TYPE_ARRAY:
3366                 if (t1->data.array->rank != t2->data.array->rank)
3367                         return FALSE;
3368                 return mono_metadata_class_equal (t1->data.array->eklass, t2->data.array->eklass, signature_only);
3369         case MONO_TYPE_GENERICINST:
3370                 return _mono_metadata_generic_class_equal (
3371                         t1->data.generic_class, t2->data.generic_class, signature_only);
3372         case MONO_TYPE_VAR:
3373                 return mono_metadata_generic_param_equal (
3374                         t1->data.generic_param, t2->data.generic_param, signature_only);
3375         case MONO_TYPE_MVAR:
3376                 return mono_metadata_generic_param_equal (
3377                         t1->data.generic_param, t2->data.generic_param, signature_only);
3378         default:
3379                 g_error ("implement type compare for %0x!", t1->type);
3380                 return FALSE;
3381         }
3382
3383         return FALSE;
3384 }
3385
3386 gboolean
3387 mono_metadata_type_equal (MonoType *t1, MonoType *t2)
3388 {
3389         return do_mono_metadata_type_equal (t1, t2, FALSE);
3390 }
3391
3392 /**
3393  * mono_metadata_signature_equal:
3394  * @sig1: a signature
3395  * @sig2: another signature
3396  *
3397  * Determine if @sig1 and @sig2 represent the same signature, with the
3398  * same number of arguments and the same types.
3399  * Returns: #TRUE if @sig1 and @sig2 are equal.
3400  */
3401 gboolean
3402 mono_metadata_signature_equal (MonoMethodSignature *sig1, MonoMethodSignature *sig2)
3403 {
3404         int i;
3405
3406         if (sig1->hasthis != sig2->hasthis || sig1->param_count != sig2->param_count)
3407                 return FALSE;
3408
3409         /*
3410          * We're just comparing the signatures of two methods here:
3411          *
3412          * If we have two generic methods `void Foo<U> (U u)' and `void Bar<V> (V v)',
3413          * U and V are equal here.
3414          *
3415          * That's what the `signature_only' argument of do_mono_metadata_type_equal() is for.
3416          */
3417
3418         for (i = 0; i < sig1->param_count; i++) { 
3419                 MonoType *p1 = sig1->params[i];
3420                 MonoType *p2 = sig2->params[i];
3421                 
3422                 /* if (p1->attrs != p2->attrs)
3423                         return FALSE;
3424                 */
3425                 if (!do_mono_metadata_type_equal (p1, p2, TRUE))
3426                         return FALSE;
3427         }
3428
3429         if (!do_mono_metadata_type_equal (sig1->ret, sig2->ret, TRUE))
3430                 return FALSE;
3431         return TRUE;
3432 }
3433
3434 guint
3435 mono_signature_hash (MonoMethodSignature *sig)
3436 {
3437         guint i, res = sig->ret->type;
3438
3439         for (i = 0; i < sig->param_count; i++)
3440                 res = (res << 5) - res + mono_type_hash (sig->params[i]);
3441
3442         return res;
3443 }
3444
3445 /*
3446  * mono_metadata_encode_value:
3447  * @value: value to encode
3448  * @buf: buffer where to write the compressed representation
3449  * @endbuf: pointer updated to point at the end of the encoded output
3450  *
3451  * Encodes the value @value in the compressed representation used
3452  * in metadata and stores the result in @buf. @buf needs to be big
3453  * enough to hold the data (4 bytes).
3454  */
3455 void
3456 mono_metadata_encode_value (guint32 value, char *buf, char **endbuf)
3457 {
3458         char *p = buf;
3459         
3460         if (value < 0x80)
3461                 *p++ = value;
3462         else if (value < 0x4000) {
3463                 p [0] = 0x80 | (value >> 8);
3464                 p [1] = value & 0xff;
3465                 p += 2;
3466         } else {
3467                 p [0] = (value >> 24) | 0xc0;
3468                 p [1] = (value >> 16) & 0xff;
3469                 p [2] = (value >> 8) & 0xff;
3470                 p [3] = value & 0xff;
3471                 p += 4;
3472         }
3473         if (endbuf)
3474                 *endbuf = p;
3475 }
3476
3477 /*
3478  * mono_metadata_field_info:
3479  * @meta: the Image the field is defined in
3480  * @index: the index in the field table representing the field
3481  * @offset: a pointer to an integer where to store the offset that 
3482  * may have been specified for the field in a FieldLayout table
3483  * @rva: a pointer to the RVA of the field data in the image that
3484  * may have been defined in a FieldRVA table
3485  * @marshal_spec: a pointer to the marshal spec that may have been 
3486  * defined for the field in a FieldMarshal table.
3487  *
3488  * Gather info for field @index that may have been defined in the FieldLayout, 
3489  * FieldRVA and FieldMarshal tables.
3490  * Either of offset, rva and marshal_spec can be NULL if you're not interested 
3491  * in the data.
3492  */
3493 void
3494 mono_metadata_field_info (MonoImage *meta, guint32 index, guint32 *offset, guint32 *rva, 
3495                           MonoMarshalSpec **marshal_spec)
3496 {
3497         MonoTableInfo *tdef;
3498         locator_t loc;
3499
3500         loc.idx = index + 1;
3501         if (offset) {
3502                 tdef = &meta->tables [MONO_TABLE_FIELDLAYOUT];
3503
3504                 loc.col_idx = MONO_FIELD_LAYOUT_FIELD;
3505                 loc.t = tdef;
3506
3507                 if (tdef->base && bsearch (&loc, tdef->base, tdef->rows, tdef->row_size, table_locator)) {
3508                         *offset = mono_metadata_decode_row_col (tdef, loc.result, MONO_FIELD_LAYOUT_OFFSET);
3509                 } else {
3510                         *offset = (guint32)-1;
3511                 }
3512         }
3513         if (rva) {
3514                 tdef = &meta->tables [MONO_TABLE_FIELDRVA];
3515
3516                 loc.col_idx = MONO_FIELD_RVA_FIELD;
3517                 loc.t = tdef;
3518                 
3519                 if (tdef->base && bsearch (&loc, tdef->base, tdef->rows, tdef->row_size, table_locator)) {
3520                         /*
3521                          * LAMESPEC: There is no signature, no nothing, just the raw data.
3522                          */
3523                         *rva = mono_metadata_decode_row_col (tdef, loc.result, MONO_FIELD_RVA_RVA);
3524                 } else {
3525                         *rva = 0;
3526                 }
3527         }
3528         if (marshal_spec) {
3529                 const char *p;
3530                 
3531                 if ((p = mono_metadata_get_marshal_info (meta, index, TRUE))) {
3532                         *marshal_spec = mono_metadata_parse_marshal_spec (meta, p);
3533                 }
3534         }
3535
3536 }
3537
3538 /*
3539  * mono_metadata_get_constant_index:
3540  * @meta: the Image the field is defined in
3541  * @index: the token that may have a row defined in the constants table
3542  * @hint: possible position for the row
3543  *
3544  * @token must be a FieldDef, ParamDef or PropertyDef token.
3545  *
3546  * Returns: the index into the Constants table or 0 if not found.
3547  */
3548 guint32
3549 mono_metadata_get_constant_index (MonoImage *meta, guint32 token, guint32 hint)
3550 {
3551         MonoTableInfo *tdef;
3552         locator_t loc;
3553         guint32 index = mono_metadata_token_index (token);
3554
3555         tdef = &meta->tables [MONO_TABLE_CONSTANT];
3556         index <<= MONO_HASCONSTANT_BITS;
3557         switch (mono_metadata_token_table (token)) {
3558         case MONO_TABLE_FIELD:
3559                 index |= MONO_HASCONSTANT_FIEDDEF;
3560                 break;
3561         case MONO_TABLE_PARAM:
3562                 index |= MONO_HASCONSTANT_PARAM;
3563                 break;
3564         case MONO_TABLE_PROPERTY:
3565                 index |= MONO_HASCONSTANT_PROPERTY;
3566                 break;
3567         default:
3568                 g_warning ("Not a valid token for the constant table: 0x%08x", token);
3569                 return 0;
3570         }
3571         loc.idx = index;
3572         loc.col_idx = MONO_CONSTANT_PARENT;
3573         loc.t = tdef;
3574
3575         if ((hint > 0) && (hint < tdef->rows) && (mono_metadata_decode_row_col (tdef, hint - 1, MONO_CONSTANT_PARENT) == index))
3576                 return hint;
3577
3578         if (tdef->base && bsearch (&loc, tdef->base, tdef->rows, tdef->row_size, table_locator)) {
3579                 return loc.result + 1;
3580         }
3581         return 0;
3582 }
3583
3584 /*
3585  * mono_metadata_events_from_typedef:
3586  * @meta: metadata context
3587  * @index: 0-based index (in the TypeDef table) describing a type
3588  *
3589  * Returns: the 0-based index in the Event table for the events in the
3590  * type. The last event that belongs to the type (plus 1) is stored
3591  * in the @end_idx pointer.
3592  */
3593 guint32
3594 mono_metadata_events_from_typedef (MonoImage *meta, guint32 index, guint *end_idx)
3595 {
3596         locator_t loc;
3597         guint32 start, end;
3598         MonoTableInfo *tdef  = &meta->tables [MONO_TABLE_EVENTMAP];
3599
3600         *end_idx = 0;
3601         
3602         if (!tdef->base)
3603                 return 0;
3604
3605         loc.t = tdef;
3606         loc.col_idx = MONO_EVENT_MAP_PARENT;
3607         loc.idx = index + 1;
3608
3609         if (!bsearch (&loc, tdef->base, tdef->rows, tdef->row_size, table_locator))
3610                 return 0;
3611         
3612         start = mono_metadata_decode_row_col (tdef, loc.result, MONO_EVENT_MAP_EVENTLIST);
3613         if (loc.result + 1 < tdef->rows) {
3614                 end = mono_metadata_decode_row_col (tdef, loc.result + 1, MONO_EVENT_MAP_EVENTLIST) - 1;
3615         } else {
3616                 end = meta->tables [MONO_TABLE_EVENT].rows;
3617         }
3618
3619         *end_idx = end;
3620         return start - 1;
3621 }
3622
3623 /*
3624  * mono_metadata_methods_from_event:
3625  * @meta: metadata context
3626  * @index: 0-based index (in the Event table) describing a event
3627  *
3628  * Returns: the 0-based index in the MethodDef table for the methods in the
3629  * event. The last method that belongs to the event (plus 1) is stored
3630  * in the @end_idx pointer.
3631  */
3632 guint32
3633 mono_metadata_methods_from_event   (MonoImage *meta, guint32 index, guint *end_idx)
3634 {
3635         locator_t loc;
3636         guint start, end;
3637         guint32 cols [MONO_METHOD_SEMA_SIZE];
3638         MonoTableInfo *msemt = &meta->tables [MONO_TABLE_METHODSEMANTICS];
3639
3640         *end_idx = 0;
3641         if (!msemt->base)
3642                 return 0;
3643
3644         loc.t = msemt;
3645         loc.col_idx = MONO_METHOD_SEMA_ASSOCIATION;
3646         loc.idx = ((index + 1) << MONO_HAS_SEMANTICS_BITS) | MONO_HAS_SEMANTICS_EVENT; /* Method association coded index */
3647
3648         if (!bsearch (&loc, msemt->base, msemt->rows, msemt->row_size, table_locator))
3649                 return 0;
3650
3651         start = loc.result;
3652         /*
3653          * We may end up in the middle of the rows... 
3654          */
3655         while (start > 0) {
3656                 if (loc.idx == mono_metadata_decode_row_col (msemt, start - 1, MONO_METHOD_SEMA_ASSOCIATION))
3657                         start--;
3658                 else
3659                         break;
3660         }
3661         end = start + 1;
3662         while (end < msemt->rows) {
3663                 mono_metadata_decode_row (msemt, end, cols, MONO_METHOD_SEMA_SIZE);
3664                 if (cols [MONO_METHOD_SEMA_ASSOCIATION] != loc.idx)
3665                         break;
3666                 ++end;
3667         }
3668         *end_idx = end;
3669         return start;
3670 }
3671
3672 /*
3673  * mono_metadata_properties_from_typedef:
3674  * @meta: metadata context
3675  * @index: 0-based index (in the TypeDef table) describing a type
3676  *
3677  * Returns: the 0-based index in the Property table for the properties in the
3678  * type. The last property that belongs to the type (plus 1) is stored
3679  * in the @end_idx pointer.
3680  */
3681 guint32
3682 mono_metadata_properties_from_typedef (MonoImage *meta, guint32 index, guint *end_idx)
3683 {
3684         locator_t loc;
3685         guint32 start, end;
3686         MonoTableInfo *tdef  = &meta->tables [MONO_TABLE_PROPERTYMAP];
3687
3688         *end_idx = 0;
3689         
3690         if (!tdef->base)
3691                 return 0;
3692
3693         loc.t = tdef;
3694         loc.col_idx = MONO_PROPERTY_MAP_PARENT;
3695         loc.idx = index + 1;
3696
3697         if (!bsearch (&loc, tdef->base, tdef->rows, tdef->row_size, table_locator))
3698                 return 0;
3699         
3700         start = mono_metadata_decode_row_col (tdef, loc.result, MONO_PROPERTY_MAP_PROPERTY_LIST);
3701         if (loc.result + 1 < tdef->rows) {
3702                 end = mono_metadata_decode_row_col (tdef, loc.result + 1, MONO_PROPERTY_MAP_PROPERTY_LIST) - 1;
3703         } else {
3704                 end = meta->tables [MONO_TABLE_PROPERTY].rows;
3705         }
3706
3707         *end_idx = end;
3708         return start - 1;
3709 }
3710
3711 /*
3712  * mono_metadata_methods_from_property:
3713  * @meta: metadata context
3714  * @index: 0-based index (in the PropertyDef table) describing a property
3715  *
3716  * Returns: the 0-based index in the MethodDef table for the methods in the
3717  * property. The last method that belongs to the property (plus 1) is stored
3718  * in the @end_idx pointer.
3719  */
3720 guint32
3721 mono_metadata_methods_from_property   (MonoImage *meta, guint32 index, guint *end_idx)
3722 {
3723         locator_t loc;
3724         guint start, end;
3725         guint32 cols [MONO_METHOD_SEMA_SIZE];
3726         MonoTableInfo *msemt = &meta->tables [MONO_TABLE_METHODSEMANTICS];
3727
3728         *end_idx = 0;
3729         if (!msemt->base)
3730                 return 0;
3731
3732         loc.t = msemt;
3733         loc.col_idx = MONO_METHOD_SEMA_ASSOCIATION;
3734         loc.idx = ((index + 1) << MONO_HAS_SEMANTICS_BITS) | MONO_HAS_SEMANTICS_PROPERTY; /* Method association coded index */
3735
3736         if (!bsearch (&loc, msemt->base, msemt->rows, msemt->row_size, table_locator))
3737                 return 0;
3738
3739         start = loc.result;
3740         /*
3741          * We may end up in the middle of the rows... 
3742          */
3743         while (start > 0) {
3744                 if (loc.idx == mono_metadata_decode_row_col (msemt, start - 1, MONO_METHOD_SEMA_ASSOCIATION))
3745                         start--;
3746                 else
3747                         break;
3748         }
3749         end = start + 1;
3750         while (end < msemt->rows) {
3751                 mono_metadata_decode_row (msemt, end, cols, MONO_METHOD_SEMA_SIZE);
3752                 if (cols [MONO_METHOD_SEMA_ASSOCIATION] != loc.idx)
3753                         break;
3754                 ++end;
3755         }
3756         *end_idx = end;
3757         return start;
3758 }
3759
3760 guint32
3761 mono_metadata_implmap_from_method (MonoImage *meta, guint32 method_idx)
3762 {
3763         locator_t loc;
3764         MonoTableInfo *tdef  = &meta->tables [MONO_TABLE_IMPLMAP];
3765
3766         if (!tdef->base)
3767                 return 0;
3768
3769         loc.t = tdef;
3770         loc.col_idx = MONO_IMPLMAP_MEMBER;
3771         loc.idx = ((method_idx + 1) << MONO_MEMBERFORWD_BITS) | MONO_MEMBERFORWD_METHODDEF;
3772
3773         if (!bsearch (&loc, tdef->base, tdef->rows, tdef->row_size, table_locator))
3774                 return 0;
3775
3776         return loc.result + 1;
3777 }
3778
3779 /**
3780  * @image: context where the image is created
3781  * @type_spec:  typespec token
3782  *
3783  * Creates a MonoType representing the TypeSpec indexed by the @type_spec
3784  * token.
3785  */
3786 MonoType *
3787 mono_type_create_from_typespec (MonoImage *image, guint32 type_spec)
3788 {
3789         guint32 idx = mono_metadata_token_index (type_spec);
3790         MonoTableInfo *t;
3791         guint32 cols [MONO_TYPESPEC_SIZE];
3792         const char *ptr;
3793         guint32 len;
3794         MonoType *type;
3795
3796         mono_loader_lock ();
3797
3798         type = g_hash_table_lookup (image->typespec_cache, GUINT_TO_POINTER (type_spec));
3799         if (type) {
3800                 mono_loader_unlock ();
3801                 return type;
3802         }
3803
3804         t = &image->tables [MONO_TABLE_TYPESPEC];
3805
3806         mono_metadata_decode_row (t, idx-1, cols, MONO_TYPESPEC_SIZE);
3807         ptr = mono_metadata_blob_heap (image, cols [MONO_TYPESPEC_SIGNATURE]);
3808         len = mono_metadata_decode_value (ptr, &ptr);
3809
3810         type = g_new0 (MonoType, 1);
3811
3812         g_hash_table_insert (image->typespec_cache, GUINT_TO_POINTER (type_spec), type);
3813
3814         if (*ptr == MONO_TYPE_BYREF) {
3815                 type->byref = 1;
3816                 ptr++;
3817         }
3818
3819         if (!do_mono_metadata_parse_type (type, image, NULL, ptr, &ptr)) {
3820                 g_hash_table_remove (image->typespec_cache, GUINT_TO_POINTER (type_spec));
3821                 g_free (type);
3822                 mono_loader_unlock ();
3823                 return NULL;
3824         }
3825
3826         mono_loader_unlock ();
3827
3828         return type;
3829 }
3830
3831 MonoMarshalSpec *
3832 mono_metadata_parse_marshal_spec (MonoImage *image, const char *ptr)
3833 {
3834         MonoMarshalSpec *res;
3835         int len;
3836         const char *start = ptr;
3837
3838         /* fixme: this is incomplete, but I cant find more infos in the specs */
3839
3840         res = g_new0 (MonoMarshalSpec, 1);
3841         
3842         len = mono_metadata_decode_value (ptr, &ptr);
3843         res->native = *ptr++;
3844
3845         if (res->native == MONO_NATIVE_LPARRAY) {
3846                 res->data.array_data.param_num = -1;
3847                 res->data.array_data.num_elem = -1;
3848                 res->data.array_data.elem_mult = -1;
3849
3850                 if (ptr - start <= len)
3851                         res->data.array_data.elem_type = *ptr++;
3852                 if (ptr - start <= len)
3853                         res->data.array_data.param_num = mono_metadata_decode_value (ptr, &ptr);
3854                 if (ptr - start <= len)
3855                         res->data.array_data.num_elem = mono_metadata_decode_value (ptr, &ptr);
3856                 if (ptr - start <= len) {
3857                         /*
3858                          * LAMESPEC: Older spec versions say this parameter comes before 
3859                          * num_elem. Never spec versions don't talk about elem_mult at
3860                          * all, but csc still emits it, and it is used to distinguish
3861                          * between param_num being 0, and param_num being omitted.
3862                          * So if (param_num == 0) && (num_elem > 0), then
3863                          * elem_mult == 0 -> the array size is num_elem
3864                          * elem_mult == 1 -> the array size is @param_num + num_elem
3865                          */
3866                         res->data.array_data.elem_mult = mono_metadata_decode_value (ptr, &ptr);
3867                 }
3868         } 
3869
3870         if (res->native == MONO_NATIVE_BYVALTSTR) {
3871                 if (ptr - start <= len)
3872                         res->data.array_data.num_elem = mono_metadata_decode_value (ptr, &ptr);
3873         }
3874
3875         if (res->native == MONO_NATIVE_BYVALARRAY) {
3876                 if (ptr - start <= len)
3877                         res->data.array_data.num_elem = mono_metadata_decode_value (ptr, &ptr);
3878         }
3879         
3880         if (res->native == MONO_NATIVE_CUSTOM) {
3881                 /* skip unused type guid */
3882                 len = mono_metadata_decode_value (ptr, &ptr);
3883                 ptr += len;
3884                 /* skip unused native type name */
3885                 len = mono_metadata_decode_value (ptr, &ptr);
3886                 ptr += len;
3887                 /* read custom marshaler type name */
3888                 len = mono_metadata_decode_value (ptr, &ptr);
3889                 res->data.custom_data.custom_name = g_strndup (ptr, len);               
3890                 ptr += len;
3891                 /* read cookie string */
3892                 len = mono_metadata_decode_value (ptr, &ptr);
3893                 res->data.custom_data.cookie = g_strndup (ptr, len);
3894         }
3895
3896         if (res->native == MONO_NATIVE_SAFEARRAY) {
3897                 res->data.safearray_data.elem_type = 0;
3898                 res->data.safearray_data.num_elem = 0;
3899                 if (ptr - start <= len)
3900                         res->data.safearray_data.elem_type = *ptr++;
3901                 if (ptr - start <= len)
3902                         res->data.safearray_data.num_elem = *ptr++;
3903         }
3904         return res;
3905 }
3906
3907 void 
3908 mono_metadata_free_marshal_spec (MonoMarshalSpec *spec)
3909 {
3910         if (spec->native == MONO_NATIVE_CUSTOM) {
3911                 g_free (spec->data.custom_data.custom_name);
3912                 g_free (spec->data.custom_data.cookie);
3913         }
3914         g_free (spec);
3915 }
3916         
3917 guint32
3918 mono_type_to_unmanaged (MonoType *type, MonoMarshalSpec *mspec, gboolean as_field,
3919                         gboolean unicode, MonoMarshalConv *conv) 
3920 {
3921         MonoMarshalConv dummy_conv;
3922         int t = type->type;
3923
3924         if (!conv)
3925                 conv = &dummy_conv;
3926
3927         *conv = MONO_MARSHAL_CONV_NONE;
3928
3929         if (type->byref)
3930                 return MONO_NATIVE_UINT;
3931
3932 handle_enum:
3933         switch (t) {
3934         case MONO_TYPE_BOOLEAN: 
3935                 if (mspec) {
3936                         switch (mspec->native) {
3937                         case MONO_NATIVE_VARIANTBOOL:
3938                                 *conv = MONO_MARSHAL_CONV_BOOL_VARIANTBOOL;
3939                                 return MONO_NATIVE_VARIANTBOOL;
3940                         case MONO_NATIVE_BOOLEAN:
3941                                 *conv = MONO_MARSHAL_CONV_BOOL_I4;
3942                                 return MONO_NATIVE_BOOLEAN;
3943                         case MONO_NATIVE_I1:
3944                         case MONO_NATIVE_U1:
3945                                 return mspec->native;
3946                         default:
3947                                 g_error ("cant marshal bool to native type %02x", mspec->native);
3948                         }
3949                 }
3950                 *conv = MONO_MARSHAL_CONV_BOOL_I4;
3951                 return MONO_NATIVE_BOOLEAN;
3952         case MONO_TYPE_CHAR: return MONO_NATIVE_U2;
3953         case MONO_TYPE_I1: return MONO_NATIVE_I1;
3954         case MONO_TYPE_U1: return MONO_NATIVE_U1;
3955         case MONO_TYPE_I2: return MONO_NATIVE_I2;
3956         case MONO_TYPE_U2: return MONO_NATIVE_U2;
3957         case MONO_TYPE_I4: return MONO_NATIVE_I4;
3958         case MONO_TYPE_U4: return MONO_NATIVE_U4;
3959         case MONO_TYPE_I8: return MONO_NATIVE_I8;
3960         case MONO_TYPE_U8: return MONO_NATIVE_U8;
3961         case MONO_TYPE_R4: return MONO_NATIVE_R4;
3962         case MONO_TYPE_R8: return MONO_NATIVE_R8;
3963         case MONO_TYPE_STRING:
3964                 if (mspec) {
3965                         switch (mspec->native) {
3966                         case MONO_NATIVE_BSTR:
3967                                 *conv = MONO_MARSHAL_CONV_STR_BSTR;
3968                                 return MONO_NATIVE_BSTR;
3969                         case MONO_NATIVE_LPSTR:
3970                                 *conv = MONO_MARSHAL_CONV_STR_LPSTR;
3971                                 return MONO_NATIVE_LPSTR;
3972                         case MONO_NATIVE_LPWSTR:
3973                                 *conv = MONO_MARSHAL_CONV_STR_LPWSTR;
3974                                 return MONO_NATIVE_LPWSTR;
3975                         case MONO_NATIVE_LPTSTR:
3976                                 *conv = MONO_MARSHAL_CONV_STR_LPTSTR;
3977                                 return MONO_NATIVE_LPTSTR;
3978                         case MONO_NATIVE_ANSIBSTR:
3979                                 *conv = MONO_MARSHAL_CONV_STR_ANSIBSTR;
3980                                 return MONO_NATIVE_ANSIBSTR;
3981                         case MONO_NATIVE_TBSTR:
3982                                 *conv = MONO_MARSHAL_CONV_STR_TBSTR;
3983                                 return MONO_NATIVE_TBSTR;
3984                         case MONO_NATIVE_BYVALTSTR:
3985                                 if (unicode)
3986                                         *conv = MONO_MARSHAL_CONV_STR_BYVALWSTR;
3987                                 else
3988                                         *conv = MONO_MARSHAL_CONV_STR_BYVALSTR;
3989                                 return MONO_NATIVE_BYVALTSTR;
3990                         default:
3991                                 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);
3992                         }
3993                 }       
3994                 *conv = MONO_MARSHAL_CONV_STR_LPTSTR;
3995                 return MONO_NATIVE_LPTSTR; 
3996         case MONO_TYPE_PTR: return MONO_NATIVE_UINT;
3997         case MONO_TYPE_VALUETYPE: /*FIXME*/
3998                 if (type->data.klass->enumtype) {
3999                         t = type->data.klass->enum_basetype->type;
4000                         goto handle_enum;
4001                 }
4002                 return MONO_NATIVE_STRUCT;
4003         case MONO_TYPE_SZARRAY: 
4004         case MONO_TYPE_ARRAY: 
4005                 if (mspec) {
4006                         switch (mspec->native) {
4007                         case MONO_NATIVE_BYVALARRAY:
4008                                 if ((type->data.klass->element_class == mono_defaults.char_class) && !unicode)
4009                                         *conv = MONO_MARSHAL_CONV_ARRAY_BYVALCHARARRAY;
4010                                 else
4011                                         *conv = MONO_MARSHAL_CONV_ARRAY_BYVALARRAY;
4012                                 return MONO_NATIVE_BYVALARRAY;
4013                         case MONO_NATIVE_SAFEARRAY:
4014                                 *conv = MONO_MARSHAL_CONV_ARRAY_SAVEARRAY;
4015                                 return MONO_NATIVE_SAFEARRAY;
4016                         case MONO_NATIVE_LPARRAY:                               
4017                                 *conv = MONO_MARSHAL_CONV_ARRAY_LPARRAY;
4018                                 return MONO_NATIVE_LPARRAY;
4019                         default:
4020                                 g_error ("cant marshal array as native type %02x", mspec->native);
4021                         }
4022                 }       
4023
4024                 *conv = MONO_MARSHAL_CONV_ARRAY_LPARRAY;
4025                 return MONO_NATIVE_LPARRAY;
4026         case MONO_TYPE_I: return MONO_NATIVE_INT;
4027         case MONO_TYPE_U: return MONO_NATIVE_UINT;
4028         case MONO_TYPE_CLASS: 
4029         case MONO_TYPE_OBJECT: {
4030                 /* FIXME : we need to handle ArrayList and StringBuilder here, probably */
4031                 if (mspec) {
4032                         switch (mspec->native) {
4033                         case MONO_NATIVE_STRUCT:
4034                                 return MONO_NATIVE_STRUCT;
4035                         case MONO_NATIVE_INTERFACE:
4036                                 *conv = MONO_MARSHAL_CONV_OBJECT_INTERFACE;
4037                                 return MONO_NATIVE_INTERFACE;
4038                         case MONO_NATIVE_IDISPATCH:
4039                                 *conv = MONO_MARSHAL_CONV_OBJECT_IDISPATCH;
4040                                 return MONO_NATIVE_IDISPATCH;
4041                         case MONO_NATIVE_IUNKNOWN:
4042                                 *conv = MONO_MARSHAL_CONV_OBJECT_IUNKNOWN;
4043                                 return MONO_NATIVE_IUNKNOWN;
4044                         case MONO_NATIVE_FUNC:
4045                                 if (t == MONO_TYPE_CLASS && (type->data.klass == mono_defaults.multicastdelegate_class ||
4046                                                                                          type->data.klass == mono_defaults.delegate_class || 
4047                                                                                          type->data.klass->parent == mono_defaults.multicastdelegate_class)) {
4048                                         *conv = MONO_MARSHAL_CONV_DEL_FTN;
4049                                         return MONO_NATIVE_FUNC;
4050                                 }
4051                                 /* Fall through */
4052                         default:
4053                                 g_error ("cant marshal object as native type %02x", mspec->native);
4054                         }
4055                 }
4056                 if (t == MONO_TYPE_CLASS && (type->data.klass == mono_defaults.multicastdelegate_class ||
4057                                              type->data.klass == mono_defaults.delegate_class || 
4058                                              type->data.klass->parent == mono_defaults.multicastdelegate_class)) {
4059                         *conv = MONO_MARSHAL_CONV_DEL_FTN;
4060                         return MONO_NATIVE_FUNC;
4061                 }
4062                 *conv = MONO_MARSHAL_CONV_OBJECT_STRUCT;
4063                 return MONO_NATIVE_STRUCT;
4064         }
4065         case MONO_TYPE_FNPTR: return MONO_NATIVE_FUNC;
4066         case MONO_TYPE_GENERICINST:
4067                 type = &type->data.generic_class->container_class->byval_arg;
4068                 t = type->type;
4069                 goto handle_enum;
4070         case MONO_TYPE_TYPEDBYREF:
4071         default:
4072                 g_error ("type 0x%02x not handled in marshal", t);
4073         }
4074         return MONO_NATIVE_MAX;
4075 }
4076
4077 const char*
4078 mono_metadata_get_marshal_info (MonoImage *meta, guint32 idx, gboolean is_field)
4079 {
4080         locator_t loc;
4081         MonoTableInfo *tdef  = &meta->tables [MONO_TABLE_FIELDMARSHAL];
4082
4083         if (!tdef->base)
4084                 return NULL;
4085
4086         loc.t = tdef;
4087         loc.col_idx = MONO_FIELD_MARSHAL_PARENT;
4088         loc.idx = ((idx + 1) << MONO_HAS_FIELD_MARSHAL_BITS) | (is_field? MONO_HAS_FIELD_MARSHAL_FIELDSREF: MONO_HAS_FIELD_MARSHAL_PARAMDEF);
4089
4090         if (!bsearch (&loc, tdef->base, tdef->rows, tdef->row_size, table_locator))
4091                 return NULL;
4092
4093         return mono_metadata_blob_heap (meta, mono_metadata_decode_row_col (tdef, loc.result, MONO_FIELD_MARSHAL_NATIVE_TYPE));
4094 }
4095
4096 static MonoMethod*
4097 method_from_method_def_or_ref (MonoImage *m, guint32 tok, MonoGenericContext *context)
4098 {
4099         guint32 idx = tok >> MONO_METHODDEFORREF_BITS;
4100         switch (tok & MONO_METHODDEFORREF_MASK) {
4101         case MONO_METHODDEFORREF_METHODDEF:
4102                 return mono_get_method_full (m, MONO_TOKEN_METHOD_DEF | idx, NULL, context);
4103         case MONO_METHODDEFORREF_METHODREF:
4104                 return mono_get_method_full (m, MONO_TOKEN_MEMBER_REF | idx, NULL, context);
4105         }
4106         g_assert_not_reached ();
4107         return NULL;
4108 }
4109
4110 /*
4111  * mono_class_get_overrides_full:
4112  *
4113  *   Return the method overrides belonging to class @type_token in @overrides, and
4114  * the number of overrides in @num_overrides.
4115  *
4116  * Returns: TRUE on success, FALSE on failure.
4117  */
4118 gboolean
4119 mono_class_get_overrides_full (MonoImage *image, guint32 type_token, MonoMethod ***overrides, gint32 *num_overrides,
4120                                MonoGenericContext *generic_context)
4121 {
4122         locator_t loc;
4123         MonoTableInfo *tdef  = &image->tables [MONO_TABLE_METHODIMPL];
4124         guint32 start, end;
4125         gint32 i, num;
4126         guint32 cols [MONO_METHODIMPL_SIZE];
4127         MonoMethod **result;
4128         gint32 ok = TRUE;
4129         
4130         *overrides = NULL;
4131         if (num_overrides)
4132                 *num_overrides = 0;
4133
4134         if (!tdef->base)
4135                 return TRUE;
4136
4137         loc.t = tdef;
4138         loc.col_idx = MONO_METHODIMPL_CLASS;
4139         loc.idx = mono_metadata_token_index (type_token);
4140
4141         if (!bsearch (&loc, tdef->base, tdef->rows, tdef->row_size, table_locator))
4142                 return TRUE;
4143
4144         start = loc.result;
4145         end = start + 1;
4146         /*
4147          * We may end up in the middle of the rows... 
4148          */
4149         while (start > 0) {
4150                 if (loc.idx == mono_metadata_decode_row_col (tdef, start - 1, MONO_METHODIMPL_CLASS))
4151                         start--;
4152                 else
4153                         break;
4154         }
4155         while (end < tdef->rows) {
4156                 if (loc.idx == mono_metadata_decode_row_col (tdef, end, MONO_METHODIMPL_CLASS))
4157                         end++;
4158                 else
4159                         break;
4160         }
4161         num = end - start;
4162         result = g_new (MonoMethod*, num * 2);
4163         for (i = 0; i < num; ++i) {
4164                 MonoMethod *method;
4165
4166                 mono_metadata_decode_row (tdef, start + i, cols, MONO_METHODIMPL_SIZE);
4167                 method = method_from_method_def_or_ref (
4168                         image, cols [MONO_METHODIMPL_DECLARATION], generic_context);
4169                 if (method == NULL)
4170                         ok = FALSE;
4171                 result [i * 2] = method;
4172                 method = method_from_method_def_or_ref (
4173                         image, cols [MONO_METHODIMPL_BODY], generic_context);
4174                 if (method == NULL)
4175                         ok = FALSE;
4176                 result [i * 2 + 1] = method;
4177         }
4178
4179         *overrides = result;
4180         if (num_overrides)
4181                 *num_overrides = num;
4182         return ok;
4183 }
4184
4185 /**
4186  * mono_guid_to_string:
4187  *
4188  * Converts a 16 byte Microsoft GUID to the standard string representation.
4189  */
4190 char *
4191 mono_guid_to_string (const guint8 *guid)
4192 {
4193         return g_strdup_printf ("%02X%02X%02X%02X-%02X%02X-%02X%02X-%02X%02X-%02X%02X%02X%02X%02X%02X", 
4194                                 guid[3], guid[2], guid[1], guid[0],
4195                                 guid[5], guid[4],
4196                                 guid[7], guid[6],
4197                                 guid[8], guid[9],
4198                                 guid[10], guid[11], guid[12], guid[13], guid[14], guid[15]);
4199 }
4200
4201 static gboolean
4202 get_constraints (MonoImage *image, int owner, MonoClass ***constraints, MonoGenericContainer *container)
4203 {
4204         MonoTableInfo *tdef  = &image->tables [MONO_TABLE_GENERICPARAMCONSTRAINT];
4205         guint32 cols [MONO_GENPARCONSTRAINT_SIZE];
4206         guint32 i, token, found;
4207         MonoClass *klass, **res;
4208         GList *cons = NULL, *tmp;
4209         MonoGenericContext *context = &container->context;
4210
4211         /* FIXME: !container->klass => this is probably monodis */
4212         g_assert (!container->klass || context->gclass || context->gmethod);
4213
4214         *constraints = NULL;
4215         found = 0;
4216         for (i = 0; i < tdef->rows; ++i) {
4217                 mono_metadata_decode_row (tdef, i, cols, MONO_GENPARCONSTRAINT_SIZE);
4218                 if (cols [MONO_GENPARCONSTRAINT_GENERICPAR] == owner) {
4219                         token = mono_metadata_token_from_dor (cols [MONO_GENPARCONSTRAINT_CONSTRAINT]);
4220                         klass = mono_class_get_full (image, token, context);
4221                         cons = g_list_append (cons, klass);
4222                         ++found;
4223                 } else {
4224                         /* contiguous list finished */
4225                         if (found)
4226                                 break;
4227                 }
4228         }
4229         if (!found)
4230                 return TRUE;
4231         res = g_new0 (MonoClass*, found + 1);
4232         for (i = 0, tmp = cons; i < found; ++i, tmp = tmp->next) {
4233                 res [i] = tmp->data;
4234         }
4235         g_list_free (cons);
4236         *constraints = res;
4237         return TRUE;
4238 }
4239
4240 /*
4241  * mono_metadata_get_generic_param_row:
4242  *
4243  * @image:
4244  * @token: TypeOrMethodDef token, owner for GenericParam
4245  * @owner: coded token, set on return
4246  * 
4247  * Returns: 1-based row-id in the GenericParam table whose
4248  * owner is @token. 0 if not found.
4249  */
4250 guint32
4251 mono_metadata_get_generic_param_row (MonoImage *image, guint32 token, guint32 *owner)
4252 {
4253         MonoTableInfo *tdef  = &image->tables [MONO_TABLE_GENERICPARAM];
4254         guint32 cols [MONO_GENERICPARAM_SIZE];
4255         guint32 i;
4256
4257         g_assert (owner);
4258         if (!tdef->base)
4259                 return 0;
4260
4261         if (mono_metadata_token_table (token) == MONO_TABLE_TYPEDEF)
4262                 *owner = MONO_TYPEORMETHOD_TYPE;
4263         else if (mono_metadata_token_table (token) == MONO_TABLE_METHOD)
4264                 *owner = MONO_TYPEORMETHOD_METHOD;
4265         else {
4266                 g_error ("wrong token %x to get_generic_param_row", token);
4267                 return 0;
4268         }
4269         *owner |= mono_metadata_token_index (token) << MONO_TYPEORMETHOD_BITS;
4270
4271         for (i = 0; i < tdef->rows; ++i) {
4272                 mono_metadata_decode_row (tdef, i, cols, MONO_GENERICPARAM_SIZE);
4273                 if (cols [MONO_GENERICPARAM_OWNER] == *owner)
4274                         return i + 1;
4275         }
4276
4277         return 0;
4278 }
4279
4280 gboolean
4281 mono_metadata_has_generic_params (MonoImage *image, guint32 token)
4282 {
4283         guint32 owner;
4284         return mono_metadata_get_generic_param_row (image, token, &owner);
4285 }
4286
4287 /*
4288  * mono_metadata_load_generic_param_constraints:
4289  *
4290  * Load the generic parameter constraints for the newly created generic type or method
4291  * represented by @token and @container.  The @container is the new container which has
4292  * been returned by a call to mono_metadata_load_generic_params() with this @token.
4293  */
4294 void
4295 mono_metadata_load_generic_param_constraints (MonoImage *image, guint32 token,
4296                                               MonoGenericContainer *container)
4297 {
4298         guint32 start_row, i, owner;
4299         if (! (start_row = mono_metadata_get_generic_param_row (image, token, &owner)))
4300                 return;
4301         for (i = 0; i < container->type_argc; i++)
4302                 get_constraints (image, start_row + i, &container->type_params [i].constraints, container);
4303 }
4304
4305 /*
4306  * mono_metadata_load_generic_params:
4307  *
4308  * Load the type parameters from the type or method definition @token.
4309  *
4310  * Use this method after parsing a type or method definition to figure out whether it's a generic
4311  * type / method.  When parsing a method definition, @parent_container points to the generic container
4312  * of the current class, if any.
4313  *
4314  * Note: This method does not load the constraints: for typedefs, this has to be done after fully
4315  *       creating the type.
4316  *
4317  * Returns: NULL if @token is not a generic type or method definition or the new generic container.
4318  *
4319  */
4320 MonoGenericContainer *
4321 mono_metadata_load_generic_params (MonoImage *image, guint32 token, MonoGenericContainer *parent_container)
4322 {
4323         MonoTableInfo *tdef  = &image->tables [MONO_TABLE_GENERICPARAM];
4324         guint32 cols [MONO_GENERICPARAM_SIZE];
4325         guint32 i, owner = 0, n;
4326         MonoGenericContainer *container;
4327         MonoGenericParam *params;
4328
4329         if (!(i = mono_metadata_get_generic_param_row (image, token, &owner)))
4330                 return NULL;
4331         mono_metadata_decode_row (tdef, i - 1, cols, MONO_GENERICPARAM_SIZE);
4332         params = NULL;
4333         n = 0;
4334         container = g_new0 (MonoGenericContainer, 1);
4335         do {
4336                 n++;
4337                 params = g_realloc (params, sizeof (MonoGenericParam) * n);
4338                 params [n - 1].owner = container;
4339                 params [n - 1].pklass = NULL;
4340                 params [n - 1].method = NULL;
4341                 params [n - 1].flags = cols [MONO_GENERICPARAM_FLAGS];
4342                 params [n - 1].num = cols [MONO_GENERICPARAM_NUMBER];
4343                 params [n - 1].name = mono_metadata_string_heap (image, cols [MONO_GENERICPARAM_NAME]);
4344                 params [n - 1].constraints = NULL;
4345                 if (++i > tdef->rows)
4346                         break;
4347                 mono_metadata_decode_row (tdef, i - 1, cols, MONO_GENERICPARAM_SIZE);
4348         } while (cols [MONO_GENERICPARAM_OWNER] == owner);
4349
4350         container->type_argc = n;
4351         container->type_params = params;
4352         container->parent = parent_container;
4353
4354         if (mono_metadata_token_table (token) == MONO_TABLE_METHOD)
4355                 container->is_method = 1;
4356
4357         container->context.container = container;
4358
4359         return container;
4360 }
4361
4362 gboolean
4363 mono_type_is_byref (MonoType *type)
4364 {
4365         return type->byref;
4366 }
4367
4368 int
4369 mono_type_get_type (MonoType *type)
4370 {
4371         return type->type;
4372 }
4373
4374 /* For MONO_TYPE_FNPTR */
4375 MonoMethodSignature*
4376 mono_type_get_signature (MonoType *type)
4377 {
4378         return type->data.method;
4379 }
4380
4381 /* For MONO_TYPE_CLASS, VALUETYPE */
4382 MonoClass*
4383 mono_type_get_class (MonoType *type)
4384 {
4385         return type->data.klass;
4386 }
4387
4388 /* For MONO_TYPE_ARRAY */
4389 MonoArrayType*
4390 mono_type_get_array_type (MonoType *type)
4391 {
4392         return type->data.array;
4393 }
4394
4395 MonoClass*
4396 mono_type_get_modifiers (MonoType *type, gboolean *is_required, gpointer *iter)
4397 {
4398         /* FIXME: implement */
4399         return NULL;
4400 }
4401
4402 MonoType*
4403 mono_signature_get_return_type (MonoMethodSignature *sig)
4404 {
4405         return sig->ret;
4406 }
4407
4408 MonoType*
4409 mono_signature_get_params (MonoMethodSignature *sig, gpointer *iter)
4410 {
4411         MonoType** type;
4412         if (!iter)
4413                 return NULL;
4414         if (!*iter) {
4415                 /* start from the first */
4416                 if (sig->param_count) {
4417                         *iter = &sig->params [0];
4418                         return sig->params [0];
4419                 } else {
4420                         /* no method */
4421                         return NULL;
4422                 }
4423         }
4424         type = *iter;
4425         type++;
4426         if (type < &sig->params [sig->param_count]) {
4427                 *iter = type;
4428                 return *type;
4429         }
4430         return NULL;
4431 }
4432
4433 guint32
4434 mono_signature_get_param_count (MonoMethodSignature *sig)
4435 {
4436         return sig->param_count;
4437 }
4438
4439 guint32
4440 mono_signature_get_call_conv (MonoMethodSignature *sig)
4441 {
4442         return sig->call_convention;
4443 }
4444
4445 int
4446 mono_signature_vararg_start (MonoMethodSignature *sig)
4447 {
4448         return sig->sentinelpos;
4449 }
4450
4451 gboolean
4452 mono_signature_is_instance (MonoMethodSignature *sig)
4453 {
4454         return sig->hasthis;
4455 }
4456
4457 gboolean
4458 mono_signature_explicit_this (MonoMethodSignature *sig)
4459 {
4460         return sig->explicit_this;
4461 }
4462
4463 /* for use with allocated memory blocks (assumes alignment is to 8 bytes) */
4464 guint
4465 mono_aligned_addr_hash (gconstpointer ptr)
4466 {
4467         return GPOINTER_TO_UINT (ptr) >> 3;
4468 }
4469