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