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