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