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