2009-02-19 Rodrigo Kumpera <rkumpera@novell.com>
[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/metadata/lock-tracer.h>
40 #include <mono/utils/mono-logger.h>
41 #include <mono/utils/mono-dl.h>
42 #include <mono/utils/mono-membar.h>
43 #include <mono/utils/mono-counters.h>
44
45 MonoDefaults mono_defaults;
46
47 /*
48  * This lock protects the hash tables inside MonoImage used by the metadata 
49  * loading functions in class.c and loader.c.
50  *
51  * See domain-internals.h for locking policy in combination with the
52  * domain lock.
53  */
54 static CRITICAL_SECTION loader_mutex;
55
56 /* Statistics */
57 static guint32 inflated_signatures_size;
58 static guint32 memberref_sig_cache_size;
59
60 /*
61  * This TLS variable contains the last type load error encountered by the loader.
62  */
63 guint32 loader_error_thread_id;
64
65 void
66 mono_loader_init ()
67 {
68         static gboolean inited;
69
70         if (!inited) {
71                 InitializeCriticalSection (&loader_mutex);
72
73                 loader_error_thread_id = TlsAlloc ();
74
75                 mono_counters_register ("Inflated signatures size",
76                                                                 MONO_COUNTER_GENERICS | MONO_COUNTER_INT, &inflated_signatures_size);
77                 mono_counters_register ("Memberref signature cache size",
78                                                                 MONO_COUNTER_METADATA | MONO_COUNTER_INT, &memberref_sig_cache_size);
79
80                 inited = TRUE;
81         }
82 }
83
84 void
85 mono_loader_cleanup (void)
86 {
87         TlsFree (loader_error_thread_id);
88
89         /*DeleteCriticalSection (&loader_mutex);*/
90 }
91
92 /*
93  * Handling of type load errors should be done as follows:
94  *
95  *   If something could not be loaded, the loader should call one of the
96  * mono_loader_set_error_XXX functions ()
97  * with the appropriate arguments, then return NULL to report the failure. The error 
98  * should be propagated until it reaches code which can throw managed exceptions. At that
99  * point, an exception should be thrown based on the information returned by
100  * mono_loader_get_last_error (). Then the error should be cleared by calling 
101  * mono_loader_clear_error ().
102  */
103
104 static void
105 set_loader_error (MonoLoaderError *error)
106 {
107         TlsSetValue (loader_error_thread_id, error);
108 }
109
110 /**
111  * mono_loader_set_error_assembly_load:
112  *
113  * Set the loader error for this thread. 
114  */
115 void
116 mono_loader_set_error_assembly_load (const char *assembly_name, gboolean ref_only)
117 {
118         MonoLoaderError *error;
119
120         if (mono_loader_get_last_error ()) 
121                 return;
122
123         error = g_new0 (MonoLoaderError, 1);
124         error->exception_type = MONO_EXCEPTION_FILE_NOT_FOUND;
125         error->assembly_name = g_strdup (assembly_name);
126         error->ref_only = ref_only;
127
128         /* 
129          * This is not strictly needed, but some (most) of the loader code still
130          * can't deal with load errors, and this message is more helpful than an
131          * assert.
132          */
133         if (ref_only)
134                 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);
135         else
136                 g_warning ("Could not load file or assembly '%s' or one of its dependencies.", assembly_name);
137
138         set_loader_error (error);
139 }
140
141 /**
142  * mono_loader_set_error_type_load:
143  *
144  * Set the loader error for this thread. 
145  */
146 void
147 mono_loader_set_error_type_load (const char *class_name, const char *assembly_name)
148 {
149         MonoLoaderError *error;
150
151         if (mono_loader_get_last_error ()) 
152                 return;
153
154         error = g_new0 (MonoLoaderError, 1);
155         error->exception_type = MONO_EXCEPTION_TYPE_LOAD;
156         error->class_name = g_strdup (class_name);
157         error->assembly_name = g_strdup (assembly_name);
158
159         /* 
160          * This is not strictly needed, but some (most) of the loader code still
161          * can't deal with load errors, and this message is more helpful than an
162          * assert.
163          */
164         g_warning ("The class %s could not be loaded, used in %s", class_name, assembly_name);
165
166         set_loader_error (error);
167 }
168
169 /*
170  * mono_loader_set_error_method_load:
171  *
172  *   Set the loader error for this thread. MEMBER_NAME should point to a string
173  * inside metadata.
174  */
175 void
176 mono_loader_set_error_method_load (const char *class_name, const char *member_name)
177 {
178         MonoLoaderError *error;
179
180         /* FIXME: Store the signature as well */
181         if (mono_loader_get_last_error ())
182                 return;
183
184         error = g_new0 (MonoLoaderError, 1);
185         error->exception_type = MONO_EXCEPTION_MISSING_METHOD;
186         error->class_name = g_strdup (class_name);
187         error->member_name = member_name;
188
189         set_loader_error (error);
190 }
191
192 /*
193  * mono_loader_set_error_field_load:
194  *
195  * Set the loader error for this thread. MEMBER_NAME should point to a string
196  * inside metadata.
197  */
198 void
199 mono_loader_set_error_field_load (MonoClass *klass, const char *member_name)
200 {
201         MonoLoaderError *error;
202
203         /* FIXME: Store the signature as well */
204         if (mono_loader_get_last_error ())
205                 return;
206
207         error = g_new0 (MonoLoaderError, 1);
208         error->exception_type = MONO_EXCEPTION_MISSING_FIELD;
209         error->klass = klass;
210         error->member_name = member_name;
211
212         set_loader_error (error);
213 }
214
215 /*
216  * mono_loader_set_error_bad_image:
217  *
218  * Set the loader error for this thread. 
219  */
220 void
221 mono_loader_set_error_bad_image (char *msg)
222 {
223         MonoLoaderError *error;
224
225         if (mono_loader_get_last_error ())
226                 return;
227
228         error = g_new0 (MonoLoaderError, 1);
229         error->exception_type = MONO_EXCEPTION_BAD_IMAGE;
230         error->msg = msg;
231
232         set_loader_error (error);
233 }       
234
235
236 /*
237  * mono_loader_get_last_error:
238  *
239  *   Returns information about the last type load exception encountered by the loader, or
240  * NULL. After use, the exception should be cleared by calling mono_loader_clear_error.
241  */
242 MonoLoaderError*
243 mono_loader_get_last_error (void)
244 {
245         return (MonoLoaderError*)TlsGetValue (loader_error_thread_id);
246 }
247
248 /**
249  * mono_loader_clear_error:
250  *
251  * Disposes any loader error messages on this thread
252  */
253 void
254 mono_loader_clear_error (void)
255 {
256         MonoLoaderError *ex = (MonoLoaderError*)TlsGetValue (loader_error_thread_id);
257
258         if (ex) {
259                 g_free (ex->class_name);
260                 g_free (ex->assembly_name);
261                 g_free (ex->msg);
262                 g_free (ex);
263         
264                 TlsSetValue (loader_error_thread_id, NULL);
265         }
266 }
267
268 /**
269  * mono_loader_error_prepare_exception:
270  * @error: The MonoLoaderError to turn into an exception
271  *
272  * This turns a MonoLoaderError into an exception that can be thrown
273  * and resets the Mono Loader Error state during this process.
274  *
275  */
276 MonoException *
277 mono_loader_error_prepare_exception (MonoLoaderError *error)
278 {
279         MonoException *ex = NULL;
280
281         switch (error->exception_type) {
282         case MONO_EXCEPTION_TYPE_LOAD: {
283                 char *cname = g_strdup (error->class_name);
284                 char *aname = g_strdup (error->assembly_name);
285                 MonoString *class_name;
286                 
287                 mono_loader_clear_error ();
288                 
289                 class_name = mono_string_new (mono_domain_get (), cname);
290
291                 ex = mono_get_exception_type_load (class_name, aname);
292                 g_free (cname);
293                 g_free (aname);
294                 break;
295         }
296         case MONO_EXCEPTION_MISSING_METHOD: {
297                 char *cname = g_strdup (error->class_name);
298                 char *aname = g_strdup (error->member_name);
299                 
300                 mono_loader_clear_error ();
301                 ex = mono_get_exception_missing_method (cname, aname);
302                 g_free (cname);
303                 g_free (aname);
304                 break;
305         }
306                 
307         case MONO_EXCEPTION_MISSING_FIELD: {
308                 char *cnspace = g_strdup (*error->klass->name_space ? error->klass->name_space : "");
309                 char *cname = g_strdup (error->klass->name);
310                 char *cmembername = g_strdup (error->member_name);
311                 char *class_name;
312
313                 mono_loader_clear_error ();
314                 class_name = g_strdup_printf ("%s%s%s", cnspace, cnspace ? "." : "", cname);
315                 
316                 ex = mono_get_exception_missing_field (class_name, cmembername);
317                 g_free (class_name);
318                 g_free (cname);
319                 g_free (cmembername);
320                 g_free (cnspace);
321                 break;
322         }
323         
324         case MONO_EXCEPTION_FILE_NOT_FOUND: {
325                 char *msg;
326                 char *filename;
327
328                 if (error->ref_only)
329                         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);
330                 else
331                         msg = g_strdup_printf ("Could not load file or assembly '%s' or one of its dependencies.", error->assembly_name);
332                 filename = g_strdup (error->assembly_name);
333                 /* Has to call this before calling anything which might call mono_class_init () */
334                 mono_loader_clear_error ();
335                 ex = mono_get_exception_file_not_found2 (msg, mono_string_new (mono_domain_get (), filename));
336                 g_free (msg);
337                 g_free (filename);
338                 break;
339         }
340
341         case MONO_EXCEPTION_BAD_IMAGE: {
342                 char *msg = g_strdup (error->msg);
343                 mono_loader_clear_error ();
344                 ex = mono_get_exception_bad_image_format (msg);
345                 g_free (msg);
346                 break;
347         }
348
349         default:
350                 g_assert_not_reached ();
351         }
352
353         return ex;
354 }
355
356 /*
357  * find_cached_memberref_sig:
358  *
359  *   Return a cached copy of the memberref signature identified by SIG_IDX.
360  * We use a gpointer since the cache stores both MonoTypes and MonoMethodSignatures.
361  * A cache is needed since the type/signature parsing routines allocate everything 
362  * from a mempool, so without a cache, multiple requests for the same signature would 
363  * lead to unbounded memory growth. For normal methods/fields this is not a problem 
364  * since the resulting methods/fields are cached, but inflated methods/fields cannot
365  * be cached.
366  * LOCKING: Acquires the loader lock.
367  */
368 static gpointer
369 find_cached_memberref_sig (MonoImage *image, guint32 sig_idx)
370 {
371         gpointer res;
372
373         mono_loader_lock ();
374         res = g_hash_table_lookup (image->memberref_signatures, GUINT_TO_POINTER (sig_idx));
375         mono_loader_unlock ();
376
377         return res;
378 }
379
380 static gpointer
381 cache_memberref_sig (MonoImage *image, guint32 sig_idx, gpointer sig)
382 {
383         gpointer prev_sig;
384
385         mono_loader_lock ();
386         prev_sig = g_hash_table_lookup (image->memberref_signatures, GUINT_TO_POINTER (sig_idx));
387         if (prev_sig) {
388                 /* Somebody got in before us */
389                 sig = prev_sig;
390         }
391         else {
392                 g_hash_table_insert (image->memberref_signatures, GUINT_TO_POINTER (sig_idx), sig);
393                 /* An approximation based on glib 2.18 */
394                 memberref_sig_cache_size += sizeof (gpointer) * 4;
395         }
396
397         mono_loader_unlock ();
398
399         return sig;
400 }
401
402 static MonoClassField*
403 field_from_memberref (MonoImage *image, guint32 token, MonoClass **retklass,
404                       MonoGenericContext *context)
405 {
406         MonoClass *klass;
407         MonoClassField *field, *sig_field = NULL;
408         MonoTableInfo *tables = image->tables;
409         MonoType *sig_type;
410         guint32 cols[6];
411         guint32 nindex, class;
412         const char *fname;
413         const char *ptr;
414         guint32 idx = mono_metadata_token_index (token);
415
416         mono_metadata_decode_row (&tables [MONO_TABLE_MEMBERREF], idx-1, cols, MONO_MEMBERREF_SIZE);
417         nindex = cols [MONO_MEMBERREF_CLASS] >> MONO_MEMBERREF_PARENT_BITS;
418         class = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
419
420         fname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
421
422         ptr = mono_metadata_blob_heap (image, cols [MONO_MEMBERREF_SIGNATURE]);
423         mono_metadata_decode_blob_size (ptr, &ptr);
424         /* we may want to check the signature here... */
425
426         if (*ptr++ != 0x6) {
427                 mono_loader_set_error_bad_image (g_strdup_printf ("Bad field signature class token %08x field name %s token %08x", class, fname, token));
428                 return NULL;
429         }
430         /* FIXME: This needs a cache, especially for generic instances, since
431          * mono_metadata_parse_type () allocates everything from a mempool.
432          */
433         sig_type = find_cached_memberref_sig (image, cols [MONO_MEMBERREF_SIGNATURE]);
434         if (!sig_type) {
435                 sig_type = mono_metadata_parse_type (image, MONO_PARSE_TYPE, 0, ptr, &ptr);
436                 sig_type = cache_memberref_sig (image, cols [MONO_MEMBERREF_SIGNATURE], sig_type);
437         }
438
439         switch (class) {
440         case MONO_MEMBERREF_PARENT_TYPEDEF:
441                 klass = mono_class_get (image, MONO_TOKEN_TYPE_DEF | nindex);
442                 if (!klass) {
443                         char *name = mono_class_name_from_token (image, MONO_TOKEN_TYPE_DEF | nindex);
444                         g_warning ("Missing field %s in class %s (typedef index %d)", fname, name, nindex);
445                         mono_loader_set_error_type_load (name, image->assembly_name);
446                         g_free (name);
447                         return NULL;
448                 }
449                 mono_class_init (klass);
450                 if (retklass)
451                         *retklass = klass;
452                 sig_field = field = mono_class_get_field_from_name (klass, fname);
453                 break;
454         case MONO_MEMBERREF_PARENT_TYPEREF:
455                 klass = mono_class_from_typeref (image, MONO_TOKEN_TYPE_REF | nindex);
456                 if (!klass) {
457                         char *name = mono_class_name_from_token (image, MONO_TOKEN_TYPE_REF | nindex);
458                         g_warning ("missing field %s in class %s (typeref index %d)", fname, name, nindex);
459                         mono_loader_set_error_type_load (name, image->assembly_name);
460                         g_free (name);
461                         return NULL;
462                 }
463                 mono_class_init (klass);
464                 if (retklass)
465                         *retklass = klass;
466                 sig_field = field = mono_class_get_field_from_name (klass, fname);
467                 break;
468         case MONO_MEMBERREF_PARENT_TYPESPEC: {
469                 klass = mono_class_get_full (image, MONO_TOKEN_TYPE_SPEC | nindex, context);
470                 //FIXME can't klass be null?
471                 mono_class_init (klass);
472                 if (retklass)
473                         *retklass = klass;
474                 field = mono_class_get_field_from_name (klass, fname);
475                 if (field)
476                         sig_field = mono_metadata_get_corresponding_field_from_generic_type_definition (field);
477                 break;
478         }
479         default:
480                 g_warning ("field load from %x", class);
481                 return NULL;
482         }
483
484         if (!field)
485                 mono_loader_set_error_field_load (klass, fname);
486         else if (sig_field && !mono_metadata_type_equal_full (sig_type, sig_field->type, TRUE)) {
487                 mono_loader_set_error_field_load (klass, fname);
488                 return NULL;
489         }
490
491         return field;
492 }
493
494 MonoClassField*
495 mono_field_from_token (MonoImage *image, guint32 token, MonoClass **retklass,
496                        MonoGenericContext *context)
497 {
498         MonoClass *k;
499         guint32 type;
500         MonoClassField *field;
501
502         if (image->dynamic) {
503                 MonoClassField *result;
504                 MonoClass *handle_class;
505
506                 *retklass = NULL;
507                 result = mono_lookup_dynamic_token_class (image, token, TRUE, &handle_class, context);
508                 // This checks the memberref type as well
509                 if (result && handle_class != mono_defaults.fieldhandle_class) {
510                         mono_loader_set_error_bad_image (g_strdup ("Bad field token."));
511                         return NULL;
512                 }
513                 *retklass = result->parent;
514                 return result;
515         }
516
517         mono_loader_lock ();
518         if ((field = g_hash_table_lookup (image->field_cache, GUINT_TO_POINTER (token)))) {
519                 *retklass = field->parent;
520                 mono_loader_unlock ();
521                 return field;
522         }
523         mono_loader_unlock ();
524
525         if (mono_metadata_token_table (token) == MONO_TABLE_MEMBERREF)
526                 field = field_from_memberref (image, token, retklass, context);
527         else {
528                 type = mono_metadata_typedef_from_field (image, mono_metadata_token_index (token));
529                 if (!type)
530                         return NULL;
531                 k = mono_class_get (image, MONO_TOKEN_TYPE_DEF | type);
532                 if (!k)
533                         return NULL;
534                 mono_class_init (k);
535                 if (retklass)
536                         *retklass = k;
537                 field = mono_class_get_field (k, token);
538         }
539
540         mono_loader_lock ();
541         if (field && !field->parent->generic_class && !field->parent->generic_container)
542                 g_hash_table_insert (image->field_cache, GUINT_TO_POINTER (token), field);
543         mono_loader_unlock ();
544         return field;
545 }
546
547 static gboolean
548 mono_metadata_signature_vararg_match (MonoMethodSignature *sig1, MonoMethodSignature *sig2)
549 {
550         int i;
551
552         if (sig1->hasthis != sig2->hasthis ||
553             sig1->sentinelpos != sig2->sentinelpos)
554                 return FALSE;
555
556         for (i = 0; i < sig1->sentinelpos; i++) { 
557                 MonoType *p1 = sig1->params[i];
558                 MonoType *p2 = sig2->params[i];
559
560                 /*if (p1->attrs != p2->attrs)
561                         return FALSE;
562                 */
563                 if (!mono_metadata_type_equal (p1, p2))
564                         return FALSE;
565         }
566
567         if (!mono_metadata_type_equal (sig1->ret, sig2->ret))
568                 return FALSE;
569         return TRUE;
570 }
571
572 static MonoMethod *
573 find_method_in_class (MonoClass *klass, const char *name, const char *qname, const char *fqname,
574                       MonoMethodSignature *sig, MonoClass *from_class)
575 {
576         int i;
577
578         /* Search directly in the metadata to avoid calling setup_methods () */
579
580         /* FIXME: !from_class->generic_class condition causes test failures. */
581         if (klass->type_token && !klass->image->dynamic && !klass->methods && !klass->rank && klass == from_class && !from_class->generic_class) {
582                 for (i = 0; i < klass->method.count; ++i) {
583                         guint32 cols [MONO_METHOD_SIZE];
584                         MonoMethod *method;
585                         const char *m_name;
586
587                         mono_metadata_decode_table_row (klass->image, MONO_TABLE_METHOD, klass->method.first + i, cols, MONO_METHOD_SIZE);
588
589                         m_name = mono_metadata_string_heap (klass->image, cols [MONO_METHOD_NAME]);
590
591                         if (!((fqname && !strcmp (m_name, fqname)) ||
592                                   (qname && !strcmp (m_name, qname)) ||
593                                   (name && !strcmp (m_name, name))))
594                                 continue;
595
596                         method = mono_get_method (klass->image, MONO_TOKEN_METHOD_DEF | (klass->method.first + i + 1), klass);
597                         if (method && (sig->call_convention != MONO_CALL_VARARG) && mono_metadata_signature_equal (sig, mono_method_signature (method)))
598                                 return method;
599                 }
600         }
601
602         mono_class_setup_methods (klass);
603         for (i = 0; i < klass->method.count; ++i) {
604                 MonoMethod *m = klass->methods [i];
605
606                 if (!((fqname && !strcmp (m->name, fqname)) ||
607                       (qname && !strcmp (m->name, qname)) ||
608                       (name && !strcmp (m->name, name))))
609                         continue;
610
611                 if (sig->call_convention == MONO_CALL_VARARG) {
612                         if (mono_metadata_signature_vararg_match (sig, mono_method_signature (m)))
613                                 break;
614                 } else {
615                         if (mono_metadata_signature_equal (sig, mono_method_signature (m)))
616                                 break;
617                 }
618         }
619
620         if (i < klass->method.count)
621                 return mono_class_get_method_by_index (from_class, i);
622         return NULL;
623 }
624
625 static MonoMethod *
626 find_method (MonoClass *in_class, MonoClass *ic, const char* name, MonoMethodSignature *sig, MonoClass *from_class)
627 {
628         int i;
629         char *qname, *fqname, *class_name;
630         gboolean is_interface;
631         MonoMethod *result = NULL;
632
633         is_interface = MONO_CLASS_IS_INTERFACE (in_class);
634
635         if (ic) {
636                 class_name = mono_type_get_name_full (&ic->byval_arg, MONO_TYPE_NAME_FORMAT_IL);
637
638                 qname = g_strconcat (class_name, ".", name, NULL); 
639                 if (ic->name_space && ic->name_space [0])
640                         fqname = g_strconcat (ic->name_space, ".", class_name, ".", name, NULL);
641                 else
642                         fqname = NULL;
643         } else
644                 class_name = qname = fqname = NULL;
645
646         while (in_class) {
647                 g_assert (from_class);
648                 result = find_method_in_class (in_class, name, qname, fqname, sig, from_class);
649                 if (result)
650                         goto out;
651
652                 if (name [0] == '.' && (!strcmp (name, ".ctor") || !strcmp (name, ".cctor")))
653                         break;
654
655                 g_assert (from_class->interface_offsets_count == in_class->interface_offsets_count);
656                 for (i = 0; i < in_class->interface_offsets_count; i++) {
657                         MonoClass *in_ic = in_class->interfaces_packed [i];
658                         MonoClass *from_ic = from_class->interfaces_packed [i];
659                         char *ic_qname, *ic_fqname, *ic_class_name;
660                         
661                         ic_class_name = mono_type_get_name_full (&in_ic->byval_arg, MONO_TYPE_NAME_FORMAT_IL);
662                         ic_qname = g_strconcat (ic_class_name, ".", name, NULL); 
663                         if (in_ic->name_space && in_ic->name_space [0])
664                                 ic_fqname = g_strconcat (in_ic->name_space, ".", ic_class_name, ".", name, NULL);
665                         else
666                                 ic_fqname = NULL;
667
668                         result = find_method_in_class (in_ic, ic ? name : NULL, ic_qname, ic_fqname, sig, from_ic);
669                         g_free (ic_class_name);
670                         g_free (ic_fqname);
671                         g_free (ic_qname);
672                         if (result)
673                                 goto out;
674                 }
675
676                 in_class = in_class->parent;
677                 from_class = from_class->parent;
678         }
679         g_assert (!in_class == !from_class);
680
681         if (is_interface)
682                 result = find_method_in_class (mono_defaults.object_class, name, qname, fqname, sig, mono_defaults.object_class);
683
684  out:
685         g_free (class_name);
686         g_free (fqname);
687         g_free (qname);
688         return result;
689 }
690
691 static MonoMethodSignature*
692 inflate_generic_signature (MonoImage *image, MonoMethodSignature *sig, MonoGenericContext *context)
693 {
694         MonoMethodSignature *res;
695         gboolean is_open;
696         int i;
697
698         if (!context)
699                 return sig;
700
701         res = g_malloc0 (sizeof (MonoMethodSignature) + ((gint32)sig->param_count - MONO_ZERO_LEN_ARRAY) * sizeof (MonoType*));
702         res->param_count = sig->param_count;
703         res->sentinelpos = -1;
704         res->ret = mono_class_inflate_generic_type (sig->ret, context);
705         is_open = mono_class_is_open_constructed_type (res->ret);
706         for (i = 0; i < sig->param_count; ++i) {
707                 res->params [i] = mono_class_inflate_generic_type (sig->params [i], context);
708                 if (!is_open)
709                         is_open = mono_class_is_open_constructed_type (res->params [i]);
710         }
711         res->hasthis = sig->hasthis;
712         res->explicit_this = sig->explicit_this;
713         res->call_convention = sig->call_convention;
714         res->pinvoke = sig->pinvoke;
715         res->generic_param_count = sig->generic_param_count;
716         res->sentinelpos = sig->sentinelpos;
717         res->has_type_parameters = is_open;
718         res->is_inflated = 1;
719         return res;
720 }
721
722 static MonoMethodHeader*
723 inflate_generic_header (MonoMethodHeader *header, MonoGenericContext *context)
724 {
725         MonoMethodHeader *res;
726         int i;
727         res = g_malloc0 (sizeof (MonoMethodHeader) + sizeof (gpointer) * header->num_locals);
728         res->code = header->code;
729         res->code_size = header->code_size;
730         res->max_stack = header->max_stack;
731         res->num_clauses = header->num_clauses;
732         res->init_locals = header->init_locals;
733         res->num_locals = header->num_locals;
734         res->clauses = header->clauses;
735         for (i = 0; i < header->num_locals; ++i)
736                 res->locals [i] = mono_class_inflate_generic_type (header->locals [i], context);
737         if (res->num_clauses) {
738                 res->clauses = g_memdup (header->clauses, sizeof (MonoExceptionClause) * res->num_clauses);
739                 for (i = 0; i < header->num_clauses; ++i) {
740                         MonoExceptionClause *clause = &res->clauses [i];
741                         if (clause->flags != MONO_EXCEPTION_CLAUSE_NONE)
742                                 continue;
743                         clause->data.catch_class = mono_class_inflate_generic_class (clause->data.catch_class, context);
744                 }
745         }
746         return res;
747 }
748
749 /*
750  * token is the method_ref or method_def token used in a call IL instruction.
751  */
752 MonoMethodSignature*
753 mono_method_get_signature_full (MonoMethod *method, MonoImage *image, guint32 token, MonoGenericContext *context)
754 {
755         int table = mono_metadata_token_table (token);
756         int idx = mono_metadata_token_index (token);
757         int sig_idx;
758         guint32 cols [MONO_MEMBERREF_SIZE];
759         MonoMethodSignature *sig;
760         const char *ptr;
761
762         /* !table is for wrappers: we should really assign their own token to them */
763         if (!table || table == MONO_TABLE_METHOD)
764                 return mono_method_signature (method);
765
766         if (table == MONO_TABLE_METHODSPEC) {
767                 g_assert (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) &&
768                           mono_method_signature (method));
769                 g_assert (method->is_inflated);
770
771                 return mono_method_signature (method);
772         }
773
774         if (method->klass->generic_class)
775                 return mono_method_signature (method);
776
777         if (image->dynamic)
778                 /* FIXME: This might be incorrect for vararg methods */
779                 return mono_method_signature (method);
780
781         mono_metadata_decode_row (&image->tables [MONO_TABLE_MEMBERREF], idx-1, cols, MONO_MEMBERREF_SIZE);
782         sig_idx = cols [MONO_MEMBERREF_SIGNATURE];
783
784         sig = find_cached_memberref_sig (image, sig_idx);
785         if (!sig) {
786                 ptr = mono_metadata_blob_heap (image, sig_idx);
787                 mono_metadata_decode_blob_size (ptr, &ptr);
788                 sig = mono_metadata_parse_method_signature (image, 0, ptr, NULL);
789
790                 sig = cache_memberref_sig (image, sig_idx, sig);
791         }
792
793         if (context) {
794                 MonoMethodSignature *cached;
795
796                 /* This signature is not owned by a MonoMethod, so need to cache */
797                 sig = inflate_generic_signature (image, sig, context);
798                 cached = mono_metadata_get_inflated_signature (sig, context);
799                 if (cached != sig)
800                         mono_metadata_free_inflated_signature (sig);
801                 else
802                         inflated_signatures_size += mono_metadata_signature_size (cached);
803                 sig = cached;
804         }
805
806         return sig;
807 }
808
809 MonoMethodSignature*
810 mono_method_get_signature (MonoMethod *method, MonoImage *image, guint32 token)
811 {
812         return mono_method_get_signature_full (method, image, token, NULL);
813 }
814
815 /* this is only for the typespec array methods */
816 MonoMethod*
817 mono_method_search_in_array_class (MonoClass *klass, const char *name, MonoMethodSignature *sig)
818 {
819         int i;
820
821         mono_class_setup_methods (klass);
822
823         for (i = 0; i < klass->method.count; ++i) {
824                 MonoMethod *method = klass->methods [i];
825                 if (strcmp (method->name, name) == 0 && sig->param_count == method->signature->param_count)
826                         return method;
827         }
828         return NULL;
829 }
830
831 static MonoMethod *
832 method_from_memberref (MonoImage *image, guint32 idx, MonoGenericContext *typespec_context,
833                        gboolean *used_context)
834 {
835         MonoClass *klass = NULL;
836         MonoMethod *method = NULL;
837         MonoTableInfo *tables = image->tables;
838         guint32 cols[6];
839         guint32 nindex, class, sig_idx;
840         const char *mname;
841         MonoMethodSignature *sig;
842         const char *ptr;
843
844         mono_metadata_decode_row (&tables [MONO_TABLE_MEMBERREF], idx-1, cols, 3);
845         nindex = cols [MONO_MEMBERREF_CLASS] >> MONO_MEMBERREF_PARENT_BITS;
846         class = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
847         /*g_print ("methodref: 0x%x 0x%x %s\n", class, nindex,
848                 mono_metadata_string_heap (m, cols [MONO_MEMBERREF_NAME]));*/
849
850         mname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
851
852         /*
853          * Whether we actually used the `typespec_context' or not.
854          * This is used to tell our caller whether or not it's safe to insert the returned
855          * method into a cache.
856          */
857         if (used_context)
858                 *used_context = class == MONO_MEMBERREF_PARENT_TYPESPEC;
859
860         switch (class) {
861         case MONO_MEMBERREF_PARENT_TYPEREF:
862                 klass = mono_class_from_typeref (image, MONO_TOKEN_TYPE_REF | nindex);
863                 if (!klass) {
864                         char *name = mono_class_name_from_token (image, MONO_TOKEN_TYPE_REF | nindex);
865                         g_warning ("Missing method %s in assembly %s, type %s", mname, image->name, name);
866                         mono_loader_set_error_type_load (name, image->assembly_name);
867                         g_free (name);
868                         return NULL;
869                 }
870                 break;
871         case MONO_MEMBERREF_PARENT_TYPESPEC:
872                 /*
873                  * Parse the TYPESPEC in the parent's context.
874                  */
875                 klass = mono_class_get_full (image, MONO_TOKEN_TYPE_SPEC | nindex, typespec_context);
876                 if (!klass) {
877                         char *name = mono_class_name_from_token (image, MONO_TOKEN_TYPE_SPEC | nindex);
878                         g_warning ("Missing method %s in assembly %s, type %s", mname, image->name, name);
879                         mono_loader_set_error_type_load (name, image->assembly_name);
880                         g_free (name);
881                         return NULL;
882                 }
883                 break;
884         case MONO_MEMBERREF_PARENT_TYPEDEF:
885                 klass = mono_class_get (image, MONO_TOKEN_TYPE_DEF | nindex);
886                 if (!klass) {
887                         char *name = mono_class_name_from_token (image, MONO_TOKEN_TYPE_DEF | nindex);
888                         g_warning ("Missing method %s in assembly %s, type %s", mname, image->name, name);
889                         mono_loader_set_error_type_load (name, image->assembly_name);
890                         g_free (name);
891                         return NULL;
892                 }
893                 break;
894         case MONO_MEMBERREF_PARENT_METHODDEF:
895                 return mono_get_method (image, MONO_TOKEN_METHOD_DEF | nindex, NULL);
896                 
897         default:
898                 {
899                         /* This message leaks */
900                         char *message = g_strdup_printf ("Memberref parent unknown: class: %d, index %d", class, nindex);
901                         mono_loader_set_error_method_load ("", message);
902                         return NULL;
903                 }
904
905         }
906         g_assert (klass);
907         mono_class_init (klass);
908
909         sig_idx = cols [MONO_MEMBERREF_SIGNATURE];
910
911         ptr = mono_metadata_blob_heap (image, sig_idx);
912         mono_metadata_decode_blob_size (ptr, &ptr);
913
914         sig = find_cached_memberref_sig (image, sig_idx);
915         if (!sig) {
916                 sig = mono_metadata_parse_method_signature (image, 0, ptr, NULL);
917                 if (sig == NULL)
918                         return NULL;
919
920                 sig = cache_memberref_sig (image, sig_idx, sig);
921         }
922
923         switch (class) {
924         case MONO_MEMBERREF_PARENT_TYPEREF:
925         case MONO_MEMBERREF_PARENT_TYPEDEF:
926                 method = find_method (klass, NULL, mname, sig, klass);
927                 break;
928
929         case MONO_MEMBERREF_PARENT_TYPESPEC: {
930                 MonoType *type;
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                 method = 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         mono_locks_acquire (&loader_mutex, LoaderLock);
1953 }
1954
1955 void
1956 mono_loader_unlock (void)
1957 {
1958         mono_locks_release (&loader_mutex, LoaderLock);
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