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