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