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