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