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