In metadata:
[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,
330                       MonoMethodSignature *sig)
331 {
332         int i;
333
334         mono_class_setup_methods (klass);
335         for (i = 0; i < klass->method.count; ++i) {
336                 MonoMethod *m = klass->methods [i];
337
338                 if (!((fqname && !strcmp (m->name, fqname)) ||
339                       (qname && !strcmp (m->name, qname)) || !strcmp (m->name, name)))
340                         continue;
341
342                 if (sig->call_convention == MONO_CALL_VARARG) {
343                         if (mono_metadata_signature_vararg_match (sig, mono_method_signature (m)))
344                                 return m;
345                 } else {
346                         if (mono_metadata_signature_equal (sig, mono_method_signature (m)))
347                                 return m;
348                 }
349         }
350
351         return NULL;
352 }
353
354 static MonoMethod *
355 find_method (MonoClass *klass, MonoClass *ic, const char* name, MonoMethodSignature *sig)
356 {
357         int i;
358         char *qname, *fqname, *class_name;
359         gboolean is_interface;
360         MonoMethod *result = NULL;
361
362         is_interface = MONO_CLASS_IS_INTERFACE (klass);
363
364         if (ic) {
365                 class_name = mono_type_get_name_full (&ic->byval_arg, MONO_TYPE_NAME_FORMAT_IL);
366
367                 qname = g_strconcat (class_name, ".", name, NULL); 
368                 if (ic->name_space && ic->name_space [0])
369                         fqname = g_strconcat (ic->name_space, ".", class_name, ".", name, NULL);
370                 else
371                         fqname = NULL;
372         } else
373                 class_name = qname = fqname = NULL;
374
375         while (klass) {
376                 result = find_method_in_class (klass, name, qname, fqname, sig);
377                 if (result)
378                         goto out;
379
380                 if (name [0] == '.' && (!strcmp (name, ".ctor") || !strcmp (name, ".cctor")))
381                         break;
382
383                 for (i = 0; i < klass->interface_count; i++) {
384                         MonoClass *ic = klass->interfaces [i];
385
386                         result = find_method_in_class (ic, name, qname, fqname, sig);
387                         if (result)
388                                 goto out;
389                 }
390
391                 klass = klass->parent;
392         }
393
394         if (is_interface)
395                 result = find_method_in_class (mono_defaults.object_class, name, qname, fqname, sig);
396
397  out:
398         g_free (class_name);
399         g_free (fqname);
400         g_free (qname);
401         return result;
402 }
403
404 /*
405  * token is the method_ref or method_def token used in a call IL instruction.
406  */
407 MonoMethodSignature*
408 mono_method_get_signature_full (MonoMethod *method, MonoImage *image, guint32 token, MonoGenericContext *context)
409 {
410         int table = mono_metadata_token_table (token);
411         int idx = mono_metadata_token_index (token);
412         guint32 cols [MONO_MEMBERREF_SIZE];
413         MonoMethodSignature *sig, *prev_sig;
414         const char *ptr;
415
416         /* !table is for wrappers: we should really assign their own token to them */
417         if (!table || table == MONO_TABLE_METHOD)
418                 return mono_method_signature (method);
419
420         if (table == MONO_TABLE_METHODSPEC) {
421                 g_assert (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) &&
422                           !(method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) &&
423                           mono_method_signature (method));
424                 g_assert (method->is_inflated);
425
426                 return mono_method_signature (method);
427         }
428
429         if (method->klass->generic_class)
430                 return mono_method_signature (method);
431
432         if (image->dynamic)
433                 /* FIXME: This might be incorrect for vararg methods */
434                 return mono_method_signature (method);
435
436         mono_loader_lock ();
437         sig = g_hash_table_lookup (image->memberref_signatures, GUINT_TO_POINTER (token));
438         mono_loader_unlock ();
439         if (!sig) {
440                 mono_metadata_decode_row (&image->tables [MONO_TABLE_MEMBERREF], idx-1, cols, MONO_MEMBERREF_SIZE);
441         
442                 ptr = mono_metadata_blob_heap (image, cols [MONO_MEMBERREF_SIGNATURE]);
443                 mono_metadata_decode_blob_size (ptr, &ptr);
444                 sig = mono_metadata_parse_method_signature_full (
445                         image, context ? context->container : NULL, 0, ptr, NULL);
446
447                 mono_loader_lock ();
448                 prev_sig = g_hash_table_lookup (image->memberref_signatures, GUINT_TO_POINTER (token));
449                 if (prev_sig) {
450                         /* Somebody got in before us */
451                         /* FIXME: Free sig */
452                         sig = prev_sig;
453                 }
454                 else
455                         g_hash_table_insert (image->memberref_signatures, GUINT_TO_POINTER (token), sig);
456                 mono_loader_unlock ();
457         }
458
459         sig = mono_class_inflate_generic_signature (image, sig, context);
460
461         return sig;
462 }
463
464 MonoMethodSignature*
465 mono_method_get_signature (MonoMethod *method, MonoImage *image, guint32 token)
466 {
467         return mono_method_get_signature_full (method, image, token, NULL);
468 }
469
470 static MonoMethod *
471 method_from_memberref (MonoImage *image, guint32 idx, MonoGenericContext *typespec_context)
472 {
473         MonoGenericContext *context = NULL;
474         MonoClass *klass = NULL;
475         MonoMethod *method = NULL;
476         MonoTableInfo *tables = image->tables;
477         guint32 cols[6];
478         guint32 nindex, class;
479         const char *mname;
480         MonoMethodSignature *sig;
481         const char *ptr;
482
483         mono_metadata_decode_row (&tables [MONO_TABLE_MEMBERREF], idx-1, cols, 3);
484         nindex = cols [MONO_MEMBERREF_CLASS] >> MONO_MEMBERREF_PARENT_BITS;
485         class = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
486         /*g_print ("methodref: 0x%x 0x%x %s\n", class, nindex,
487                 mono_metadata_string_heap (m, cols [MONO_MEMBERREF_NAME]));*/
488
489         mname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
490
491         switch (class) {
492         case MONO_MEMBERREF_PARENT_TYPEREF:
493                 klass = mono_class_from_typeref (image, MONO_TOKEN_TYPE_REF | nindex);
494                 if (!klass) {
495                         char *name = mono_class_name_from_token (image, MONO_TOKEN_TYPE_REF | nindex);
496                         g_warning ("Missing method %s in assembly %s, type %s", mname, image->name, name);
497                         g_free (name);
498                         return NULL;
499                 }
500                 break;
501         case MONO_MEMBERREF_PARENT_TYPESPEC:
502                 /*
503                  * Parse the TYPESPEC in the parent's context.
504                  */
505                 klass = mono_class_get_full (image, MONO_TOKEN_TYPE_SPEC | nindex, typespec_context);
506                 if (!klass) {
507                         char *name = mono_class_name_from_token (image, MONO_TOKEN_TYPE_SPEC | nindex);
508                         g_warning ("Missing method %s in assembly %s, type %s", mname, image->name, name);
509                         g_free (name);
510                         return NULL;
511                 }
512                 break;
513         case MONO_MEMBERREF_PARENT_TYPEDEF:
514                 klass = mono_class_get (image, MONO_TOKEN_TYPE_DEF | nindex);
515                 if (!klass) {
516                         char *name = mono_class_name_from_token (image, MONO_TOKEN_TYPE_DEF | nindex);
517                         g_warning ("Missing method %s in assembly %s, type %s", mname, image->name, name);
518                         g_free (name);
519                         return NULL;
520                 }
521                 break;
522         case MONO_MEMBERREF_PARENT_METHODDEF:
523                 return mono_get_method (image, MONO_TOKEN_METHOD_DEF | nindex, NULL);
524         default:
525                 g_error ("Memberref parent unknown: class: %d, index %d", class, nindex);
526                 g_assert_not_reached ();
527         }
528         g_assert (klass);
529         mono_class_init (klass);
530
531         ptr = mono_metadata_blob_heap (image, cols [MONO_MEMBERREF_SIGNATURE]);
532         mono_metadata_decode_blob_size (ptr, &ptr);
533
534         sig = mono_metadata_parse_method_signature (image, 0, ptr, NULL);
535
536         switch (class) {
537         case MONO_MEMBERREF_PARENT_TYPEREF:
538                 method = find_method (klass, NULL, mname, sig);
539                 if (!method)
540                         mono_loader_set_error_method_load (klass, mname);
541                 mono_metadata_free_method_signature (sig);
542                 break;
543         case MONO_MEMBERREF_PARENT_TYPESPEC: {
544                 MonoType *type;
545                 MonoMethod *result;
546
547                 type = &klass->byval_arg;
548
549                 if (type->type != MONO_TYPE_ARRAY && type->type != MONO_TYPE_SZARRAY) {
550                         MonoClass *in_class = klass->generic_class ? klass->generic_class->container_class : klass;
551                         method = find_method (in_class, NULL, mname, sig);
552                         if (!method)
553                                 g_warning ("Missing method %s in assembly %s, type %s", mname, image->name, mono_class_get_name (klass));
554                         else if (klass->generic_class) {
555                                 method = mono_class_inflate_generic_method (method, klass->generic_class->context);
556                                 method = mono_get_inflated_method (method);
557                         }
558                         mono_metadata_free_method_signature (sig);
559                         break;
560                 }
561
562                 result = (MonoMethod *)g_new0 (MonoMethodPInvoke, 1);
563                 result->klass = klass;
564                 result->iflags = METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL;
565                 result->signature = sig;
566                 result->name = mname;
567
568                 if (!strcmp (mname, ".ctor")) {
569                         /* we special-case this in the runtime. */
570                         return result;
571                 }
572                 
573                 if (!strcmp (mname, "Set")) {
574                         g_assert (sig->hasthis);
575                         g_assert (type->data.array->rank + 1 == sig->param_count);
576                         result->iflags |= METHOD_IMPL_ATTRIBUTE_RUNTIME;
577                         return result;
578                 }
579
580                 if (!strcmp (mname, "Get")) {
581                         g_assert (sig->hasthis);
582                         g_assert (type->data.array->rank == sig->param_count);
583                         result->iflags |= METHOD_IMPL_ATTRIBUTE_RUNTIME;
584                         return result;
585                 }
586
587                 if (!strcmp (mname, "Address")) {
588                         g_assert (sig->hasthis);
589                         g_assert (type->data.array->rank == sig->param_count);
590                         result->iflags |= METHOD_IMPL_ATTRIBUTE_RUNTIME;
591                         return result;
592                 }
593
594                 g_assert_not_reached ();
595                 break;
596         }
597         case MONO_MEMBERREF_PARENT_TYPEDEF:
598                 method = find_method (klass, NULL, mname, sig);
599                 if (!method)
600                         g_warning (
601                                 "Missing method %s::%s(%s) in assembly %s", 
602                                 mono_type_get_name (&klass->byval_arg), mname, mono_signature_get_desc (sig, FALSE), image->name);
603                 mono_metadata_free_method_signature (sig);
604                 break;
605         default:
606                 g_error ("Memberref parent unknown: class: %d, index %d", class, nindex);
607                 g_assert_not_reached ();
608         }
609
610         return method;
611 }
612
613 static MonoMethod *
614 method_from_methodspec (MonoImage *image, MonoGenericContext *context, guint32 idx)
615 {
616         MonoMethod *method, *inflated;
617         MonoTableInfo *tables = image->tables;
618         MonoGenericContext *new_context = NULL;
619         MonoGenericMethod *gmethod;
620         MonoGenericContainer *container = NULL;
621         const char *ptr;
622         guint32 cols [MONO_METHODSPEC_SIZE];
623         guint32 token, nindex, param_count;
624
625         mono_metadata_decode_row (&tables [MONO_TABLE_METHODSPEC], idx - 1, cols, MONO_METHODSPEC_SIZE);
626         token = cols [MONO_METHODSPEC_METHOD];
627         nindex = token >> MONO_METHODDEFORREF_BITS;
628
629         ptr = mono_metadata_blob_heap (image, cols [MONO_METHODSPEC_SIGNATURE]);
630         
631         mono_metadata_decode_value (ptr, &ptr);
632         ptr++;
633         param_count = mono_metadata_decode_value (ptr, &ptr);
634         g_assert (param_count);
635
636         /*
637          * Be careful with the two contexts here:
638          *
639          * ----------------------------------------
640          * class Foo<S> {
641          *   static void Hello<T> (S s, T t) { }
642          *
643          *   static void Test<U> (U u) {
644          *     Foo<U>.Hello<string> (u, "World");
645          *   }
646          * }
647          * ----------------------------------------
648          *
649          * Let's assume we're currently JITing Foo<int>.Test<long>
650          * (ie. `S' is instantiated as `int' and `U' is instantiated as `long').
651          *
652          * The call to Hello() is encoded with a MethodSpec with a TypeSpec as parent
653          * (MONO_MEMBERREF_PARENT_TYPESPEC).
654          *
655          * The TypeSpec is encoded as `Foo<!!0>', so we need to parse it in the current
656          * context (S=int, U=long) to get the correct `Foo<long>'.
657          * 
658          * After that, we parse the memberref signature in the new context
659          * (S=int, T=uninstantiated) and get the open generic method `Foo<long>.Hello<T>'.
660          *
661          */
662         if ((token & MONO_METHODDEFORREF_MASK) == MONO_METHODDEFORREF_METHODDEF)
663                 method = mono_get_method_full (image, MONO_TOKEN_METHOD_DEF | nindex, NULL, context);
664         else
665                 method = method_from_memberref (image, nindex, context);
666
667         method = mono_get_inflated_method (method);
668
669         container = method->generic_container;
670         g_assert (container);
671
672         gmethod = g_new0 (MonoGenericMethod, 1);
673         gmethod->generic_class = method->klass->generic_class;
674         gmethod->container = container;
675
676         new_context = g_new0 (MonoGenericContext, 1);
677         new_context->container = container;
678         new_context->gmethod = gmethod;
679         if (container->parent)
680                 new_context->gclass = container->parent->context.gclass;
681
682         /*
683          * When parsing the methodspec signature, we're in the old context again:
684          *
685          * ----------------------------------------
686          * class Foo {
687          *   static void Hello<T> (T t) { }
688          *
689          *   static void Test<U> (U u) {
690          *     Foo.Hello<U> (u);
691          *   }
692          * }
693          * ----------------------------------------
694          *
695          * Let's assume we're currently JITing "Foo.Test<float>".
696          *
697          * In this case, we already parsed the memberref as "Foo.Hello<T>" and the methodspec
698          * signature is "<!!0>".  This means that we must instantiate the method type parameter
699          * `T' from the new method with the method type parameter `U' from the current context;
700          * ie. instantiate the method as `Foo.Hello<float>.
701          */
702
703         gmethod->inst = mono_metadata_parse_generic_inst (image, context, param_count, ptr, &ptr);
704
705         if (context)
706                 gmethod->inst = mono_metadata_inflate_generic_inst (gmethod->inst, context);
707
708         if (!container->method_hash)
709                 container->method_hash = g_hash_table_new (
710                         (GHashFunc)mono_metadata_generic_method_hash, (GEqualFunc)mono_metadata_generic_method_equal);
711
712         inflated = g_hash_table_lookup (container->method_hash, gmethod);
713         if (inflated) {
714                 g_free (gmethod);
715                 g_free (new_context);
716                 return inflated;
717         }
718
719         context = new_context;
720
721         mono_stats.generics_metadata_size += sizeof (MonoGenericMethod) +
722                 sizeof (MonoGenericContext) + param_count * sizeof (MonoType);
723
724         inflated = mono_class_inflate_generic_method (method, new_context);
725         g_hash_table_insert (container->method_hash, gmethod, inflated);
726
727         new_context->gclass = inflated->klass->generic_class;
728         return inflated;
729 }
730
731 typedef struct MonoDllMap MonoDllMap;
732
733 struct MonoDllMap {
734         char *name;
735         char *target;
736         char *dll;
737         MonoDllMap *next;
738 };
739
740 static GHashTable *global_dll_map;
741
742 static int 
743 mono_dllmap_lookup_hash (GHashTable *dll_map, const char *dll, const char* func, const char **rdll, const char **rfunc) {
744         MonoDllMap *map, *tmp;
745
746         *rdll = dll;
747
748         if (!dll_map)
749                 return 0;
750
751         mono_loader_lock ();
752
753         map = g_hash_table_lookup (dll_map, dll);
754         if (!map) {
755                 mono_loader_unlock ();
756                 return 0;
757         }
758         *rdll = map->target? map->target: dll;
759                 
760         for (tmp = map->next; tmp; tmp = tmp->next) {
761                 if (strcmp (func, tmp->name) == 0) {
762                         *rfunc = tmp->name;
763                         if (tmp->dll)
764                                 *rdll = tmp->dll;
765                         mono_loader_unlock ();
766                         return 1;
767                 }
768         }
769         *rfunc = func;
770         mono_loader_unlock ();
771         return 1;
772 }
773
774 static int 
775 mono_dllmap_lookup (MonoImage *assembly, const char *dll, const char* func, const char **rdll, const char **rfunc)
776 {
777         int res;
778         if (assembly && assembly->dll_map) {
779                 res = mono_dllmap_lookup_hash (assembly->dll_map, dll, func, rdll, rfunc);
780                 if (res)
781                         return res;
782         }
783         return mono_dllmap_lookup_hash (global_dll_map, dll, func, rdll, rfunc);
784 }
785
786 void
787 mono_dllmap_insert (MonoImage *assembly, const char *dll, const char *func, const char *tdll, const char *tfunc) {
788         MonoDllMap *map, *entry;
789         GHashTable *dll_map = NULL;
790
791         mono_loader_lock ();
792
793         if (!assembly) {
794                 if (!global_dll_map)
795                         global_dll_map = g_hash_table_new (g_str_hash, g_str_equal);
796                 dll_map = global_dll_map;
797         } else {
798                 if (!assembly->dll_map)
799                         assembly->dll_map = g_hash_table_new (g_str_hash, g_str_equal);
800                 dll_map = assembly->dll_map;
801         }
802
803         map = g_hash_table_lookup (dll_map, dll);
804         if (!map) {
805                 map = g_new0 (MonoDllMap, 1);
806                 map->dll = g_strdup (dll);
807                 if (tdll)
808                         map->target = g_strdup (tdll);
809                 g_hash_table_insert (dll_map, map->dll, map);
810         }
811         if (func) {
812                 entry = g_new0 (MonoDllMap, 1);
813                 entry->name = g_strdup (func);
814                 if (tfunc)
815                         entry->target = g_strdup (tfunc);
816                 if (tdll && map->target && strcmp (map->target, tdll))
817                         entry->dll = g_strdup (tdll);
818                 entry->next = map->next;
819                 map->next = entry;
820         }
821
822         mono_loader_unlock ();
823 }
824
825 gpointer
826 mono_lookup_pinvoke_call (MonoMethod *method, const char **exc_class, const char **exc_arg)
827 {
828         MonoImage *image = method->klass->image;
829         MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)method;
830         MonoTableInfo *tables = image->tables;
831         MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
832         MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
833         guint32 im_cols [MONO_IMPLMAP_SIZE];
834         guint32 scope_token;
835         const char *import = NULL;
836         const char *orig_scope;
837         const char *new_scope;
838         char *full_name, *file_name;
839         int i;
840         GModule *gmodule = NULL;
841
842         g_assert (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL);
843
844         if (piinfo->addr)
845                 return piinfo->addr;
846
847         if (method->klass->image->dynamic) {
848                 MonoReflectionMethodAux *method_aux = 
849                         g_hash_table_lookup (
850                                 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
851                 if (!method_aux)
852                         return NULL;
853
854                 import = method_aux->dllentry;
855                 orig_scope = method_aux->dll;
856         }
857         else {
858                 if (!piinfo->implmap_idx)
859                         return NULL;
860
861                 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
862
863                 piinfo->piflags = im_cols [MONO_IMPLMAP_FLAGS];
864                 import = mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]);
865                 scope_token = mono_metadata_decode_row_col (mr, im_cols [MONO_IMPLMAP_SCOPE] - 1, MONO_MODULEREF_NAME);
866                 orig_scope = mono_metadata_string_heap (image, scope_token);
867         }
868
869         mono_dllmap_lookup (image, orig_scope, import, &new_scope, &import);
870
871         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
872                         "DllImport attempting to load: '%s'.", new_scope);
873
874         if (exc_class) {
875                 *exc_class = NULL;
876                 *exc_arg = NULL;
877         }
878
879         /* we allow a special name to dlopen from the running process namespace */
880         if (strcmp (new_scope, "__Internal") == 0)
881                 gmodule = g_module_open (NULL, G_MODULE_BIND_LAZY);
882                 
883         /*
884          * Try loading the module using a variety of names
885          */
886         for (i = 0; i < 4; ++i) {
887                 switch (i) {
888                 case 0:
889                         /* Try the original name */
890                         file_name = g_strdup (new_scope);
891                         break;
892                 case 1:
893                         /* Try trimming the .dll extension */
894                         if (strstr (new_scope, ".dll") == (new_scope + strlen (new_scope) - 4)) {
895                                 file_name = g_strdup (new_scope);
896                                 file_name [strlen (new_scope) - 4] = '\0';
897                         }
898                         else
899                                 continue;
900                         break;
901                 case 2:
902                         if (strstr (new_scope, "lib") != new_scope) {
903                                 file_name = g_strdup_printf ("lib%s", new_scope);
904                         }
905                         else
906                                 continue;
907                         break;
908                 default:
909 #ifndef PLATFORM_WIN32
910                         if (!g_ascii_strcasecmp ("user32.dll", new_scope) ||
911                             !g_ascii_strcasecmp ("kernel32.dll", new_scope) ||
912                             !g_ascii_strcasecmp ("user32", new_scope) ||
913                             !g_ascii_strcasecmp ("kernel", new_scope)) {
914                                 file_name = g_strdup ("libMonoSupportW.so");
915                         } else
916 #endif
917                                     continue;
918 #ifndef PLATFORM_WIN32
919                         break;
920 #endif
921                 }
922
923                 if (!gmodule) {
924                         full_name = g_module_build_path (NULL, file_name);
925                         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
926                                         "DllImport loading location: '%s'.", full_name);
927                         gmodule = g_module_open (full_name, G_MODULE_BIND_LAZY);
928                         if (!gmodule) {
929                                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
930                                                 "DllImport error loading library: '%s'.",
931                                                 g_module_error ());
932                         }
933                         g_free (full_name);
934                 }
935
936                 if (!gmodule) {
937                         full_name = g_module_build_path (".", file_name);
938                         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
939                                         "DllImport loading library: '%s'.", full_name);
940                         gmodule = g_module_open (full_name, G_MODULE_BIND_LAZY);
941                         if (!gmodule) {
942                                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
943                                                 "DllImport error loading library '%s'.",
944                                                 g_module_error ());
945                         }
946                         g_free (full_name);
947                 }
948
949                 if (!gmodule) {
950                         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
951                                         "DllImport loading: '%s'.", file_name);
952                         gmodule=g_module_open (file_name, G_MODULE_BIND_LAZY);
953                         if (!gmodule) {
954                                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
955                                                 "DllImport error loading library '%s'.",
956                                                 g_module_error ());
957                         }
958                 }
959
960                 g_free (file_name);
961
962                 if (gmodule)
963                         break;
964         }
965
966         if (!gmodule) {
967                 mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_DLLIMPORT,
968                                 "DllImport unable to load library '%s'.",
969                                 g_module_error ());
970
971                 if (exc_class) {
972                         *exc_class = "DllNotFoundException";
973                         *exc_arg = new_scope;
974                 }
975                 return NULL;
976         }
977
978         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
979                                 "Searching for '%s'.", import);
980
981         if (piinfo->piflags & PINVOKE_ATTRIBUTE_NO_MANGLE) {
982                 g_module_symbol (gmodule, import, &piinfo->addr); 
983         } else {
984                 char *mangled_name = NULL, *mangled_name2 = NULL;
985                 int mangle_charset;
986                 int mangle_stdcall;
987                 int mangle_param_count;
988 #ifdef PLATFORM_WIN32
989                 int param_count;
990 #endif
991
992                 /*
993                  * Search using a variety of mangled names
994                  */
995                 for (mangle_charset = 0; mangle_charset <= 1; mangle_charset ++) {
996                         for (mangle_stdcall = 0; mangle_stdcall <= 1; mangle_stdcall ++) {
997                                 gboolean need_param_count = FALSE;
998 #ifdef PLATFORM_WIN32
999                                 if (mangle_stdcall > 0)
1000                                         need_param_count = TRUE;
1001 #endif
1002                                 for (mangle_param_count = 0; mangle_param_count <= (need_param_count ? 256 : 0); mangle_param_count += 4) {
1003
1004                                         if (piinfo->addr)
1005                                                 continue;
1006
1007                                         mangled_name = (char*)import;
1008                                         switch (piinfo->piflags & PINVOKE_ATTRIBUTE_CHAR_SET_MASK) {
1009                                         case PINVOKE_ATTRIBUTE_CHAR_SET_UNICODE:
1010                                                 /* Try the mangled name first */
1011                                                 if (mangle_charset == 0)
1012                                                         mangled_name = g_strconcat (import, "W", NULL);
1013                                                 break;
1014                                         case PINVOKE_ATTRIBUTE_CHAR_SET_AUTO:
1015 #ifdef PLATFORM_WIN32
1016                                                 if (mangle_charset == 0)
1017                                                         mangled_name = g_strconcat (import, "W", NULL);
1018 #endif
1019                                                 break;
1020                                         case PINVOKE_ATTRIBUTE_CHAR_SET_ANSI:
1021                                         default:
1022                                                 /* Try the mangled name last */
1023                                                 if (mangle_charset == 1)
1024                                                         mangled_name = g_strconcat (import, "A", NULL);
1025                                                 break;
1026                                         }
1027
1028 #ifdef PLATFORM_WIN32
1029                                         if (mangle_param_count == 0)
1030                                                 param_count = mono_method_signature (method)->param_count * sizeof (gpointer);
1031                                         else
1032                                                 /* Try brute force, since it would be very hard to compute the stack usage correctly */
1033                                                 param_count = mangle_param_count;
1034
1035                                         /* Try the stdcall mangled name */
1036                                         /* 
1037                                          * gcc under windows creates mangled names without the underscore, but MS.NET
1038                                          * doesn't support it, so we doesn't support it either.
1039                                          */
1040                                         if (mangle_stdcall == 1)
1041                                                 mangled_name2 = g_strdup_printf ("_%s@%d", mangled_name, param_count);
1042                                         else
1043                                                 mangled_name2 = mangled_name;
1044 #else
1045                                         mangled_name2 = mangled_name;
1046 #endif
1047
1048                                         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1049                                                                 "Probing '%s'.", mangled_name2);
1050
1051                                         g_module_symbol (gmodule, mangled_name2, &piinfo->addr);
1052
1053                                         if (piinfo->addr)
1054                                                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1055                                                                         "Found as '%s'.", mangled_name2);
1056
1057                                         if (mangled_name != mangled_name2)
1058                                                 g_free (mangled_name2);
1059                                         if (mangled_name != import)
1060                                                 g_free (mangled_name);
1061                                 }
1062                         }
1063                 }
1064         }
1065
1066         if (!piinfo->addr) {
1067                 if (exc_class) {
1068                         *exc_class = "EntryPointNotFoundException";
1069                         *exc_arg = import;
1070                 }
1071                 return NULL;
1072         }
1073         return piinfo->addr;
1074 }
1075
1076 static MonoMethod *
1077 mono_get_method_from_token (MonoImage *image, guint32 token, MonoClass *klass,
1078                             MonoGenericContext *context)
1079 {
1080         MonoMethod *result;
1081         int table = mono_metadata_token_table (token);
1082         int idx = mono_metadata_token_index (token);
1083         MonoTableInfo *tables = image->tables;
1084         MonoGenericContainer *generic_container = NULL, *container = NULL;
1085         const char *sig = NULL;
1086         int size, i;
1087         guint32 cols [MONO_TYPEDEF_SIZE];
1088
1089         if (image->dynamic)
1090                 return mono_lookup_dynamic_token (image, token);
1091
1092         if (table != MONO_TABLE_METHOD) {
1093                 if (table == MONO_TABLE_METHODSPEC)
1094                         return method_from_methodspec (image, context, idx);
1095                 if (table != MONO_TABLE_MEMBERREF)
1096                         g_print("got wrong token: 0x%08x\n", token);
1097                 g_assert (table == MONO_TABLE_MEMBERREF);
1098                 result = method_from_memberref (image, idx, context);
1099
1100                 return result;
1101         }
1102
1103         mono_metadata_decode_row (&tables [table], idx - 1, cols, 6);
1104
1105         if ((cols [2] & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
1106             (cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))
1107                 result = (MonoMethod *)g_new0 (MonoMethodPInvoke, 1);
1108         else 
1109                 result = (MonoMethod *)g_new0 (MonoMethodNormal, 1);
1110
1111         if (!klass) {
1112                 guint32 type = mono_metadata_typedef_from_method (image, token);
1113                 klass = mono_class_get (image, MONO_TOKEN_TYPE_DEF | type);
1114         }
1115         
1116         result->slot = -1;
1117         result->klass = klass;
1118         result->flags = cols [2];
1119         result->iflags = cols [1];
1120         result->token = token;
1121         result->name = mono_metadata_string_heap (image, cols [3]);
1122
1123         container = klass->generic_container;
1124         generic_container = mono_metadata_load_generic_params (image, token, container);
1125         if (generic_container) {
1126                 mono_metadata_load_generic_param_constraints (image, token, generic_container);
1127
1128                 for (i = 0; i < generic_container->type_argc; i++) {
1129                         generic_container->type_params [i].method = result;
1130
1131                         mono_class_from_generic_parameter (
1132                                 &generic_container->type_params [i], image, TRUE);
1133                 }
1134
1135                 container = generic_container;
1136         }
1137
1138         if (!sig) /* already taken from the methodref */
1139                 sig = mono_metadata_blob_heap (image, cols [4]);
1140         size = mono_metadata_decode_blob_size (sig, &sig);
1141         
1142         /* there are generic params, or a container. FIXME: be lazy here for generics*/
1143         if (* sig & 0x10 || container) {
1144                 result->signature = mono_metadata_parse_method_signature_full (
1145                         image, container, idx, sig, NULL);
1146
1147                 /* Verify metadata consistency */
1148                 if (result->signature->generic_param_count) {
1149                         if (!container || !container->is_method)
1150                                 g_error ("Signature claims method has generic parameters, but generic_params table says it doesn't");
1151                         if (container->type_argc != result->signature->generic_param_count)
1152                                 g_error ("Inconsistent generic parameter count.  Signature says %d, generic_params table says %d",
1153                                          result->signature->generic_param_count, container->type_argc);
1154                 } else if (container && container->is_method && container->type_argc)
1155                         g_error ("generic_params table claims method has generic parameters, but signature says it doesn't");
1156
1157                 if (cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
1158                         result->signature->pinvoke = 1;
1159         }
1160
1161         if (cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
1162                 if (result->klass == mono_defaults.string_class && !strcmp (result->name, ".ctor"))
1163                         result->string_ctor = 1;
1164         } else if ((cols [2] & METHOD_ATTRIBUTE_PINVOKE_IMPL) && (!(cols [1] & METHOD_IMPL_ATTRIBUTE_NATIVE))) {
1165                 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)result;
1166                 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
1167                 
1168                 piinfo->implmap_idx = mono_metadata_implmap_from_method (image, idx - 1);
1169                 piinfo->piflags = mono_metadata_decode_row_col (im, piinfo->implmap_idx - 1, MONO_IMPLMAP_FLAGS);
1170         }
1171                 
1172         /* FIXME: lazyness for generics too, but how? */
1173         if (!result->klass->dummy && !(result->flags & METHOD_ATTRIBUTE_ABSTRACT) &&
1174             !(cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) &&
1175             !(result->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) && container) {
1176                 gpointer loc = mono_image_rva_map (image, cols [0]);
1177                 g_assert (loc);
1178                 ((MonoMethodNormal *) result)->header = mono_metadata_parse_mh_full (
1179                         image, (MonoGenericContext *) container, loc);
1180         }
1181                 
1182         result->generic_container = generic_container;
1183
1184         return result;
1185 }
1186
1187 MonoMethod *
1188 mono_get_method (MonoImage *image, guint32 token, MonoClass *klass)
1189 {
1190         return mono_get_method_full (image, token, klass, NULL);
1191 }
1192
1193 MonoMethod *
1194 mono_get_method_full (MonoImage *image, guint32 token, MonoClass *klass,
1195                       MonoGenericContext *context)
1196 {
1197         MonoMethod *result;
1198
1199         /* We do everything inside the lock to prevent creation races */
1200
1201         mono_loader_lock ();
1202
1203         if ((result = g_hash_table_lookup (image->method_cache, GINT_TO_POINTER (token)))) {
1204                 mono_loader_unlock ();
1205                 return result;
1206         }
1207
1208         result = mono_get_method_from_token (image, token, klass, context);
1209
1210         //printf ("GET: %s\n", mono_method_full_name (result, TRUE));
1211
1212         if (!(result && result->is_inflated))
1213                 g_hash_table_insert (image->method_cache, GINT_TO_POINTER (token), result);
1214
1215         mono_loader_unlock ();
1216
1217         return result;
1218 }
1219
1220 /**
1221  * mono_get_method_constrained:
1222  *
1223  * This is used when JITing the `constrained.' opcode.
1224  */
1225 MonoMethod *
1226 mono_get_method_constrained (MonoImage *image, guint32 token, MonoClass *constrained_class,
1227                              MonoGenericContext *context)
1228 {
1229         MonoMethod *method, *result;
1230         MonoClass *ic = NULL;
1231         MonoGenericClass *gclass = NULL;
1232
1233         mono_loader_lock ();
1234
1235         method = mono_get_method_from_token (image, token, NULL, context);
1236         if (!method) {
1237                 mono_loader_unlock ();
1238                 return NULL;
1239         }
1240
1241         mono_class_init (constrained_class);
1242         method = mono_get_inflated_method (method);
1243
1244         if ((constrained_class != method->klass) && (method->klass->interface_id != 0))
1245                 ic = method->klass;
1246
1247         if (constrained_class->generic_class)
1248                 gclass = constrained_class->generic_class;
1249
1250         result = find_method (constrained_class, ic, method->name, mono_method_signature (method));
1251         if (!result)
1252                 g_warning ("Missing method %s in assembly %s token %x", method->name,
1253                            image->name, token);
1254
1255         if (gclass)
1256                 result = mono_class_inflate_generic_method (result, gclass->context);
1257
1258         mono_loader_unlock ();
1259         return result;
1260 }
1261
1262 void
1263 mono_free_method  (MonoMethod *method)
1264 {
1265         if (method->signature) {
1266                 /* 
1267                  * FIXME: This causes crashes because the types inside signatures and
1268                  * locals are shared.
1269                  */
1270                 /* mono_metadata_free_method_signature (method->signature); */
1271                 g_free (method->signature);
1272         }
1273
1274         if (method->dynamic) {
1275                 MonoMethodWrapper *mw = (MonoMethodWrapper*)method;
1276
1277                 g_free ((char*)method->name);
1278                 if (mw->method.header)
1279                         g_free ((char*)mw->method.header->code);
1280                 g_free (mw->method_data);
1281         }
1282
1283         if (!(method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && ((MonoMethodNormal *)method)->header) {
1284                 /* FIXME: Ditto */
1285                 /* mono_metadata_free_mh (((MonoMethodNormal *)method)->header); */
1286                 g_free (((MonoMethodNormal*)method)->header);
1287         }
1288
1289         g_free (method);
1290 }
1291
1292 void
1293 mono_method_get_param_names (MonoMethod *method, const char **names)
1294 {
1295         int i, lastp;
1296         MonoClass *klass = method->klass;
1297         MonoTableInfo *methodt;
1298         MonoTableInfo *paramt;
1299         guint32 idx;
1300
1301         if (!mono_method_signature (method)->param_count)
1302                 return;
1303         for (i = 0; i < mono_method_signature (method)->param_count; ++i)
1304                 names [i] = "";
1305
1306         if (klass->generic_class) /* copy the names later */
1307                 return;
1308
1309         mono_class_init (klass);
1310
1311         if (klass->image->dynamic) {
1312                 MonoReflectionMethodAux *method_aux = 
1313                         g_hash_table_lookup (
1314                                 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
1315                 if (method_aux && method_aux->param_names) {
1316                         for (i = 0; i < mono_method_signature (method)->param_count; ++i)
1317                                 if (method_aux->param_names [i + 1])
1318                                         names [i] = method_aux->param_names [i + 1];
1319                 }
1320                 return;
1321         }
1322
1323         methodt = &klass->image->tables [MONO_TABLE_METHOD];
1324         paramt = &klass->image->tables [MONO_TABLE_PARAM];
1325         idx = mono_method_get_index (method);
1326         if (idx > 0) {
1327                 guint32 cols [MONO_PARAM_SIZE];
1328                 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
1329
1330                 if (idx < methodt->rows)
1331                         lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
1332                 else
1333                         lastp = paramt->rows + 1;
1334                 for (i = param_index; i < lastp; ++i) {
1335                         mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
1336                         if (cols [MONO_PARAM_SEQUENCE]) /* skip return param spec */
1337                                 names [cols [MONO_PARAM_SEQUENCE] - 1] = mono_metadata_string_heap (klass->image, cols [MONO_PARAM_NAME]);
1338                 }
1339                 return;
1340         }
1341 }
1342
1343 guint32
1344 mono_method_get_param_token (MonoMethod *method, int index)
1345 {
1346         MonoClass *klass = method->klass;
1347         MonoTableInfo *methodt;
1348         guint32 idx;
1349
1350         if (klass->generic_class)
1351                 g_assert_not_reached ();
1352
1353         mono_class_init (klass);
1354
1355         if (klass->image->dynamic) {
1356                 g_assert_not_reached ();
1357         }
1358
1359         methodt = &klass->image->tables [MONO_TABLE_METHOD];
1360         idx = mono_method_get_index (method);
1361         if (idx > 0) {
1362                 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
1363
1364                 return mono_metadata_make_token (MONO_TABLE_PARAM, param_index + index);
1365         }
1366
1367         return 0;
1368 }
1369
1370 void
1371 mono_method_get_marshal_info (MonoMethod *method, MonoMarshalSpec **mspecs)
1372 {
1373         int i, lastp;
1374         MonoClass *klass = method->klass;
1375         MonoTableInfo *methodt;
1376         MonoTableInfo *paramt;
1377         guint32 idx;
1378
1379         for (i = 0; i < mono_method_signature (method)->param_count + 1; ++i)
1380                 mspecs [i] = NULL;
1381
1382         if (method->klass->image->dynamic) {
1383                 MonoReflectionMethodAux *method_aux = 
1384                         g_hash_table_lookup (
1385                                 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
1386                 if (method_aux && method_aux->param_marshall) {
1387                         MonoMarshalSpec **dyn_specs = method_aux->param_marshall;
1388                         for (i = 0; i < mono_method_signature (method)->param_count + 1; ++i)
1389                                 if (dyn_specs [i]) {
1390                                         mspecs [i] = g_new0 (MonoMarshalSpec, 1);
1391                                         memcpy (mspecs [i], dyn_specs [i], sizeof (MonoMarshalSpec));
1392                                 }
1393                 }
1394                 return;
1395         }
1396
1397         mono_class_init (klass);
1398
1399         methodt = &klass->image->tables [MONO_TABLE_METHOD];
1400         paramt = &klass->image->tables [MONO_TABLE_PARAM];
1401         idx = mono_method_get_index (method);
1402         if (idx > 0) {
1403                 guint32 cols [MONO_PARAM_SIZE];
1404                 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
1405
1406                 if (idx < methodt->rows)
1407                         lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
1408                 else
1409                         lastp = paramt->rows + 1;
1410
1411                 for (i = param_index; i < lastp; ++i) {
1412                         mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
1413
1414                         if (cols [MONO_PARAM_FLAGS] & PARAM_ATTRIBUTE_HAS_FIELD_MARSHAL) {
1415                                 const char *tp;
1416                                 tp = mono_metadata_get_marshal_info (klass->image, i - 1, FALSE);
1417                                 g_assert (tp);
1418                                 mspecs [cols [MONO_PARAM_SEQUENCE]]= mono_metadata_parse_marshal_spec (klass->image, tp);
1419                         }
1420                 }
1421
1422                 return;
1423         }
1424 }
1425
1426 gboolean
1427 mono_method_has_marshal_info (MonoMethod *method)
1428 {
1429         int i, lastp;
1430         MonoClass *klass = method->klass;
1431         MonoTableInfo *methodt;
1432         MonoTableInfo *paramt;
1433         guint32 idx;
1434
1435         if (method->klass->image->dynamic) {
1436                 MonoReflectionMethodAux *method_aux = 
1437                         g_hash_table_lookup (
1438                                 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
1439                 MonoMarshalSpec **dyn_specs = method_aux->param_marshall;
1440                 if (dyn_specs) {
1441                         for (i = 0; i < mono_method_signature (method)->param_count + 1; ++i)
1442                                 if (dyn_specs [i])
1443                                         return TRUE;
1444                 }
1445                 return FALSE;
1446         }
1447
1448         mono_class_init (klass);
1449
1450         methodt = &klass->image->tables [MONO_TABLE_METHOD];
1451         paramt = &klass->image->tables [MONO_TABLE_PARAM];
1452         idx = mono_method_get_index (method);
1453         if (idx > 0) {
1454                 guint32 cols [MONO_PARAM_SIZE];
1455                 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
1456                 
1457                 if (idx + 1 < methodt->rows)
1458                         lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
1459                 else
1460                         lastp = paramt->rows + 1;
1461
1462                 for (i = param_index; i < lastp; ++i) {
1463                         mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
1464
1465                         if (cols [MONO_PARAM_FLAGS] & PARAM_ATTRIBUTE_HAS_FIELD_MARSHAL)
1466                                 return TRUE;
1467                 }
1468                 return FALSE;
1469         }
1470         return FALSE;
1471 }
1472
1473 gpointer
1474 mono_method_get_wrapper_data (MonoMethod *method, guint32 id)
1475 {
1476         void **data;
1477         g_assert (method != NULL);
1478         g_assert (method->wrapper_type != MONO_WRAPPER_NONE);
1479
1480         data = ((MonoMethodWrapper *)method)->method_data;
1481         g_assert (data != NULL);
1482         g_assert (id <= GPOINTER_TO_UINT (*data));
1483         return data [id];
1484 }
1485
1486 static void
1487 default_stack_walk (MonoStackWalk func, gboolean do_il_offset, gpointer user_data) {
1488         g_error ("stack walk not installed");
1489 }
1490
1491 static MonoStackWalkImpl stack_walk = default_stack_walk;
1492
1493 void
1494 mono_stack_walk (MonoStackWalk func, gpointer user_data)
1495 {
1496         stack_walk (func, TRUE, user_data);
1497 }
1498
1499 void
1500 mono_stack_walk_no_il (MonoStackWalk func, gpointer user_data)
1501 {
1502         stack_walk (func, FALSE, user_data);
1503 }
1504
1505 void
1506 mono_install_stack_walk (MonoStackWalkImpl func)
1507 {
1508         stack_walk = func;
1509 }
1510
1511 static gboolean
1512 last_managed (MonoMethod *m, gint no, gint ilo, gboolean managed, gpointer data)
1513 {
1514         MonoMethod **dest = data;
1515         *dest = m;
1516         /*g_print ("In %s::%s [%d] [%d]\n", m->klass->name, m->name, no, ilo);*/
1517
1518         return managed;
1519 }
1520
1521 MonoMethod*
1522 mono_method_get_last_managed (void)
1523 {
1524         MonoMethod *m = NULL;
1525         stack_walk (last_managed, FALSE, &m);
1526         return m;
1527 }
1528
1529 void
1530 mono_loader_lock (void)
1531 {
1532         EnterCriticalSection (&loader_mutex);
1533 }
1534
1535 void
1536 mono_loader_unlock (void)
1537 {
1538         LeaveCriticalSection (&loader_mutex);
1539 }
1540
1541 MonoMethodSignature* 
1542 mono_method_signature (MonoMethod *m)
1543 {
1544         m = mono_get_inflated_method (m);
1545         return mono_method_signature_full (m, NULL);
1546 }
1547
1548 MonoMethodSignature* 
1549 mono_method_signature_full (MonoMethod *m, MonoGenericContainer *container)
1550 {
1551         int idx;
1552         int size;
1553         MonoImage* img;
1554         const char *sig;
1555         
1556         if (m->signature)
1557                 return m->signature;
1558                 
1559         mono_loader_lock ();
1560         
1561         if (m->signature) {
1562                 mono_loader_unlock ();
1563                 return m->signature;
1564         }
1565         
1566         g_assert (mono_metadata_token_table (m->token) == MONO_TABLE_METHOD);
1567         idx = mono_metadata_token_index (m->token);
1568         img = m->klass->image;
1569         
1570         sig = mono_metadata_blob_heap (img, mono_metadata_decode_row_col (&img->tables [MONO_TABLE_METHOD], idx - 1, MONO_METHOD_SIGNATURE));
1571         size = mono_metadata_decode_blob_size (sig, &sig);
1572         
1573         m->signature = mono_metadata_parse_method_signature_full (img, container, idx, sig, NULL);
1574         
1575         if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
1576                 m->signature->pinvoke = 1;
1577         else if ((m->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) && (!(m->iflags & METHOD_IMPL_ATTRIBUTE_NATIVE))) {
1578                 MonoCallConvention conv = 0;
1579                 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)m;
1580                 m->signature->pinvoke = 1;
1581                 
1582                 switch (piinfo->piflags & PINVOKE_ATTRIBUTE_CALL_CONV_MASK) {
1583                 case 0: /* no call conv, so using default */
1584                 case PINVOKE_ATTRIBUTE_CALL_CONV_WINAPI:
1585                         conv = MONO_CALL_DEFAULT;
1586                         break;
1587                 case PINVOKE_ATTRIBUTE_CALL_CONV_CDECL:
1588                         conv = MONO_CALL_C;
1589                         break;
1590                 case PINVOKE_ATTRIBUTE_CALL_CONV_STDCALL:
1591                         conv = MONO_CALL_STDCALL;
1592                         break;
1593                 case PINVOKE_ATTRIBUTE_CALL_CONV_THISCALL:
1594                         conv = MONO_CALL_THISCALL;
1595                         break;
1596                 case PINVOKE_ATTRIBUTE_CALL_CONV_FASTCALL:
1597                         conv = MONO_CALL_FASTCALL;
1598                         break;
1599                 case PINVOKE_ATTRIBUTE_CALL_CONV_GENERIC:
1600                 case PINVOKE_ATTRIBUTE_CALL_CONV_GENERICINST:
1601                 default:
1602                         g_warning ("unsupported calling convention : 0x%04x", piinfo->piflags);
1603                         g_assert_not_reached ();
1604                 }       
1605                 m->signature->call_convention = conv;
1606         }
1607         
1608         mono_loader_unlock ();
1609         return m->signature;
1610 }
1611
1612 const char*
1613 mono_method_get_name (MonoMethod *method)
1614 {
1615         return method->name;
1616 }
1617
1618 MonoClass*
1619 mono_method_get_class (MonoMethod *method)
1620 {
1621         return method->klass;
1622 }
1623
1624 guint32
1625 mono_method_get_token (MonoMethod *method)
1626 {
1627         return method->token;
1628 }
1629
1630 MonoMethodHeader* 
1631 mono_method_get_header (MonoMethod *method)
1632 {
1633         int idx;
1634         guint32 rva;
1635         MonoImage* img;
1636         gpointer loc;
1637         MonoMethodNormal* mn = (MonoMethodNormal*) method;
1638         
1639         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))
1640                 return NULL;
1641         
1642 #ifdef G_LIKELY
1643         if (G_LIKELY (mn->header))
1644 #else
1645         if (mn->header)
1646 #endif
1647                 return mn->header;
1648         
1649         mono_loader_lock ();
1650         
1651         if (mn->header) {
1652                 mono_loader_unlock ();
1653                 return mn->header;
1654         }
1655         
1656         g_assert (mono_metadata_token_table (method->token) == MONO_TABLE_METHOD);
1657         idx = mono_metadata_token_index (method->token);
1658         img = method->klass->image;
1659         rva = mono_metadata_decode_row_col (&img->tables [MONO_TABLE_METHOD], idx - 1, MONO_METHOD_RVA);
1660         loc = mono_image_rva_map (img, rva);
1661         
1662         g_assert (loc);
1663         
1664         mn->header = mono_metadata_parse_mh_full (img, (MonoGenericContext *) method->generic_container, loc);
1665         
1666         mono_loader_unlock ();
1667         return mn->header;
1668 }
1669
1670 guint32
1671 mono_method_get_flags (MonoMethod *method, guint32 *iflags)
1672 {
1673         if (iflags)
1674                 *iflags = method->iflags;
1675         return method->flags;
1676 }
1677
1678 /*
1679  * Find the method index in the metadata methodDef table.
1680  */
1681 guint32
1682 mono_method_get_index (MonoMethod *method) {
1683         MonoClass *klass = method->klass;
1684         int i;
1685
1686         if (method->token)
1687                 return mono_metadata_token_index (method->token);
1688
1689         mono_class_setup_methods (klass);
1690         for (i = 0; i < klass->method.count; ++i) {
1691                 if (method == klass->methods [i])
1692                         return klass->method.first + 1 + i;
1693         }
1694         return 0;
1695 }
1696