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