In .:
[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  * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
10  * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
11  *
12  * This file is used by the interpreter and the JIT engine to locate
13  * assemblies.  Used to load AssemblyRef and later to resolve various
14  * kinds of `Refs'.
15  *
16  * TODO:
17  *   This should keep track of the assembly versions that we are loading.
18  *
19  */
20 #include <config.h>
21 #include <glib.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/tabledefs.h>
30 #include <mono/metadata/metadata-internals.h>
31 #include <mono/metadata/loader.h>
32 #include <mono/metadata/class-internals.h>
33 #include <mono/metadata/debug-helpers.h>
34 #include <mono/metadata/reflection.h>
35 #include <mono/metadata/profiler.h>
36 #include <mono/metadata/profiler-private.h>
37 #include <mono/metadata/exception.h>
38 #include <mono/metadata/marshal.h>
39 #include <mono/utils/mono-logger.h>
40 #include <mono/utils/mono-dl.h>
41 #include <mono/utils/mono-membar.h>
42 #include <mono/utils/mono-counters.h>
43
44 MonoDefaults mono_defaults;
45
46 /*
47  * This lock protects the hash tables inside MonoImage used by the metadata 
48  * loading functions in class.c and loader.c.
49  *
50  * See domain-internals.h for locking policy in combination with the
51  * domain lock.
52  */
53 static CRITICAL_SECTION loader_mutex;
54
55 /* Statistics */
56 static guint32 inflated_signatures_size;
57 static guint32 memberref_sig_cache_size;
58
59 /*
60  * This TLS variable contains the last type load error encountered by the loader.
61  */
62 guint32 loader_error_thread_id;
63
64 void
65 mono_loader_init ()
66 {
67         static gboolean inited;
68
69         if (!inited) {
70                 InitializeCriticalSection (&loader_mutex);
71
72                 loader_error_thread_id = TlsAlloc ();
73
74                 mono_counters_register ("Inflated signatures size",
75                                                                 MONO_COUNTER_GENERICS | MONO_COUNTER_INT, &inflated_signatures_size);
76                 mono_counters_register ("Memberref signature cache size",
77                                                                 MONO_COUNTER_METADATA | MONO_COUNTER_INT, &memberref_sig_cache_size);
78
79                 inited = TRUE;
80         }
81 }
82
83 void
84 mono_loader_cleanup (void)
85 {
86         TlsFree (loader_error_thread_id);
87
88         /*DeleteCriticalSection (&loader_mutex);*/
89 }
90
91 /*
92  * Handling of type load errors should be done as follows:
93  *
94  *   If something could not be loaded, the loader should call one of the
95  * mono_loader_set_error_XXX functions ()
96  * with the appropriate arguments, then return NULL to report the failure. The error 
97  * should be propagated until it reaches code which can throw managed exceptions. At that
98  * point, an exception should be thrown based on the information returned by
99  * mono_loader_get_last_error (). Then the error should be cleared by calling 
100  * mono_loader_clear_error ().
101  */
102
103 static void
104 set_loader_error (MonoLoaderError *error)
105 {
106         TlsSetValue (loader_error_thread_id, error);
107 }
108
109 /**
110  * mono_loader_set_error_assembly_load:
111  *
112  * Set the loader error for this thread. 
113  */
114 void
115 mono_loader_set_error_assembly_load (const char *assembly_name, gboolean ref_only)
116 {
117         MonoLoaderError *error;
118
119         if (mono_loader_get_last_error ()) 
120                 return;
121
122         error = g_new0 (MonoLoaderError, 1);
123         error->exception_type = MONO_EXCEPTION_FILE_NOT_FOUND;
124         error->assembly_name = g_strdup (assembly_name);
125         error->ref_only = ref_only;
126
127         /* 
128          * This is not strictly needed, but some (most) of the loader code still
129          * can't deal with load errors, and this message is more helpful than an
130          * assert.
131          */
132         if (ref_only)
133                 g_warning ("Cannot resolve dependency to assembly '%s' because it has not been preloaded. When using the ReflectionOnly APIs, dependent assemblies must be pre-loaded or loaded on demand through the ReflectionOnlyAssemblyResolve event.", assembly_name);
134         else
135                 g_warning ("Could not load file or assembly '%s' or one of its dependencies.", assembly_name);
136
137         set_loader_error (error);
138 }
139
140 /**
141  * mono_loader_set_error_type_load:
142  *
143  * Set the loader error for this thread. 
144  */
145 void
146 mono_loader_set_error_type_load (const char *class_name, const char *assembly_name)
147 {
148         MonoLoaderError *error;
149
150         if (mono_loader_get_last_error ()) 
151                 return;
152
153         error = g_new0 (MonoLoaderError, 1);
154         error->exception_type = MONO_EXCEPTION_TYPE_LOAD;
155         error->class_name = g_strdup (class_name);
156         error->assembly_name = g_strdup (assembly_name);
157
158         /* 
159          * This is not strictly needed, but some (most) of the loader code still
160          * can't deal with load errors, and this message is more helpful than an
161          * assert.
162          */
163         g_warning ("The class %s could not be loaded, used in %s", class_name, assembly_name);
164
165         set_loader_error (error);
166 }
167
168 /*
169  * mono_loader_set_error_method_load:
170  *
171  *   Set the loader error for this thread. MEMBER_NAME should point to a string
172  * inside metadata.
173  */
174 void
175 mono_loader_set_error_method_load (const char *class_name, const char *member_name)
176 {
177         MonoLoaderError *error;
178
179         /* FIXME: Store the signature as well */
180         if (mono_loader_get_last_error ())
181                 return;
182
183         error = g_new0 (MonoLoaderError, 1);
184         error->exception_type = MONO_EXCEPTION_MISSING_METHOD;
185         error->class_name = g_strdup (class_name);
186         error->member_name = member_name;
187
188         set_loader_error (error);
189 }
190
191 /*
192  * mono_loader_set_error_field_load:
193  *
194  * Set the loader error for this thread. MEMBER_NAME should point to a string
195  * inside metadata.
196  */
197 void
198 mono_loader_set_error_field_load (MonoClass *klass, const char *member_name)
199 {
200         MonoLoaderError *error;
201
202         /* FIXME: Store the signature as well */
203         if (mono_loader_get_last_error ())
204                 return;
205
206         error = g_new0 (MonoLoaderError, 1);
207         error->exception_type = MONO_EXCEPTION_MISSING_FIELD;
208         error->klass = klass;
209         error->member_name = member_name;
210
211         set_loader_error (error);
212 }
213
214 /*
215  * mono_loader_set_error_bad_image:
216  *
217  * Set the loader error for this thread. 
218  */
219 void
220 mono_loader_set_error_bad_image (char *msg)
221 {
222         MonoLoaderError *error;
223
224         if (mono_loader_get_last_error ())
225                 return;
226
227         error = g_new0 (MonoLoaderError, 1);
228         error->exception_type = MONO_EXCEPTION_BAD_IMAGE;
229         error->msg = msg;
230
231         set_loader_error (error);
232 }       
233
234
235 /*
236  * mono_loader_get_last_error:
237  *
238  *   Returns information about the last type load exception encountered by the loader, or
239  * NULL. After use, the exception should be cleared by calling mono_loader_clear_error.
240  */
241 MonoLoaderError*
242 mono_loader_get_last_error (void)
243 {
244         return (MonoLoaderError*)TlsGetValue (loader_error_thread_id);
245 }
246
247 /**
248  * mono_loader_clear_error:
249  *
250  * Disposes any loader error messages on this thread
251  */
252 void
253 mono_loader_clear_error (void)
254 {
255         MonoLoaderError *ex = (MonoLoaderError*)TlsGetValue (loader_error_thread_id);
256
257         if (ex) {
258                 g_free (ex->class_name);
259                 g_free (ex->assembly_name);
260                 g_free (ex->msg);
261                 g_free (ex);
262         
263                 TlsSetValue (loader_error_thread_id, NULL);
264         }
265 }
266
267 /**
268  * mono_loader_error_prepare_exception:
269  * @error: The MonoLoaderError to turn into an exception
270  *
271  * This turns a MonoLoaderError into an exception that can be thrown
272  * and resets the Mono Loader Error state during this process.
273  *
274  */
275 MonoException *
276 mono_loader_error_prepare_exception (MonoLoaderError *error)
277 {
278         MonoException *ex = NULL;
279
280         switch (error->exception_type) {
281         case MONO_EXCEPTION_TYPE_LOAD: {
282                 char *cname = g_strdup (error->class_name);
283                 char *aname = g_strdup (error->assembly_name);
284                 MonoString *class_name;
285                 
286                 mono_loader_clear_error ();
287                 
288                 class_name = mono_string_new (mono_domain_get (), cname);
289
290                 ex = mono_get_exception_type_load (class_name, aname);
291                 g_free (cname);
292                 g_free (aname);
293                 break;
294         }
295         case MONO_EXCEPTION_MISSING_METHOD: {
296                 char *cname = g_strdup (error->class_name);
297                 char *aname = g_strdup (error->member_name);
298                 
299                 mono_loader_clear_error ();
300                 ex = mono_get_exception_missing_method (cname, aname);
301                 g_free (cname);
302                 g_free (aname);
303                 break;
304         }
305                 
306         case MONO_EXCEPTION_MISSING_FIELD: {
307                 char *cnspace = g_strdup (*error->klass->name_space ? error->klass->name_space : "");
308                 char *cname = g_strdup (error->klass->name);
309                 char *cmembername = g_strdup (error->member_name);
310                 char *class_name;
311
312                 mono_loader_clear_error ();
313                 class_name = g_strdup_printf ("%s%s%s", cnspace, cnspace ? "." : "", cname);
314                 
315                 ex = mono_get_exception_missing_field (class_name, cmembername);
316                 g_free (class_name);
317                 g_free (cname);
318                 g_free (cmembername);
319                 g_free (cnspace);
320                 break;
321         }
322         
323         case MONO_EXCEPTION_FILE_NOT_FOUND: {
324                 char *msg;
325                 char *filename;
326
327                 if (error->ref_only)
328                         msg = g_strdup_printf ("Cannot resolve dependency to assembly '%s' because it has not been preloaded. When using the ReflectionOnly APIs, dependent assemblies must be pre-loaded or loaded on demand through the ReflectionOnlyAssemblyResolve event.", error->assembly_name);
329                 else
330                         msg = g_strdup_printf ("Could not load file or assembly '%s' or one of its dependencies.", error->assembly_name);
331                 filename = g_strdup (error->assembly_name);
332                 /* Has to call this before calling anything which might call mono_class_init () */
333                 mono_loader_clear_error ();
334                 ex = mono_get_exception_file_not_found2 (msg, mono_string_new (mono_domain_get (), filename));
335                 g_free (msg);
336                 g_free (filename);
337                 break;
338         }
339
340         case MONO_EXCEPTION_BAD_IMAGE: {
341                 char *msg = g_strdup (error->msg);
342                 mono_loader_clear_error ();
343                 ex = mono_get_exception_bad_image_format (msg);
344                 g_free (msg);
345                 break;
346         }
347
348         default:
349                 g_assert_not_reached ();
350         }
351
352         return ex;
353 }
354
355 /*
356  * find_cached_memberref_sig:
357  *
358  *   Return a cached copy of the memberref signature identified by SIG_IDX.
359  * We use a gpointer since the cache stores both MonoTypes and MonoMethodSignatures.
360  * A cache is needed since the type/signature parsing routines allocate everything 
361  * from a mempool, so without a cache, multiple requests for the same signature would 
362  * lead to unbounded memory growth. For normal methods/fields this is not a problem 
363  * since the resulting methods/fields are cached, but inflated methods/fields cannot
364  * be cached.
365  * LOCKING: Acquires the loader lock.
366  */
367 static gpointer
368 find_cached_memberref_sig (MonoImage *image, guint32 sig_idx)
369 {
370         gpointer res;
371
372         mono_loader_lock ();
373         res = g_hash_table_lookup (image->memberref_signatures, GUINT_TO_POINTER (sig_idx));
374         mono_loader_unlock ();
375
376         return res;
377 }
378
379 static gpointer
380 cache_memberref_sig (MonoImage *image, guint32 sig_idx, gpointer sig)
381 {
382         gpointer prev_sig;
383
384         mono_loader_lock ();
385         prev_sig = g_hash_table_lookup (image->memberref_signatures, GUINT_TO_POINTER (sig_idx));
386         if (prev_sig) {
387                 /* Somebody got in before us */
388                 sig = prev_sig;
389         }
390         else {
391                 g_hash_table_insert (image->memberref_signatures, GUINT_TO_POINTER (sig_idx), sig);
392                 /* An approximation based on glib 2.18 */
393                 memberref_sig_cache_size += sizeof (gpointer) * 4;
394         }
395
396         mono_loader_unlock ();
397
398         return sig;
399 }
400
401 static MonoClassField*
402 field_from_memberref (MonoImage *image, guint32 token, MonoClass **retklass,
403                       MonoGenericContext *context)
404 {
405         MonoClass *klass;
406         MonoClassField *field, *sig_field = NULL;
407         MonoTableInfo *tables = image->tables;
408         MonoType *sig_type;
409         guint32 cols[6];
410         guint32 nindex, class;
411         const char *fname;
412         const char *ptr;
413         guint32 idx = mono_metadata_token_index (token);
414
415         mono_metadata_decode_row (&tables [MONO_TABLE_MEMBERREF], idx-1, cols, MONO_MEMBERREF_SIZE);
416         nindex = cols [MONO_MEMBERREF_CLASS] >> MONO_MEMBERREF_PARENT_BITS;
417         class = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
418
419         fname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
420
421         ptr = mono_metadata_blob_heap (image, cols [MONO_MEMBERREF_SIGNATURE]);
422         mono_metadata_decode_blob_size (ptr, &ptr);
423         /* we may want to check the signature here... */
424
425         if (*ptr++ != 0x6) {
426                 mono_loader_set_error_bad_image (g_strdup_printf ("Bad field signature class token %08x field name %s token %08x", class, fname, token));
427                 return NULL;
428         }
429         /* FIXME: This needs a cache, especially for generic instances, since
430          * mono_metadata_parse_type () allocates everything from a mempool.
431          */
432         sig_type = find_cached_memberref_sig (image, cols [MONO_MEMBERREF_SIGNATURE]);
433         if (!sig_type) {
434                 sig_type = mono_metadata_parse_type (image, MONO_PARSE_TYPE, 0, ptr, &ptr);
435                 sig_type = cache_memberref_sig (image, cols [MONO_MEMBERREF_SIGNATURE], sig_type);
436         }
437
438         switch (class) {
439         case MONO_MEMBERREF_PARENT_TYPEDEF:
440                 klass = mono_class_get (image, MONO_TOKEN_TYPE_DEF | nindex);
441                 if (!klass) {
442                         char *name = mono_class_name_from_token (image, MONO_TOKEN_TYPE_DEF | nindex);
443                         g_warning ("Missing field %s in class %s (typedef index %d)", fname, name, nindex);
444                         mono_loader_set_error_type_load (name, image->assembly_name);
445                         g_free (name);
446                         return NULL;
447                 }
448                 mono_class_init (klass);
449                 if (retklass)
450                         *retklass = klass;
451                 sig_field = field = mono_class_get_field_from_name (klass, fname);
452                 break;
453         case MONO_MEMBERREF_PARENT_TYPEREF:
454                 klass = mono_class_from_typeref (image, MONO_TOKEN_TYPE_REF | nindex);
455                 if (!klass) {
456                         char *name = mono_class_name_from_token (image, MONO_TOKEN_TYPE_REF | nindex);
457                         g_warning ("missing field %s in class %s (typeref index %d)", fname, name, nindex);
458                         mono_loader_set_error_type_load (name, image->assembly_name);
459                         g_free (name);
460                         return NULL;
461                 }
462                 mono_class_init (klass);
463                 if (retklass)
464                         *retklass = klass;
465                 sig_field = field = mono_class_get_field_from_name (klass, fname);
466                 break;
467         case MONO_MEMBERREF_PARENT_TYPESPEC: {
468                 klass = mono_class_get_full (image, MONO_TOKEN_TYPE_SPEC | nindex, context);
469                 //FIXME can't klass be null?
470                 mono_class_init (klass);
471                 if (retklass)
472                         *retklass = klass;
473                 field = mono_class_get_field_from_name (klass, fname);
474                 if (field)
475                         sig_field = mono_metadata_get_corresponding_field_from_generic_type_definition (field);
476                 break;
477         }
478         default:
479                 g_warning ("field load from %x", class);
480                 return NULL;
481         }
482
483         if (!field)
484                 mono_loader_set_error_field_load (klass, fname);
485         else if (sig_field && !mono_metadata_type_equal_full (sig_type, sig_field->type, TRUE)) {
486                 mono_loader_set_error_field_load (klass, fname);
487                 return NULL;
488         }
489
490         return field;
491 }
492
493 MonoClassField*
494 mono_field_from_token (MonoImage *image, guint32 token, MonoClass **retklass,
495                        MonoGenericContext *context)
496 {
497         MonoClass *k;
498         guint32 type;
499         MonoClassField *field;
500
501         if (image->dynamic) {
502                 MonoClassField *result;
503                 MonoClass *handle_class;
504
505                 *retklass = NULL;
506                 result = mono_lookup_dynamic_token_class (image, token, TRUE, &handle_class, context);
507                 // This checks the memberref type as well
508                 if (result && handle_class != mono_defaults.fieldhandle_class) {
509                         mono_loader_set_error_bad_image (g_strdup ("Bad field token."));
510                         return NULL;
511                 }
512                 *retklass = result->parent;
513                 return result;
514         }
515
516         mono_loader_lock ();
517         if ((field = g_hash_table_lookup (image->field_cache, GUINT_TO_POINTER (token)))) {
518                 *retklass = field->parent;
519                 mono_loader_unlock ();
520                 return field;
521         }
522         mono_loader_unlock ();
523
524         if (mono_metadata_token_table (token) == MONO_TABLE_MEMBERREF)
525                 field = field_from_memberref (image, token, retklass, context);
526         else {
527                 type = mono_metadata_typedef_from_field (image, mono_metadata_token_index (token));
528                 if (!type)
529                         return NULL;
530                 k = mono_class_get (image, MONO_TOKEN_TYPE_DEF | type);
531                 if (!k)
532                         return NULL;
533                 mono_class_init (k);
534                 if (retklass)
535                         *retklass = k;
536                 field = mono_class_get_field (k, token);
537         }
538
539         mono_loader_lock ();
540         if (field && !field->parent->generic_class && !field->parent->generic_container)
541                 g_hash_table_insert (image->field_cache, GUINT_TO_POINTER (token), field);
542         mono_loader_unlock ();
543         return field;
544 }
545
546 static gboolean
547 mono_metadata_signature_vararg_match (MonoMethodSignature *sig1, MonoMethodSignature *sig2)
548 {
549         int i;
550
551         if (sig1->hasthis != sig2->hasthis ||
552             sig1->sentinelpos != sig2->sentinelpos)
553                 return FALSE;
554
555         for (i = 0; i < sig1->sentinelpos; i++) { 
556                 MonoType *p1 = sig1->params[i];
557                 MonoType *p2 = sig2->params[i];
558
559                 /*if (p1->attrs != p2->attrs)
560                         return FALSE;
561                 */
562                 if (!mono_metadata_type_equal (p1, p2))
563                         return FALSE;
564         }
565
566         if (!mono_metadata_type_equal (sig1->ret, sig2->ret))
567                 return FALSE;
568         return TRUE;
569 }
570
571 static MonoMethod *
572 find_method_in_class (MonoClass *klass, const char *name, const char *qname, const char *fqname,
573                       MonoMethodSignature *sig, MonoClass *from_class)
574 {
575         int i;
576
577         /* Search directly in the metadata to avoid calling setup_methods () */
578
579         /* FIXME: !from_class->generic_class condition causes test failures. */
580         if (klass->type_token && !klass->image->dynamic && !klass->methods && !klass->rank && klass == from_class && !from_class->generic_class) {
581                 for (i = 0; i < klass->method.count; ++i) {
582                         guint32 cols [MONO_METHOD_SIZE];
583                         MonoMethod *method;
584                         const char *m_name;
585
586                         mono_metadata_decode_table_row (klass->image, MONO_TABLE_METHOD, klass->method.first + i, cols, MONO_METHOD_SIZE);
587
588                         m_name = mono_metadata_string_heap (klass->image, cols [MONO_METHOD_NAME]);
589
590                         if (!((fqname && !strcmp (m_name, fqname)) ||
591                                   (qname && !strcmp (m_name, qname)) ||
592                                   (name && !strcmp (m_name, name))))
593                                 continue;
594
595                         method = mono_get_method (klass->image, MONO_TOKEN_METHOD_DEF | (klass->method.first + i + 1), klass);
596                         if (method && (sig->call_convention != MONO_CALL_VARARG) && mono_metadata_signature_equal (sig, mono_method_signature (method)))
597                                 return method;
598                 }
599         }
600
601         mono_class_setup_methods (klass);
602         for (i = 0; i < klass->method.count; ++i) {
603                 MonoMethod *m = klass->methods [i];
604
605                 if (!((fqname && !strcmp (m->name, fqname)) ||
606                       (qname && !strcmp (m->name, qname)) ||
607                       (name && !strcmp (m->name, name))))
608                         continue;
609
610                 if (sig->call_convention == MONO_CALL_VARARG) {
611                         if (mono_metadata_signature_vararg_match (sig, mono_method_signature (m)))
612                                 break;
613                 } else {
614                         if (mono_metadata_signature_equal (sig, mono_method_signature (m)))
615                                 break;
616                 }
617         }
618
619         if (i < klass->method.count)
620                 return mono_class_get_method_by_index (from_class, i);
621         return NULL;
622 }
623
624 static MonoMethod *
625 find_method (MonoClass *in_class, MonoClass *ic, const char* name, MonoMethodSignature *sig, MonoClass *from_class)
626 {
627         int i;
628         char *qname, *fqname, *class_name;
629         gboolean is_interface;
630         MonoMethod *result = NULL;
631
632         is_interface = MONO_CLASS_IS_INTERFACE (in_class);
633
634         if (ic) {
635                 class_name = mono_type_get_name_full (&ic->byval_arg, MONO_TYPE_NAME_FORMAT_IL);
636
637                 qname = g_strconcat (class_name, ".", name, NULL); 
638                 if (ic->name_space && ic->name_space [0])
639                         fqname = g_strconcat (ic->name_space, ".", class_name, ".", name, NULL);
640                 else
641                         fqname = NULL;
642         } else
643                 class_name = qname = fqname = NULL;
644
645         while (in_class) {
646                 g_assert (from_class);
647                 result = find_method_in_class (in_class, name, qname, fqname, sig, from_class);
648                 if (result)
649                         goto out;
650
651                 if (name [0] == '.' && (!strcmp (name, ".ctor") || !strcmp (name, ".cctor")))
652                         break;
653
654                 g_assert (from_class->interface_offsets_count == in_class->interface_offsets_count);
655                 for (i = 0; i < in_class->interface_offsets_count; i++) {
656                         MonoClass *in_ic = in_class->interfaces_packed [i];
657                         MonoClass *from_ic = from_class->interfaces_packed [i];
658                         char *ic_qname, *ic_fqname, *ic_class_name;
659                         
660                         ic_class_name = mono_type_get_name_full (&in_ic->byval_arg, MONO_TYPE_NAME_FORMAT_IL);
661                         ic_qname = g_strconcat (ic_class_name, ".", name, NULL); 
662                         if (in_ic->name_space && in_ic->name_space [0])
663                                 ic_fqname = g_strconcat (in_ic->name_space, ".", ic_class_name, ".", name, NULL);
664                         else
665                                 ic_fqname = NULL;
666
667                         result = find_method_in_class (in_ic, ic ? name : NULL, ic_qname, ic_fqname, sig, from_ic);
668                         g_free (ic_class_name);
669                         g_free (ic_fqname);
670                         g_free (ic_qname);
671                         if (result)
672                                 goto out;
673                 }
674
675                 in_class = in_class->parent;
676                 from_class = from_class->parent;
677         }
678         g_assert (!in_class == !from_class);
679
680         if (is_interface)
681                 result = find_method_in_class (mono_defaults.object_class, name, qname, fqname, sig, mono_defaults.object_class);
682
683  out:
684         g_free (class_name);
685         g_free (fqname);
686         g_free (qname);
687         return result;
688 }
689
690 static MonoMethodSignature*
691 inflate_generic_signature (MonoImage *image, MonoMethodSignature *sig, MonoGenericContext *context)
692 {
693         MonoMethodSignature *res;
694         gboolean is_open;
695         int i;
696
697         if (!context)
698                 return sig;
699
700         res = g_malloc0 (sizeof (MonoMethodSignature) + ((gint32)sig->param_count - MONO_ZERO_LEN_ARRAY) * sizeof (MonoType*));
701         res->param_count = sig->param_count;
702         res->sentinelpos = -1;
703         res->ret = mono_class_inflate_generic_type (sig->ret, context);
704         is_open = mono_class_is_open_constructed_type (res->ret);
705         for (i = 0; i < sig->param_count; ++i) {
706                 res->params [i] = mono_class_inflate_generic_type (sig->params [i], context);
707                 if (!is_open)
708                         is_open = mono_class_is_open_constructed_type (res->params [i]);
709         }
710         res->hasthis = sig->hasthis;
711         res->explicit_this = sig->explicit_this;
712         res->call_convention = sig->call_convention;
713         res->pinvoke = sig->pinvoke;
714         res->generic_param_count = sig->generic_param_count;
715         res->sentinelpos = sig->sentinelpos;
716         res->has_type_parameters = is_open;
717         res->is_inflated = 1;
718         return res;
719 }
720
721 static MonoMethodHeader*
722 inflate_generic_header (MonoMethodHeader *header, MonoGenericContext *context)
723 {
724         MonoMethodHeader *res;
725         int i;
726         res = g_malloc0 (sizeof (MonoMethodHeader) + sizeof (gpointer) * header->num_locals);
727         res->code = header->code;
728         res->code_size = header->code_size;
729         res->max_stack = header->max_stack;
730         res->num_clauses = header->num_clauses;
731         res->init_locals = header->init_locals;
732         res->num_locals = header->num_locals;
733         res->clauses = header->clauses;
734         for (i = 0; i < header->num_locals; ++i)
735                 res->locals [i] = mono_class_inflate_generic_type (header->locals [i], context);
736         if (res->num_clauses) {
737                 res->clauses = g_memdup (header->clauses, sizeof (MonoExceptionClause) * res->num_clauses);
738                 for (i = 0; i < header->num_clauses; ++i) {
739                         MonoExceptionClause *clause = &res->clauses [i];
740                         if (clause->flags != MONO_EXCEPTION_CLAUSE_NONE)
741                                 continue;
742                         clause->data.catch_class = mono_class_inflate_generic_class (clause->data.catch_class, context);
743                 }
744         }
745         return res;
746 }
747
748 /*
749  * token is the method_ref or method_def token used in a call IL instruction.
750  */
751 MonoMethodSignature*
752 mono_method_get_signature_full (MonoMethod *method, MonoImage *image, guint32 token, MonoGenericContext *context)
753 {
754         int table = mono_metadata_token_table (token);
755         int idx = mono_metadata_token_index (token);
756         int sig_idx;
757         guint32 cols [MONO_MEMBERREF_SIZE];
758         MonoMethodSignature *sig;
759         const char *ptr;
760
761         /* !table is for wrappers: we should really assign their own token to them */
762         if (!table || table == MONO_TABLE_METHOD)
763                 return mono_method_signature (method);
764
765         if (table == MONO_TABLE_METHODSPEC) {
766                 g_assert (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) &&
767                           mono_method_signature (method));
768                 g_assert (method->is_inflated);
769
770                 return mono_method_signature (method);
771         }
772
773         if (method->klass->generic_class)
774                 return mono_method_signature (method);
775
776         if (image->dynamic)
777                 /* FIXME: This might be incorrect for vararg methods */
778                 return mono_method_signature (method);
779
780         mono_metadata_decode_row (&image->tables [MONO_TABLE_MEMBERREF], idx-1, cols, MONO_MEMBERREF_SIZE);
781         sig_idx = cols [MONO_MEMBERREF_SIGNATURE];
782
783         sig = find_cached_memberref_sig (image, sig_idx);
784         if (!sig) {
785                 ptr = mono_metadata_blob_heap (image, sig_idx);
786                 mono_metadata_decode_blob_size (ptr, &ptr);
787                 sig = mono_metadata_parse_method_signature (image, 0, ptr, NULL);
788
789                 sig = cache_memberref_sig (image, sig_idx, sig);
790         }
791
792         if (context) {
793                 MonoMethodSignature *cached;
794
795                 /* This signature is not owned by a MonoMethod, so need to cache */
796                 sig = inflate_generic_signature (image, sig, context);
797                 cached = mono_metadata_get_inflated_signature (sig, context);
798                 if (cached != sig)
799                         mono_metadata_free_inflated_signature (sig);
800                 else
801                         inflated_signatures_size += mono_metadata_signature_size (cached);
802                 sig = cached;
803         }
804
805         return sig;
806 }
807
808 MonoMethodSignature*
809 mono_method_get_signature (MonoMethod *method, MonoImage *image, guint32 token)
810 {
811         return mono_method_get_signature_full (method, image, token, NULL);
812 }
813
814 /* this is only for the typespec array methods */
815 MonoMethod*
816 mono_method_search_in_array_class (MonoClass *klass, const char *name, MonoMethodSignature *sig)
817 {
818         int i;
819
820         mono_class_setup_methods (klass);
821
822         for (i = 0; i < klass->method.count; ++i) {
823                 MonoMethod *method = klass->methods [i];
824                 if (strcmp (method->name, name) == 0 && sig->param_count == method->signature->param_count)
825                         return method;
826         }
827         return NULL;
828 }
829
830 static MonoMethod *
831 method_from_memberref (MonoImage *image, guint32 idx, MonoGenericContext *typespec_context,
832                        gboolean *used_context)
833 {
834         MonoClass *klass = NULL;
835         MonoMethod *method = NULL;
836         MonoTableInfo *tables = image->tables;
837         guint32 cols[6];
838         guint32 nindex, class, sig_idx;
839         const char *mname;
840         MonoMethodSignature *sig;
841         const char *ptr;
842
843         mono_metadata_decode_row (&tables [MONO_TABLE_MEMBERREF], idx-1, cols, 3);
844         nindex = cols [MONO_MEMBERREF_CLASS] >> MONO_MEMBERREF_PARENT_BITS;
845         class = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
846         /*g_print ("methodref: 0x%x 0x%x %s\n", class, nindex,
847                 mono_metadata_string_heap (m, cols [MONO_MEMBERREF_NAME]));*/
848
849         mname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
850
851         /*
852          * Whether we actually used the `typespec_context' or not.
853          * This is used to tell our caller whether or not it's safe to insert the returned
854          * method into a cache.
855          */
856         if (used_context)
857                 *used_context = class == MONO_MEMBERREF_PARENT_TYPESPEC;
858
859         switch (class) {
860         case MONO_MEMBERREF_PARENT_TYPEREF:
861                 klass = mono_class_from_typeref (image, MONO_TOKEN_TYPE_REF | nindex);
862                 if (!klass) {
863                         char *name = mono_class_name_from_token (image, MONO_TOKEN_TYPE_REF | nindex);
864                         g_warning ("Missing method %s in assembly %s, type %s", mname, image->name, name);
865                         mono_loader_set_error_type_load (name, image->assembly_name);
866                         g_free (name);
867                         return NULL;
868                 }
869                 break;
870         case MONO_MEMBERREF_PARENT_TYPESPEC:
871                 /*
872                  * Parse the TYPESPEC in the parent's context.
873                  */
874                 klass = mono_class_get_full (image, MONO_TOKEN_TYPE_SPEC | nindex, typespec_context);
875                 if (!klass) {
876                         char *name = mono_class_name_from_token (image, MONO_TOKEN_TYPE_SPEC | nindex);
877                         g_warning ("Missing method %s in assembly %s, type %s", mname, image->name, name);
878                         mono_loader_set_error_type_load (name, image->assembly_name);
879                         g_free (name);
880                         return NULL;
881                 }
882                 break;
883         case MONO_MEMBERREF_PARENT_TYPEDEF:
884                 klass = mono_class_get (image, MONO_TOKEN_TYPE_DEF | nindex);
885                 if (!klass) {
886                         char *name = mono_class_name_from_token (image, MONO_TOKEN_TYPE_DEF | nindex);
887                         g_warning ("Missing method %s in assembly %s, type %s", mname, image->name, name);
888                         mono_loader_set_error_type_load (name, image->assembly_name);
889                         g_free (name);
890                         return NULL;
891                 }
892                 break;
893         case MONO_MEMBERREF_PARENT_METHODDEF:
894                 return mono_get_method (image, MONO_TOKEN_METHOD_DEF | nindex, NULL);
895                 
896         default:
897                 {
898                         /* This message leaks */
899                         char *message = g_strdup_printf ("Memberref parent unknown: class: %d, index %d", class, nindex);
900                         mono_loader_set_error_method_load ("", message);
901                         return NULL;
902                 }
903
904         }
905         g_assert (klass);
906         mono_class_init (klass);
907
908         sig_idx = cols [MONO_MEMBERREF_SIGNATURE];
909
910         ptr = mono_metadata_blob_heap (image, sig_idx);
911         mono_metadata_decode_blob_size (ptr, &ptr);
912
913         sig = find_cached_memberref_sig (image, sig_idx);
914         if (!sig) {
915                 sig = mono_metadata_parse_method_signature (image, 0, ptr, NULL);
916                 if (sig == NULL)
917                         return NULL;
918
919                 sig = cache_memberref_sig (image, sig_idx, sig);
920         }
921
922         switch (class) {
923         case MONO_MEMBERREF_PARENT_TYPEREF:
924         case MONO_MEMBERREF_PARENT_TYPEDEF:
925                 method = find_method (klass, NULL, mname, sig, klass);
926                 break;
927
928         case MONO_MEMBERREF_PARENT_TYPESPEC: {
929                 MonoType *type;
930                 MonoMethod *result;
931
932                 type = &klass->byval_arg;
933
934                 if (type->type != MONO_TYPE_ARRAY && type->type != MONO_TYPE_SZARRAY) {
935                         MonoClass *in_class = klass->generic_class ? klass->generic_class->container_class : klass;
936                         method = find_method (in_class, NULL, mname, sig, klass);
937                         break;
938                 }
939
940                 /* we're an array and we created these methods already in klass in mono_class_init () */
941                 result = mono_method_search_in_array_class (klass, mname, sig);
942                 if (result)
943                         return result;
944
945                 g_assert_not_reached ();
946                 break;
947         }
948         default:
949                 g_error ("Memberref parent unknown: class: %d, index %d", class, nindex);
950                 g_assert_not_reached ();
951         }
952
953         if (!method) {
954                 char *msig = mono_signature_get_desc (sig, FALSE);
955                 char * class_name = mono_type_get_name (&klass->byval_arg);
956                 GString *s = g_string_new (mname);
957                 if (sig->generic_param_count)
958                         g_string_append_printf (s, "<[%d]>", sig->generic_param_count);
959                 g_string_append_printf (s, "(%s)", msig);
960                 g_free (msig);
961                 msig = g_string_free (s, FALSE);
962
963                 g_warning (
964                         "Missing method %s::%s in assembly %s, referenced in assembly %s",
965                         class_name, msig, klass->image->name, image->name);
966                 mono_loader_set_error_method_load (class_name, mname);
967                 g_free (msig);
968                 g_free (class_name);
969         }
970
971         return method;
972 }
973
974 static MonoMethod *
975 method_from_methodspec (MonoImage *image, MonoGenericContext *context, guint32 idx)
976 {
977         MonoMethod *method;
978         MonoClass *klass;
979         MonoTableInfo *tables = image->tables;
980         MonoGenericContext new_context;
981         MonoGenericInst *inst;
982         const char *ptr;
983         guint32 cols [MONO_METHODSPEC_SIZE];
984         guint32 token, nindex, param_count;
985
986         mono_metadata_decode_row (&tables [MONO_TABLE_METHODSPEC], idx - 1, cols, MONO_METHODSPEC_SIZE);
987         token = cols [MONO_METHODSPEC_METHOD];
988         nindex = token >> MONO_METHODDEFORREF_BITS;
989
990         ptr = mono_metadata_blob_heap (image, cols [MONO_METHODSPEC_SIGNATURE]);
991
992         mono_metadata_decode_value (ptr, &ptr);
993         ptr++;
994         param_count = mono_metadata_decode_value (ptr, &ptr);
995         g_assert (param_count);
996
997         inst = mono_metadata_parse_generic_inst (image, NULL, param_count, ptr, &ptr);
998         if (context && inst->is_open)
999                 inst = mono_metadata_inflate_generic_inst (inst, context);
1000
1001         if ((token & MONO_METHODDEFORREF_MASK) == MONO_METHODDEFORREF_METHODDEF)
1002                 method = mono_get_method_full (image, MONO_TOKEN_METHOD_DEF | nindex, NULL, context);
1003         else
1004                 method = method_from_memberref (image, nindex, context, NULL);
1005
1006         if (!method)
1007                 return NULL;
1008
1009         klass = method->klass;
1010
1011         if (klass->generic_class) {
1012                 g_assert (method->is_inflated);
1013                 method = ((MonoMethodInflated *) method)->declaring;
1014         }
1015
1016         new_context.class_inst = klass->generic_class ? klass->generic_class->context.class_inst : NULL;
1017         new_context.method_inst = inst;
1018
1019         return mono_class_inflate_generic_method_full (method, klass, &new_context);
1020 }
1021
1022 struct _MonoDllMap {
1023         char *dll;
1024         char *target;
1025         char *func;
1026         char *target_func;
1027         MonoDllMap *next;
1028 };
1029
1030 static MonoDllMap *global_dll_map;
1031
1032 static int 
1033 mono_dllmap_lookup_list (MonoDllMap *dll_map, const char *dll, const char* func, const char **rdll, const char **rfunc) {
1034         int found = 0;
1035
1036         *rdll = dll;
1037
1038         if (!dll_map)
1039                 return 0;
1040
1041         mono_loader_lock ();
1042
1043         /* 
1044          * we use the first entry we find that matches, since entries from
1045          * the config file are prepended to the list and we document that the
1046          * later entries win.
1047          */
1048         for (; dll_map; dll_map = dll_map->next) {
1049                 if (dll_map->dll [0] == 'i' && dll_map->dll [1] == ':') {
1050                         if (g_ascii_strcasecmp (dll_map->dll + 2, dll))
1051                                 continue;
1052                 } else if (strcmp (dll_map->dll, dll)) {
1053                         continue;
1054                 }
1055                 if (!found && dll_map->target) {
1056                         *rdll = dll_map->target;
1057                         found = 1;
1058                         /* we don't quit here, because we could find a full
1059                          * entry that matches also function and that has priority.
1060                          */
1061                 }
1062                 if (dll_map->func && strcmp (dll_map->func, func) == 0) {
1063                         *rfunc = dll_map->target_func;
1064                         break;
1065                 }
1066         }
1067
1068         mono_loader_unlock ();
1069         return found;
1070 }
1071
1072 static int 
1073 mono_dllmap_lookup (MonoImage *assembly, const char *dll, const char* func, const char **rdll, const char **rfunc)
1074 {
1075         int res;
1076         if (assembly && assembly->dll_map) {
1077                 res = mono_dllmap_lookup_list (assembly->dll_map, dll, func, rdll, rfunc);
1078                 if (res)
1079                         return res;
1080         }
1081         return mono_dllmap_lookup_list (global_dll_map, dll, func, rdll, rfunc);
1082 }
1083
1084 /*
1085  * mono_dllmap_insert:
1086  *
1087  * LOCKING: Acquires the loader lock.
1088  *
1089  * NOTE: This can be called before the runtime is initialized, for example from
1090  * mono_config_parse ().
1091  */
1092 void
1093 mono_dllmap_insert (MonoImage *assembly, const char *dll, const char *func, const char *tdll, const char *tfunc)
1094 {
1095         MonoDllMap *entry;
1096
1097         mono_loader_init ();
1098
1099         mono_loader_lock ();
1100
1101         if (!assembly) {
1102                 entry = g_malloc0 (sizeof (MonoDllMap));
1103                 entry->dll = dll? g_strdup (dll): NULL;
1104                 entry->target = tdll? g_strdup (tdll): NULL;
1105                 entry->func = func? g_strdup (func): NULL;
1106                 entry->target_func = tfunc? g_strdup (tfunc): NULL;
1107                 entry->next = global_dll_map;
1108                 global_dll_map = entry;
1109         } else {
1110                 entry = mono_image_alloc0 (assembly, sizeof (MonoDllMap));
1111                 entry->dll = dll? mono_image_strdup (assembly, dll): NULL;
1112                 entry->target = tdll? mono_image_strdup (assembly, tdll): NULL;
1113                 entry->func = func? mono_image_strdup (assembly, func): NULL;
1114                 entry->target_func = tfunc? mono_image_strdup (assembly, tfunc): NULL;
1115                 entry->next = assembly->dll_map;
1116                 assembly->dll_map = entry;
1117         }
1118
1119         mono_loader_unlock ();
1120 }
1121
1122 static GHashTable *global_module_map;
1123
1124 static MonoDl*
1125 cached_module_load (const char *name, int flags, char **err)
1126 {
1127         MonoDl *res;
1128         mono_loader_lock ();
1129         if (!global_module_map)
1130                 global_module_map = g_hash_table_new (g_str_hash, g_str_equal);
1131         res = g_hash_table_lookup (global_module_map, name);
1132         if (res) {
1133                 *err = NULL;
1134                 mono_loader_unlock ();
1135                 return res;
1136         }
1137         res = mono_dl_open (name, flags, err);
1138         if (res)
1139                 g_hash_table_insert (global_module_map, g_strdup (name), res);
1140         mono_loader_unlock ();
1141         return res;
1142 }
1143
1144 gpointer
1145 mono_lookup_pinvoke_call (MonoMethod *method, const char **exc_class, const char **exc_arg)
1146 {
1147         MonoImage *image = method->klass->image;
1148         MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)method;
1149         MonoTableInfo *tables = image->tables;
1150         MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
1151         MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
1152         guint32 im_cols [MONO_IMPLMAP_SIZE];
1153         guint32 scope_token;
1154         const char *import = NULL;
1155         const char *orig_scope;
1156         const char *new_scope;
1157         char *error_msg;
1158         char *full_name, *file_name;
1159         int i;
1160         MonoDl *module = NULL;
1161
1162         g_assert (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL);
1163
1164         if (piinfo->addr)
1165                 return piinfo->addr;
1166
1167         if (method->klass->image->dynamic) {
1168                 MonoReflectionMethodAux *method_aux = 
1169                         g_hash_table_lookup (
1170                                 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
1171                 if (!method_aux)
1172                         return NULL;
1173
1174                 import = method_aux->dllentry;
1175                 orig_scope = method_aux->dll;
1176         }
1177         else {
1178                 if (!piinfo->implmap_idx)
1179                         return NULL;
1180
1181                 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
1182
1183                 piinfo->piflags = im_cols [MONO_IMPLMAP_FLAGS];
1184                 import = mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]);
1185                 scope_token = mono_metadata_decode_row_col (mr, im_cols [MONO_IMPLMAP_SCOPE] - 1, MONO_MODULEREF_NAME);
1186                 orig_scope = mono_metadata_string_heap (image, scope_token);
1187         }
1188
1189         mono_dllmap_lookup (image, orig_scope, import, &new_scope, &import);
1190
1191         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1192                         "DllImport attempting to load: '%s'.", new_scope);
1193
1194         if (exc_class) {
1195                 *exc_class = NULL;
1196                 *exc_arg = NULL;
1197         }
1198
1199         /* we allow a special name to dlopen from the running process namespace */
1200         if (strcmp (new_scope, "__Internal") == 0)
1201                 module = mono_dl_open (NULL, MONO_DL_LAZY, &error_msg);
1202
1203         /*
1204          * Try loading the module using a variety of names
1205          */
1206         for (i = 0; i < 4; ++i) {
1207                 switch (i) {
1208                 case 0:
1209                         /* Try the original name */
1210                         file_name = g_strdup (new_scope);
1211                         break;
1212                 case 1:
1213                         /* Try trimming the .dll extension */
1214                         if (strstr (new_scope, ".dll") == (new_scope + strlen (new_scope) - 4)) {
1215                                 file_name = g_strdup (new_scope);
1216                                 file_name [strlen (new_scope) - 4] = '\0';
1217                         }
1218                         else
1219                                 continue;
1220                         break;
1221                 case 2:
1222                         if (strstr (new_scope, "lib") != new_scope) {
1223                                 file_name = g_strdup_printf ("lib%s", new_scope);
1224                         }
1225                         else
1226                                 continue;
1227                         break;
1228                 default:
1229 #ifndef PLATFORM_WIN32
1230                         if (!g_ascii_strcasecmp ("user32.dll", new_scope) ||
1231                             !g_ascii_strcasecmp ("kernel32.dll", new_scope) ||
1232                             !g_ascii_strcasecmp ("user32", new_scope) ||
1233                             !g_ascii_strcasecmp ("kernel", new_scope)) {
1234                                 file_name = g_strdup ("libMonoSupportW.so");
1235                         } else
1236 #endif
1237                                     continue;
1238 #ifndef PLATFORM_WIN32
1239                         break;
1240 #endif
1241                 }
1242
1243                 if (!module) {
1244                         void *iter = NULL;
1245                         while ((full_name = mono_dl_build_path (NULL, file_name, &iter))) {
1246                                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1247                                                 "DllImport loading location: '%s'.", full_name);
1248                                 module = cached_module_load (full_name, MONO_DL_LAZY, &error_msg);
1249                                 if (!module) {
1250                                         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1251                                                         "DllImport error loading library: '%s'.",
1252                                                         error_msg);
1253                                         g_free (error_msg);
1254                                 }
1255                                 g_free (full_name);
1256                                 if (module)
1257                                         break;
1258                         }
1259                 }
1260
1261                 if (!module) {
1262                         void *iter = NULL;
1263                         while ((full_name = mono_dl_build_path (".", file_name, &iter))) {
1264                                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1265                                         "DllImport loading library: '%s'.", full_name);
1266                                 module = cached_module_load (full_name, MONO_DL_LAZY, &error_msg);
1267                                 if (!module) {
1268                                         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1269                                                 "DllImport error loading library '%s'.",
1270                                                 error_msg);
1271                                         g_free (error_msg);
1272                                 }
1273                                 g_free (full_name);
1274                                 if (module)
1275                                         break;
1276                         }
1277                 }
1278
1279                 if (!module) {
1280                         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1281                                         "DllImport loading: '%s'.", file_name);
1282                         module = cached_module_load (file_name, MONO_DL_LAZY, &error_msg);
1283                         if (!module) {
1284                                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1285                                                 "DllImport error loading library '%s'.",
1286                                                 error_msg);
1287                         }
1288                 }
1289
1290                 g_free (file_name);
1291
1292                 if (module)
1293                         break;
1294         }
1295
1296         if (!module) {
1297                 mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_DLLIMPORT,
1298                                 "DllImport unable to load library '%s'.",
1299                                 error_msg);
1300                 g_free (error_msg);
1301
1302                 if (exc_class) {
1303                         *exc_class = "DllNotFoundException";
1304                         *exc_arg = new_scope;
1305                 }
1306                 return NULL;
1307         }
1308
1309         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1310                                 "Searching for '%s'.", import);
1311
1312         if (piinfo->piflags & PINVOKE_ATTRIBUTE_NO_MANGLE) {
1313                 error_msg = mono_dl_symbol (module, import, &piinfo->addr); 
1314         } else {
1315                 char *mangled_name = NULL, *mangled_name2 = NULL;
1316                 int mangle_charset;
1317                 int mangle_stdcall;
1318                 int mangle_param_count;
1319 #ifdef PLATFORM_WIN32
1320                 int param_count;
1321 #endif
1322
1323                 /*
1324                  * Search using a variety of mangled names
1325                  */
1326                 for (mangle_charset = 0; mangle_charset <= 1; mangle_charset ++) {
1327                         for (mangle_stdcall = 0; mangle_stdcall <= 1; mangle_stdcall ++) {
1328                                 gboolean need_param_count = FALSE;
1329 #ifdef PLATFORM_WIN32
1330                                 if (mangle_stdcall > 0)
1331                                         need_param_count = TRUE;
1332 #endif
1333                                 for (mangle_param_count = 0; mangle_param_count <= (need_param_count ? 256 : 0); mangle_param_count += 4) {
1334
1335                                         if (piinfo->addr)
1336                                                 continue;
1337
1338                                         mangled_name = (char*)import;
1339                                         switch (piinfo->piflags & PINVOKE_ATTRIBUTE_CHAR_SET_MASK) {
1340                                         case PINVOKE_ATTRIBUTE_CHAR_SET_UNICODE:
1341                                                 /* Try the mangled name first */
1342                                                 if (mangle_charset == 0)
1343                                                         mangled_name = g_strconcat (import, "W", NULL);
1344                                                 break;
1345                                         case PINVOKE_ATTRIBUTE_CHAR_SET_AUTO:
1346 #ifdef PLATFORM_WIN32
1347                                                 if (mangle_charset == 0)
1348                                                         mangled_name = g_strconcat (import, "W", NULL);
1349 #else
1350                                                 /* Try the mangled name last */
1351                                                 if (mangle_charset == 1)
1352                                                         mangled_name = g_strconcat (import, "A", NULL);
1353 #endif
1354                                                 break;
1355                                         case PINVOKE_ATTRIBUTE_CHAR_SET_ANSI:
1356                                         default:
1357                                                 /* Try the mangled name last */
1358                                                 if (mangle_charset == 1)
1359                                                         mangled_name = g_strconcat (import, "A", NULL);
1360                                                 break;
1361                                         }
1362
1363 #ifdef PLATFORM_WIN32
1364                                         if (mangle_param_count == 0)
1365                                                 param_count = mono_method_signature (method)->param_count * sizeof (gpointer);
1366                                         else
1367                                                 /* Try brute force, since it would be very hard to compute the stack usage correctly */
1368                                                 param_count = mangle_param_count;
1369
1370                                         /* Try the stdcall mangled name */
1371                                         /* 
1372                                          * gcc under windows creates mangled names without the underscore, but MS.NET
1373                                          * doesn't support it, so we doesn't support it either.
1374                                          */
1375                                         if (mangle_stdcall == 1)
1376                                                 mangled_name2 = g_strdup_printf ("_%s@%d", mangled_name, param_count);
1377                                         else
1378                                                 mangled_name2 = mangled_name;
1379 #else
1380                                         mangled_name2 = mangled_name;
1381 #endif
1382
1383                                         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1384                                                                 "Probing '%s'.", mangled_name2);
1385
1386                                         error_msg = mono_dl_symbol (module, mangled_name2, &piinfo->addr);
1387
1388                                         if (piinfo->addr)
1389                                                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1390                                                                         "Found as '%s'.", mangled_name2);
1391
1392                                         if (mangled_name != mangled_name2)
1393                                                 g_free (mangled_name2);
1394                                         if (mangled_name != import)
1395                                                 g_free (mangled_name);
1396                                 }
1397                         }
1398                 }
1399         }
1400
1401         if (!piinfo->addr) {
1402                 g_free (error_msg);
1403                 if (exc_class) {
1404                         *exc_class = "EntryPointNotFoundException";
1405                         *exc_arg = import;
1406                 }
1407                 return NULL;
1408         }
1409         return piinfo->addr;
1410 }
1411
1412 /*
1413  * LOCKING: assumes the loader lock to be taken.
1414  */
1415 static MonoMethod *
1416 mono_get_method_from_token (MonoImage *image, guint32 token, MonoClass *klass,
1417                             MonoGenericContext *context, gboolean *used_context)
1418 {
1419         MonoMethod *result;
1420         int table = mono_metadata_token_table (token);
1421         int idx = mono_metadata_token_index (token);
1422         MonoTableInfo *tables = image->tables;
1423         MonoGenericContainer *generic_container = NULL, *container = NULL;
1424         const char *sig = NULL;
1425         int size;
1426         guint32 cols [MONO_TYPEDEF_SIZE];
1427
1428         if (image->dynamic) {
1429                 MonoClass *handle_class;
1430
1431                 result = mono_lookup_dynamic_token_class (image, token, TRUE, &handle_class, context);
1432                 // This checks the memberref type as well
1433                 if (result && handle_class != mono_defaults.methodhandle_class) {
1434                         mono_loader_set_error_bad_image (g_strdup ("Bad method token."));
1435                         return NULL;
1436                 }
1437                 return result;
1438         }
1439
1440         if (table != MONO_TABLE_METHOD) {
1441                 if (table == MONO_TABLE_METHODSPEC) {
1442                         if (used_context) *used_context = TRUE;
1443                         return method_from_methodspec (image, context, idx);
1444                 }
1445                 if (table != MONO_TABLE_MEMBERREF)
1446                         g_print("got wrong token: 0x%08x\n", token);
1447                 g_assert (table == MONO_TABLE_MEMBERREF);
1448                 return method_from_memberref (image, idx, context, used_context);
1449         }
1450
1451         if (used_context) *used_context = FALSE;
1452
1453         if (idx > image->tables [MONO_TABLE_METHOD].rows) {
1454                 mono_loader_set_error_bad_image (g_strdup ("Bad method token."));
1455                 return NULL;
1456         }
1457
1458         mono_metadata_decode_row (&image->tables [MONO_TABLE_METHOD], idx - 1, cols, 6);
1459
1460         if ((cols [2] & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
1461             (cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))
1462                 result = (MonoMethod *)mono_image_alloc0_lock (image, sizeof (MonoMethodPInvoke));
1463         else
1464                 result = (MonoMethod *)mono_image_alloc0_lock (image, sizeof (MonoMethodNormal));
1465
1466         mono_stats.method_count ++;
1467
1468         if (!klass) {
1469                 guint32 type = mono_metadata_typedef_from_method (image, token);
1470                 klass = mono_class_get (image, MONO_TOKEN_TYPE_DEF | type);
1471                 if (klass == NULL)
1472                         return NULL;
1473         }
1474
1475         result->slot = -1;
1476         result->klass = klass;
1477         result->flags = cols [2];
1478         result->iflags = cols [1];
1479         result->token = token;
1480         result->name = mono_metadata_string_heap (image, cols [3]);
1481
1482         container = klass->generic_container;
1483         generic_container = mono_metadata_load_generic_params (image, token, container);
1484         if (generic_container) {
1485                 result->is_generic = TRUE;
1486                 generic_container->owner.method = result;
1487
1488                 mono_metadata_load_generic_param_constraints (image, token, generic_container);
1489
1490                 container = generic_container;
1491         }
1492
1493
1494         if (!sig) /* already taken from the methodref */
1495                 sig = mono_metadata_blob_heap (image, cols [4]);
1496         size = mono_metadata_decode_blob_size (sig, &sig);
1497
1498         if (cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
1499                 if (result->klass == mono_defaults.string_class && !strcmp (result->name, ".ctor"))
1500                         result->string_ctor = 1;
1501         } else if (cols [2] & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
1502                 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)result;
1503
1504 #ifdef PLATFORM_WIN32
1505                 /* IJW is P/Invoke with a predefined function pointer. */
1506                 if (image->is_module_handle && (cols [1] & METHOD_IMPL_ATTRIBUTE_NATIVE)) {
1507                         piinfo->addr = mono_image_rva_map (image, cols [0]);
1508                         g_assert (piinfo->addr);
1509                 }
1510 #endif
1511                 piinfo->implmap_idx = mono_metadata_implmap_from_method (image, idx - 1);
1512                 /* Native methods can have no map. */
1513                 if (piinfo->implmap_idx)
1514                         piinfo->piflags = mono_metadata_decode_row_col (&tables [MONO_TABLE_IMPLMAP], piinfo->implmap_idx - 1, MONO_IMPLMAP_FLAGS);
1515         }
1516
1517         if (generic_container)
1518                 mono_method_set_generic_container (result, generic_container);
1519
1520         return result;
1521 }
1522
1523 MonoMethod *
1524 mono_get_method (MonoImage *image, guint32 token, MonoClass *klass)
1525 {
1526         return mono_get_method_full (image, token, klass, NULL);
1527 }
1528
1529 static gpointer
1530 get_method_token (gpointer value)
1531 {
1532         MonoMethod *m = (MonoMethod*)value;
1533
1534         return GUINT_TO_POINTER (m->token);
1535 }
1536
1537 MonoMethod *
1538 mono_get_method_full (MonoImage *image, guint32 token, MonoClass *klass,
1539                       MonoGenericContext *context)
1540 {
1541         MonoMethod *result;
1542         gboolean used_context = FALSE;
1543
1544         /* We do everything inside the lock to prevent creation races */
1545
1546         mono_loader_lock ();
1547
1548         if (mono_metadata_token_table (token) == MONO_TABLE_METHOD) {
1549                 if (!image->method_cache)
1550                         image->method_cache = mono_value_hash_table_new (NULL, NULL, get_method_token);
1551                 result = mono_value_hash_table_lookup (image->method_cache, GINT_TO_POINTER (token));
1552         } else {
1553                 if (!image->methodref_cache)
1554                         image->methodref_cache = g_hash_table_new (NULL, NULL);
1555                 result = g_hash_table_lookup (image->methodref_cache, GINT_TO_POINTER (token));
1556         }
1557         if (result) {
1558                 mono_loader_unlock ();
1559                 return result;
1560         }
1561
1562         mono_loader_unlock ();
1563         result = mono_get_method_from_token (image, token, klass, context, &used_context);
1564         if (!result)
1565                 return NULL;
1566
1567         mono_loader_lock ();
1568         if (!used_context && !result->is_inflated) {
1569                 MonoMethod *result2;
1570                 if (mono_metadata_token_table (token) == MONO_TABLE_METHOD)
1571                         result2 = mono_value_hash_table_lookup (image->method_cache, GINT_TO_POINTER (token));
1572                 else
1573                         result2 = g_hash_table_lookup (image->methodref_cache, GINT_TO_POINTER (token));
1574
1575                 if (result2) {
1576                         mono_loader_unlock ();
1577                         return result2;
1578                 }
1579
1580                 if (mono_metadata_token_table (token) == MONO_TABLE_METHOD)
1581                         mono_value_hash_table_insert (image->method_cache, GINT_TO_POINTER (token), result);
1582                 else
1583                         g_hash_table_insert (image->methodref_cache, GINT_TO_POINTER (token), result);
1584         }
1585
1586         mono_loader_unlock ();
1587
1588         return result;
1589 }
1590
1591 /**
1592  * mono_get_method_constrained:
1593  *
1594  * This is used when JITing the `constrained.' opcode.
1595  *
1596  * This returns two values: the contrained method, which has been inflated
1597  * as the function return value;   And the original CIL-stream method as
1598  * declared in cil_method.  The later is used for verification.
1599  */
1600 MonoMethod *
1601 mono_get_method_constrained (MonoImage *image, guint32 token, MonoClass *constrained_class,
1602                              MonoGenericContext *context, MonoMethod **cil_method)
1603 {
1604         MonoMethod *method, *result;
1605         MonoClass *ic = NULL;
1606         MonoGenericContext *method_context = NULL;
1607         MonoMethodSignature *sig, *original_sig;
1608
1609         mono_loader_lock ();
1610
1611         *cil_method = mono_get_method_from_token (image, token, NULL, context, NULL);
1612         if (!*cil_method) {
1613                 mono_loader_unlock ();
1614                 return NULL;
1615         }
1616
1617         mono_class_init (constrained_class);
1618         method = *cil_method;
1619         original_sig = sig = mono_method_signature (method);
1620
1621         if (method->is_inflated && sig->generic_param_count) {
1622                 MonoMethodInflated *imethod = (MonoMethodInflated *) method;
1623                 sig = mono_method_signature (imethod->declaring);
1624                 method_context = mono_method_get_context (method);
1625
1626                 original_sig = sig;
1627                 /*
1628                  * We must inflate the signature with the class instantiation to work on
1629                  * cases where a class inherit from a generic type and the override replaces
1630                  * and type argument which a concrete type. See #325283.
1631                  */
1632                 if (method_context->class_inst) {
1633                         MonoGenericContext ctx;
1634                         ctx.method_inst = NULL;
1635                         ctx.class_inst = method_context->class_inst;
1636                 
1637                         sig = inflate_generic_signature (method->klass->image, sig, &ctx);
1638                 }
1639         }
1640
1641         if ((constrained_class != method->klass) && (MONO_CLASS_IS_INTERFACE (method->klass)))
1642                 ic = method->klass;
1643
1644         result = find_method (constrained_class, ic, method->name, sig, constrained_class);
1645         if (sig != original_sig)
1646                 mono_metadata_free_inflated_signature (sig);
1647
1648         if (!result) {
1649                 g_warning ("Missing method %s.%s.%s in assembly %s token %x", method->klass->name_space,
1650                            method->klass->name, method->name, image->name, token);
1651                 mono_loader_unlock ();
1652                 return NULL;
1653         }
1654
1655         if (method_context)
1656                 result = mono_class_inflate_generic_method (result, method_context);
1657
1658         mono_loader_unlock ();
1659         return result;
1660 }
1661
1662 void
1663 mono_free_method  (MonoMethod *method)
1664 {
1665         if (mono_profiler_get_events () & MONO_PROFILE_METHOD_EVENTS)
1666                 mono_profiler_method_free (method);
1667         
1668         /* FIXME: This hack will go away when the profiler will support freeing methods */
1669         if (mono_profiler_get_events () != MONO_PROFILE_NONE)
1670                 return;
1671         
1672         if (method->signature) {
1673                 /* 
1674                  * FIXME: This causes crashes because the types inside signatures and
1675                  * locals are shared.
1676                  */
1677                 /* mono_metadata_free_method_signature (method->signature); */
1678                 /* g_free (method->signature); */
1679         }
1680         
1681         if (method->dynamic) {
1682                 MonoMethodWrapper *mw = (MonoMethodWrapper*)method;
1683                 int i;
1684
1685                 mono_marshal_free_dynamic_wrappers (method);
1686
1687                 mono_loader_lock ();
1688                 mono_property_hash_remove_object (method->klass->image->property_hash, method);
1689                 mono_loader_unlock ();
1690
1691                 g_free ((char*)method->name);
1692                 if (mw->method.header) {
1693                         g_free ((char*)mw->method.header->code);
1694                         for (i = 0; i < mw->method.header->num_locals; ++i)
1695                                 g_free (mw->method.header->locals [i]);
1696                         g_free (mw->method.header->clauses);
1697                         g_free (mw->method.header);
1698                 }
1699                 g_free (mw->method_data);
1700                 g_free (method->signature);
1701                 g_free (method);
1702         }
1703 }
1704
1705 void
1706 mono_method_get_param_names (MonoMethod *method, const char **names)
1707 {
1708         int i, lastp;
1709         MonoClass *klass;
1710         MonoTableInfo *methodt;
1711         MonoTableInfo *paramt;
1712         guint32 idx;
1713
1714         if (method->is_inflated)
1715                 method = ((MonoMethodInflated *) method)->declaring;
1716
1717         if (!mono_method_signature (method)->param_count)
1718                 return;
1719         for (i = 0; i < mono_method_signature (method)->param_count; ++i)
1720                 names [i] = "";
1721
1722         klass = method->klass;
1723         if (klass->rank)
1724                 return;
1725
1726         mono_class_init (klass);
1727
1728         if (klass->image->dynamic) {
1729                 MonoReflectionMethodAux *method_aux = 
1730                         g_hash_table_lookup (
1731                                 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
1732                 if (method_aux && method_aux->param_names) {
1733                         for (i = 0; i < mono_method_signature (method)->param_count; ++i)
1734                                 if (method_aux->param_names [i + 1])
1735                                         names [i] = method_aux->param_names [i + 1];
1736                 }
1737                 return;
1738         }
1739
1740         methodt = &klass->image->tables [MONO_TABLE_METHOD];
1741         paramt = &klass->image->tables [MONO_TABLE_PARAM];
1742         idx = mono_method_get_index (method);
1743         if (idx > 0) {
1744                 guint32 cols [MONO_PARAM_SIZE];
1745                 guint param_index;
1746
1747                 param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
1748
1749                 if (idx < methodt->rows)
1750                         lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
1751                 else
1752                         lastp = paramt->rows + 1;
1753                 for (i = param_index; i < lastp; ++i) {
1754                         mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
1755                         if (cols [MONO_PARAM_SEQUENCE]) /* skip return param spec */
1756                                 names [cols [MONO_PARAM_SEQUENCE] - 1] = mono_metadata_string_heap (klass->image, cols [MONO_PARAM_NAME]);
1757                 }
1758                 return;
1759         }
1760 }
1761
1762 guint32
1763 mono_method_get_param_token (MonoMethod *method, int index)
1764 {
1765         MonoClass *klass = method->klass;
1766         MonoTableInfo *methodt;
1767         guint32 idx;
1768
1769         mono_class_init (klass);
1770
1771         if (klass->image->dynamic) {
1772                 g_assert_not_reached ();
1773         }
1774
1775         methodt = &klass->image->tables [MONO_TABLE_METHOD];
1776         idx = mono_method_get_index (method);
1777         if (idx > 0) {
1778                 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
1779
1780                 if (index == -1)
1781                         /* Return value */
1782                         return mono_metadata_make_token (MONO_TABLE_PARAM, 0);
1783                 else
1784                         return mono_metadata_make_token (MONO_TABLE_PARAM, param_index + index);
1785         }
1786
1787         return 0;
1788 }
1789
1790 void
1791 mono_method_get_marshal_info (MonoMethod *method, MonoMarshalSpec **mspecs)
1792 {
1793         int i, lastp;
1794         MonoClass *klass = method->klass;
1795         MonoTableInfo *methodt;
1796         MonoTableInfo *paramt;
1797         guint32 idx;
1798
1799         for (i = 0; i < mono_method_signature (method)->param_count + 1; ++i)
1800                 mspecs [i] = NULL;
1801
1802         if (method->klass->image->dynamic) {
1803                 MonoReflectionMethodAux *method_aux = 
1804                         g_hash_table_lookup (
1805                                 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
1806                 if (method_aux && method_aux->param_marshall) {
1807                         MonoMarshalSpec **dyn_specs = method_aux->param_marshall;
1808                         for (i = 0; i < mono_method_signature (method)->param_count + 1; ++i)
1809                                 if (dyn_specs [i]) {
1810                                         mspecs [i] = g_new0 (MonoMarshalSpec, 1);
1811                                         memcpy (mspecs [i], dyn_specs [i], sizeof (MonoMarshalSpec));
1812                                 }
1813                 }
1814                 return;
1815         }
1816
1817         mono_class_init (klass);
1818
1819         methodt = &klass->image->tables [MONO_TABLE_METHOD];
1820         paramt = &klass->image->tables [MONO_TABLE_PARAM];
1821         idx = mono_method_get_index (method);
1822         if (idx > 0) {
1823                 guint32 cols [MONO_PARAM_SIZE];
1824                 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
1825
1826                 if (idx < methodt->rows)
1827                         lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
1828                 else
1829                         lastp = paramt->rows + 1;
1830
1831                 for (i = param_index; i < lastp; ++i) {
1832                         mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
1833
1834                         if (cols [MONO_PARAM_FLAGS] & PARAM_ATTRIBUTE_HAS_FIELD_MARSHAL) {
1835                                 const char *tp;
1836                                 tp = mono_metadata_get_marshal_info (klass->image, i - 1, FALSE);
1837                                 g_assert (tp);
1838                                 mspecs [cols [MONO_PARAM_SEQUENCE]]= mono_metadata_parse_marshal_spec (klass->image, tp);
1839                         }
1840                 }
1841
1842                 return;
1843         }
1844 }
1845
1846 gboolean
1847 mono_method_has_marshal_info (MonoMethod *method)
1848 {
1849         int i, lastp;
1850         MonoClass *klass = method->klass;
1851         MonoTableInfo *methodt;
1852         MonoTableInfo *paramt;
1853         guint32 idx;
1854
1855         if (method->klass->image->dynamic) {
1856                 MonoReflectionMethodAux *method_aux = 
1857                         g_hash_table_lookup (
1858                                 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
1859                 MonoMarshalSpec **dyn_specs = method_aux->param_marshall;
1860                 if (dyn_specs) {
1861                         for (i = 0; i < mono_method_signature (method)->param_count + 1; ++i)
1862                                 if (dyn_specs [i])
1863                                         return TRUE;
1864                 }
1865                 return FALSE;
1866         }
1867
1868         mono_class_init (klass);
1869
1870         methodt = &klass->image->tables [MONO_TABLE_METHOD];
1871         paramt = &klass->image->tables [MONO_TABLE_PARAM];
1872         idx = mono_method_get_index (method);
1873         if (idx > 0) {
1874                 guint32 cols [MONO_PARAM_SIZE];
1875                 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
1876
1877                 if (idx + 1 < methodt->rows)
1878                         lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
1879                 else
1880                         lastp = paramt->rows + 1;
1881
1882                 for (i = param_index; i < lastp; ++i) {
1883                         mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
1884
1885                         if (cols [MONO_PARAM_FLAGS] & PARAM_ATTRIBUTE_HAS_FIELD_MARSHAL)
1886                                 return TRUE;
1887                 }
1888                 return FALSE;
1889         }
1890         return FALSE;
1891 }
1892
1893 gpointer
1894 mono_method_get_wrapper_data (MonoMethod *method, guint32 id)
1895 {
1896         void **data;
1897         g_assert (method != NULL);
1898         g_assert (method->wrapper_type != MONO_WRAPPER_NONE);
1899
1900         data = ((MonoMethodWrapper *)method)->method_data;
1901         g_assert (data != NULL);
1902         g_assert (id <= GPOINTER_TO_UINT (*data));
1903         return data [id];
1904 }
1905
1906 static void
1907 default_stack_walk (MonoStackWalk func, gboolean do_il_offset, gpointer user_data) {
1908         g_error ("stack walk not installed");
1909 }
1910
1911 static MonoStackWalkImpl stack_walk = default_stack_walk;
1912
1913 void
1914 mono_stack_walk (MonoStackWalk func, gpointer user_data)
1915 {
1916         stack_walk (func, TRUE, user_data);
1917 }
1918
1919 void
1920 mono_stack_walk_no_il (MonoStackWalk func, gpointer user_data)
1921 {
1922         stack_walk (func, FALSE, user_data);
1923 }
1924
1925 void
1926 mono_install_stack_walk (MonoStackWalkImpl func)
1927 {
1928         stack_walk = func;
1929 }
1930
1931 static gboolean
1932 last_managed (MonoMethod *m, gint no, gint ilo, gboolean managed, gpointer data)
1933 {
1934         MonoMethod **dest = data;
1935         *dest = m;
1936         /*g_print ("In %s::%s [%d] [%d]\n", m->klass->name, m->name, no, ilo);*/
1937
1938         return managed;
1939 }
1940
1941 MonoMethod*
1942 mono_method_get_last_managed (void)
1943 {
1944         MonoMethod *m = NULL;
1945         stack_walk (last_managed, FALSE, &m);
1946         return m;
1947 }
1948
1949 void
1950 mono_loader_lock (void)
1951 {
1952         EnterCriticalSection (&loader_mutex);
1953 }
1954
1955 void
1956 mono_loader_unlock (void)
1957 {
1958         LeaveCriticalSection (&loader_mutex);
1959 }
1960
1961 /**
1962  * mono_method_signature:
1963  *
1964  * Return the signature of the method M. On failure, returns NULL.
1965  */
1966 MonoMethodSignature*
1967 mono_method_signature (MonoMethod *m)
1968 {
1969         int idx;
1970         int size;
1971         MonoImage* img;
1972         const char *sig;
1973         gboolean can_cache_signature;
1974         MonoGenericContainer *container;
1975         MonoMethodSignature *signature = NULL;
1976         int *pattrs;
1977
1978         /* We need memory barriers below because of the double-checked locking pattern */ 
1979
1980         if (m->signature)
1981                 return m->signature;
1982
1983         mono_loader_lock ();
1984
1985         if (m->signature) {
1986                 mono_loader_unlock ();
1987                 return m->signature;
1988         }
1989
1990         if (m->is_inflated) {
1991                 MonoMethodInflated *imethod = (MonoMethodInflated *) m;
1992                 /* the lock is recursive */
1993                 signature = mono_method_signature (imethod->declaring);
1994                 signature = inflate_generic_signature (imethod->declaring->klass->image, signature, mono_method_get_context (m));
1995
1996                 inflated_signatures_size += mono_metadata_signature_size (signature);
1997
1998                 mono_memory_barrier ();
1999                 m->signature = signature;
2000                 mono_loader_unlock ();
2001                 return m->signature;
2002         }
2003
2004         g_assert (mono_metadata_token_table (m->token) == MONO_TABLE_METHOD);
2005         idx = mono_metadata_token_index (m->token);
2006         img = m->klass->image;
2007
2008         sig = mono_metadata_blob_heap (img, mono_metadata_decode_row_col (&img->tables [MONO_TABLE_METHOD], idx - 1, MONO_METHOD_SIGNATURE));
2009
2010         g_assert (!m->klass->generic_class);
2011         container = mono_method_get_generic_container (m);
2012         if (!container)
2013                 container = m->klass->generic_container;
2014
2015         /* Generic signatures depend on the container so they cannot be cached */
2016         /* icall/pinvoke signatures cannot be cached cause we modify them below */
2017         can_cache_signature = !(m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && !(m->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) && !container;
2018
2019         /* If the method has parameter attributes, that can modify the signature */
2020         pattrs = mono_metadata_get_param_attrs (img, idx);
2021         if (pattrs) {
2022                 can_cache_signature = FALSE;
2023                 g_free (pattrs);
2024         }
2025
2026         if (can_cache_signature)
2027                 signature = g_hash_table_lookup (img->method_signatures, sig);
2028
2029         if (!signature) {
2030                 const char *sig_body;
2031
2032                 size = mono_metadata_decode_blob_size (sig, &sig_body);
2033
2034                 signature = mono_metadata_parse_method_signature_full (img, container, idx, sig_body, NULL);
2035                 if (!signature) {
2036                         mono_loader_unlock ();
2037                         return NULL;
2038                 }
2039
2040                 if (can_cache_signature)
2041                         g_hash_table_insert (img->method_signatures, (gpointer)sig, signature);
2042         }
2043
2044         /* Verify metadata consistency */
2045         if (signature->generic_param_count) {
2046                 if (!container || !container->is_method)
2047                         g_error ("Signature claims method has generic parameters, but generic_params table says it doesn't");
2048                 if (container->type_argc != signature->generic_param_count)
2049                         g_error ("Inconsistent generic parameter count.  Signature says %d, generic_params table says %d",
2050                                  signature->generic_param_count, container->type_argc);
2051         } else if (container && container->is_method && container->type_argc)
2052                 g_error ("generic_params table claims method has generic parameters, but signature says it doesn't");
2053
2054         if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
2055                 signature->pinvoke = 1;
2056         else if (m->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
2057                 MonoCallConvention conv = 0;
2058                 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)m;
2059                 signature->pinvoke = 1;
2060
2061                 switch (piinfo->piflags & PINVOKE_ATTRIBUTE_CALL_CONV_MASK) {
2062                 case 0: /* no call conv, so using default */
2063                 case PINVOKE_ATTRIBUTE_CALL_CONV_WINAPI:
2064                         conv = MONO_CALL_DEFAULT;
2065                         break;
2066                 case PINVOKE_ATTRIBUTE_CALL_CONV_CDECL:
2067                         conv = MONO_CALL_C;
2068                         break;
2069                 case PINVOKE_ATTRIBUTE_CALL_CONV_STDCALL:
2070                         conv = MONO_CALL_STDCALL;
2071                         break;
2072                 case PINVOKE_ATTRIBUTE_CALL_CONV_THISCALL:
2073                         conv = MONO_CALL_THISCALL;
2074                         break;
2075                 case PINVOKE_ATTRIBUTE_CALL_CONV_FASTCALL:
2076                         conv = MONO_CALL_FASTCALL;
2077                         break;
2078                 case PINVOKE_ATTRIBUTE_CALL_CONV_GENERIC:
2079                 case PINVOKE_ATTRIBUTE_CALL_CONV_GENERICINST:
2080                 default:
2081                         g_warning ("unsupported calling convention : 0x%04x", piinfo->piflags);
2082                         g_assert_not_reached ();
2083                 }
2084                 signature->call_convention = conv;
2085         }
2086
2087         mono_memory_barrier ();
2088         m->signature = signature;
2089
2090         mono_loader_unlock ();
2091         return m->signature;
2092 }
2093
2094 const char*
2095 mono_method_get_name (MonoMethod *method)
2096 {
2097         return method->name;
2098 }
2099
2100 MonoClass*
2101 mono_method_get_class (MonoMethod *method)
2102 {
2103         return method->klass;
2104 }
2105
2106 guint32
2107 mono_method_get_token (MonoMethod *method)
2108 {
2109         return method->token;
2110 }
2111
2112 MonoMethodHeader*
2113 mono_method_get_header (MonoMethod *method)
2114 {
2115         int idx;
2116         guint32 rva;
2117         MonoImage* img;
2118         gpointer loc;
2119         MonoMethodNormal* mn = (MonoMethodNormal*) method;
2120         MonoMethodHeader *header;
2121
2122         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))
2123                 return NULL;
2124
2125 #ifdef G_LIKELY
2126         if (G_LIKELY (mn->header))
2127 #else
2128         if (mn->header)
2129 #endif
2130                 return mn->header;
2131
2132         if (method->is_inflated) {
2133                 MonoMethodInflated *imethod = (MonoMethodInflated *) method;
2134                 MonoMethodHeader *header;
2135
2136                 header = mono_method_get_header (imethod->declaring);
2137
2138                 mono_loader_lock ();
2139
2140                 if (mn->header) {
2141                         mono_loader_unlock ();
2142                         return mn->header;
2143                 }
2144
2145                 mn->header = inflate_generic_header (header, mono_method_get_context (method));
2146                 mono_loader_unlock ();
2147                 return mn->header;
2148         }
2149
2150         /* 
2151          * Do most of the work outside the loader lock, to avoid assembly loader hook
2152          * deadlocks.
2153          */
2154         g_assert (mono_metadata_token_table (method->token) == MONO_TABLE_METHOD);
2155         idx = mono_metadata_token_index (method->token);
2156         img = method->klass->image;
2157         rva = mono_metadata_decode_row_col (&img->tables [MONO_TABLE_METHOD], idx - 1, MONO_METHOD_RVA);
2158         loc = mono_image_rva_map (img, rva);
2159
2160         g_assert (loc);
2161
2162         header = mono_metadata_parse_mh_full (img, mono_method_get_generic_container (method), loc);
2163
2164         mono_loader_lock ();
2165
2166         if (mn->header) {
2167                 /* header is allocated from the image mempool, no need to free it */
2168                 mono_loader_unlock ();
2169                 return mn->header;
2170         }
2171
2172         mono_memory_barrier ();
2173
2174         mn->header = header;
2175
2176         mono_loader_unlock ();
2177         return mn->header;
2178 }
2179
2180 guint32
2181 mono_method_get_flags (MonoMethod *method, guint32 *iflags)
2182 {
2183         if (iflags)
2184                 *iflags = method->iflags;
2185         return method->flags;
2186 }
2187
2188 /*
2189  * Find the method index in the metadata methodDef table.
2190  */
2191 guint32
2192 mono_method_get_index (MonoMethod *method) {
2193         MonoClass *klass = method->klass;
2194         int i;
2195
2196         if (method->token)
2197                 return mono_metadata_token_index (method->token);
2198
2199         mono_class_setup_methods (klass);
2200         for (i = 0; i < klass->method.count; ++i) {
2201                 if (method == klass->methods [i]) {
2202                         if (klass->image->uncompressed_metadata)
2203                                 return mono_metadata_translate_token_index (klass->image, MONO_TABLE_METHOD, klass->method.first + i + 1);
2204                         else
2205                                 return klass->method.first + i + 1;
2206                 }
2207         }
2208         return 0;
2209 }
2210