56630da1eddbdf44b210c32f3670351a49b502e7
[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  * Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
12  *
13  * This file is used by the interpreter and the JIT engine to locate
14  * assemblies.  Used to load AssemblyRef and later to resolve various
15  * kinds of `Refs'.
16  *
17  * TODO:
18  *   This should keep track of the assembly versions that we are loading.
19  *
20  */
21 #include <config.h>
22 #include <glib.h>
23 #include <stdlib.h>
24 #include <stdio.h>
25 #include <string.h>
26 #include <mono/metadata/metadata.h>
27 #include <mono/metadata/image.h>
28 #include <mono/metadata/assembly.h>
29 #include <mono/metadata/tokentype.h>
30 #include <mono/metadata/tabledefs.h>
31 #include <mono/metadata/metadata-internals.h>
32 #include <mono/metadata/loader.h>
33 #include <mono/metadata/class-internals.h>
34 #include <mono/metadata/debug-helpers.h>
35 #include <mono/metadata/reflection.h>
36 #include <mono/metadata/profiler.h>
37 #include <mono/metadata/profiler-private.h>
38 #include <mono/metadata/exception.h>
39 #include <mono/metadata/marshal.h>
40 #include <mono/metadata/lock-tracer.h>
41 #include <mono/metadata/verify-internals.h>
42 #include <mono/utils/mono-logger-internals.h>
43 #include <mono/utils/mono-dl.h>
44 #include <mono/utils/mono-membar.h>
45 #include <mono/utils/mono-counters.h>
46 #include <mono/utils/mono-error-internals.h>
47 #include <mono/utils/mono-tls.h>
48 #include <mono/utils/mono-path.h>
49
50 MonoDefaults mono_defaults;
51
52 /*
53  * This lock protects the hash tables inside MonoImage used by the metadata 
54  * loading functions in class.c and loader.c.
55  *
56  * See domain-internals.h for locking policy in combination with the
57  * domain lock.
58  */
59 static MonoCoopMutex loader_mutex;
60 static mono_mutex_t global_loader_data_mutex;
61 static gboolean loader_lock_inited;
62
63 /* Statistics */
64 static guint32 inflated_signatures_size;
65 static guint32 memberref_sig_cache_size;
66 static guint32 methods_size;
67 static guint32 signatures_size;
68
69 /*
70  * This TLS variable contains the last type load error encountered by the loader.
71  */
72 MonoNativeTlsKey loader_error_thread_id;
73
74 /*
75  * This TLS variable holds how many times the current thread has acquired the loader 
76  * lock.
77  */
78 MonoNativeTlsKey loader_lock_nest_id;
79
80 static void dllmap_cleanup (void);
81
82
83 static void
84 global_loader_data_lock (void)
85 {
86         mono_locks_os_acquire (&global_loader_data_mutex, LoaderGlobalDataLock);
87 }
88
89 static void
90 global_loader_data_unlock (void)
91 {
92         mono_locks_os_release (&global_loader_data_mutex, LoaderGlobalDataLock);
93 }
94
95 void
96 mono_loader_init ()
97 {
98         static gboolean inited;
99
100         if (!inited) {
101                 mono_coop_mutex_init_recursive (&loader_mutex);
102                 mono_os_mutex_init_recursive (&global_loader_data_mutex);
103                 loader_lock_inited = TRUE;
104
105                 mono_native_tls_alloc (&loader_error_thread_id, NULL);
106                 mono_native_tls_alloc (&loader_lock_nest_id, NULL);
107
108                 mono_counters_init ();
109                 mono_counters_register ("Inflated signatures size",
110                                                                 MONO_COUNTER_GENERICS | MONO_COUNTER_INT, &inflated_signatures_size);
111                 mono_counters_register ("Memberref signature cache size",
112                                                                 MONO_COUNTER_METADATA | MONO_COUNTER_INT, &memberref_sig_cache_size);
113                 mono_counters_register ("MonoMethod size",
114                                                                 MONO_COUNTER_METADATA | MONO_COUNTER_INT, &methods_size);
115                 mono_counters_register ("MonoMethodSignature size",
116                                                                 MONO_COUNTER_METADATA | MONO_COUNTER_INT, &signatures_size);
117
118                 inited = TRUE;
119         }
120 }
121
122 void
123 mono_loader_cleanup (void)
124 {
125         dllmap_cleanup ();
126
127         mono_native_tls_free (loader_error_thread_id);
128         mono_native_tls_free (loader_lock_nest_id);
129
130         mono_coop_mutex_destroy (&loader_mutex);
131         mono_os_mutex_destroy (&global_loader_data_mutex);
132         loader_lock_inited = FALSE;     
133 }
134
135 /*
136  * Handling of type load errors should be done as follows:
137  *
138  *   If something could not be loaded, the loader should call one of the
139  * mono_loader_set_error_XXX functions ()
140  * with the appropriate arguments, then return NULL to report the failure. The error 
141  * should be propagated until it reaches code which can throw managed exceptions. At that
142  * point, an exception should be thrown based on the information returned by
143  * mono_loader_get_last_error (). Then the error should be cleared by calling 
144  * mono_loader_clear_error ().
145  */
146
147 static void
148 set_loader_error (MonoLoaderError *error)
149 {
150         mono_loader_clear_error ();
151         mono_native_tls_set_value (loader_error_thread_id, error);
152 }
153
154 /**
155  * mono_loader_set_error_assembly_load:
156  *
157  * Set the loader error for this thread. 
158  */
159 void
160 mono_loader_set_error_assembly_load (const char *assembly_name, gboolean ref_only)
161 {
162         MonoLoaderError *error;
163
164         if (mono_loader_get_last_error ()) 
165                 return;
166
167         error = g_new0 (MonoLoaderError, 1);
168         error->exception_type = MONO_EXCEPTION_FILE_NOT_FOUND;
169         error->assembly_name = g_strdup (assembly_name);
170         error->ref_only = ref_only;
171
172         /* 
173          * This is not strictly needed, but some (most) of the loader code still
174          * can't deal with load errors, and this message is more helpful than an
175          * assert.
176          */
177         if (ref_only)
178                 mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_ASSEMBLY, "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);
179         else
180                 mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_ASSEMBLY, "Could not load file or assembly '%s' or one of its dependencies.", assembly_name);
181
182         set_loader_error (error);
183 }
184
185 /**
186  * mono_loader_set_error_type_load:
187  *
188  * Set the loader error for this thread. 
189  */
190 void
191 mono_loader_set_error_type_load (const char *class_name, const char *assembly_name)
192 {
193         MonoLoaderError *error;
194
195         if (mono_loader_get_last_error ()) 
196                 return;
197
198         error = g_new0 (MonoLoaderError, 1);
199         error->exception_type = MONO_EXCEPTION_TYPE_LOAD;
200         error->class_name = g_strdup (class_name);
201         error->assembly_name = g_strdup (assembly_name);
202
203         /* 
204          * This is not strictly needed, but some (most) of the loader code still
205          * can't deal with load errors, and this message is more helpful than an
206          * assert.
207          */
208         mono_trace_warning (MONO_TRACE_TYPE, "The class %s could not be loaded, used in %s", class_name, assembly_name);
209
210         set_loader_error (error);
211 }
212
213 /*
214  * mono_loader_set_error_method_load:
215  *
216  *   Set the loader error for this thread. MEMBER_NAME should point to a string
217  * inside metadata.
218  */
219 void
220 mono_loader_set_error_method_load (const char *class_name, const char *member_name)
221 {
222         MonoLoaderError *error;
223
224         /* FIXME: Store the signature as well */
225         if (mono_loader_get_last_error ())
226                 return;
227
228         error = g_new0 (MonoLoaderError, 1);
229         error->exception_type = MONO_EXCEPTION_MISSING_METHOD;
230         error->class_name = g_strdup (class_name);
231         error->member_name = member_name;
232
233         set_loader_error (error);
234 }
235
236 /*
237  * mono_loader_set_error_field_load:
238  *
239  * Set the loader error for this thread. MEMBER_NAME should point to a string
240  * inside metadata.
241  */
242 void
243 mono_loader_set_error_field_load (MonoClass *klass, const char *member_name)
244 {
245         MonoLoaderError *error;
246
247         /* FIXME: Store the signature as well */
248         if (mono_loader_get_last_error ())
249                 return;
250
251         error = g_new0 (MonoLoaderError, 1);
252         error->exception_type = MONO_EXCEPTION_MISSING_FIELD;
253         error->klass = klass;
254         error->member_name = member_name;
255
256         set_loader_error (error);
257 }
258
259 /*
260  * mono_loader_set_error_bad_image:
261  *
262  * Set the loader error for this thread. 
263  */
264 void
265 mono_loader_set_error_bad_image (char *msg)
266 {
267         MonoLoaderError *error;
268
269         if (mono_loader_get_last_error ())
270                 return;
271
272         error = g_new0 (MonoLoaderError, 1);
273         error->exception_type = MONO_EXCEPTION_BAD_IMAGE;
274         error->msg = msg;
275
276         set_loader_error (error);
277 }       
278
279
280 /*
281  * mono_loader_get_last_error:
282  *
283  *   Returns information about the last type load exception encountered by the loader, or
284  * NULL. After use, the exception should be cleared by calling mono_loader_clear_error.
285  */
286 MonoLoaderError*
287 mono_loader_get_last_error (void)
288 {
289         return (MonoLoaderError*)mono_native_tls_get_value (loader_error_thread_id);
290 }
291
292 void
293 mono_loader_assert_no_error (void)
294 {
295         MonoLoaderError *error = mono_loader_get_last_error ();
296
297         if (error) {
298                 g_print ("Unhandled loader error: %x, %s %s %s\n", error->exception_type, error->msg, error->assembly_name, error->class_name);
299                 g_assert_not_reached ();
300         }
301 }
302
303 /**
304  * mono_loader_clear_error:
305  *
306  * Disposes any loader error messages on this thread
307  */
308 void
309 mono_loader_clear_error (void)
310 {
311         MonoLoaderError *ex = (MonoLoaderError*)mono_native_tls_get_value (loader_error_thread_id);
312
313         if (ex) {
314                 g_free (ex->class_name);
315                 g_free (ex->assembly_name);
316                 g_free (ex->msg);
317                 g_free (ex);
318
319                 mono_native_tls_set_value (loader_error_thread_id, NULL);
320         }
321 }
322
323 /**
324  * mono_loader_error_prepare_exception:
325  * @error: The MonoLoaderError to turn into an exception
326  *
327  * This turns a MonoLoaderError into an exception that can be thrown
328  * and resets the Mono Loader Error state during this process.
329  *
330  */
331 MonoException *
332 mono_loader_error_prepare_exception (MonoLoaderError *error)
333 {
334         MonoException *ex = NULL;
335
336         switch (error->exception_type) {
337         case MONO_EXCEPTION_TYPE_LOAD: {
338                 char *cname = g_strdup (error->class_name);
339                 char *aname = g_strdup (error->assembly_name);
340                 MonoString *class_name;
341                 
342                 mono_loader_clear_error ();
343                 
344                 class_name = mono_string_new (mono_domain_get (), cname);
345
346                 ex = mono_get_exception_type_load (class_name, aname);
347                 g_free (cname);
348                 g_free (aname);
349                 break;
350         }
351         case MONO_EXCEPTION_MISSING_METHOD: {
352                 char *cname = g_strdup (error->class_name);
353                 char *aname = g_strdup (error->member_name);
354                 
355                 mono_loader_clear_error ();
356                 ex = mono_get_exception_missing_method (cname, aname);
357                 g_free (cname);
358                 g_free (aname);
359                 break;
360         }
361                 
362         case MONO_EXCEPTION_MISSING_FIELD: {
363                 char *class_name;
364                 char *cmembername = g_strdup (error->member_name);
365                 if (error->klass)
366                         class_name = mono_type_get_full_name (error->klass);
367                 else
368                         class_name = g_strdup ("");
369
370                 mono_loader_clear_error ();
371                 
372                 ex = mono_get_exception_missing_field (class_name, cmembername);
373                 g_free (class_name);
374                 g_free (cmembername);
375                 break;
376         }
377         
378         case MONO_EXCEPTION_FILE_NOT_FOUND: {
379                 char *msg;
380                 char *filename;
381
382                 if (error->ref_only)
383                         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);
384                 else
385                         msg = g_strdup_printf ("Could not load file or assembly '%s' or one of its dependencies.", error->assembly_name);
386                 filename = g_strdup (error->assembly_name);
387                 /* Has to call this before calling anything which might call mono_class_init () */
388                 mono_loader_clear_error ();
389                 ex = mono_get_exception_file_not_found2 (msg, mono_string_new (mono_domain_get (), filename));
390                 g_free (msg);
391                 g_free (filename);
392                 break;
393         }
394
395         case MONO_EXCEPTION_BAD_IMAGE: {
396                 char *msg = g_strdup (error->msg);
397                 mono_loader_clear_error ();
398                 ex = mono_get_exception_bad_image_format (msg);
399                 g_free (msg);
400                 break;
401         }
402
403         default:
404                 g_assert_not_reached ();
405         }
406
407         return ex;
408 }
409
410 /*
411  * find_cached_memberref_sig:
412  *
413  *   Return a cached copy of the memberref signature identified by SIG_IDX.
414  * We use a gpointer since the cache stores both MonoTypes and MonoMethodSignatures.
415  * A cache is needed since the type/signature parsing routines allocate everything 
416  * from a mempool, so without a cache, multiple requests for the same signature would 
417  * lead to unbounded memory growth. For normal methods/fields this is not a problem 
418  * since the resulting methods/fields are cached, but inflated methods/fields cannot
419  * be cached.
420  * LOCKING: Acquires the loader lock.
421  */
422 static gpointer
423 find_cached_memberref_sig (MonoImage *image, guint32 sig_idx)
424 {
425         gpointer res;
426
427         mono_image_lock (image);
428         res = g_hash_table_lookup (image->memberref_signatures, GUINT_TO_POINTER (sig_idx));
429         mono_image_unlock (image);
430
431         return res;
432 }
433
434 static gpointer
435 cache_memberref_sig (MonoImage *image, guint32 sig_idx, gpointer sig)
436 {
437         gpointer prev_sig;
438
439         mono_image_lock (image);
440         prev_sig = g_hash_table_lookup (image->memberref_signatures, GUINT_TO_POINTER (sig_idx));
441         if (prev_sig) {
442                 /* Somebody got in before us */
443                 sig = prev_sig;
444         }
445         else {
446                 g_hash_table_insert (image->memberref_signatures, GUINT_TO_POINTER (sig_idx), sig);
447                 /* An approximation based on glib 2.18 */
448                 memberref_sig_cache_size += sizeof (gpointer) * 4;
449         }
450         mono_image_unlock (image);
451
452         return sig;
453 }
454
455 static MonoClassField*
456 field_from_memberref (MonoImage *image, guint32 token, MonoClass **retklass,
457                       MonoGenericContext *context, MonoError *error)
458 {
459         MonoClass *klass = NULL;
460         MonoClassField *field;
461         MonoTableInfo *tables = image->tables;
462         MonoType *sig_type;
463         guint32 cols[6];
464         guint32 nindex, class_index;
465         const char *fname;
466         const char *ptr;
467         guint32 idx = mono_metadata_token_index (token);
468
469         mono_error_init (error);
470
471         mono_metadata_decode_row (&tables [MONO_TABLE_MEMBERREF], idx-1, cols, MONO_MEMBERREF_SIZE);
472         nindex = cols [MONO_MEMBERREF_CLASS] >> MONO_MEMBERREF_PARENT_BITS;
473         class_index = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
474
475         fname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
476
477         if (!mono_verifier_verify_memberref_field_signature (image, cols [MONO_MEMBERREF_SIGNATURE], NULL)) {
478                 mono_error_set_bad_image (error, image, "Bad field '%s' signature 0x%08x", class_index, token);
479                 return NULL;
480         }
481
482         switch (class_index) {
483         case MONO_MEMBERREF_PARENT_TYPEDEF:
484                 klass = mono_class_get_checked (image, MONO_TOKEN_TYPE_DEF | nindex, error);
485                 break;
486         case MONO_MEMBERREF_PARENT_TYPEREF:
487                 klass = mono_class_from_typeref_checked (image, MONO_TOKEN_TYPE_REF | nindex, error);
488                 break;
489         case MONO_MEMBERREF_PARENT_TYPESPEC:
490                 klass = mono_class_get_and_inflate_typespec_checked (image, MONO_TOKEN_TYPE_SPEC | nindex, context, error);
491                 break;
492         default:
493                 mono_error_set_bad_image (error, image, "Bad field field '%s' signature 0x%08x", class_index, token);
494         }
495
496         if (!klass)
497                 return NULL;
498
499         ptr = mono_metadata_blob_heap (image, cols [MONO_MEMBERREF_SIGNATURE]);
500         mono_metadata_decode_blob_size (ptr, &ptr);
501         /* we may want to check the signature here... */
502
503         if (*ptr++ != 0x6) {
504                 mono_error_set_field_load (error, klass, fname, "Bad field signature class token %08x field name %s token %08x", class_index, fname, token);
505                 return NULL;
506         }
507
508         /* FIXME: This needs a cache, especially for generic instances, since
509          * we ask mono_metadata_parse_type_checked () to allocates everything from a mempool.
510          * FIXME part2, mono_metadata_parse_type_checked actually allows for a transient type instead.
511          * FIXME part3, transient types are not 100% transient, so we need to take care of that first.
512          */
513         sig_type = (MonoType *)find_cached_memberref_sig (image, cols [MONO_MEMBERREF_SIGNATURE]);
514         if (!sig_type) {
515                 MonoError inner_error;
516                 sig_type = mono_metadata_parse_type_checked (image, NULL, 0, FALSE, ptr, &ptr, &inner_error);
517                 if (sig_type == NULL) {
518                         mono_error_set_field_load (error, klass, fname, "Could not parse field '%s' signature %08x due to: %s", fname, token, mono_error_get_message (&inner_error));
519                         mono_error_cleanup (&inner_error);
520                         return NULL;
521                 }
522                 sig_type = (MonoType *)cache_memberref_sig (image, cols [MONO_MEMBERREF_SIGNATURE], sig_type);
523         }
524
525         mono_class_init (klass); /*FIXME is this really necessary?*/
526         if (retklass)
527                 *retklass = klass;
528         field = mono_class_get_field_from_name_full (klass, fname, sig_type);
529
530         if (!field) {
531                 mono_loader_assert_no_error ();
532                 mono_error_set_field_load (error, klass, fname, "Could not find field '%s'", fname);
533         }
534
535         return field;
536 }
537
538 /*
539  * mono_field_from_token:
540  * @deprecated use the _checked variant
541  * Notes: runtime code MUST not use this function
542 */
543 MonoClassField*
544 mono_field_from_token (MonoImage *image, guint32 token, MonoClass **retklass, MonoGenericContext *context)
545 {
546         MonoError error;
547         MonoClassField *res = mono_field_from_token_checked (image, token, retklass, context, &error);
548         g_assert (mono_error_ok (&error));
549         return res;
550 }
551
552 MonoClassField*
553 mono_field_from_token_checked (MonoImage *image, guint32 token, MonoClass **retklass, MonoGenericContext *context, MonoError *error)
554 {
555         MonoClass *k;
556         guint32 type;
557         MonoClassField *field;
558
559         mono_error_init (error);
560
561         if (image_is_dynamic (image)) {
562                 MonoClassField *result;
563                 MonoClass *handle_class;
564
565                 *retklass = NULL;
566                 result = (MonoClassField *)mono_lookup_dynamic_token_class (image, token, TRUE, &handle_class, context);
567                 // This checks the memberref type as well
568                 if (!result || handle_class != mono_defaults.fieldhandle_class) {
569                         mono_error_set_bad_image (error, image, "Bad field token 0x%08x", token);
570                         return NULL;
571                 }
572                 *retklass = result->parent;
573                 return result;
574         }
575
576         if ((field = (MonoClassField *)mono_conc_hashtable_lookup (image->field_cache, GUINT_TO_POINTER (token)))) {
577                 *retklass = field->parent;
578                 return field;
579         }
580
581         if (mono_metadata_token_table (token) == MONO_TABLE_MEMBERREF) {
582                 field = field_from_memberref (image, token, retklass, context, error);
583                 mono_loader_assert_no_error ();
584         } else {
585                 type = mono_metadata_typedef_from_field (image, mono_metadata_token_index (token));
586                 if (!type) {
587                         mono_error_set_bad_image (error, image, "Invalid field token 0x%08x", token);
588                         return NULL;
589                 }
590                 k = mono_class_get_checked (image, MONO_TOKEN_TYPE_DEF | type, error);
591                 if (!k)
592                         return NULL;
593
594                 mono_class_init (k);
595                 if (retklass)
596                         *retklass = k;
597                 field = mono_class_get_field (k, token);
598                 if (!field) {
599                         if (mono_loader_get_last_error ())
600                                 mono_error_set_from_loader_error (error);
601                         else
602                                 mono_error_set_bad_image (error, image, "Could not resolve field token 0x%08x", token);
603                 }
604         }
605
606         if (field && field->parent && !field->parent->generic_class && !field->parent->generic_container) {
607                 mono_image_lock (image);
608                 mono_conc_hashtable_insert (image->field_cache, GUINT_TO_POINTER (token), field);
609                 mono_image_unlock (image);
610         }
611
612         mono_loader_assert_no_error ();
613         return field;
614 }
615
616 static gboolean
617 mono_metadata_signature_vararg_match (MonoMethodSignature *sig1, MonoMethodSignature *sig2)
618 {
619         int i;
620
621         if (sig1->hasthis != sig2->hasthis ||
622             sig1->sentinelpos != sig2->sentinelpos)
623                 return FALSE;
624
625         for (i = 0; i < sig1->sentinelpos; i++) { 
626                 MonoType *p1 = sig1->params[i];
627                 MonoType *p2 = sig2->params[i];
628
629                 /*if (p1->attrs != p2->attrs)
630                         return FALSE;
631                 */
632                 if (!mono_metadata_type_equal (p1, p2))
633                         return FALSE;
634         }
635
636         if (!mono_metadata_type_equal (sig1->ret, sig2->ret))
637                 return FALSE;
638         return TRUE;
639 }
640
641 static MonoMethod *
642 find_method_in_class (MonoClass *klass, const char *name, const char *qname, const char *fqname,
643                       MonoMethodSignature *sig, MonoClass *from_class, MonoError *error)
644 {
645         int i;
646
647         /* Search directly in the metadata to avoid calling setup_methods () */
648         mono_error_init (error);
649
650         /* FIXME: !from_class->generic_class condition causes test failures. */
651         if (klass->type_token && !image_is_dynamic (klass->image) && !klass->methods && !klass->rank && klass == from_class && !from_class->generic_class) {
652                 for (i = 0; i < klass->method.count; ++i) {
653                         guint32 cols [MONO_METHOD_SIZE];
654                         MonoMethod *method;
655                         const char *m_name;
656                         MonoMethodSignature *other_sig;
657
658                         mono_metadata_decode_table_row (klass->image, MONO_TABLE_METHOD, klass->method.first + i, cols, MONO_METHOD_SIZE);
659
660                         m_name = mono_metadata_string_heap (klass->image, cols [MONO_METHOD_NAME]);
661
662                         if (!((fqname && !strcmp (m_name, fqname)) ||
663                                   (qname && !strcmp (m_name, qname)) ||
664                                   (name && !strcmp (m_name, name))))
665                                 continue;
666
667                         method = mono_get_method_checked (klass->image, MONO_TOKEN_METHOD_DEF | (klass->method.first + i + 1), klass, NULL, error);
668                         if (!mono_error_ok (error)) //bail out if we hit a loader error
669                                 return NULL;
670                         if (method) {
671                                 other_sig = mono_method_signature_checked (method, error);
672                                 if (!mono_error_ok (error)) //bail out if we hit a loader error
673                                         return NULL;                            
674                                 if (other_sig && (sig->call_convention != MONO_CALL_VARARG) && mono_metadata_signature_equal (sig, other_sig))
675                                         return method;
676                         }
677                 }
678         }
679
680         mono_class_setup_methods (klass); /* FIXME don't swallow the error here. */
681         /*
682         We can't fail lookup of methods otherwise the runtime will fail with MissingMethodException instead of TypeLoadException.
683         See mono/tests/generic-type-load-exception.2.il
684         FIXME we should better report this error to the caller
685          */
686         if (!klass->methods || mono_class_has_failure (klass)) {
687                 mono_error_set_type_load_class (error, klass, "Could not find method due to a type load error"); //FIXME get the error from the class 
688
689                 return NULL;
690         }
691         for (i = 0; i < klass->method.count; ++i) {
692                 MonoMethod *m = klass->methods [i];
693                 MonoMethodSignature *msig;
694
695                 /* We must cope with failing to load some of the types. */
696                 if (!m)
697                         continue;
698
699                 if (!((fqname && !strcmp (m->name, fqname)) ||
700                       (qname && !strcmp (m->name, qname)) ||
701                       (name && !strcmp (m->name, name))))
702                         continue;
703                 msig = mono_method_signature_checked (m, error);
704                 if (!mono_error_ok (error)) //bail out if we hit a loader error
705                         return NULL;
706
707                 if (!msig)
708                         continue;
709
710                 if (sig->call_convention == MONO_CALL_VARARG) {
711                         if (mono_metadata_signature_vararg_match (sig, msig))
712                                 break;
713                 } else {
714                         if (mono_metadata_signature_equal (sig, msig))
715                                 break;
716                 }
717         }
718
719         if (i < klass->method.count)
720                 return mono_class_get_method_by_index (from_class, i);
721         return NULL;
722 }
723
724 static MonoMethod *
725 find_method (MonoClass *in_class, MonoClass *ic, const char* name, MonoMethodSignature *sig, MonoClass *from_class, MonoError *error)
726 {
727         int i;
728         char *qname, *fqname, *class_name;
729         gboolean is_interface;
730         MonoMethod *result = NULL;
731         MonoClass *initial_class = in_class;
732
733         mono_error_init (error);
734         is_interface = MONO_CLASS_IS_INTERFACE (in_class);
735
736         if (ic) {
737                 class_name = mono_type_get_name_full (&ic->byval_arg, MONO_TYPE_NAME_FORMAT_IL);
738
739                 qname = g_strconcat (class_name, ".", name, NULL); 
740                 if (ic->name_space && ic->name_space [0])
741                         fqname = g_strconcat (ic->name_space, ".", class_name, ".", name, NULL);
742                 else
743                         fqname = NULL;
744         } else
745                 class_name = qname = fqname = NULL;
746
747         while (in_class) {
748                 g_assert (from_class);
749                 result = find_method_in_class (in_class, name, qname, fqname, sig, from_class, error);
750                 if (result || !mono_error_ok (error))
751                         goto out;
752
753                 if (name [0] == '.' && (!strcmp (name, ".ctor") || !strcmp (name, ".cctor")))
754                         break;
755
756                 /*
757                  * This happens when we fail to lazily load the interfaces of one of the types.
758                  * On such case we can't just bail out since user code depends on us trying harder.
759                  */
760                 if (from_class->interface_offsets_count != in_class->interface_offsets_count) {
761                         in_class = in_class->parent;
762                         from_class = from_class->parent;
763                         continue;
764                 }
765
766                 for (i = 0; i < in_class->interface_offsets_count; i++) {
767                         MonoClass *in_ic = in_class->interfaces_packed [i];
768                         MonoClass *from_ic = from_class->interfaces_packed [i];
769                         char *ic_qname, *ic_fqname, *ic_class_name;
770                         
771                         ic_class_name = mono_type_get_name_full (&in_ic->byval_arg, MONO_TYPE_NAME_FORMAT_IL);
772                         ic_qname = g_strconcat (ic_class_name, ".", name, NULL); 
773                         if (in_ic->name_space && in_ic->name_space [0])
774                                 ic_fqname = g_strconcat (in_ic->name_space, ".", ic_class_name, ".", name, NULL);
775                         else
776                                 ic_fqname = NULL;
777
778                         result = find_method_in_class (in_ic, ic ? name : NULL, ic_qname, ic_fqname, sig, from_ic, error);
779                         g_free (ic_class_name);
780                         g_free (ic_fqname);
781                         g_free (ic_qname);
782                         if (result || !mono_error_ok (error))
783                                 goto out;
784                 }
785
786                 in_class = in_class->parent;
787                 from_class = from_class->parent;
788         }
789         g_assert (!in_class == !from_class);
790
791         if (is_interface)
792                 result = find_method_in_class (mono_defaults.object_class, name, qname, fqname, sig, mono_defaults.object_class, error);
793
794         //we did not find the method
795         if (!result && mono_error_ok (error)) {
796                 char *desc = mono_signature_get_desc (sig, FALSE);
797                 mono_error_set_method_load (error, initial_class, name, "Could not find method with signature %s", desc);
798                 g_free (desc);
799         }
800                 
801  out:
802         g_free (class_name);
803         g_free (fqname);
804         g_free (qname);
805         return result;
806 }
807
808 static MonoMethodSignature*
809 inflate_generic_signature_checked (MonoImage *image, MonoMethodSignature *sig, MonoGenericContext *context, MonoError *error)
810 {
811         MonoMethodSignature *res;
812         gboolean is_open;
813         int i;
814
815         mono_error_init (error);
816         if (!context)
817                 return sig;
818
819         res = (MonoMethodSignature *)g_malloc0 (MONO_SIZEOF_METHOD_SIGNATURE + ((gint32)sig->param_count) * sizeof (MonoType*));
820         res->param_count = sig->param_count;
821         res->sentinelpos = -1;
822         res->ret = mono_class_inflate_generic_type_checked (sig->ret, context, error);
823         if (!mono_error_ok (error))
824                 goto fail;
825         is_open = mono_class_is_open_constructed_type (res->ret);
826         for (i = 0; i < sig->param_count; ++i) {
827                 res->params [i] = mono_class_inflate_generic_type_checked (sig->params [i], context, error);
828                 if (!mono_error_ok (error))
829                         goto fail;
830
831                 if (!is_open)
832                         is_open = mono_class_is_open_constructed_type (res->params [i]);
833         }
834         res->hasthis = sig->hasthis;
835         res->explicit_this = sig->explicit_this;
836         res->call_convention = sig->call_convention;
837         res->pinvoke = sig->pinvoke;
838         res->generic_param_count = sig->generic_param_count;
839         res->sentinelpos = sig->sentinelpos;
840         res->has_type_parameters = is_open;
841         res->is_inflated = 1;
842         return res;
843
844 fail:
845         if (res->ret)
846                 mono_metadata_free_type (res->ret);
847         for (i = 0; i < sig->param_count; ++i) {
848                 if (res->params [i])
849                         mono_metadata_free_type (res->params [i]);
850         }
851         g_free (res);
852         return NULL;
853 }
854
855 /*
856  * mono_inflate_generic_signature:
857  *
858  *   Inflate SIG with CONTEXT, and return a canonical copy. On error, set ERROR, and return NULL.
859  */
860 MonoMethodSignature*
861 mono_inflate_generic_signature (MonoMethodSignature *sig, MonoGenericContext *context, MonoError *error)
862 {
863         MonoMethodSignature *res, *cached;
864
865         res = inflate_generic_signature_checked (NULL, sig, context, error);
866         if (!mono_error_ok (error))
867                 return NULL;
868         cached = mono_metadata_get_inflated_signature (res, context);
869         if (cached != res)
870                 mono_metadata_free_inflated_signature (res);
871         return cached;
872 }
873
874 static MonoMethodHeader*
875 inflate_generic_header (MonoMethodHeader *header, MonoGenericContext *context, MonoError *error)
876 {
877         MonoMethodHeader *res;
878         int i;
879         res = (MonoMethodHeader *)g_malloc0 (MONO_SIZEOF_METHOD_HEADER + sizeof (gpointer) * header->num_locals);
880         res->code = header->code;
881         res->code_size = header->code_size;
882         res->max_stack = header->max_stack;
883         res->num_clauses = header->num_clauses;
884         res->init_locals = header->init_locals;
885         res->num_locals = header->num_locals;
886         res->clauses = header->clauses;
887
888         mono_error_init (error);
889
890         for (i = 0; i < header->num_locals; ++i) {
891                 res->locals [i] = mono_class_inflate_generic_type_checked (header->locals [i], context, error);
892                 if (!is_ok (error))
893                         goto fail;
894         }
895         if (res->num_clauses) {
896                 res->clauses = (MonoExceptionClause *)g_memdup (header->clauses, sizeof (MonoExceptionClause) * res->num_clauses);
897                 for (i = 0; i < header->num_clauses; ++i) {
898                         MonoExceptionClause *clause = &res->clauses [i];
899                         if (clause->flags != MONO_EXCEPTION_CLAUSE_NONE)
900                                 continue;
901                         clause->data.catch_class = mono_class_inflate_generic_class_checked (clause->data.catch_class, context, error);
902                         if (!is_ok (error))
903                                 goto fail;
904                 }
905         }
906         return res;
907 fail:
908         g_free (res);
909         return NULL;
910 }
911
912 /*
913  * token is the method_ref/def/spec token used in a call IL instruction.
914  * @deprecated use the _checked variant
915  * Notes: runtime code MUST not use this function
916  */
917 MonoMethodSignature*
918 mono_method_get_signature_full (MonoMethod *method, MonoImage *image, guint32 token, MonoGenericContext *context)
919 {
920         MonoError error;
921         MonoMethodSignature *res = mono_method_get_signature_checked (method, image, token, context, &error);
922         mono_error_cleanup (&error);
923         return res;
924 }
925
926 MonoMethodSignature*
927 mono_method_get_signature_checked (MonoMethod *method, MonoImage *image, guint32 token, MonoGenericContext *context, MonoError *error)
928 {
929         int table = mono_metadata_token_table (token);
930         int idx = mono_metadata_token_index (token);
931         int sig_idx;
932         guint32 cols [MONO_MEMBERREF_SIZE];
933         MonoMethodSignature *sig;
934         const char *ptr;
935
936         mono_error_init (error);
937
938         /* !table is for wrappers: we should really assign their own token to them */
939         if (!table || table == MONO_TABLE_METHOD)
940                 return mono_method_signature_checked (method, error);
941
942         if (table == MONO_TABLE_METHODSPEC) {
943                 /* the verifier (do_invoke_method) will turn the NULL into a verifier error */
944                 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) || !method->is_inflated) {
945                         mono_error_set_bad_image (error, image, "Method is a pinvoke or open generic");
946                         return NULL;
947                 }
948
949                 return mono_method_signature_checked (method, error);
950         }
951
952         if (method->klass->generic_class)
953                 return mono_method_signature_checked (method, error);
954
955         if (image_is_dynamic (image)) {
956                 sig = mono_reflection_lookup_signature (image, method, token, error);
957                 if (!sig)
958                         return NULL;
959         } else {
960                 mono_metadata_decode_row (&image->tables [MONO_TABLE_MEMBERREF], idx-1, cols, MONO_MEMBERREF_SIZE);
961                 sig_idx = cols [MONO_MEMBERREF_SIGNATURE];
962
963                 sig = (MonoMethodSignature *)find_cached_memberref_sig (image, sig_idx);
964                 if (!sig) {
965                         if (!mono_verifier_verify_memberref_method_signature (image, sig_idx, NULL)) {
966                                 guint32 klass = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
967                                 const char *fname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
968
969                                 //FIXME include the verification error
970                                 mono_error_set_bad_image (error, image, "Bad method signature class token 0x%08x field name %s token 0x%08x", klass, fname, token);
971                                 return NULL;
972                         }
973
974                         ptr = mono_metadata_blob_heap (image, sig_idx);
975                         mono_metadata_decode_blob_size (ptr, &ptr);
976
977                         sig = mono_metadata_parse_method_signature_full (image, NULL, 0, ptr, NULL, error);
978                         if (!sig)
979                                 return NULL;
980
981                         sig = (MonoMethodSignature *)cache_memberref_sig (image, sig_idx, sig);
982                 }
983                 /* FIXME: we probably should verify signature compat in the dynamic case too*/
984                 if (!mono_verifier_is_sig_compatible (image, method, sig)) {
985                         guint32 klass = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
986                         const char *fname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
987
988                         mono_error_set_bad_image (error, image, "Incompatible method signature class token 0x%08x field name %s token 0x%08x", klass, fname, token);
989                         return NULL;
990                 }
991         }
992
993         if (context) {
994                 MonoMethodSignature *cached;
995
996                 /* This signature is not owned by a MonoMethod, so need to cache */
997                 sig = inflate_generic_signature_checked (image, sig, context, error);
998                 if (!mono_error_ok (error))
999                         return NULL;
1000
1001                 cached = mono_metadata_get_inflated_signature (sig, context);
1002                 if (cached != sig)
1003                         mono_metadata_free_inflated_signature (sig);
1004                 else
1005                         inflated_signatures_size += mono_metadata_signature_size (cached);
1006                 sig = cached;
1007         }
1008
1009         g_assert (mono_error_ok (error));
1010         return sig;
1011 }
1012
1013 /*
1014  * token is the method_ref/def/spec token used in a call IL instruction.
1015  * @deprecated use the _checked variant
1016  * Notes: runtime code MUST not use this function
1017  */
1018 MonoMethodSignature*
1019 mono_method_get_signature (MonoMethod *method, MonoImage *image, guint32 token)
1020 {
1021         MonoError error;
1022         MonoMethodSignature *res = mono_method_get_signature_checked (method, image, token, NULL, &error);
1023         mono_error_cleanup (&error);
1024         return res;
1025 }
1026
1027 /* this is only for the typespec array methods */
1028 MonoMethod*
1029 mono_method_search_in_array_class (MonoClass *klass, const char *name, MonoMethodSignature *sig)
1030 {
1031         int i;
1032
1033         mono_class_setup_methods (klass);
1034         g_assert (!mono_class_has_failure (klass)); /*FIXME this should not fail, right?*/
1035         for (i = 0; i < klass->method.count; ++i) {
1036                 MonoMethod *method = klass->methods [i];
1037                 if (strcmp (method->name, name) == 0 && sig->param_count == method->signature->param_count)
1038                         return method;
1039         }
1040         return NULL;
1041 }
1042
1043 static MonoMethod *
1044 method_from_memberref (MonoImage *image, guint32 idx, MonoGenericContext *typespec_context,
1045                        gboolean *used_context, MonoError *error)
1046 {
1047         MonoClass *klass = NULL;
1048         MonoMethod *method = NULL;
1049         MonoTableInfo *tables = image->tables;
1050         guint32 cols[6];
1051         guint32 nindex, class_index, sig_idx;
1052         const char *mname;
1053         MonoMethodSignature *sig;
1054         const char *ptr;
1055
1056         mono_error_init (error);
1057
1058         mono_metadata_decode_row (&tables [MONO_TABLE_MEMBERREF], idx-1, cols, 3);
1059         nindex = cols [MONO_MEMBERREF_CLASS] >> MONO_MEMBERREF_PARENT_BITS;
1060         class_index = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
1061         /*g_print ("methodref: 0x%x 0x%x %s\n", class, nindex,
1062                 mono_metadata_string_heap (m, cols [MONO_MEMBERREF_NAME]));*/
1063
1064         mname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
1065
1066         /*
1067          * Whether we actually used the `typespec_context' or not.
1068          * This is used to tell our caller whether or not it's safe to insert the returned
1069          * method into a cache.
1070          */
1071         if (used_context)
1072                 *used_context = class_index == MONO_MEMBERREF_PARENT_TYPESPEC;
1073
1074         switch (class_index) {
1075         case MONO_MEMBERREF_PARENT_TYPEREF:
1076                 klass = mono_class_from_typeref_checked (image, MONO_TOKEN_TYPE_REF | nindex, error);
1077                 if (!klass)
1078                         goto fail;
1079                 break;
1080         case MONO_MEMBERREF_PARENT_TYPESPEC:
1081                 /*
1082                  * Parse the TYPESPEC in the parent's context.
1083                  */
1084                 klass = mono_class_get_and_inflate_typespec_checked (image, MONO_TOKEN_TYPE_SPEC | nindex, typespec_context, error);
1085                 if (!klass)
1086                         goto fail;
1087                 break;
1088         case MONO_MEMBERREF_PARENT_TYPEDEF:
1089                 klass = mono_class_get_checked (image, MONO_TOKEN_TYPE_DEF | nindex, error);
1090                 if (!klass)
1091                         goto fail;
1092                 break;
1093         case MONO_MEMBERREF_PARENT_METHODDEF: {
1094                 method = mono_get_method_checked (image, MONO_TOKEN_METHOD_DEF | nindex, NULL, NULL, error);
1095                 if (!method)
1096                         goto fail;
1097                 return method;
1098         }
1099         default:
1100                 mono_error_set_bad_image (error, image, "Memberref parent unknown: class: %d, index %d", class_index, nindex);
1101                 goto fail;
1102         }
1103
1104         g_assert (klass);
1105         mono_class_init (klass);
1106
1107         sig_idx = cols [MONO_MEMBERREF_SIGNATURE];
1108
1109         if (!mono_verifier_verify_memberref_method_signature (image, sig_idx, NULL)) {
1110                 mono_error_set_method_load (error, klass, mname, "Verifier rejected method signature");
1111                 goto fail;
1112         }
1113
1114         ptr = mono_metadata_blob_heap (image, sig_idx);
1115         mono_metadata_decode_blob_size (ptr, &ptr);
1116
1117         sig = (MonoMethodSignature *)find_cached_memberref_sig (image, sig_idx);
1118         if (!sig) {
1119                 sig = mono_metadata_parse_method_signature_full (image, NULL, 0, ptr, NULL, error);
1120                 if (sig == NULL)
1121                         goto fail;
1122
1123                 sig = (MonoMethodSignature *)cache_memberref_sig (image, sig_idx, sig);
1124         }
1125
1126         switch (class_index) {
1127         case MONO_MEMBERREF_PARENT_TYPEREF:
1128         case MONO_MEMBERREF_PARENT_TYPEDEF:
1129                 method = find_method (klass, NULL, mname, sig, klass, error);
1130                 break;
1131
1132         case MONO_MEMBERREF_PARENT_TYPESPEC: {
1133                 MonoType *type;
1134
1135                 type = &klass->byval_arg;
1136
1137                 if (type->type != MONO_TYPE_ARRAY && type->type != MONO_TYPE_SZARRAY) {
1138                         MonoClass *in_class = klass->generic_class ? klass->generic_class->container_class : klass;
1139                         method = find_method (in_class, NULL, mname, sig, klass, error);
1140                         break;
1141                 }
1142
1143                 /* we're an array and we created these methods already in klass in mono_class_init () */
1144                 method = mono_method_search_in_array_class (klass, mname, sig);
1145                 break;
1146         }
1147         default:
1148                 mono_error_set_bad_image (error, image,"Memberref parent unknown: class: %d, index %d", class_index, nindex);
1149                 goto fail;
1150         }
1151
1152         if (!method && mono_error_ok (error)) {
1153                 char *msig = mono_signature_get_desc (sig, FALSE);
1154                 GString *s = g_string_new (mname);
1155                 if (sig->generic_param_count)
1156                         g_string_append_printf (s, "<[%d]>", sig->generic_param_count);
1157                 g_string_append_printf (s, "(%s)", msig);
1158                 g_free (msig);
1159                 msig = g_string_free (s, FALSE);
1160
1161                 if (mono_loader_get_last_error ()) /* FIXME find_method and mono_method_search_in_array_class can leak a loader error */
1162                         mono_error_set_from_loader_error (error);
1163                 else
1164                         mono_error_set_method_load (error, klass, mname, "Could not find method %s", msig);
1165
1166                 g_free (msig);
1167         }
1168
1169         mono_loader_assert_no_error ();
1170         return method;
1171
1172 fail:
1173         mono_loader_assert_no_error ();
1174         g_assert (!mono_error_ok (error));
1175         return NULL;
1176 }
1177
1178 static MonoMethod *
1179 method_from_methodspec (MonoImage *image, MonoGenericContext *context, guint32 idx, MonoError *error)
1180 {
1181         MonoMethod *method;
1182         MonoClass *klass;
1183         MonoTableInfo *tables = image->tables;
1184         MonoGenericContext new_context;
1185         MonoGenericInst *inst;
1186         const char *ptr;
1187         guint32 cols [MONO_METHODSPEC_SIZE];
1188         guint32 token, nindex, param_count;
1189
1190         mono_error_init (error);
1191
1192         mono_metadata_decode_row (&tables [MONO_TABLE_METHODSPEC], idx - 1, cols, MONO_METHODSPEC_SIZE);
1193         token = cols [MONO_METHODSPEC_METHOD];
1194         nindex = token >> MONO_METHODDEFORREF_BITS;
1195
1196         if (!mono_verifier_verify_methodspec_signature (image, cols [MONO_METHODSPEC_SIGNATURE], NULL)) {
1197                 mono_error_set_bad_image (error, image, "Bad method signals signature 0x%08x", idx);
1198                 return NULL;
1199         }
1200
1201         ptr = mono_metadata_blob_heap (image, cols [MONO_METHODSPEC_SIGNATURE]);
1202
1203         mono_metadata_decode_value (ptr, &ptr);
1204         ptr++;
1205         param_count = mono_metadata_decode_value (ptr, &ptr);
1206
1207         inst = mono_metadata_parse_generic_inst (image, NULL, param_count, ptr, &ptr, error);
1208         if (!inst)
1209                 return NULL;
1210
1211         if (context && inst->is_open) {
1212                 inst = mono_metadata_inflate_generic_inst (inst, context, error);
1213                 if (!mono_error_ok (error))
1214                         return NULL;
1215         }
1216
1217         if ((token & MONO_METHODDEFORREF_MASK) == MONO_METHODDEFORREF_METHODDEF) {
1218                 method = mono_get_method_checked (image, MONO_TOKEN_METHOD_DEF | nindex, NULL, context, error);
1219                 if (!method)
1220                         return NULL;
1221         } else {
1222                 method = method_from_memberref (image, nindex, context, NULL, error);
1223         }
1224
1225         if (!method)
1226                 return NULL;
1227
1228         klass = method->klass;
1229
1230         if (klass->generic_class) {
1231                 g_assert (method->is_inflated);
1232                 method = ((MonoMethodInflated *) method)->declaring;
1233         }
1234
1235         new_context.class_inst = klass->generic_class ? klass->generic_class->context.class_inst : NULL;
1236         new_context.method_inst = inst;
1237
1238         method = mono_class_inflate_generic_method_full_checked (method, klass, &new_context, error);
1239         mono_loader_assert_no_error ();
1240         return method;
1241 }
1242
1243 struct _MonoDllMap {
1244         char *dll;
1245         char *target;
1246         char *func;
1247         char *target_func;
1248         MonoDllMap *next;
1249 };
1250
1251 static MonoDllMap *global_dll_map;
1252
1253 static int 
1254 mono_dllmap_lookup_list (MonoDllMap *dll_map, const char *dll, const char* func, const char **rdll, const char **rfunc) {
1255         int found = 0;
1256
1257         *rdll = dll;
1258
1259         if (!dll_map)
1260                 return 0;
1261
1262         global_loader_data_lock ();
1263
1264         /* 
1265          * we use the first entry we find that matches, since entries from
1266          * the config file are prepended to the list and we document that the
1267          * later entries win.
1268          */
1269         for (; dll_map; dll_map = dll_map->next) {
1270                 if (dll_map->dll [0] == 'i' && dll_map->dll [1] == ':') {
1271                         if (g_ascii_strcasecmp (dll_map->dll + 2, dll))
1272                                 continue;
1273                 } else if (strcmp (dll_map->dll, dll)) {
1274                         continue;
1275                 }
1276                 if (!found && dll_map->target) {
1277                         *rdll = dll_map->target;
1278                         found = 1;
1279                         /* we don't quit here, because we could find a full
1280                          * entry that matches also function and that has priority.
1281                          */
1282                 }
1283                 if (dll_map->func && strcmp (dll_map->func, func) == 0) {
1284                         *rfunc = dll_map->target_func;
1285                         break;
1286                 }
1287         }
1288
1289         global_loader_data_unlock ();
1290         return found;
1291 }
1292
1293 static int 
1294 mono_dllmap_lookup (MonoImage *assembly, const char *dll, const char* func, const char **rdll, const char **rfunc)
1295 {
1296         int res;
1297         if (assembly && assembly->dll_map) {
1298                 res = mono_dllmap_lookup_list (assembly->dll_map, dll, func, rdll, rfunc);
1299                 if (res)
1300                         return res;
1301         }
1302         return mono_dllmap_lookup_list (global_dll_map, dll, func, rdll, rfunc);
1303 }
1304
1305 /**
1306  * mono_dllmap_insert:
1307  * @assembly: if NULL, this is a global mapping, otherwise the remapping of the dynamic library will only apply to the specified assembly
1308  * @dll: The name of the external library, as it would be found in the DllImport declaration.  If prefixed with 'i:' the matching of the library name is done without case sensitivity
1309  * @func: if not null, the mapping will only applied to the named function (the value of EntryPoint)
1310  * @tdll: The name of the library to map the specified @dll if it matches.
1311  * @tfunc: if func is not NULL, the name of the function that replaces the invocation
1312  *
1313  * LOCKING: Acquires the loader lock.
1314  *
1315  * This function is used to programatically add DllImport remapping in either
1316  * a specific assembly, or as a global remapping.   This is done by remapping
1317  * references in a DllImport attribute from the @dll library name into the @tdll
1318  * name.    If the @dll name contains the prefix "i:", the comparison of the 
1319  * library name is done without case sensitivity.
1320  *
1321  * If you pass @func, this is the name of the EntryPoint in a DllImport if specified
1322  * or the name of the function as determined by DllImport.    If you pass @func, you
1323  * must also pass @tfunc which is the name of the target function to invoke on a match.
1324  *
1325  * Example:
1326  * mono_dllmap_insert (NULL, "i:libdemo.dll", NULL, relocated_demo_path, NULL);
1327  *
1328  * The above will remap DllImport statments for "libdemo.dll" and "LIBDEMO.DLL" to
1329  * the contents of relocated_demo_path for all assemblies in the Mono process.
1330  *
1331  * NOTE: This can be called before the runtime is initialized, for example from
1332  * mono_config_parse ().
1333  */
1334 void
1335 mono_dllmap_insert (MonoImage *assembly, const char *dll, const char *func, const char *tdll, const char *tfunc)
1336 {
1337         MonoDllMap *entry;
1338
1339         mono_loader_init ();
1340
1341         if (!assembly) {
1342                 entry = (MonoDllMap *)g_malloc0 (sizeof (MonoDllMap));
1343                 entry->dll = dll? g_strdup (dll): NULL;
1344                 entry->target = tdll? g_strdup (tdll): NULL;
1345                 entry->func = func? g_strdup (func): NULL;
1346                 entry->target_func = tfunc? g_strdup (tfunc): NULL;
1347
1348                 global_loader_data_lock ();
1349                 entry->next = global_dll_map;
1350                 global_dll_map = entry;
1351                 global_loader_data_unlock ();
1352         } else {
1353                 entry = (MonoDllMap *)mono_image_alloc0 (assembly, sizeof (MonoDllMap));
1354                 entry->dll = dll? mono_image_strdup (assembly, dll): NULL;
1355                 entry->target = tdll? mono_image_strdup (assembly, tdll): NULL;
1356                 entry->func = func? mono_image_strdup (assembly, func): NULL;
1357                 entry->target_func = tfunc? mono_image_strdup (assembly, tfunc): NULL;
1358
1359                 mono_image_lock (assembly);
1360                 entry->next = assembly->dll_map;
1361                 assembly->dll_map = entry;
1362                 mono_image_unlock (assembly);
1363         }
1364 }
1365
1366 static void
1367 free_dllmap (MonoDllMap *map)
1368 {
1369         while (map) {
1370                 MonoDllMap *next = map->next;
1371
1372                 g_free (map->dll);
1373                 g_free (map->target);
1374                 g_free (map->func);
1375                 g_free (map->target_func);
1376                 g_free (map);
1377                 map = next;
1378         }
1379 }
1380
1381 static void
1382 dllmap_cleanup (void)
1383 {
1384         free_dllmap (global_dll_map);
1385         global_dll_map = NULL;
1386 }
1387
1388 static GHashTable *global_module_map;
1389
1390 static MonoDl*
1391 cached_module_load (const char *name, int flags, char **err)
1392 {
1393         MonoDl *res;
1394
1395         if (err)
1396                 *err = NULL;
1397         global_loader_data_lock ();
1398         if (!global_module_map)
1399                 global_module_map = g_hash_table_new (g_str_hash, g_str_equal);
1400         res = (MonoDl *)g_hash_table_lookup (global_module_map, name);
1401         if (res) {
1402                 global_loader_data_unlock ();
1403                 return res;
1404         }
1405         res = mono_dl_open (name, flags, err);
1406         if (res)
1407                 g_hash_table_insert (global_module_map, g_strdup (name), res);
1408         global_loader_data_unlock ();
1409         return res;
1410 }
1411
1412 static MonoDl *internal_module;
1413
1414 static gboolean
1415 is_absolute_path (const char *path)
1416 {
1417 #ifdef PLATFORM_MACOSX
1418         if (!strncmp (path, "@executable_path/", 17) || !strncmp (path, "@loader_path/", 13) ||
1419             !strncmp (path, "@rpath/", 7))
1420             return TRUE;
1421 #endif
1422         return g_path_is_absolute (path);
1423 }
1424
1425 gpointer
1426 mono_lookup_pinvoke_call (MonoMethod *method, const char **exc_class, const char **exc_arg)
1427 {
1428         MonoImage *image = method->klass->image;
1429         MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)method;
1430         MonoTableInfo *tables = image->tables;
1431         MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
1432         MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
1433         guint32 im_cols [MONO_IMPLMAP_SIZE];
1434         guint32 scope_token;
1435         const char *import = NULL;
1436         const char *orig_scope;
1437         const char *new_scope;
1438         char *error_msg;
1439         char *full_name, *file_name, *found_name = NULL;
1440         int i,j;
1441         MonoDl *module = NULL;
1442         gboolean cached = FALSE;
1443
1444         g_assert (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL);
1445
1446         if (exc_class) {
1447                 *exc_class = NULL;
1448                 *exc_arg = NULL;
1449         }
1450
1451         if (piinfo->addr)
1452                 return piinfo->addr;
1453
1454         if (image_is_dynamic (method->klass->image)) {
1455                 MonoReflectionMethodAux *method_aux = 
1456                         (MonoReflectionMethodAux *)g_hash_table_lookup (
1457                                 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
1458                 if (!method_aux)
1459                         return NULL;
1460
1461                 import = method_aux->dllentry;
1462                 orig_scope = method_aux->dll;
1463         }
1464         else {
1465                 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
1466                         return NULL;
1467
1468                 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
1469
1470                 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
1471                         return NULL;
1472
1473                 piinfo->piflags = im_cols [MONO_IMPLMAP_FLAGS];
1474                 import = mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]);
1475                 scope_token = mono_metadata_decode_row_col (mr, im_cols [MONO_IMPLMAP_SCOPE] - 1, MONO_MODULEREF_NAME);
1476                 orig_scope = mono_metadata_string_heap (image, scope_token);
1477         }
1478
1479         mono_dllmap_lookup (image, orig_scope, import, &new_scope, &import);
1480
1481         if (!module) {
1482                 mono_image_lock (image);
1483                 if (!image->pinvoke_scopes) {
1484                         image->pinvoke_scopes = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
1485                         image->pinvoke_scope_filenames = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);
1486                 }
1487                 module = (MonoDl *)g_hash_table_lookup (image->pinvoke_scopes, new_scope);
1488                 found_name = (char *)g_hash_table_lookup (image->pinvoke_scope_filenames, new_scope);
1489                 mono_image_unlock (image);
1490                 if (module)
1491                         cached = TRUE;
1492                 if (found_name)
1493                         found_name = g_strdup (found_name);
1494         }
1495
1496         if (!module) {
1497                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1498                                         "DllImport attempting to load: '%s'.", new_scope);
1499
1500                 /* we allow a special name to dlopen from the running process namespace */
1501                 if (strcmp (new_scope, "__Internal") == 0){
1502                         if (internal_module == NULL)
1503                                 internal_module = mono_dl_open (NULL, MONO_DL_LAZY, &error_msg);
1504                         module = internal_module;
1505                 }
1506         }
1507
1508         /*
1509          * Try loading the module using a variety of names
1510          */
1511         for (i = 0; i < 5; ++i) {
1512                 char *base_name = NULL, *dir_name = NULL;
1513                 gboolean is_absolute = is_absolute_path (new_scope);
1514                 
1515                 switch (i) {
1516                 case 0:
1517                         /* Try the original name */
1518                         file_name = g_strdup (new_scope);
1519                         break;
1520                 case 1:
1521                         /* Try trimming the .dll extension */
1522                         if (strstr (new_scope, ".dll") == (new_scope + strlen (new_scope) - 4)) {
1523                                 file_name = g_strdup (new_scope);
1524                                 file_name [strlen (new_scope) - 4] = '\0';
1525                         }
1526                         else
1527                                 continue;
1528                         break;
1529                 case 2:
1530                         if (is_absolute) {
1531                                 dir_name = g_path_get_dirname (new_scope);
1532                                 base_name = g_path_get_basename (new_scope);
1533                                 if (strstr (base_name, "lib") != base_name) {
1534                                         char *tmp = g_strdup_printf ("lib%s", base_name);       
1535                                         g_free (base_name);
1536                                         base_name = tmp;
1537                                         file_name = g_strdup_printf ("%s%s%s", dir_name, G_DIR_SEPARATOR_S, base_name);
1538                                         break;
1539                                 }
1540                         } else if (strstr (new_scope, "lib") != new_scope) {
1541                                 file_name = g_strdup_printf ("lib%s", new_scope);
1542                                 break;
1543                         }
1544                         continue;
1545                 case 3:
1546                         if (!is_absolute && mono_dl_get_system_dir ()) {
1547                                 dir_name = (char*)mono_dl_get_system_dir ();
1548                                 file_name = g_path_get_basename (new_scope);
1549                                 base_name = NULL;
1550                         } else
1551                                 continue;
1552                         break;
1553                 default:
1554 #ifndef TARGET_WIN32
1555                         if (!g_ascii_strcasecmp ("user32.dll", new_scope) ||
1556                             !g_ascii_strcasecmp ("kernel32.dll", new_scope) ||
1557                             !g_ascii_strcasecmp ("user32", new_scope) ||
1558                             !g_ascii_strcasecmp ("kernel", new_scope)) {
1559                                 file_name = g_strdup ("libMonoSupportW.so");
1560                         } else
1561 #endif
1562                                     continue;
1563 #ifndef TARGET_WIN32
1564                         break;
1565 #endif
1566                 }
1567                 
1568                 if (is_absolute) {
1569                         if (!dir_name)
1570                                 dir_name = g_path_get_dirname (file_name);
1571                         if (!base_name)
1572                                 base_name = g_path_get_basename (file_name);
1573                 }
1574                 
1575                 if (!module && is_absolute) {
1576                         module = cached_module_load (file_name, MONO_DL_LAZY, &error_msg);
1577                         if (!module) {
1578                                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1579                                                 "DllImport error loading library '%s': '%s'.",
1580                                                         file_name, error_msg);
1581                                 g_free (error_msg);
1582                         } else {
1583                                 found_name = g_strdup (file_name);
1584                         }
1585                 }
1586
1587                 if (!module && !is_absolute) {
1588                         void *iter;
1589                         char *mdirname;
1590
1591                         for (j = 0; j < 3; ++j) {
1592                                 iter = NULL;
1593                                 mdirname = NULL;
1594                                 switch (j) {
1595                                         case 0:
1596                                                 mdirname = g_path_get_dirname (image->name);
1597                                                 break;
1598                                         case 1: /* @executable_path@/../lib */
1599                                         {
1600                                                 char buf [4096];
1601                                                 int binl;
1602                                                 binl = mono_dl_get_executable_path (buf, sizeof (buf));
1603                                                 if (binl != -1) {
1604                                                         char *base, *newbase;
1605                                                         char *resolvedname;
1606                                                         buf [binl] = 0;
1607                                                         resolvedname = mono_path_resolve_symlinks (buf);
1608
1609                                                         base = g_path_get_dirname (resolvedname);
1610                                                         newbase = g_path_get_dirname(base);
1611                                                         mdirname = g_strdup_printf ("%s/lib", newbase);
1612
1613                                                         g_free (resolvedname);
1614                                                         g_free (base);
1615                                                         g_free (newbase);
1616                                                 }
1617                                                 break;
1618                                         }
1619 #ifdef __MACH__
1620                                         case 2: /* @executable_path@/../Libraries */
1621                                         {
1622                                                 char buf [4096];
1623                                                 int binl;
1624                                                 binl = mono_dl_get_executable_path (buf, sizeof (buf));
1625                                                 if (binl != -1) {
1626                                                         char *base, *newbase;
1627                                                         char *resolvedname;
1628                                                         buf [binl] = 0;
1629                                                         resolvedname = mono_path_resolve_symlinks (buf);
1630
1631                                                         base = g_path_get_dirname (resolvedname);
1632                                                         newbase = g_path_get_dirname(base);
1633                                                         mdirname = g_strdup_printf ("%s/Libraries", newbase);
1634
1635                                                         g_free (resolvedname);
1636                                                         g_free (base);
1637                                                         g_free (newbase);
1638                                                 }
1639                                                 break;
1640                                         }
1641 #endif
1642                                 }
1643
1644                                 if (!mdirname)
1645                                         continue;
1646
1647                                 while ((full_name = mono_dl_build_path (mdirname, file_name, &iter))) {
1648                                         module = cached_module_load (full_name, MONO_DL_LAZY, &error_msg);
1649                                         if (!module) {
1650                                                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1651                                                         "DllImport error loading library '%s': '%s'.",
1652                                                                         full_name, error_msg);
1653                                                 g_free (error_msg);
1654                                         } else {
1655                                                 found_name = g_strdup (full_name);
1656                                         }
1657                                         g_free (full_name);
1658                                         if (module)
1659                                                 break;
1660
1661                                 }
1662                                 g_free (mdirname);
1663                                 if (module)
1664                                         break;
1665                         }
1666
1667                 }
1668
1669                 if (!module) {
1670                         void *iter = NULL;
1671                         char *file_or_base = is_absolute ? base_name : file_name;
1672                         while ((full_name = mono_dl_build_path (dir_name, file_or_base, &iter))) {
1673                                 module = cached_module_load (full_name, MONO_DL_LAZY, &error_msg);
1674                                 if (!module) {
1675                                         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1676                                                         "DllImport error loading library '%s': '%s'.",
1677                                                                 full_name, error_msg);
1678                                         g_free (error_msg);
1679                                 } else {
1680                                         found_name = g_strdup (full_name);
1681                                 }
1682                                 g_free (full_name);
1683                                 if (module)
1684                                         break;
1685                         }
1686                 }
1687
1688                 if (!module) {
1689                         module = cached_module_load (file_name, MONO_DL_LAZY, &error_msg);
1690                         if (!module) {
1691                                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1692                                                 "DllImport error loading library '%s': '%s'.",
1693                                                         file_name, error_msg);
1694                         } else {
1695                                 found_name = g_strdup (file_name);
1696                         }
1697                 }
1698
1699                 g_free (file_name);
1700                 if (is_absolute) {
1701                         g_free (base_name);
1702                         g_free (dir_name);
1703                 }
1704
1705                 if (module)
1706                         break;
1707         }
1708
1709         if (!module) {
1710                 mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_DLLIMPORT,
1711                                 "DllImport unable to load library '%s'.",
1712                                 error_msg);
1713                 g_free (error_msg);
1714
1715                 if (exc_class) {
1716                         *exc_class = "DllNotFoundException";
1717                         *exc_arg = new_scope;
1718                 }
1719                 return NULL;
1720         }
1721
1722         if (!cached) {
1723                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1724                                         "DllImport loaded library '%s'.", found_name);
1725                 mono_image_lock (image);
1726                 if (!g_hash_table_lookup (image->pinvoke_scopes, new_scope)) {
1727                         g_hash_table_insert (image->pinvoke_scopes, g_strdup (new_scope), module);
1728                         g_hash_table_insert (image->pinvoke_scope_filenames, g_strdup (new_scope), g_strdup (found_name));
1729                 }
1730                 mono_image_unlock (image);
1731         }
1732
1733         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1734                                 "DllImport searching in: '%s' ('%s').", new_scope, found_name);
1735         g_free (found_name);
1736
1737 #ifdef TARGET_WIN32
1738         if (import && import [0] == '#' && isdigit (import [1])) {
1739                 char *end;
1740                 long id;
1741
1742                 id = strtol (import + 1, &end, 10);
1743                 if (id > 0 && *end == '\0')
1744                         import++;
1745         }
1746 #endif
1747         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1748                                 "Searching for '%s'.", import);
1749
1750         if (piinfo->piflags & PINVOKE_ATTRIBUTE_NO_MANGLE) {
1751                 error_msg = mono_dl_symbol (module, import, &piinfo->addr); 
1752         } else {
1753                 char *mangled_name = NULL, *mangled_name2 = NULL;
1754                 int mangle_charset;
1755                 int mangle_stdcall;
1756                 int mangle_param_count;
1757 #ifdef TARGET_WIN32
1758                 int param_count;
1759 #endif
1760
1761                 /*
1762                  * Search using a variety of mangled names
1763                  */
1764                 for (mangle_charset = 0; mangle_charset <= 1; mangle_charset ++) {
1765                         for (mangle_stdcall = 0; mangle_stdcall <= 1; mangle_stdcall ++) {
1766                                 gboolean need_param_count = FALSE;
1767 #ifdef TARGET_WIN32
1768                                 if (mangle_stdcall > 0)
1769                                         need_param_count = TRUE;
1770 #endif
1771                                 for (mangle_param_count = 0; mangle_param_count <= (need_param_count ? 256 : 0); mangle_param_count += 4) {
1772
1773                                         if (piinfo->addr)
1774                                                 continue;
1775
1776                                         mangled_name = (char*)import;
1777                                         switch (piinfo->piflags & PINVOKE_ATTRIBUTE_CHAR_SET_MASK) {
1778                                         case PINVOKE_ATTRIBUTE_CHAR_SET_UNICODE:
1779                                                 /* Try the mangled name first */
1780                                                 if (mangle_charset == 0)
1781                                                         mangled_name = g_strconcat (import, "W", NULL);
1782                                                 break;
1783                                         case PINVOKE_ATTRIBUTE_CHAR_SET_AUTO:
1784 #ifdef TARGET_WIN32
1785                                                 if (mangle_charset == 0)
1786                                                         mangled_name = g_strconcat (import, "W", NULL);
1787 #else
1788                                                 /* Try the mangled name last */
1789                                                 if (mangle_charset == 1)
1790                                                         mangled_name = g_strconcat (import, "A", NULL);
1791 #endif
1792                                                 break;
1793                                         case PINVOKE_ATTRIBUTE_CHAR_SET_ANSI:
1794                                         default:
1795                                                 /* Try the mangled name last */
1796                                                 if (mangle_charset == 1)
1797                                                         mangled_name = g_strconcat (import, "A", NULL);
1798                                                 break;
1799                                         }
1800
1801 #ifdef TARGET_WIN32
1802                                         if (mangle_param_count == 0)
1803                                                 param_count = mono_method_signature (method)->param_count * sizeof (gpointer);
1804                                         else
1805                                                 /* Try brute force, since it would be very hard to compute the stack usage correctly */
1806                                                 param_count = mangle_param_count;
1807
1808                                         /* Try the stdcall mangled name */
1809                                         /* 
1810                                          * gcc under windows creates mangled names without the underscore, but MS.NET
1811                                          * doesn't support it, so we doesn't support it either.
1812                                          */
1813                                         if (mangle_stdcall == 1)
1814                                                 mangled_name2 = g_strdup_printf ("_%s@%d", mangled_name, param_count);
1815                                         else
1816                                                 mangled_name2 = mangled_name;
1817 #else
1818                                         mangled_name2 = mangled_name;
1819 #endif
1820
1821                                         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1822                                                                 "Probing '%s'.", mangled_name2);
1823
1824                                         error_msg = mono_dl_symbol (module, mangled_name2, &piinfo->addr);
1825
1826                                         if (piinfo->addr)
1827                                                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1828                                                                         "Found as '%s'.", mangled_name2);
1829                                         else
1830                                                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1831                                                                         "Could not find '%s' due to '%s'.", mangled_name2, error_msg);
1832
1833                                         g_free (error_msg);
1834                                         error_msg = NULL;
1835
1836                                         if (mangled_name != mangled_name2)
1837                                                 g_free (mangled_name2);
1838                                         if (mangled_name != import)
1839                                                 g_free (mangled_name);
1840                                 }
1841                         }
1842                 }
1843         }
1844
1845         if (!piinfo->addr) {
1846                 g_free (error_msg);
1847                 if (exc_class) {
1848                         *exc_class = "EntryPointNotFoundException";
1849                         *exc_arg = import;
1850                 }
1851                 return NULL;
1852         }
1853         return piinfo->addr;
1854 }
1855
1856 /*
1857  * LOCKING: assumes the loader lock to be taken.
1858  */
1859 static MonoMethod *
1860 mono_get_method_from_token (MonoImage *image, guint32 token, MonoClass *klass,
1861                             MonoGenericContext *context, gboolean *used_context, MonoError *error)
1862 {
1863         MonoMethod *result;
1864         int table = mono_metadata_token_table (token);
1865         int idx = mono_metadata_token_index (token);
1866         MonoTableInfo *tables = image->tables;
1867         MonoGenericContainer *generic_container = NULL, *container = NULL;
1868         const char *sig = NULL;
1869         guint32 cols [MONO_TYPEDEF_SIZE];
1870
1871         mono_error_init (error);
1872
1873         if (image_is_dynamic (image)) {
1874                 MonoClass *handle_class;
1875
1876                 result = (MonoMethod *)mono_lookup_dynamic_token_class (image, token, TRUE, &handle_class, context);
1877                 mono_loader_assert_no_error ();
1878
1879                 // This checks the memberref type as well
1880                 if (result && handle_class != mono_defaults.methodhandle_class) {
1881                         mono_error_set_bad_image (error, image, "Bad method token 0x%08x on dynamic image", token);
1882                         return NULL;
1883                 }
1884                 return result;
1885         }
1886
1887         if (table != MONO_TABLE_METHOD) {
1888                 if (table == MONO_TABLE_METHODSPEC) {
1889                         if (used_context) *used_context = TRUE;
1890                         return method_from_methodspec (image, context, idx, error);
1891                 }
1892                 if (table != MONO_TABLE_MEMBERREF) {
1893                         mono_error_set_bad_image (error, image, "Bad method token 0x%08x.", token);
1894                         return NULL;
1895                 }
1896                 return method_from_memberref (image, idx, context, used_context, error);
1897         }
1898
1899         if (used_context) *used_context = FALSE;
1900
1901         if (idx > image->tables [MONO_TABLE_METHOD].rows) {
1902                 mono_error_set_bad_image (error, image, "Bad method token 0x%08x (out of bounds).", token);
1903                 return NULL;
1904         }
1905
1906         if (!klass) {
1907                 guint32 type = mono_metadata_typedef_from_method (image, token);
1908                 if (!type) {
1909                         mono_error_set_bad_image (error, image, "Bad method token 0x%08x (could not find corresponding typedef).", token);
1910                         return NULL;
1911                 }
1912                 klass = mono_class_get_checked (image, MONO_TOKEN_TYPE_DEF | type, error);
1913                 if (klass == NULL)
1914                         return NULL;
1915         }
1916
1917         mono_metadata_decode_row (&image->tables [MONO_TABLE_METHOD], idx - 1, cols, 6);
1918
1919         if ((cols [2] & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
1920             (cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
1921                 result = (MonoMethod *)mono_image_alloc0 (image, sizeof (MonoMethodPInvoke));
1922         } else {
1923                 result = (MonoMethod *)mono_image_alloc0 (image, sizeof (MonoMethod));
1924                 methods_size += sizeof (MonoMethod);
1925         }
1926
1927         mono_stats.method_count ++;
1928
1929         result->slot = -1;
1930         result->klass = klass;
1931         result->flags = cols [2];
1932         result->iflags = cols [1];
1933         result->token = token;
1934         result->name = mono_metadata_string_heap (image, cols [3]);
1935
1936         if (!sig) /* already taken from the methodref */
1937                 sig = mono_metadata_blob_heap (image, cols [4]);
1938         /* size = */ mono_metadata_decode_blob_size (sig, &sig);
1939
1940         container = klass->generic_container;
1941
1942         /* 
1943          * load_generic_params does a binary search so only call it if the method 
1944          * is generic.
1945          */
1946         if (*sig & 0x10) {
1947                 generic_container = mono_metadata_load_generic_params (image, token, container);
1948                 mono_loader_assert_no_error (); /* FIXME don't swallow this error. */
1949         }
1950         if (generic_container) {
1951                 result->is_generic = TRUE;
1952                 generic_container->owner.method = result;
1953                 generic_container->is_anonymous = FALSE; // Method is now known, container is no longer anonymous
1954                 /*FIXME put this before the image alloc*/
1955                 if (!mono_metadata_load_generic_param_constraints_checked (image, token, generic_container, error))
1956                         return NULL;
1957
1958                 container = generic_container;
1959         }
1960
1961         if (cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
1962                 if (result->klass == mono_defaults.string_class && !strcmp (result->name, ".ctor"))
1963                         result->string_ctor = 1;
1964         } else if (cols [2] & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
1965                 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)result;
1966
1967 #ifdef TARGET_WIN32
1968                 /* IJW is P/Invoke with a predefined function pointer. */
1969                 if (image->is_module_handle && (cols [1] & METHOD_IMPL_ATTRIBUTE_NATIVE)) {
1970                         piinfo->addr = mono_image_rva_map (image, cols [0]);
1971                         g_assert (piinfo->addr);
1972                 }
1973 #endif
1974                 piinfo->implmap_idx = mono_metadata_implmap_from_method (image, idx - 1);
1975                 /* Native methods can have no map. */
1976                 if (piinfo->implmap_idx)
1977                         piinfo->piflags = mono_metadata_decode_row_col (&tables [MONO_TABLE_IMPLMAP], piinfo->implmap_idx - 1, MONO_IMPLMAP_FLAGS);
1978         }
1979
1980         if (generic_container)
1981                 mono_method_set_generic_container (result, generic_container);
1982
1983         mono_loader_assert_no_error ();
1984         return result;
1985 }
1986
1987 MonoMethod *
1988 mono_get_method (MonoImage *image, guint32 token, MonoClass *klass)
1989 {
1990         MonoError error;
1991         MonoMethod *result = mono_get_method_checked (image, token, klass, NULL, &error);
1992         mono_error_cleanup (&error);
1993         return result;
1994 }
1995
1996 MonoMethod *
1997 mono_get_method_full (MonoImage *image, guint32 token, MonoClass *klass,
1998                       MonoGenericContext *context)
1999 {
2000         MonoError error;
2001         MonoMethod *result = mono_get_method_checked (image, token, klass, context, &error);
2002         mono_error_cleanup (&error);
2003         return result;
2004 }
2005
2006 MonoMethod *
2007 mono_get_method_checked (MonoImage *image, guint32 token, MonoClass *klass, MonoGenericContext *context, MonoError *error)
2008 {
2009         MonoMethod *result = NULL;
2010         gboolean used_context = FALSE;
2011
2012         /* We do everything inside the lock to prevent creation races */
2013
2014         mono_error_init (error);
2015
2016         mono_image_lock (image);
2017
2018         if (mono_metadata_token_table (token) == MONO_TABLE_METHOD) {
2019                 if (!image->method_cache)
2020                         image->method_cache = g_hash_table_new (NULL, NULL);
2021                 result = (MonoMethod *)g_hash_table_lookup (image->method_cache, GINT_TO_POINTER (mono_metadata_token_index (token)));
2022         } else if (!image_is_dynamic (image)) {
2023                 if (!image->methodref_cache)
2024                         image->methodref_cache = g_hash_table_new (NULL, NULL);
2025                 result = (MonoMethod *)g_hash_table_lookup (image->methodref_cache, GINT_TO_POINTER (token));
2026         }
2027         mono_image_unlock (image);
2028
2029         if (result)
2030                 return result;
2031
2032
2033         result = mono_get_method_from_token (image, token, klass, context, &used_context, error);
2034         if (!result)
2035                 return NULL;
2036
2037         mono_image_lock (image);
2038         if (!used_context && !result->is_inflated) {
2039                 MonoMethod *result2 = NULL;
2040
2041                 if (mono_metadata_token_table (token) == MONO_TABLE_METHOD)
2042                         result2 = (MonoMethod *)g_hash_table_lookup (image->method_cache, GINT_TO_POINTER (mono_metadata_token_index (token)));
2043                 else if (!image_is_dynamic (image))
2044                         result2 = (MonoMethod *)g_hash_table_lookup (image->methodref_cache, GINT_TO_POINTER (token));
2045
2046                 if (result2) {
2047                         mono_image_unlock (image);
2048                         return result2;
2049                 }
2050
2051                 if (mono_metadata_token_table (token) == MONO_TABLE_METHOD)
2052                         g_hash_table_insert (image->method_cache, GINT_TO_POINTER (mono_metadata_token_index (token)), result);
2053                 else if (!image_is_dynamic (image))
2054                         g_hash_table_insert (image->methodref_cache, GINT_TO_POINTER (token), result);
2055         }
2056
2057         mono_image_unlock (image);
2058
2059         return result;
2060 }
2061
2062 static MonoMethod *
2063 get_method_constrained (MonoImage *image, MonoMethod *method, MonoClass *constrained_class, MonoGenericContext *context, MonoError *error)
2064 {
2065         MonoMethod *result;
2066         MonoClass *ic = NULL;
2067         MonoGenericContext *method_context = NULL;
2068         MonoMethodSignature *sig, *original_sig;
2069
2070         mono_error_init (error);
2071
2072         mono_class_init (constrained_class);
2073         original_sig = sig = mono_method_signature_checked (method, error);
2074         if (sig == NULL) {
2075                 return NULL;
2076         }
2077
2078         if (method->is_inflated && sig->generic_param_count) {
2079                 MonoMethodInflated *imethod = (MonoMethodInflated *) method;
2080                 sig = mono_method_signature_checked (imethod->declaring, error); /*We assume that if the inflated method signature is valid, the declaring method is too*/
2081                 if (!sig)
2082                         return NULL;
2083                 method_context = mono_method_get_context (method);
2084
2085                 original_sig = sig;
2086                 /*
2087                  * We must inflate the signature with the class instantiation to work on
2088                  * cases where a class inherit from a generic type and the override replaces
2089                  * any type argument which a concrete type. See #325283.
2090                  */
2091                 if (method_context->class_inst) {
2092                         MonoGenericContext ctx;
2093                         ctx.method_inst = NULL;
2094                         ctx.class_inst = method_context->class_inst;
2095                         /*Fixme, property propagate this error*/
2096                         sig = inflate_generic_signature_checked (method->klass->image, sig, &ctx, error);
2097                         if (!sig)
2098                                 return NULL;
2099                 }
2100         }
2101
2102         if ((constrained_class != method->klass) && (MONO_CLASS_IS_INTERFACE (method->klass)))
2103                 ic = method->klass;
2104
2105         result = find_method (constrained_class, ic, method->name, sig, constrained_class, error);
2106         if (sig != original_sig)
2107                 mono_metadata_free_inflated_signature (sig);
2108
2109         if (!result)
2110                 return NULL;
2111
2112         if (method_context) {
2113                 result = mono_class_inflate_generic_method_checked (result, method_context, error);
2114                 if (!result)
2115                         return NULL;
2116         }
2117
2118         return result;
2119 }
2120
2121 MonoMethod *
2122 mono_get_method_constrained_with_method (MonoImage *image, MonoMethod *method, MonoClass *constrained_class,
2123                              MonoGenericContext *context, MonoError *error)
2124 {
2125         g_assert (method);
2126
2127         return get_method_constrained (image, method, constrained_class, context, error);
2128 }
2129
2130 /**
2131  * mono_get_method_constrained:
2132  *
2133  * This is used when JITing the `constrained.' opcode.
2134  *
2135  * This returns two values: the contrained method, which has been inflated
2136  * as the function return value;   And the original CIL-stream method as
2137  * declared in cil_method.  The later is used for verification.
2138  */
2139 MonoMethod *
2140 mono_get_method_constrained (MonoImage *image, guint32 token, MonoClass *constrained_class,
2141                              MonoGenericContext *context, MonoMethod **cil_method)
2142 {
2143         MonoError error;
2144         MonoMethod *result = mono_get_method_constrained_checked (image, token, constrained_class, context, cil_method, &error);
2145         mono_error_cleanup (&error);
2146         return result;
2147 }
2148
2149 MonoMethod *
2150 mono_get_method_constrained_checked (MonoImage *image, guint32 token, MonoClass *constrained_class, MonoGenericContext *context, MonoMethod **cil_method, MonoError *error)
2151 {
2152         mono_error_init (error);
2153
2154         *cil_method = mono_get_method_from_token (image, token, NULL, context, NULL, error);
2155         if (!*cil_method)
2156                 return NULL;
2157
2158         return get_method_constrained (image, *cil_method, constrained_class, context, error);
2159 }
2160
2161 void
2162 mono_free_method  (MonoMethod *method)
2163 {
2164         if (mono_profiler_get_events () & MONO_PROFILE_METHOD_EVENTS)
2165                 mono_profiler_method_free (method);
2166         
2167         /* FIXME: This hack will go away when the profiler will support freeing methods */
2168         if (mono_profiler_get_events () != MONO_PROFILE_NONE)
2169                 return;
2170         
2171         if (method->signature) {
2172                 /* 
2173                  * FIXME: This causes crashes because the types inside signatures and
2174                  * locals are shared.
2175                  */
2176                 /* mono_metadata_free_method_signature (method->signature); */
2177                 /* g_free (method->signature); */
2178         }
2179         
2180         if (method_is_dynamic (method)) {
2181                 MonoMethodWrapper *mw = (MonoMethodWrapper*)method;
2182                 int i;
2183
2184                 mono_marshal_free_dynamic_wrappers (method);
2185
2186                 mono_image_property_remove (method->klass->image, method);
2187
2188                 g_free ((char*)method->name);
2189                 if (mw->header) {
2190                         g_free ((char*)mw->header->code);
2191                         for (i = 0; i < mw->header->num_locals; ++i)
2192                                 g_free (mw->header->locals [i]);
2193                         g_free (mw->header->clauses);
2194                         g_free (mw->header);
2195                 }
2196                 g_free (mw->method_data);
2197                 g_free (method->signature);
2198                 g_free (method);
2199         }
2200 }
2201
2202 void
2203 mono_method_get_param_names (MonoMethod *method, const char **names)
2204 {
2205         int i, lastp;
2206         MonoClass *klass;
2207         MonoTableInfo *methodt;
2208         MonoTableInfo *paramt;
2209         MonoMethodSignature *signature;
2210         guint32 idx;
2211
2212         if (method->is_inflated)
2213                 method = ((MonoMethodInflated *) method)->declaring;
2214
2215         signature = mono_method_signature (method);
2216         /*FIXME this check is somewhat redundant since the caller usally will have to get the signature to figure out the
2217           number of arguments and allocate a properly sized array. */
2218         if (signature == NULL)
2219                 return;
2220
2221         if (!signature->param_count)
2222                 return;
2223
2224         for (i = 0; i < signature->param_count; ++i)
2225                 names [i] = "";
2226
2227         klass = method->klass;
2228         if (klass->rank)
2229                 return;
2230
2231         mono_class_init (klass);
2232
2233         if (image_is_dynamic (klass->image)) {
2234                 MonoReflectionMethodAux *method_aux = 
2235                         (MonoReflectionMethodAux *)g_hash_table_lookup (
2236                                 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
2237                 if (method_aux && method_aux->param_names) {
2238                         for (i = 0; i < mono_method_signature (method)->param_count; ++i)
2239                                 if (method_aux->param_names [i + 1])
2240                                         names [i] = method_aux->param_names [i + 1];
2241                 }
2242                 return;
2243         }
2244
2245         if (method->wrapper_type) {
2246                 char **pnames = NULL;
2247
2248                 mono_image_lock (klass->image);
2249                 if (klass->image->wrapper_param_names)
2250                         pnames = (char **)g_hash_table_lookup (klass->image->wrapper_param_names, method);
2251                 mono_image_unlock (klass->image);
2252
2253                 if (pnames) {
2254                         for (i = 0; i < signature->param_count; ++i)
2255                                 names [i] = pnames [i];
2256                 }
2257                 return;
2258         }
2259
2260         methodt = &klass->image->tables [MONO_TABLE_METHOD];
2261         paramt = &klass->image->tables [MONO_TABLE_PARAM];
2262         idx = mono_method_get_index (method);
2263         if (idx > 0) {
2264                 guint32 cols [MONO_PARAM_SIZE];
2265                 guint param_index;
2266
2267                 param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
2268
2269                 if (idx < methodt->rows)
2270                         lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
2271                 else
2272                         lastp = paramt->rows + 1;
2273                 for (i = param_index; i < lastp; ++i) {
2274                         mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
2275                         if (cols [MONO_PARAM_SEQUENCE] && cols [MONO_PARAM_SEQUENCE] <= signature->param_count) /* skip return param spec and bounds check*/
2276                                 names [cols [MONO_PARAM_SEQUENCE] - 1] = mono_metadata_string_heap (klass->image, cols [MONO_PARAM_NAME]);
2277                 }
2278         }
2279 }
2280
2281 guint32
2282 mono_method_get_param_token (MonoMethod *method, int index)
2283 {
2284         MonoClass *klass = method->klass;
2285         MonoTableInfo *methodt;
2286         guint32 idx;
2287
2288         mono_class_init (klass);
2289
2290         if (image_is_dynamic (klass->image))
2291                 g_assert_not_reached ();
2292
2293         methodt = &klass->image->tables [MONO_TABLE_METHOD];
2294         idx = mono_method_get_index (method);
2295         if (idx > 0) {
2296                 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
2297
2298                 if (index == -1)
2299                         /* Return value */
2300                         return mono_metadata_make_token (MONO_TABLE_PARAM, 0);
2301                 else
2302                         return mono_metadata_make_token (MONO_TABLE_PARAM, param_index + index);
2303         }
2304
2305         return 0;
2306 }
2307
2308 void
2309 mono_method_get_marshal_info (MonoMethod *method, MonoMarshalSpec **mspecs)
2310 {
2311         int i, lastp;
2312         MonoClass *klass = method->klass;
2313         MonoTableInfo *methodt;
2314         MonoTableInfo *paramt;
2315         MonoMethodSignature *signature;
2316         guint32 idx;
2317
2318         signature = mono_method_signature (method);
2319         g_assert (signature); /*FIXME there is no way to signal error from this function*/
2320
2321         for (i = 0; i < signature->param_count + 1; ++i)
2322                 mspecs [i] = NULL;
2323
2324         if (image_is_dynamic (method->klass->image)) {
2325                 MonoReflectionMethodAux *method_aux = 
2326                         (MonoReflectionMethodAux *)g_hash_table_lookup (
2327                                 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
2328                 if (method_aux && method_aux->param_marshall) {
2329                         MonoMarshalSpec **dyn_specs = method_aux->param_marshall;
2330                         for (i = 0; i < signature->param_count + 1; ++i)
2331                                 if (dyn_specs [i]) {
2332                                         mspecs [i] = g_new0 (MonoMarshalSpec, 1);
2333                                         memcpy (mspecs [i], dyn_specs [i], sizeof (MonoMarshalSpec));
2334                                         mspecs [i]->data.custom_data.custom_name = g_strdup (dyn_specs [i]->data.custom_data.custom_name);
2335                                         mspecs [i]->data.custom_data.cookie = g_strdup (dyn_specs [i]->data.custom_data.cookie);
2336                                 }
2337                 }
2338                 return;
2339         }
2340
2341         mono_class_init (klass);
2342
2343         methodt = &klass->image->tables [MONO_TABLE_METHOD];
2344         paramt = &klass->image->tables [MONO_TABLE_PARAM];
2345         idx = mono_method_get_index (method);
2346         if (idx > 0) {
2347                 guint32 cols [MONO_PARAM_SIZE];
2348                 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
2349
2350                 if (idx < methodt->rows)
2351                         lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
2352                 else
2353                         lastp = paramt->rows + 1;
2354
2355                 for (i = param_index; i < lastp; ++i) {
2356                         mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
2357
2358                         if (cols [MONO_PARAM_FLAGS] & PARAM_ATTRIBUTE_HAS_FIELD_MARSHAL && cols [MONO_PARAM_SEQUENCE] <= signature->param_count) {
2359                                 const char *tp;
2360                                 tp = mono_metadata_get_marshal_info (klass->image, i - 1, FALSE);
2361                                 g_assert (tp);
2362                                 mspecs [cols [MONO_PARAM_SEQUENCE]]= mono_metadata_parse_marshal_spec (klass->image, tp);
2363                         }
2364                 }
2365
2366                 return;
2367         }
2368 }
2369
2370 gboolean
2371 mono_method_has_marshal_info (MonoMethod *method)
2372 {
2373         int i, lastp;
2374         MonoClass *klass = method->klass;
2375         MonoTableInfo *methodt;
2376         MonoTableInfo *paramt;
2377         guint32 idx;
2378
2379         if (image_is_dynamic (method->klass->image)) {
2380                 MonoReflectionMethodAux *method_aux = 
2381                         (MonoReflectionMethodAux *)g_hash_table_lookup (
2382                                 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
2383                 MonoMarshalSpec **dyn_specs = method_aux->param_marshall;
2384                 if (dyn_specs) {
2385                         for (i = 0; i < mono_method_signature (method)->param_count + 1; ++i)
2386                                 if (dyn_specs [i])
2387                                         return TRUE;
2388                 }
2389                 return FALSE;
2390         }
2391
2392         mono_class_init (klass);
2393
2394         methodt = &klass->image->tables [MONO_TABLE_METHOD];
2395         paramt = &klass->image->tables [MONO_TABLE_PARAM];
2396         idx = mono_method_get_index (method);
2397         if (idx > 0) {
2398                 guint32 cols [MONO_PARAM_SIZE];
2399                 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
2400
2401                 if (idx + 1 < methodt->rows)
2402                         lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
2403                 else
2404                         lastp = paramt->rows + 1;
2405
2406                 for (i = param_index; i < lastp; ++i) {
2407                         mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
2408
2409                         if (cols [MONO_PARAM_FLAGS] & PARAM_ATTRIBUTE_HAS_FIELD_MARSHAL)
2410                                 return TRUE;
2411                 }
2412                 return FALSE;
2413         }
2414         return FALSE;
2415 }
2416
2417 gpointer
2418 mono_method_get_wrapper_data (MonoMethod *method, guint32 id)
2419 {
2420         void **data;
2421         g_assert (method != NULL);
2422         g_assert (method->wrapper_type != MONO_WRAPPER_NONE);
2423
2424         if (method->is_inflated)
2425                 method = ((MonoMethodInflated *) method)->declaring;
2426         data = (void **)((MonoMethodWrapper *)method)->method_data;
2427         g_assert (data != NULL);
2428         g_assert (id <= GPOINTER_TO_UINT (*data));
2429         return data [id];
2430 }
2431
2432 typedef struct {
2433         MonoStackWalk func;
2434         gpointer user_data;
2435 } StackWalkUserData;
2436
2437 static gboolean
2438 stack_walk_adapter (MonoStackFrameInfo *frame, MonoContext *ctx, gpointer data)
2439 {
2440         StackWalkUserData *d = (StackWalkUserData *)data;
2441
2442         switch (frame->type) {
2443         case FRAME_TYPE_DEBUGGER_INVOKE:
2444         case FRAME_TYPE_MANAGED_TO_NATIVE:
2445         case FRAME_TYPE_TRAMPOLINE:
2446                 return FALSE;
2447         case FRAME_TYPE_MANAGED:
2448                 g_assert (frame->ji);
2449                 return d->func (frame->actual_method, frame->native_offset, frame->il_offset, frame->managed, d->user_data);
2450                 break;
2451         default:
2452                 g_assert_not_reached ();
2453                 return FALSE;
2454         }
2455 }
2456
2457 void
2458 mono_stack_walk (MonoStackWalk func, gpointer user_data)
2459 {
2460         StackWalkUserData ud = { func, user_data };
2461         mono_get_eh_callbacks ()->mono_walk_stack_with_ctx (stack_walk_adapter, NULL, MONO_UNWIND_LOOKUP_ALL, &ud);
2462 }
2463
2464 void
2465 mono_stack_walk_no_il (MonoStackWalk func, gpointer user_data)
2466 {
2467         StackWalkUserData ud = { func, user_data };
2468         mono_get_eh_callbacks ()->mono_walk_stack_with_ctx (stack_walk_adapter, NULL, MONO_UNWIND_DEFAULT, &ud);
2469 }
2470
2471 typedef struct {
2472         MonoStackWalkAsyncSafe func;
2473         gpointer user_data;
2474 } AsyncStackWalkUserData;
2475
2476
2477 static gboolean
2478 async_stack_walk_adapter (MonoStackFrameInfo *frame, MonoContext *ctx, gpointer data)
2479 {
2480         AsyncStackWalkUserData *d = (AsyncStackWalkUserData *)data;
2481
2482         switch (frame->type) {
2483         case FRAME_TYPE_DEBUGGER_INVOKE:
2484         case FRAME_TYPE_MANAGED_TO_NATIVE:
2485         case FRAME_TYPE_TRAMPOLINE:
2486                 return FALSE;
2487         case FRAME_TYPE_MANAGED:
2488                 if (!frame->ji)
2489                         return FALSE;
2490                 if (frame->ji->async) {
2491                         return d->func (NULL, frame->domain, frame->ji->code_start, frame->native_offset, d->user_data);
2492                 } else {
2493                         return d->func (frame->actual_method, frame->domain, frame->ji->code_start, frame->native_offset, d->user_data);
2494                 }
2495                 break;
2496         default:
2497                 g_assert_not_reached ();
2498                 return FALSE;
2499         }
2500 }
2501
2502
2503 /*
2504  * mono_stack_walk_async_safe:
2505  *
2506  *   Async safe version callable from signal handlers.
2507  */
2508 void
2509 mono_stack_walk_async_safe (MonoStackWalkAsyncSafe func, void *initial_sig_context, void *user_data)
2510 {
2511         MonoContext ctx;
2512         AsyncStackWalkUserData ud = { func, user_data };
2513
2514         mono_sigctx_to_monoctx (initial_sig_context, &ctx);
2515         mono_get_eh_callbacks ()->mono_walk_stack_with_ctx (async_stack_walk_adapter, NULL, MONO_UNWIND_SIGNAL_SAFE, &ud);
2516 }
2517
2518 static gboolean
2519 last_managed (MonoMethod *m, gint no, gint ilo, gboolean managed, gpointer data)
2520 {
2521         MonoMethod **dest = (MonoMethod **)data;
2522         *dest = m;
2523         /*g_print ("In %s::%s [%d] [%d]\n", m->klass->name, m->name, no, ilo);*/
2524
2525         return managed;
2526 }
2527
2528 MonoMethod*
2529 mono_method_get_last_managed (void)
2530 {
2531         MonoMethod *m = NULL;
2532         mono_stack_walk_no_il (last_managed, &m);
2533         return m;
2534 }
2535
2536 static gboolean loader_lock_track_ownership = FALSE;
2537
2538 /**
2539  * mono_loader_lock:
2540  *
2541  * See docs/thread-safety.txt for the locking strategy.
2542  */
2543 void
2544 mono_loader_lock (void)
2545 {
2546         mono_locks_coop_acquire (&loader_mutex, LoaderLock);
2547         if (G_UNLIKELY (loader_lock_track_ownership)) {
2548                 mono_native_tls_set_value (loader_lock_nest_id, GUINT_TO_POINTER (GPOINTER_TO_UINT (mono_native_tls_get_value (loader_lock_nest_id)) + 1));
2549         }
2550 }
2551
2552 void
2553 mono_loader_unlock (void)
2554 {
2555         mono_locks_coop_release (&loader_mutex, LoaderLock);
2556         if (G_UNLIKELY (loader_lock_track_ownership)) {
2557                 mono_native_tls_set_value (loader_lock_nest_id, GUINT_TO_POINTER (GPOINTER_TO_UINT (mono_native_tls_get_value (loader_lock_nest_id)) - 1));
2558         }
2559 }
2560
2561 /*
2562  * mono_loader_lock_track_ownership:
2563  *
2564  *   Set whenever the runtime should track ownership of the loader lock. If set to TRUE,
2565  * the mono_loader_lock_is_owned_by_self () can be called to query whenever the current
2566  * thread owns the loader lock. 
2567  */
2568 void
2569 mono_loader_lock_track_ownership (gboolean track)
2570 {
2571         loader_lock_track_ownership = track;
2572 }
2573
2574 /*
2575  * mono_loader_lock_is_owned_by_self:
2576  *
2577  *   Return whenever the current thread owns the loader lock.
2578  * This is useful to avoid blocking operations while holding the loader lock.
2579  */
2580 gboolean
2581 mono_loader_lock_is_owned_by_self (void)
2582 {
2583         g_assert (loader_lock_track_ownership);
2584
2585         return GPOINTER_TO_UINT (mono_native_tls_get_value (loader_lock_nest_id)) > 0;
2586 }
2587
2588 /*
2589  * mono_loader_lock_if_inited:
2590  *
2591  *   Acquire the loader lock if it has been initialized, no-op otherwise. This can
2592  * be used in runtime initialization code which can be executed before mono_loader_init ().
2593  */
2594 void
2595 mono_loader_lock_if_inited (void)
2596 {
2597         if (loader_lock_inited)
2598                 mono_loader_lock ();
2599 }
2600
2601 void
2602 mono_loader_unlock_if_inited (void)
2603 {
2604         if (loader_lock_inited)
2605                 mono_loader_unlock ();
2606 }
2607
2608 /**
2609  * mono_method_signature:
2610  *
2611  * Return the signature of the method M. On failure, returns NULL, and ERR is set.
2612  */
2613 MonoMethodSignature*
2614 mono_method_signature_checked (MonoMethod *m, MonoError *error)
2615 {
2616         int idx;
2617         MonoImage* img;
2618         const char *sig;
2619         gboolean can_cache_signature;
2620         MonoGenericContainer *container;
2621         MonoMethodSignature *signature = NULL, *sig2;
2622         guint32 sig_offset;
2623
2624         /* We need memory barriers below because of the double-checked locking pattern */ 
2625
2626         mono_error_init (error);
2627
2628         if (m->signature)
2629                 return m->signature;
2630
2631         img = m->klass->image;
2632
2633         if (m->is_inflated) {
2634                 MonoMethodInflated *imethod = (MonoMethodInflated *) m;
2635                 /* the lock is recursive */
2636                 signature = mono_method_signature (imethod->declaring);
2637                 signature = inflate_generic_signature_checked (imethod->declaring->klass->image, signature, mono_method_get_context (m), error);
2638                 if (!mono_error_ok (error))
2639                         return NULL;
2640
2641                 inflated_signatures_size += mono_metadata_signature_size (signature);
2642
2643                 mono_image_lock (img);
2644
2645                 mono_memory_barrier ();
2646                 if (!m->signature)
2647                         m->signature = signature;
2648
2649                 mono_image_unlock (img);
2650
2651                 return m->signature;
2652         }
2653
2654         g_assert (mono_metadata_token_table (m->token) == MONO_TABLE_METHOD);
2655         idx = mono_metadata_token_index (m->token);
2656
2657         sig = mono_metadata_blob_heap (img, sig_offset = mono_metadata_decode_row_col (&img->tables [MONO_TABLE_METHOD], idx - 1, MONO_METHOD_SIGNATURE));
2658
2659         g_assert (!m->klass->generic_class);
2660         container = mono_method_get_generic_container (m);
2661         if (!container)
2662                 container = m->klass->generic_container;
2663
2664         /* Generic signatures depend on the container so they cannot be cached */
2665         /* icall/pinvoke signatures cannot be cached cause we modify them below */
2666         can_cache_signature = !(m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && !(m->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) && !container;
2667
2668         /* If the method has parameter attributes, that can modify the signature */
2669         if (mono_metadata_method_has_param_attrs (img, idx))
2670                 can_cache_signature = FALSE;
2671
2672         if (can_cache_signature) {
2673                 mono_image_lock (img);
2674                 signature = (MonoMethodSignature *)g_hash_table_lookup (img->method_signatures, sig);
2675                 mono_image_unlock (img);
2676         }
2677
2678         if (!signature) {
2679                 const char *sig_body;
2680                 /*TODO we should cache the failure result somewhere*/
2681                 if (!mono_verifier_verify_method_signature (img, sig_offset, error))
2682                         return NULL;
2683
2684                 /* size = */ mono_metadata_decode_blob_size (sig, &sig_body);
2685
2686                 signature = mono_metadata_parse_method_signature_full (img, container, idx, sig_body, NULL, error);
2687                 if (!signature)
2688                         return NULL;
2689
2690                 if (can_cache_signature) {
2691                         mono_image_lock (img);
2692                         sig2 = (MonoMethodSignature *)g_hash_table_lookup (img->method_signatures, sig);
2693                         if (!sig2)
2694                                 g_hash_table_insert (img->method_signatures, (gpointer)sig, signature);
2695                         mono_image_unlock (img);
2696                 }
2697
2698                 signatures_size += mono_metadata_signature_size (signature);
2699         }
2700
2701         /* Verify metadata consistency */
2702         if (signature->generic_param_count) {
2703                 if (!container || !container->is_method) {
2704                         mono_error_set_method_load (error, m->klass, m->name, "Signature claims method has generic parameters, but generic_params table says it doesn't for method 0x%08x from image %s", idx, img->name);
2705                         return NULL;
2706                 }
2707                 if (container->type_argc != signature->generic_param_count) {
2708                         mono_error_set_method_load (error, m->klass, m->name, "Inconsistent generic parameter count.  Signature says %d, generic_params table says %d for method 0x%08x from image %s", signature->generic_param_count, container->type_argc, idx, img->name);
2709                         return NULL;
2710                 }
2711         } else if (container && container->is_method && container->type_argc) {
2712                 mono_error_set_method_load (error, m->klass, m->name, "generic_params table claims method has generic parameters, but signature says it doesn't for method 0x%08x from image %s", idx, img->name);
2713                 return NULL;
2714         }
2715         if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
2716                 signature->pinvoke = 1;
2717         else if (m->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
2718                 MonoCallConvention conv = (MonoCallConvention)0;
2719                 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)m;
2720                 signature->pinvoke = 1;
2721
2722                 switch (piinfo->piflags & PINVOKE_ATTRIBUTE_CALL_CONV_MASK) {
2723                 case 0: /* no call conv, so using default */
2724                 case PINVOKE_ATTRIBUTE_CALL_CONV_WINAPI:
2725                         conv = MONO_CALL_DEFAULT;
2726                         break;
2727                 case PINVOKE_ATTRIBUTE_CALL_CONV_CDECL:
2728                         conv = MONO_CALL_C;
2729                         break;
2730                 case PINVOKE_ATTRIBUTE_CALL_CONV_STDCALL:
2731                         conv = MONO_CALL_STDCALL;
2732                         break;
2733                 case PINVOKE_ATTRIBUTE_CALL_CONV_THISCALL:
2734                         conv = MONO_CALL_THISCALL;
2735                         break;
2736                 case PINVOKE_ATTRIBUTE_CALL_CONV_FASTCALL:
2737                         conv = MONO_CALL_FASTCALL;
2738                         break;
2739                 case PINVOKE_ATTRIBUTE_CALL_CONV_GENERIC:
2740                 case PINVOKE_ATTRIBUTE_CALL_CONV_GENERICINST:
2741                 default:
2742                         mono_error_set_method_load (error, m->klass, m->name, "unsupported calling convention : 0x%04x for method 0x%08x from image %s", piinfo->piflags, idx, img->name);
2743                         return NULL;
2744                 }
2745                 signature->call_convention = conv;
2746         }
2747
2748         mono_image_lock (img);
2749
2750         mono_memory_barrier ();
2751         if (!m->signature)
2752                 m->signature = signature;
2753
2754         mono_image_unlock (img);
2755
2756         return m->signature;
2757 }
2758
2759 /**
2760  * mono_method_signature:
2761  *
2762  * Return the signature of the method M. On failure, returns NULL.
2763  */
2764 MonoMethodSignature*
2765 mono_method_signature (MonoMethod *m)
2766 {
2767         MonoError error;
2768         MonoMethodSignature *sig;
2769
2770         sig = mono_method_signature_checked (m, &error);
2771         if (!sig) {
2772                 char *type_name = mono_type_get_full_name (m->klass);
2773                 g_warning ("Could not load signature of %s:%s due to: %s", type_name, m->name, mono_error_get_message (&error));
2774                 g_free (type_name);
2775                 mono_error_cleanup (&error);
2776         }
2777
2778         return sig;
2779 }
2780
2781 const char*
2782 mono_method_get_name (MonoMethod *method)
2783 {
2784         return method->name;
2785 }
2786
2787 MonoClass*
2788 mono_method_get_class (MonoMethod *method)
2789 {
2790         return method->klass;
2791 }
2792
2793 guint32
2794 mono_method_get_token (MonoMethod *method)
2795 {
2796         return method->token;
2797 }
2798
2799 MonoMethodHeader*
2800 mono_method_get_header_checked (MonoMethod *method, MonoError *error)
2801 {
2802         int idx;
2803         guint32 rva;
2804         MonoImage* img;
2805         gpointer loc;
2806         MonoGenericContainer *container;
2807
2808         mono_error_init (error);
2809         img = method->klass->image;
2810
2811         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)) {
2812                 mono_error_set_bad_image (error, img, "Method has no body");
2813                 return NULL;
2814         }
2815
2816         if (method->is_inflated) {
2817                 MonoMethodInflated *imethod = (MonoMethodInflated *) method;
2818                 MonoMethodHeader *header, *iheader;
2819
2820                 header = mono_method_get_header_checked (imethod->declaring, error);
2821                 if (!header)
2822                         return NULL;
2823
2824                 iheader = inflate_generic_header (header, mono_method_get_context (method), error);
2825                 mono_metadata_free_mh (header);
2826                 if (!iheader) {
2827                         return NULL;
2828                 }
2829
2830                 mono_image_lock (img);
2831
2832                 if (imethod->header) {
2833                         mono_metadata_free_mh (iheader);
2834                         mono_image_unlock (img);
2835                         return imethod->header;
2836                 }
2837
2838                 mono_memory_barrier ();
2839                 imethod->header = iheader;
2840
2841                 mono_image_unlock (img);
2842
2843                 return imethod->header;
2844         }
2845
2846         if (method->wrapper_type != MONO_WRAPPER_NONE || method->sre_method) {
2847                 MonoMethodWrapper *mw = (MonoMethodWrapper *)method;
2848                 g_assert (mw->header);
2849                 return mw->header;
2850         }
2851
2852         /* 
2853          * We don't need locks here: the new header is allocated from malloc memory
2854          * and is not stored anywhere in the runtime, the user needs to free it.
2855          */
2856         g_assert (mono_metadata_token_table (method->token) == MONO_TABLE_METHOD);
2857         idx = mono_metadata_token_index (method->token);
2858         rva = mono_metadata_decode_row_col (&img->tables [MONO_TABLE_METHOD], idx - 1, MONO_METHOD_RVA);
2859
2860         if (!mono_verifier_verify_method_header (img, rva, NULL)) {
2861                 mono_error_set_bad_image (error, img, "Invalid method header, failed verification");
2862                 return NULL;
2863         }
2864
2865         loc = mono_image_rva_map (img, rva);
2866         if (!loc) {
2867                 mono_error_set_bad_image (error, img, "Method has zero rva");
2868                 return NULL;
2869         }
2870
2871         /*
2872          * When parsing the types of local variables, we must pass any container available
2873          * to ensure that both VAR and MVAR will get the right owner.
2874          */
2875         container = mono_method_get_generic_container (method);
2876         if (!container)
2877                 container = method->klass->generic_container;
2878         return mono_metadata_parse_mh_full (img, container, (const char *)loc, error);
2879 }
2880
2881 MonoMethodHeader*
2882 mono_method_get_header (MonoMethod *method)
2883 {
2884         MonoError error;
2885         MonoMethodHeader *header = mono_method_get_header_checked (method, &error);
2886         mono_error_cleanup (&error);
2887         return header;
2888 }
2889
2890
2891 guint32
2892 mono_method_get_flags (MonoMethod *method, guint32 *iflags)
2893 {
2894         if (iflags)
2895                 *iflags = method->iflags;
2896         return method->flags;
2897 }
2898
2899 /*
2900  * Find the method index in the metadata methodDef table.
2901  */
2902 guint32
2903 mono_method_get_index (MonoMethod *method)
2904 {
2905         MonoClass *klass = method->klass;
2906         int i;
2907
2908         if (klass->rank)
2909                 /* constructed array methods are not in the MethodDef table */
2910                 return 0;
2911
2912         if (method->token)
2913                 return mono_metadata_token_index (method->token);
2914
2915         mono_class_setup_methods (klass);
2916         if (mono_class_has_failure (klass))
2917                 return 0;
2918         for (i = 0; i < klass->method.count; ++i) {
2919                 if (method == klass->methods [i]) {
2920                         if (klass->image->uncompressed_metadata)
2921                                 return mono_metadata_translate_token_index (klass->image, MONO_TABLE_METHOD, klass->method.first + i + 1);
2922                         else
2923                                 return klass->method.first + i + 1;
2924                 }
2925         }
2926         return 0;
2927 }