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