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