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