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