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