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