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