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