Added a bulk of tests from Mainsoft repository.
[mono.git] / mono / metadata / loader.c
1 /*
2  * loader.c: Image Loader 
3  *
4  * Authors:
5  *   Paolo Molaro (lupus@ximian.com)
6  *   Miguel de Icaza (miguel@ximian.com)
7  *   Patrik Torstensson (patrik.torstensson@labs2.com)
8  *
9  * (C) 2001 Ximian, Inc.
10  *
11  * This file is used by the interpreter and the JIT engine to locate
12  * assemblies.  Used to load AssemblyRef and later to resolve various
13  * kinds of `Refs'.
14  *
15  * TODO:
16  *   This should keep track of the assembly versions that we are loading.
17  *
18  */
19 #include <config.h>
20 #include <glib.h>
21 #include <gmodule.h>
22 #include <stdlib.h>
23 #include <stdio.h>
24 #include <string.h>
25 #include <mono/metadata/metadata.h>
26 #include <mono/metadata/image.h>
27 #include <mono/metadata/assembly.h>
28 #include <mono/metadata/tokentype.h>
29 #include <mono/metadata/cil-coff.h>
30 #include <mono/metadata/tabledefs.h>
31 #include <mono/metadata/metadata-internals.h>
32 #include <mono/metadata/loader.h>
33 #include <mono/metadata/class-internals.h>
34 #include <mono/metadata/debug-helpers.h>
35 #include <mono/metadata/reflection.h>
36 #include <mono/utils/mono-logger.h>
37
38 MonoDefaults mono_defaults;
39
40 /*
41  * This lock protects the hash tables inside MonoImage used by the metadata 
42  * loading functions in class.c and loader.c.
43  */
44 static CRITICAL_SECTION loader_mutex;
45
46
47 /*
48  * This TLS variable contains the last type load error encountered by the loader.
49  */
50 guint32 loader_error_thread_id;
51
52 void
53 mono_loader_init ()
54 {
55         InitializeCriticalSection (&loader_mutex);
56
57         loader_error_thread_id = TlsAlloc ();
58 }
59
60 /*
61  * Handling of type load errors should be done as follows:
62  *
63  *   If something could not be loaded, the loader should call one of the
64  * mono_loader_set_error_XXX functions ()
65  * with the appropriate arguments, then return NULL to report the failure. The error 
66  * should be propagated until it reaches code which can throw managed exceptions. At that
67  * point, an exception should be thrown based on the information returned by
68  * mono_loader_get_error (). Then the error should be cleared by calling 
69  * mono_loader_clear_error ().
70  */
71
72 static void
73 set_loader_error (MonoLoaderError *error)
74 {
75         TlsSetValue (loader_error_thread_id, error);
76 }       
77
78 /*
79  * mono_loader_set_error_type_load:
80  *
81  *   Set the loader error for this thread. CLASS_NAME and ASSEMBLY_NAME should be
82  * dynamically allocated strings whose ownership is passed to this function.
83  */
84 void
85 mono_loader_set_error_type_load (char *class_name, char *assembly_name)
86 {
87         MonoLoaderError *error;
88
89         if (mono_loader_get_last_error ()) {
90                 g_free (class_name);
91                 g_free (assembly_name);
92                 return;
93         }
94
95         error = g_new0 (MonoLoaderError, 1);
96         error->kind = MONO_LOADER_ERROR_TYPE;
97         error->class_name = class_name;
98         error->assembly_name = assembly_name;
99
100         /* 
101          * This is not strictly needed, but some (most) of the loader code still
102          * can't deal with load errors, and this message is more helpful than an
103          * assert.
104          */
105         g_warning ("The class %s could not be loaded, used in %s", class_name, assembly_name);
106         
107         set_loader_error (error);
108 }
109
110 /*
111  * mono_loader_set_error_method_load:
112  *
113  *   Set the loader error for this thread. MEMBER_NAME should point to a string
114  * inside metadata.
115  */
116 void
117 mono_loader_set_error_method_load (MonoClass *klass, const char *member_name)
118 {
119         MonoLoaderError *error;
120
121         /* FIXME: Store the signature as well */
122         if (mono_loader_get_last_error ())
123                 return;
124
125         error = g_new0 (MonoLoaderError, 1);
126         error->kind = MONO_LOADER_ERROR_METHOD;
127         error->klass = klass;
128         error->member_name = member_name;
129
130         g_warning ("Missing member %s in type %s, assembly %s", member_name, mono_class_get_name (klass), klass->image->name);
131         
132         set_loader_error (error);
133 }
134
135 /*
136  * mono_loader_set_error_field_load:
137  *
138  *   Set the loader error for this thread. MEMBER_NAME should point to a string
139  * inside metadata.
140  */
141 void
142 mono_loader_set_error_field_load (MonoClass *klass, const char *member_name)
143 {
144         MonoLoaderError *error;
145
146         /* FIXME: Store the signature as well */
147         if (mono_loader_get_last_error ())
148                 return;
149
150         error = g_new0 (MonoLoaderError, 1);
151         error->kind = MONO_LOADER_ERROR_FIELD;
152         error->klass = klass;
153         error->member_name = member_name;
154         
155         set_loader_error (error);
156 }
157
158 /*
159  * mono_loader_get_last_error:
160  *
161  *   Returns information about the last type load exception encountered by the loader, or
162  * NULL. After use, the exception should be cleared by calling mono_loader_clear_error.
163  */
164 MonoLoaderError*
165 mono_loader_get_last_error (void)
166 {
167         return (MonoLoaderError*)TlsGetValue (loader_error_thread_id);
168 }
169
170 void
171 mono_loader_clear_error (void)
172 {
173         MonoLoaderError *ex = (MonoLoaderError*)TlsGetValue (loader_error_thread_id);
174
175         g_assert (ex);  
176
177         g_free (ex->class_name);
178         g_free (ex->assembly_name);
179         g_free (ex);
180
181         TlsSetValue (loader_error_thread_id, NULL);
182 }
183
184 static MonoClassField*
185 field_from_memberref (MonoImage *image, guint32 token, MonoClass **retklass,
186                       MonoGenericContext *context)
187 {
188         MonoClass *klass;
189         MonoClassField *field;
190         MonoTableInfo *tables = image->tables;
191         guint32 cols[6];
192         guint32 nindex, class;
193         const char *fname;
194         const char *ptr;
195         guint32 idx = mono_metadata_token_index (token);
196
197         if (image->dynamic) {
198                 MonoClassField *result = mono_lookup_dynamic_token (image, token);
199                 *retklass = result->parent;
200                 return result;
201         }
202
203         mono_metadata_decode_row (&tables [MONO_TABLE_MEMBERREF], idx-1, cols, MONO_MEMBERREF_SIZE);
204         nindex = cols [MONO_MEMBERREF_CLASS] >> MONO_MEMBERREF_PARENT_BITS;
205         class = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
206
207         fname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
208         
209         ptr = mono_metadata_blob_heap (image, cols [MONO_MEMBERREF_SIGNATURE]);
210         mono_metadata_decode_blob_size (ptr, &ptr);
211         /* we may want to check the signature here... */
212
213         switch (class) {
214         case MONO_MEMBERREF_PARENT_TYPEREF:
215                 klass = mono_class_from_typeref (image, MONO_TOKEN_TYPE_REF | nindex);
216                 if (!klass) {
217                         char *name = mono_class_name_from_token (image, MONO_TOKEN_TYPE_REF | nindex);
218                         g_warning ("Missing field %s in class %s (typeref index %d)", fname, name, nindex);
219                         g_free (name);
220                         return NULL;
221                 }
222                 mono_class_init (klass);
223                 if (retklass)
224                         *retklass = klass;
225                 field = mono_class_get_field_from_name (klass, fname);
226                 break;
227         case MONO_MEMBERREF_PARENT_TYPESPEC: {
228                 /*guint32 bcols [MONO_TYPESPEC_SIZE];
229                 guint32 len;
230                 MonoType *type;
231
232                 mono_metadata_decode_row (&tables [MONO_TABLE_TYPESPEC], nindex - 1, 
233                                           bcols, MONO_TYPESPEC_SIZE);
234                 ptr = mono_metadata_blob_heap (image, bcols [MONO_TYPESPEC_SIGNATURE]);
235                 len = mono_metadata_decode_value (ptr, &ptr);   
236                 type = mono_metadata_parse_type (image, MONO_PARSE_TYPE, 0, ptr, &ptr);
237
238                 klass = mono_class_from_mono_type (type);
239                 mono_class_init (klass);
240                 g_print ("type in sig: %s\n", klass->name);*/
241                 klass = mono_class_get_full (image, MONO_TOKEN_TYPE_SPEC | nindex, context);
242                 mono_class_init (klass);
243                 if (retklass)
244                         *retklass = klass;
245                 field = mono_class_get_field_from_name (klass, fname);
246                 break;
247         }
248         default:
249                 g_warning ("field load from %x", class);
250                 return NULL;
251         }
252
253         if (!field)
254                 mono_loader_set_error_field_load (klass, fname);
255
256         return field;
257 }
258
259 MonoClassField*
260 mono_field_from_token (MonoImage *image, guint32 token, MonoClass **retklass,
261                        MonoGenericContext *context)
262 {
263         MonoClass *k;
264         guint32 type;
265         MonoClassField *field;
266
267         if (image->dynamic) {
268                 MonoClassField *result = mono_lookup_dynamic_token (image, token);
269                 *retklass = result->parent;
270                 return result;
271         }
272
273         mono_loader_lock ();
274         if ((field = g_hash_table_lookup (image->field_cache, GUINT_TO_POINTER (token)))) {
275                 *retklass = field->parent;
276                 mono_loader_unlock ();
277                 return field;
278         }
279         mono_loader_unlock ();
280
281         if (mono_metadata_token_table (token) == MONO_TABLE_MEMBERREF)
282                 field = field_from_memberref (image, token, retklass, context);
283         else {
284                 type = mono_metadata_typedef_from_field (image, mono_metadata_token_index (token));
285                 if (!type)
286                         return NULL;
287                 k = mono_class_get (image, MONO_TOKEN_TYPE_DEF | type);
288                 mono_class_init (k);
289                 if (!k)
290                         return NULL;
291                 if (retklass)
292                         *retklass = k;
293                 field = mono_class_get_field (k, token);
294         }
295
296         mono_loader_lock ();
297         if (field && !field->parent->generic_class)
298                 g_hash_table_insert (image->field_cache, GUINT_TO_POINTER (token), field);
299         mono_loader_unlock ();
300         return field;
301 }
302
303 static gboolean
304 mono_metadata_signature_vararg_match (MonoMethodSignature *sig1, MonoMethodSignature *sig2)
305 {
306         int i;
307
308         if (sig1->hasthis != sig2->hasthis ||
309             sig1->sentinelpos != sig2->sentinelpos)
310                 return FALSE;
311
312         for (i = 0; i < sig1->sentinelpos; i++) { 
313                 MonoType *p1 = sig1->params[i];
314                 MonoType *p2 = sig2->params[i];
315                 
316                 /*if (p1->attrs != p2->attrs)
317                         return FALSE;
318                 */
319                 if (!mono_metadata_type_equal (p1, p2))
320                         return FALSE;
321         }
322
323         if (!mono_metadata_type_equal (sig1->ret, sig2->ret))
324                 return FALSE;
325         return TRUE;
326 }
327
328 static MonoMethod *
329 find_method_in_class (MonoClass *klass, const char *name, const char *qname, const char *fqname, MonoMethodSignature *sig)
330 {
331         int i;
332
333         mono_class_setup_methods (klass);
334         for (i = 0; i < klass->method.count; ++i) {
335                 MonoMethod *m = klass->methods [i];
336
337                 if (!((fqname && !strcmp (m->name, fqname)) ||
338                       (qname && !strcmp (m->name, qname)) || !strcmp (m->name, name)))
339                         continue;
340
341                 if (sig->call_convention == MONO_CALL_VARARG) {
342                         if (mono_metadata_signature_vararg_match (sig, mono_method_signature (m)))
343                                 return m;
344                 } else {
345                         MonoMethodSignature *msig = mono_method_signature (m);
346                         if (mono_metadata_signature_equal (sig, msig))
347                                 return m;
348                 }
349         }
350         return NULL;
351 }
352
353 static MonoMethod *
354 find_method (MonoClass *klass, MonoClass *ic, const char* name, MonoMethodSignature *sig)
355 {
356         int i;
357         char *qname, *fqname, *class_name;
358         gboolean is_interface;
359         MonoMethod *result = NULL;
360
361         is_interface = MONO_CLASS_IS_INTERFACE (klass);
362
363         if (ic) {
364                 class_name = mono_type_get_name_full (&ic->byval_arg, MONO_TYPE_NAME_FORMAT_IL);
365
366                 qname = g_strconcat (class_name, ".", name, NULL); 
367                 if (ic->name_space && ic->name_space [0])
368                         fqname = g_strconcat (ic->name_space, ".", class_name, ".", name, NULL);
369                 else
370                         fqname = NULL;
371         } else
372                 class_name = qname = fqname = NULL;
373
374         while (klass) {
375                 result = find_method_in_class (klass, name, qname, fqname, sig);
376                 if (result)
377                         goto out;
378
379                 if (name [0] == '.' && (!strcmp (name, ".ctor") || !strcmp (name, ".cctor")))
380                         break;
381
382                 for (i = 0; i < klass->interface_count; i++) {
383                         MonoClass *ic = klass->interfaces [i];
384
385                         result = find_method_in_class (ic, name, qname, fqname, sig);
386                         if (result)
387                                 goto out;
388                 }
389
390                 klass = klass->parent;
391         }
392
393         if (is_interface)
394                 result = find_method_in_class (mono_defaults.object_class, name, qname, fqname, sig);
395
396  out:
397         g_free (class_name);
398         g_free (fqname);
399         g_free (qname);
400         return result;
401 }
402
403 /*
404  * token is the method_ref or method_def token used in a call IL instruction.
405  */
406 MonoMethodSignature*
407 mono_method_get_signature_full (MonoMethod *method, MonoImage *image, guint32 token, MonoGenericContext *context)
408 {
409         int table = mono_metadata_token_table (token);
410         int idx = mono_metadata_token_index (token);
411         guint32 cols [MONO_MEMBERREF_SIZE];
412         MonoMethodSignature *sig, *prev_sig;
413         const char *ptr;
414
415         /* !table is for wrappers: we should really assign their own token to them */
416         if (!table || table == MONO_TABLE_METHOD)
417                 return mono_method_signature (method);
418
419         if (table == MONO_TABLE_METHODSPEC) {
420                 g_assert (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) &&
421                           !(method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) &&
422                           mono_method_signature (method));
423                 g_assert (method->is_inflated);
424
425                 return mono_method_signature (method);
426         }
427
428         if (method->klass->generic_class)
429                 return mono_method_signature (method);
430
431         if (image->dynamic)
432                 /* FIXME: This might be incorrect for vararg methods */
433                 return mono_method_signature (method);
434
435         mono_loader_lock ();
436         sig = g_hash_table_lookup (image->memberref_signatures, GUINT_TO_POINTER (token));
437         mono_loader_unlock ();
438         if (!sig) {
439                 mono_metadata_decode_row (&image->tables [MONO_TABLE_MEMBERREF], idx-1, cols, MONO_MEMBERREF_SIZE);
440         
441                 ptr = mono_metadata_blob_heap (image, cols [MONO_MEMBERREF_SIGNATURE]);
442                 mono_metadata_decode_blob_size (ptr, &ptr);
443                 sig = mono_metadata_parse_method_signature_full (
444                         image, context ? context->container : NULL, 0, ptr, NULL);
445
446                 mono_loader_lock ();
447                 prev_sig = g_hash_table_lookup (image->memberref_signatures, GUINT_TO_POINTER (token));
448                 if (prev_sig) {
449                         /* Somebody got in before us */
450                         /* FIXME: Free sig */
451                         sig = prev_sig;
452                 }
453                 else
454                         g_hash_table_insert (image->memberref_signatures, GUINT_TO_POINTER (token), sig);
455                 mono_loader_unlock ();
456         }
457
458         sig = mono_class_inflate_generic_signature (image, sig, context);
459
460         return sig;
461 }
462
463 MonoMethodSignature*
464 mono_method_get_signature (MonoMethod *method, MonoImage *image, guint32 token)
465 {
466         return mono_method_get_signature_full (method, image, token, NULL);
467 }
468
469 static MonoMethod *
470 method_from_memberref (MonoImage *image, guint32 idx, MonoGenericContext *typespec_context)
471 {
472         MonoGenericContext *context = NULL;
473         MonoClass *klass = NULL;
474         MonoMethod *method = NULL;
475         MonoTableInfo *tables = image->tables;
476         guint32 cols[6];
477         guint32 nindex, class;
478         const char *mname;
479         MonoMethodSignature *sig;
480         const char *ptr;
481
482         mono_metadata_decode_row (&tables [MONO_TABLE_MEMBERREF], idx-1, cols, 3);
483         nindex = cols [MONO_MEMBERREF_CLASS] >> MONO_MEMBERREF_PARENT_BITS;
484         class = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
485         /*g_print ("methodref: 0x%x 0x%x %s\n", class, nindex,
486                 mono_metadata_string_heap (m, cols [MONO_MEMBERREF_NAME]));*/
487
488         mname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
489
490         switch (class) {
491         case MONO_MEMBERREF_PARENT_TYPEREF:
492                 klass = mono_class_from_typeref (image, MONO_TOKEN_TYPE_REF | nindex);
493                 if (!klass) {
494                         char *name = mono_class_name_from_token (image, MONO_TOKEN_TYPE_REF | nindex);
495                         g_warning ("Missing method %s in assembly %s, type %s", mname, image->name, name);
496                         g_free (name);
497                         return NULL;
498                 }
499                 break;
500         case MONO_MEMBERREF_PARENT_TYPESPEC:
501                 /*
502                  * Parse the TYPESPEC in the parent's context.
503                  */
504                 klass = mono_class_get_full (image, MONO_TOKEN_TYPE_SPEC | nindex, typespec_context);
505                 if (!klass) {
506                         char *name = mono_class_name_from_token (image, MONO_TOKEN_TYPE_SPEC | nindex);
507                         g_warning ("Missing method %s in assembly %s, type %s", mname, image->name, name);
508                         g_free (name);
509                         return NULL;
510                 }
511                 break;
512         case MONO_MEMBERREF_PARENT_TYPEDEF:
513                 klass = mono_class_get (image, MONO_TOKEN_TYPE_DEF | nindex);
514                 if (!klass) {
515                         char *name = mono_class_name_from_token (image, MONO_TOKEN_TYPE_DEF | nindex);
516                         g_warning ("Missing method %s in assembly %s, type %s", mname, image->name, name);
517                         g_free (name);
518                         return NULL;
519                 }
520                 break;
521         case MONO_MEMBERREF_PARENT_METHODDEF:
522                 return mono_get_method (image, MONO_TOKEN_METHOD_DEF | nindex, NULL);
523         default:
524                 g_error ("Memberref parent unknown: class: %d, index %d", class, nindex);
525                 g_assert_not_reached ();
526         }
527         g_assert (klass);
528         mono_class_init (klass);
529
530         ptr = mono_metadata_blob_heap (image, cols [MONO_MEMBERREF_SIGNATURE]);
531         mono_metadata_decode_blob_size (ptr, &ptr);
532
533         sig = mono_metadata_parse_method_signature (image, 0, ptr, NULL);
534
535         /* If the class is a generic instantiation, ensure that all VAR references in the signature
536            are replaced by the corresponding type argument.  Note that MVARs are left alone. */
537         if (klass->generic_class && sig->has_type_parameters) {
538                 MonoMethodSignature *old_sig = sig;
539                 sig = mono_class_inflate_generic_signature (image, sig, klass->generic_class->context);
540                 g_assert (sig != old_sig);
541                 mono_metadata_free_method_signature (old_sig);
542         }
543
544         switch (class) {
545         case MONO_MEMBERREF_PARENT_TYPEREF:
546                 method = find_method (klass, NULL, mname, sig);
547                 if (!method)
548                         mono_loader_set_error_method_load (klass, mname);
549                 mono_metadata_free_method_signature (sig);
550                 break;
551         case MONO_MEMBERREF_PARENT_TYPESPEC: {
552                 MonoType *type;
553                 MonoMethod *result;
554
555                 type = &klass->byval_arg;
556
557                 if (type->type != MONO_TYPE_ARRAY && type->type != MONO_TYPE_SZARRAY) {
558                         method = find_method (klass, NULL, mname, sig);
559                         if (!method)
560                                 g_warning ("Missing method %s in assembly %s, type %s", mname, image->name, mono_class_get_name (klass));
561                         else if (klass->generic_class && (klass != method->klass))
562                                 method = mono_class_inflate_generic_method (
563                                         method, klass->generic_class->context);
564                         mono_metadata_free_method_signature (sig);
565                         break;
566                 }
567
568                 result = (MonoMethod *)g_new0 (MonoMethodPInvoke, 1);
569                 result->klass = klass;
570                 result->iflags = METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL;
571                 result->signature = sig;
572                 result->name = mname;
573
574                 if (!strcmp (mname, ".ctor")) {
575                         /* we special-case this in the runtime. */
576                         return result;
577                 }
578                 
579                 if (!strcmp (mname, "Set")) {
580                         g_assert (sig->hasthis);
581                         g_assert (type->data.array->rank + 1 == sig->param_count);
582                         result->iflags |= METHOD_IMPL_ATTRIBUTE_RUNTIME;
583                         return result;
584                 }
585
586                 if (!strcmp (mname, "Get")) {
587                         g_assert (sig->hasthis);
588                         g_assert (type->data.array->rank == sig->param_count);
589                         result->iflags |= METHOD_IMPL_ATTRIBUTE_RUNTIME;
590                         return result;
591                 }
592
593                 if (!strcmp (mname, "Address")) {
594                         g_assert (sig->hasthis);
595                         g_assert (type->data.array->rank == sig->param_count);
596                         result->iflags |= METHOD_IMPL_ATTRIBUTE_RUNTIME;
597                         return result;
598                 }
599
600                 g_assert_not_reached ();
601                 break;
602         }
603         case MONO_MEMBERREF_PARENT_TYPEDEF:
604                 method = find_method (klass, NULL, mname, sig);
605                 if (!method)
606                         g_warning (
607                                 "Missing method %s::%s(%s) in assembly %s", 
608                                 mono_type_get_name (&klass->byval_arg), mname, mono_signature_get_desc (sig, FALSE), image->name);
609                 mono_metadata_free_method_signature (sig);
610                 break;
611         default:
612                 g_error ("Memberref parent unknown: class: %d, index %d", class, nindex);
613                 g_assert_not_reached ();
614         }
615
616         return method;
617 }
618
619 static MonoMethod *
620 method_from_methodspec (MonoImage *image, MonoGenericContext *context, guint32 idx)
621 {
622         MonoMethod *method, *inflated;
623         MonoTableInfo *tables = image->tables;
624         MonoGenericContext *new_context = NULL;
625         MonoGenericMethod *gmethod;
626         MonoGenericContainer *container = NULL;
627         const char *ptr;
628         guint32 cols [MONO_METHODSPEC_SIZE];
629         guint32 token, nindex, param_count;
630
631         mono_metadata_decode_row (&tables [MONO_TABLE_METHODSPEC], idx - 1, cols, MONO_METHODSPEC_SIZE);
632         token = cols [MONO_METHODSPEC_METHOD];
633         nindex = token >> MONO_METHODDEFORREF_BITS;
634
635         ptr = mono_metadata_blob_heap (image, cols [MONO_METHODSPEC_SIGNATURE]);
636         
637         mono_metadata_decode_value (ptr, &ptr);
638         ptr++;
639         param_count = mono_metadata_decode_value (ptr, &ptr);
640         g_assert (param_count);
641
642         /*
643          * Be careful with the two contexts here:
644          *
645          * ----------------------------------------
646          * class Foo<S> {
647          *   static void Hello<T> (S s, T t) { }
648          *
649          *   static void Test<U> (U u) {
650          *     Foo<U>.Hello<string> (u, "World");
651          *   }
652          * }
653          * ----------------------------------------
654          *
655          * Let's assume we're currently JITing Foo<int>.Test<long>
656          * (ie. `S' is instantiated as `int' and `U' is instantiated as `long').
657          *
658          * The call to Hello() is encoded with a MethodSpec with a TypeSpec as parent
659          * (MONO_MEMBERREF_PARENT_TYPESPEC).
660          *
661          * The TypeSpec is encoded as `Foo<!!0>', so we need to parse it in the current
662          * context (S=int, U=long) to get the correct `Foo<long>'.
663          * 
664          * After that, we parse the memberref signature in the new context
665          * (S=int, T=uninstantiated) and get the open generic method `Foo<long>.Hello<T>'.
666          *
667          */
668         if ((token & MONO_METHODDEFORREF_MASK) == MONO_METHODDEFORREF_METHODDEF)
669                 method = mono_get_method_full (image, MONO_TOKEN_METHOD_DEF | nindex, NULL, context);
670         else
671                 method = method_from_memberref (image, nindex, context);
672
673         method = mono_get_inflated_method (method);
674
675         container = method->generic_container;
676         g_assert (container);
677
678         gmethod = g_new0 (MonoGenericMethod, 1);
679         gmethod->generic_class = method->klass->generic_class;
680         gmethod->container = container;
681
682         new_context = g_new0 (MonoGenericContext, 1);
683         new_context->container = container;
684         new_context->gmethod = gmethod;
685         if (container->parent)
686                 new_context->gclass = container->parent->context.gclass;
687
688         /*
689          * When parsing the methodspec signature, we're in the old context again:
690          *
691          * ----------------------------------------
692          * class Foo {
693          *   static void Hello<T> (T t) { }
694          *
695          *   static void Test<U> (U u) {
696          *     Foo.Hello<U> (u);
697          *   }
698          * }
699          * ----------------------------------------
700          *
701          * Let's assume we're currently JITing "Foo.Test<float>".
702          *
703          * In this case, we already parsed the memberref as "Foo.Hello<T>" and the methodspec
704          * signature is "<!!0>".  This means that we must instantiate the method type parameter
705          * `T' from the new method with the method type parameter `U' from the current context;
706          * ie. instantiate the method as `Foo.Hello<float>.
707          */
708
709         gmethod->inst = mono_metadata_parse_generic_inst (image, context, param_count, ptr, &ptr);
710
711         if (context)
712                 gmethod->inst = mono_metadata_inflate_generic_inst (gmethod->inst, context);
713
714         if (!container->method_hash)
715                 container->method_hash = g_hash_table_new (
716                         (GHashFunc)mono_metadata_generic_method_hash, (GEqualFunc)mono_metadata_generic_method_equal);
717
718         inflated = g_hash_table_lookup (container->method_hash, gmethod);
719         if (inflated) {
720                 g_free (gmethod);
721                 g_free (new_context);
722                 return inflated;
723         }
724
725         context = new_context;
726
727         mono_stats.generics_metadata_size += sizeof (MonoGenericMethod) +
728                 sizeof (MonoGenericContext) + param_count * sizeof (MonoType);
729
730         inflated = mono_class_inflate_generic_method (method, new_context);
731         g_hash_table_insert (container->method_hash, gmethod, inflated);
732
733         new_context->gclass = inflated->klass->generic_class;
734         return inflated;
735 }
736
737 typedef struct MonoDllMap MonoDllMap;
738
739 struct MonoDllMap {
740         char *name;
741         char *target;
742         char *dll;
743         MonoDllMap *next;
744 };
745
746 static GHashTable *global_dll_map;
747
748 static int 
749 mono_dllmap_lookup_hash (GHashTable *dll_map, const char *dll, const char* func, const char **rdll, const char **rfunc) {
750         MonoDllMap *map, *tmp;
751
752         *rdll = dll;
753
754         if (!dll_map)
755                 return 0;
756
757         mono_loader_lock ();
758
759         map = g_hash_table_lookup (dll_map, dll);
760         if (!map) {
761                 mono_loader_unlock ();
762                 return 0;
763         }
764         *rdll = map->target? map->target: dll;
765                 
766         for (tmp = map->next; tmp; tmp = tmp->next) {
767                 if (strcmp (func, tmp->name) == 0) {
768                         *rfunc = tmp->name;
769                         if (tmp->dll)
770                                 *rdll = tmp->dll;
771                         mono_loader_unlock ();
772                         return 1;
773                 }
774         }
775         *rfunc = func;
776         mono_loader_unlock ();
777         return 1;
778 }
779
780 static int 
781 mono_dllmap_lookup (MonoImage *assembly, const char *dll, const char* func, const char **rdll, const char **rfunc)
782 {
783         int res;
784         if (assembly && assembly->dll_map) {
785                 res = mono_dllmap_lookup_hash (assembly->dll_map, dll, func, rdll, rfunc);
786                 if (res)
787                         return res;
788         }
789         return mono_dllmap_lookup_hash (global_dll_map, dll, func, rdll, rfunc);
790 }
791
792 void
793 mono_dllmap_insert (MonoImage *assembly, const char *dll, const char *func, const char *tdll, const char *tfunc) {
794         MonoDllMap *map, *entry;
795         GHashTable *dll_map = NULL;
796
797         mono_loader_lock ();
798
799         if (!assembly) {
800                 if (!global_dll_map)
801                         global_dll_map = g_hash_table_new (g_str_hash, g_str_equal);
802                 dll_map = global_dll_map;
803         } else {
804                 if (!assembly->dll_map)
805                         assembly->dll_map = g_hash_table_new (g_str_hash, g_str_equal);
806                 dll_map = assembly->dll_map;
807         }
808
809         map = g_hash_table_lookup (dll_map, dll);
810         if (!map) {
811                 map = g_new0 (MonoDllMap, 1);
812                 map->dll = g_strdup (dll);
813                 if (tdll)
814                         map->target = g_strdup (tdll);
815                 g_hash_table_insert (dll_map, map->dll, map);
816         }
817         if (func) {
818                 entry = g_new0 (MonoDllMap, 1);
819                 entry->name = g_strdup (func);
820                 if (tfunc)
821                         entry->target = g_strdup (tfunc);
822                 if (tdll && map->target && strcmp (map->target, tdll))
823                         entry->dll = g_strdup (tdll);
824                 entry->next = map->next;
825                 map->next = entry;
826         }
827
828         mono_loader_unlock ();
829 }
830
831 gpointer
832 mono_lookup_pinvoke_call (MonoMethod *method, const char **exc_class, const char **exc_arg)
833 {
834         MonoImage *image = method->klass->image;
835         MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)method;
836         MonoTableInfo *tables = image->tables;
837         MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
838         MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
839         guint32 im_cols [MONO_IMPLMAP_SIZE];
840         guint32 scope_token;
841         const char *import = NULL;
842         const char *orig_scope;
843         const char *new_scope;
844         char *full_name, *file_name;
845         int i;
846         GModule *gmodule = NULL;
847
848         g_assert (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL);
849
850         if (piinfo->addr)
851                 return piinfo->addr;
852
853         if (method->klass->image->dynamic) {
854                 MonoReflectionMethodAux *method_aux = 
855                         g_hash_table_lookup (
856                                 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
857                 if (!method_aux)
858                         return NULL;
859
860                 import = method_aux->dllentry;
861                 orig_scope = method_aux->dll;
862         }
863         else {
864                 if (!piinfo->implmap_idx)
865                         return NULL;
866
867                 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
868
869                 piinfo->piflags = im_cols [MONO_IMPLMAP_FLAGS];
870                 import = mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]);
871                 scope_token = mono_metadata_decode_row_col (mr, im_cols [MONO_IMPLMAP_SCOPE] - 1, MONO_MODULEREF_NAME);
872                 orig_scope = mono_metadata_string_heap (image, scope_token);
873         }
874
875         mono_dllmap_lookup (image, orig_scope, import, &new_scope, &import);
876
877         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
878                         "DllImport attempting to load: '%s'.", new_scope);
879
880         if (exc_class) {
881                 *exc_class = NULL;
882                 *exc_arg = NULL;
883         }
884
885         /* we allow a special name to dlopen from the running process namespace */
886         if (strcmp (new_scope, "__Internal") == 0)
887                 gmodule = g_module_open (NULL, G_MODULE_BIND_LAZY);
888                 
889         /*
890          * Try loading the module using a variety of names
891          */
892         for (i = 0; i < 4; ++i) {
893                 switch (i) {
894                 case 0:
895                         /* Try the original name */
896                         file_name = g_strdup (new_scope);
897                         break;
898                 case 1:
899                         /* Try trimming the .dll extension */
900                         if (strstr (new_scope, ".dll") == (new_scope + strlen (new_scope) - 4)) {
901                                 file_name = g_strdup (new_scope);
902                                 file_name [strlen (new_scope) - 4] = '\0';
903                         }
904                         else
905                                 continue;
906                         break;
907                 case 2:
908                         if (strstr (new_scope, "lib") != new_scope) {
909                                 file_name = g_strdup_printf ("lib%s", new_scope);
910                         }
911                         else
912                                 continue;
913                         break;
914                 default:
915 #ifndef PLATFORM_WIN32
916                         if (!g_ascii_strcasecmp ("user32.dll", new_scope) ||
917                             !g_ascii_strcasecmp ("kernel32.dll", new_scope) ||
918                             !g_ascii_strcasecmp ("user32", new_scope) ||
919                             !g_ascii_strcasecmp ("kernel", new_scope)) {
920                                 file_name = g_strdup ("libMonoSupportW.so");
921                         } else
922 #endif
923                                     continue;
924 #ifndef PLATFORM_WIN32
925                         break;
926 #endif
927                 }
928
929                 if (!gmodule) {
930                         full_name = g_module_build_path (NULL, file_name);
931                         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
932                                         "DllImport loading location: '%s'.", full_name);
933                         gmodule = g_module_open (full_name, G_MODULE_BIND_LAZY);
934                         if (!gmodule) {
935                                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
936                                                 "DllImport error loading library: '%s'.",
937                                                 g_module_error ());
938                         }
939                         g_free (full_name);
940                 }
941
942                 if (!gmodule) {
943                         full_name = g_module_build_path (".", file_name);
944                         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
945                                         "DllImport loading library: '%s'.", full_name);
946                         gmodule = g_module_open (full_name, G_MODULE_BIND_LAZY);
947                         if (!gmodule) {
948                                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
949                                                 "DllImport error loading library '%s'.",
950                                                 g_module_error ());
951                         }
952                         g_free (full_name);
953                 }
954
955                 if (!gmodule) {
956                         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
957                                         "DllImport loading: '%s'.", file_name);
958                         gmodule=g_module_open (file_name, G_MODULE_BIND_LAZY);
959                         if (!gmodule) {
960                                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
961                                                 "DllImport error loading library '%s'.",
962                                                 g_module_error ());
963                         }
964                 }
965
966                 g_free (file_name);
967
968                 if (gmodule)
969                         break;
970         }
971
972         if (!gmodule) {
973                 mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_DLLIMPORT,
974                                 "DllImport unable to load library '%s'.",
975                                 g_module_error ());
976
977                 if (exc_class) {
978                         *exc_class = "DllNotFoundException";
979                         *exc_arg = new_scope;
980                 }
981                 return NULL;
982         }
983
984         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
985                                 "Searching for '%s'.", import);
986
987         if (piinfo->piflags & PINVOKE_ATTRIBUTE_NO_MANGLE) {
988                 g_module_symbol (gmodule, import, &piinfo->addr); 
989         } else {
990                 char *mangled_name = NULL, *mangled_name2 = NULL;
991                 int mangle_charset;
992                 int mangle_stdcall;
993                 int mangle_param_count;
994 #ifdef PLATFORM_WIN32
995                 int param_count;
996 #endif
997
998                 /*
999                  * Search using a variety of mangled names
1000                  */
1001                 for (mangle_charset = 0; mangle_charset <= 1; mangle_charset ++) {
1002                         for (mangle_stdcall = 0; mangle_stdcall <= 1; mangle_stdcall ++) {
1003                                 gboolean need_param_count = FALSE;
1004 #ifdef PLATFORM_WIN32
1005                                 if (mangle_stdcall > 0)
1006                                         need_param_count = TRUE;
1007 #endif
1008                                 for (mangle_param_count = 0; mangle_param_count <= (need_param_count ? 256 : 0); mangle_param_count += 4) {
1009
1010                                         if (piinfo->addr)
1011                                                 continue;
1012
1013                                         mangled_name = (char*)import;
1014                                         switch (piinfo->piflags & PINVOKE_ATTRIBUTE_CHAR_SET_MASK) {
1015                                         case PINVOKE_ATTRIBUTE_CHAR_SET_UNICODE:
1016                                                 /* Try the mangled name first */
1017                                                 if (mangle_charset == 0)
1018                                                         mangled_name = g_strconcat (import, "W", NULL);
1019                                                 break;
1020                                         case PINVOKE_ATTRIBUTE_CHAR_SET_AUTO:
1021 #ifdef PLATFORM_WIN32
1022                                                 if (mangle_charset == 0)
1023                                                         mangled_name = g_strconcat (import, "W", NULL);
1024 #endif
1025                                                 break;
1026                                         case PINVOKE_ATTRIBUTE_CHAR_SET_ANSI:
1027                                         default:
1028                                                 /* Try the mangled name last */
1029                                                 if (mangle_charset == 1)
1030                                                         mangled_name = g_strconcat (import, "A", NULL);
1031                                                 break;
1032                                         }
1033
1034 #ifdef PLATFORM_WIN32
1035                                         if (mangle_param_count == 0)
1036                                                 param_count = mono_method_signature (method)->param_count * sizeof (gpointer);
1037                                         else
1038                                                 /* Try brute force, since it would be very hard to compute the stack usage correctly */
1039                                                 param_count = mangle_param_count;
1040
1041                                         /* Try the stdcall mangled name */
1042                                         /* 
1043                                          * gcc under windows creates mangled names without the underscore, but MS.NET
1044                                          * doesn't support it, so we doesn't support it either.
1045                                          */
1046                                         if (mangle_stdcall == 1)
1047                                                 mangled_name2 = g_strdup_printf ("_%s@%d", mangled_name, param_count);
1048                                         else
1049                                                 mangled_name2 = mangled_name;
1050 #else
1051                                         mangled_name2 = mangled_name;
1052 #endif
1053
1054                                         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1055                                                                 "Probing '%s'.", mangled_name2);
1056
1057                                         g_module_symbol (gmodule, mangled_name2, &piinfo->addr);
1058
1059                                         if (piinfo->addr)
1060                                                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1061                                                                         "Found as '%s'.", mangled_name2);
1062
1063                                         if (mangled_name != mangled_name2)
1064                                                 g_free (mangled_name2);
1065                                         if (mangled_name != import)
1066                                                 g_free (mangled_name);
1067                                 }
1068                         }
1069                 }
1070         }
1071
1072         if (!piinfo->addr) {
1073                 if (exc_class) {
1074                         *exc_class = "EntryPointNotFoundException";
1075                         *exc_arg = import;
1076                 }
1077                 return NULL;
1078         }
1079         return piinfo->addr;
1080 }
1081
1082 static MonoMethod *
1083 mono_get_method_from_token (MonoImage *image, guint32 token, MonoClass *klass,
1084                             MonoGenericContext *context)
1085 {
1086         MonoMethod *result;
1087         int table = mono_metadata_token_table (token);
1088         int idx = mono_metadata_token_index (token);
1089         MonoTableInfo *tables = image->tables;
1090         MonoGenericContainer *generic_container = NULL, *container = NULL;
1091         const char *sig = NULL;
1092         int size, i;
1093         guint32 cols [MONO_TYPEDEF_SIZE];
1094
1095         if (image->dynamic)
1096                 return mono_lookup_dynamic_token (image, token);
1097
1098         if (table != MONO_TABLE_METHOD) {
1099                 if (table == MONO_TABLE_METHODSPEC)
1100                         return method_from_methodspec (image, context, idx);
1101                 if (table != MONO_TABLE_MEMBERREF)
1102                         g_print("got wrong token: 0x%08x\n", token);
1103                 g_assert (table == MONO_TABLE_MEMBERREF);
1104                 result = method_from_memberref (image, idx, context);
1105
1106                 return result;
1107         }
1108
1109         mono_metadata_decode_row (&tables [table], idx - 1, cols, 6);
1110
1111         if ((cols [2] & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
1112             (cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))
1113                 result = (MonoMethod *)g_new0 (MonoMethodPInvoke, 1);
1114         else 
1115                 result = (MonoMethod *)g_new0 (MonoMethodNormal, 1);
1116
1117         if (!klass) {
1118                 guint32 type = mono_metadata_typedef_from_method (image, token);
1119                 klass = mono_class_get (image, MONO_TOKEN_TYPE_DEF | type);
1120         }
1121         
1122         result->slot = -1;
1123         result->klass = klass;
1124         result->flags = cols [2];
1125         result->iflags = cols [1];
1126         result->token = token;
1127         result->name = mono_metadata_string_heap (image, cols [3]);
1128
1129         container = klass->generic_container;
1130         generic_container = mono_metadata_load_generic_params (image, token, container);
1131         if (generic_container) {
1132                 mono_metadata_load_generic_param_constraints (image, token, generic_container);
1133
1134                 for (i = 0; i < generic_container->type_argc; i++) {
1135                         generic_container->type_params [i].method = result;
1136
1137                         mono_class_from_generic_parameter (
1138                                 &generic_container->type_params [i], image, TRUE);
1139                 }
1140
1141                 container = generic_container;
1142         }
1143
1144         if (!sig) /* already taken from the methodref */
1145                 sig = mono_metadata_blob_heap (image, cols [4]);
1146         size = mono_metadata_decode_blob_size (sig, &sig);
1147         
1148         /* there are generic params, or a container. FIXME: be lazy here for generics*/
1149         if (* sig & 0x10 || container) {
1150                 result->signature = mono_metadata_parse_method_signature_full (
1151                         image, container, idx, sig, NULL);
1152
1153                 /* Verify metadata consistency */
1154                 if (result->signature->generic_param_count) {
1155                         if (!container || !container->is_method)
1156                                 g_error ("Signature claims method has generic parameters, but generic_params table says it doesn't");
1157                         if (container->type_argc != result->signature->generic_param_count)
1158                                 g_error ("Inconsistent generic parameter count.  Signature says %d, generic_params table says %d",
1159                                          result->signature->generic_param_count, container->type_argc);
1160                 } else if (container && container->is_method && container->type_argc)
1161                         g_error ("generic_params table claims method has generic parameters, but signature says it doesn't");
1162
1163                 if (cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
1164                         result->signature->pinvoke = 1;
1165         }
1166
1167         if (cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
1168                 if (result->klass == mono_defaults.string_class && !strcmp (result->name, ".ctor"))
1169                         result->string_ctor = 1;
1170         } else if ((cols [2] & METHOD_ATTRIBUTE_PINVOKE_IMPL) && (!(cols [1] & METHOD_IMPL_ATTRIBUTE_NATIVE))) {
1171                 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)result;
1172                 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
1173                 
1174                 piinfo->implmap_idx = mono_metadata_implmap_from_method (image, idx - 1);
1175                 piinfo->piflags = mono_metadata_decode_row_col (im, piinfo->implmap_idx - 1, MONO_IMPLMAP_FLAGS);
1176         }
1177                 
1178         /* FIXME: lazyness for generics too, but how? */
1179         if (!result->klass->dummy && !(result->flags & METHOD_ATTRIBUTE_ABSTRACT) &&
1180             !(cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) &&
1181             !(result->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) && container) {
1182                 gpointer loc = mono_image_rva_map (image, cols [0]);
1183                 g_assert (loc);
1184                 ((MonoMethodNormal *) result)->header = mono_metadata_parse_mh_full (
1185                         image, (MonoGenericContext *) container, loc);
1186         }
1187                 
1188         result->generic_container = generic_container;
1189
1190         return result;
1191 }
1192
1193 MonoMethod *
1194 mono_get_method (MonoImage *image, guint32 token, MonoClass *klass)
1195 {
1196         return mono_get_method_full (image, token, klass, NULL);
1197 }
1198
1199 MonoMethod *
1200 mono_get_method_full (MonoImage *image, guint32 token, MonoClass *klass,
1201                       MonoGenericContext *context)
1202 {
1203         MonoMethod *result;
1204
1205         /* We do everything inside the lock to prevent creation races */
1206
1207         mono_loader_lock ();
1208
1209         if ((result = g_hash_table_lookup (image->method_cache, GINT_TO_POINTER (token)))) {
1210                 mono_loader_unlock ();
1211                 return result;
1212         }
1213
1214         result = mono_get_method_from_token (image, token, klass, context);
1215
1216         //printf ("GET: %s\n", mono_method_full_name (result, TRUE));
1217
1218         if (!(result && result->is_inflated))
1219                 g_hash_table_insert (image->method_cache, GINT_TO_POINTER (token), result);
1220
1221         mono_loader_unlock ();
1222
1223         return result;
1224 }
1225
1226 /**
1227  * mono_get_method_constrained:
1228  *
1229  * This is used when JITing the `constrained.' opcode.
1230  */
1231 MonoMethod *
1232 mono_get_method_constrained (MonoImage *image, guint32 token, MonoClass *constrained_class,
1233                              MonoGenericContext *context)
1234 {
1235         MonoMethod *method, *result;
1236         MonoClass *ic = NULL;
1237         MonoGenericClass *gclass = NULL;
1238
1239         mono_loader_lock ();
1240
1241         method = mono_get_method_from_token (image, token, NULL, context);
1242         if (!method) {
1243                 mono_loader_unlock ();
1244                 return NULL;
1245         }
1246
1247         mono_class_init (constrained_class);
1248         method = mono_get_inflated_method (method);
1249
1250         if ((constrained_class != method->klass) && (method->klass->interface_id != 0))
1251                 ic = method->klass;
1252
1253         if (constrained_class->generic_class)
1254                 gclass = constrained_class->generic_class;
1255
1256         result = find_method (constrained_class, ic, method->name, mono_method_signature (method));
1257         if (!result)
1258                 g_warning ("Missing method %s in assembly %s token %x", method->name,
1259                            image->name, token);
1260
1261         if (gclass)
1262                 result = mono_class_inflate_generic_method (result, gclass->context);
1263
1264         mono_loader_unlock ();
1265         return result;
1266 }
1267
1268 void
1269 mono_free_method  (MonoMethod *method)
1270 {
1271         if (method->signature) {
1272                 /* 
1273                  * FIXME: This causes crashes because the types inside signatures and
1274                  * locals are shared.
1275                  */
1276                 /* mono_metadata_free_method_signature (method->signature); */
1277                 g_free (method->signature);
1278         }
1279
1280         if (method->dynamic) {
1281                 MonoMethodWrapper *mw = (MonoMethodWrapper*)method;
1282
1283                 g_free ((char*)method->name);
1284                 if (mw->method.header)
1285                         g_free ((char*)mw->method.header->code);
1286                 g_free (mw->method_data);
1287         }
1288
1289         if (!(method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && ((MonoMethodNormal *)method)->header) {
1290                 /* FIXME: Ditto */
1291                 /* mono_metadata_free_mh (((MonoMethodNormal *)method)->header); */
1292                 g_free (((MonoMethodNormal*)method)->header);
1293         }
1294
1295         g_free (method);
1296 }
1297
1298 void
1299 mono_method_get_param_names (MonoMethod *method, const char **names)
1300 {
1301         int i, lastp;
1302         MonoClass *klass = method->klass;
1303         MonoTableInfo *methodt;
1304         MonoTableInfo *paramt;
1305         guint32 idx;
1306
1307         if (!mono_method_signature (method)->param_count)
1308                 return;
1309         for (i = 0; i < mono_method_signature (method)->param_count; ++i)
1310                 names [i] = "";
1311
1312         if (klass->generic_class) /* copy the names later */
1313                 return;
1314
1315         mono_class_init (klass);
1316
1317         if (klass->image->dynamic) {
1318                 MonoReflectionMethodAux *method_aux = 
1319                         g_hash_table_lookup (
1320                                 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
1321                 if (method_aux && method_aux->param_names) {
1322                         for (i = 0; i < mono_method_signature (method)->param_count; ++i)
1323                                 if (method_aux->param_names [i + 1])
1324                                         names [i] = method_aux->param_names [i + 1];
1325                 }
1326                 return;
1327         }
1328
1329         methodt = &klass->image->tables [MONO_TABLE_METHOD];
1330         paramt = &klass->image->tables [MONO_TABLE_PARAM];
1331         idx = mono_method_get_index (method);
1332         if (idx > 0) {
1333                 guint32 cols [MONO_PARAM_SIZE];
1334                 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
1335
1336                 if (idx < methodt->rows)
1337                         lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
1338                 else
1339                         lastp = paramt->rows + 1;
1340                 for (i = param_index; i < lastp; ++i) {
1341                         mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
1342                         if (cols [MONO_PARAM_SEQUENCE]) /* skip return param spec */
1343                                 names [cols [MONO_PARAM_SEQUENCE] - 1] = mono_metadata_string_heap (klass->image, cols [MONO_PARAM_NAME]);
1344                 }
1345                 return;
1346         }
1347 }
1348
1349 guint32
1350 mono_method_get_param_token (MonoMethod *method, int index)
1351 {
1352         MonoClass *klass = method->klass;
1353         MonoTableInfo *methodt;
1354         guint32 idx;
1355
1356         if (klass->generic_class)
1357                 g_assert_not_reached ();
1358
1359         mono_class_init (klass);
1360
1361         if (klass->image->dynamic) {
1362                 g_assert_not_reached ();
1363         }
1364
1365         methodt = &klass->image->tables [MONO_TABLE_METHOD];
1366         idx = mono_method_get_index (method);
1367         if (idx > 0) {
1368                 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
1369
1370                 return mono_metadata_make_token (MONO_TABLE_PARAM, param_index + index);
1371         }
1372
1373         return 0;
1374 }
1375
1376 void
1377 mono_method_get_marshal_info (MonoMethod *method, MonoMarshalSpec **mspecs)
1378 {
1379         int i, lastp;
1380         MonoClass *klass = method->klass;
1381         MonoTableInfo *methodt;
1382         MonoTableInfo *paramt;
1383         guint32 idx;
1384
1385         for (i = 0; i < mono_method_signature (method)->param_count + 1; ++i)
1386                 mspecs [i] = NULL;
1387
1388         if (method->klass->image->dynamic) {
1389                 MonoReflectionMethodAux *method_aux = 
1390                         g_hash_table_lookup (
1391                                 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
1392                 if (method_aux && method_aux->param_marshall) {
1393                         MonoMarshalSpec **dyn_specs = method_aux->param_marshall;
1394                         for (i = 0; i < mono_method_signature (method)->param_count + 1; ++i)
1395                                 if (dyn_specs [i]) {
1396                                         mspecs [i] = g_new0 (MonoMarshalSpec, 1);
1397                                         memcpy (mspecs [i], dyn_specs [i], sizeof (MonoMarshalSpec));
1398                                 }
1399                 }
1400                 return;
1401         }
1402
1403         mono_class_init (klass);
1404
1405         methodt = &klass->image->tables [MONO_TABLE_METHOD];
1406         paramt = &klass->image->tables [MONO_TABLE_PARAM];
1407         idx = mono_method_get_index (method);
1408         if (idx > 0) {
1409                 guint32 cols [MONO_PARAM_SIZE];
1410                 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
1411
1412                 if (idx < methodt->rows)
1413                         lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
1414                 else
1415                         lastp = paramt->rows + 1;
1416
1417                 for (i = param_index; i < lastp; ++i) {
1418                         mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
1419
1420                         if (cols [MONO_PARAM_FLAGS] & PARAM_ATTRIBUTE_HAS_FIELD_MARSHAL) {
1421                                 const char *tp;
1422                                 tp = mono_metadata_get_marshal_info (klass->image, i - 1, FALSE);
1423                                 g_assert (tp);
1424                                 mspecs [cols [MONO_PARAM_SEQUENCE]]= mono_metadata_parse_marshal_spec (klass->image, tp);
1425                         }
1426                 }
1427
1428                 return;
1429         }
1430 }
1431
1432 gboolean
1433 mono_method_has_marshal_info (MonoMethod *method)
1434 {
1435         int i, lastp;
1436         MonoClass *klass = method->klass;
1437         MonoTableInfo *methodt;
1438         MonoTableInfo *paramt;
1439         guint32 idx;
1440
1441         if (method->klass->image->dynamic) {
1442                 MonoReflectionMethodAux *method_aux = 
1443                         g_hash_table_lookup (
1444                                 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
1445                 MonoMarshalSpec **dyn_specs = method_aux->param_marshall;
1446                 if (dyn_specs) {
1447                         for (i = 0; i < mono_method_signature (method)->param_count + 1; ++i)
1448                                 if (dyn_specs [i])
1449                                         return TRUE;
1450                 }
1451                 return FALSE;
1452         }
1453
1454         mono_class_init (klass);
1455
1456         methodt = &klass->image->tables [MONO_TABLE_METHOD];
1457         paramt = &klass->image->tables [MONO_TABLE_PARAM];
1458         idx = mono_method_get_index (method);
1459         if (idx > 0) {
1460                 guint32 cols [MONO_PARAM_SIZE];
1461                 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
1462                 
1463                 if (idx + 1 < methodt->rows)
1464                         lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
1465                 else
1466                         lastp = paramt->rows + 1;
1467
1468                 for (i = param_index; i < lastp; ++i) {
1469                         mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
1470
1471                         if (cols [MONO_PARAM_FLAGS] & PARAM_ATTRIBUTE_HAS_FIELD_MARSHAL)
1472                                 return TRUE;
1473                 }
1474                 return FALSE;
1475         }
1476         return FALSE;
1477 }
1478
1479 gpointer
1480 mono_method_get_wrapper_data (MonoMethod *method, guint32 id)
1481 {
1482         void **data;
1483         g_assert (method != NULL);
1484         g_assert (method->wrapper_type != MONO_WRAPPER_NONE);
1485
1486         data = ((MonoMethodWrapper *)method)->method_data;
1487         g_assert (data != NULL);
1488         g_assert (id <= GPOINTER_TO_UINT (*data));
1489         return data [id];
1490 }
1491
1492 static void
1493 default_stack_walk (MonoStackWalk func, gboolean do_il_offset, gpointer user_data) {
1494         g_error ("stack walk not installed");
1495 }
1496
1497 static MonoStackWalkImpl stack_walk = default_stack_walk;
1498
1499 void
1500 mono_stack_walk (MonoStackWalk func, gpointer user_data)
1501 {
1502         stack_walk (func, TRUE, user_data);
1503 }
1504
1505 void
1506 mono_stack_walk_no_il (MonoStackWalk func, gpointer user_data)
1507 {
1508         stack_walk (func, FALSE, user_data);
1509 }
1510
1511 void
1512 mono_install_stack_walk (MonoStackWalkImpl func)
1513 {
1514         stack_walk = func;
1515 }
1516
1517 static gboolean
1518 last_managed (MonoMethod *m, gint no, gint ilo, gboolean managed, gpointer data)
1519 {
1520         MonoMethod **dest = data;
1521         *dest = m;
1522         /*g_print ("In %s::%s [%d] [%d]\n", m->klass->name, m->name, no, ilo);*/
1523
1524         return managed;
1525 }
1526
1527 MonoMethod*
1528 mono_method_get_last_managed (void)
1529 {
1530         MonoMethod *m = NULL;
1531         stack_walk (last_managed, FALSE, &m);
1532         return m;
1533 }
1534
1535 void
1536 mono_loader_lock (void)
1537 {
1538         EnterCriticalSection (&loader_mutex);
1539 }
1540
1541 void
1542 mono_loader_unlock (void)
1543 {
1544         LeaveCriticalSection (&loader_mutex);
1545 }
1546
1547 MonoMethodSignature* 
1548 mono_method_signature (MonoMethod *m)
1549 {
1550         m = mono_get_inflated_method (m);
1551         return mono_method_signature_full (m, NULL);
1552 }
1553
1554 MonoMethodSignature* 
1555 mono_method_signature_full (MonoMethod *m, MonoGenericContainer *container)
1556 {
1557         int idx;
1558         int size;
1559         MonoImage* img;
1560         const char *sig;
1561         
1562         if (m->signature)
1563                 return m->signature;
1564                 
1565         mono_loader_lock ();
1566         
1567         if (m->signature) {
1568                 mono_loader_unlock ();
1569                 return m->signature;
1570         }
1571         
1572         g_assert (mono_metadata_token_table (m->token) == MONO_TABLE_METHOD);
1573         idx = mono_metadata_token_index (m->token);
1574         img = m->klass->image;
1575         
1576         sig = mono_metadata_blob_heap (img, mono_metadata_decode_row_col (&img->tables [MONO_TABLE_METHOD], idx - 1, MONO_METHOD_SIGNATURE));
1577         size = mono_metadata_decode_blob_size (sig, &sig);
1578         
1579         m->signature = mono_metadata_parse_method_signature_full (img, container, idx, sig, NULL);
1580         
1581         if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
1582                 m->signature->pinvoke = 1;
1583         else if ((m->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) && (!(m->iflags & METHOD_IMPL_ATTRIBUTE_NATIVE))) {
1584                 MonoCallConvention conv = 0;
1585                 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)m;
1586                 m->signature->pinvoke = 1;
1587                 
1588                 switch (piinfo->piflags & PINVOKE_ATTRIBUTE_CALL_CONV_MASK) {
1589                 case 0: /* no call conv, so using default */
1590                 case PINVOKE_ATTRIBUTE_CALL_CONV_WINAPI:
1591                         conv = MONO_CALL_DEFAULT;
1592                         break;
1593                 case PINVOKE_ATTRIBUTE_CALL_CONV_CDECL:
1594                         conv = MONO_CALL_C;
1595                         break;
1596                 case PINVOKE_ATTRIBUTE_CALL_CONV_STDCALL:
1597                         conv = MONO_CALL_STDCALL;
1598                         break;
1599                 case PINVOKE_ATTRIBUTE_CALL_CONV_THISCALL:
1600                         conv = MONO_CALL_THISCALL;
1601                         break;
1602                 case PINVOKE_ATTRIBUTE_CALL_CONV_FASTCALL:
1603                         conv = MONO_CALL_FASTCALL;
1604                         break;
1605                 case PINVOKE_ATTRIBUTE_CALL_CONV_GENERIC:
1606                 case PINVOKE_ATTRIBUTE_CALL_CONV_GENERICINST:
1607                 default:
1608                         g_warning ("unsupported calling convention : 0x%04x", piinfo->piflags);
1609                         g_assert_not_reached ();
1610                 }       
1611                 m->signature->call_convention = conv;
1612         }
1613         
1614         mono_loader_unlock ();
1615         return m->signature;
1616 }
1617
1618 const char*
1619 mono_method_get_name (MonoMethod *method)
1620 {
1621         return method->name;
1622 }
1623
1624 MonoClass*
1625 mono_method_get_class (MonoMethod *method)
1626 {
1627         return method->klass;
1628 }
1629
1630 guint32
1631 mono_method_get_token (MonoMethod *method)
1632 {
1633         return method->token;
1634 }
1635
1636 MonoMethodHeader* 
1637 mono_method_get_header (MonoMethod *method)
1638 {
1639         int idx;
1640         guint32 rva;
1641         MonoImage* img;
1642         gpointer loc;
1643         MonoMethodNormal* mn = (MonoMethodNormal*) method;
1644         
1645         if (method->klass->dummy || (method->flags & METHOD_ATTRIBUTE_ABSTRACT) || (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) || (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) || (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
1646                 return NULL;
1647         
1648 #ifdef G_LIKELY
1649         if (G_LIKELY (mn->header))
1650 #else
1651         if (mn->header)
1652 #endif
1653                 return mn->header;
1654         
1655         mono_loader_lock ();
1656         
1657         if (mn->header) {
1658                 mono_loader_unlock ();
1659                 return mn->header;
1660         }
1661         
1662         g_assert (mono_metadata_token_table (method->token) == MONO_TABLE_METHOD);
1663         idx = mono_metadata_token_index (method->token);
1664         img = method->klass->image;
1665         rva = mono_metadata_decode_row_col (&img->tables [MONO_TABLE_METHOD], idx - 1, MONO_METHOD_RVA);
1666         loc = mono_image_rva_map (img, rva);
1667         
1668         g_assert (loc);
1669         
1670         mn->header = mono_metadata_parse_mh_full (img, (MonoGenericContext *) method->generic_container, loc);
1671         
1672         mono_loader_unlock ();
1673         return mn->header;
1674 }
1675
1676 guint32
1677 mono_method_get_flags (MonoMethod *method, guint32 *iflags)
1678 {
1679         if (iflags)
1680                 *iflags = method->iflags;
1681         return method->flags;
1682 }
1683
1684 /*
1685  * Find the method index in the metadata methodDef table.
1686  */
1687 guint32
1688 mono_method_get_index (MonoMethod *method) {
1689         MonoClass *klass = method->klass;
1690         int i;
1691
1692         if (method->token)
1693                 return mono_metadata_token_index (method->token);
1694
1695         mono_class_setup_methods (klass);
1696         for (i = 0; i < klass->method.count; ++i) {
1697                 if (method == klass->methods [i])
1698                         return klass->method.first + 1 + i;
1699         }
1700         return 0;
1701 }
1702