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