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