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