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