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