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