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