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