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