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