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