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