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