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