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