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