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