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