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