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