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