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