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