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