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