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