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