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