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