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