2008-10-19 Zoltan Varga <vargaz@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 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 *in_class, const char *name, const char *qname, const char *fqname,
507                       MonoMethodSignature *sig, MonoClass *from_class)
508 {
509         int i;
510
511         mono_class_setup_methods (in_class);
512         for (i = 0; i < in_class->method.count; ++i) {
513                 MonoMethod *m = in_class->methods [i];
514
515                 if (!((fqname && !strcmp (m->name, fqname)) ||
516                       (qname && !strcmp (m->name, qname)) ||
517                       (name && !strcmp (m->name, name))))
518                         continue;
519
520                 if (sig->call_convention == MONO_CALL_VARARG) {
521                         if (mono_metadata_signature_vararg_match (sig, mono_method_signature (m)))
522                                 break;
523                 } else {
524                         if (mono_metadata_signature_equal (sig, mono_method_signature (m)))
525                                 break;
526                 }
527         }
528
529         if (i < in_class->method.count)
530                 return mono_class_get_method_by_index (from_class, i);
531         return NULL;
532 }
533
534 static MonoMethod *
535 find_method (MonoClass *in_class, MonoClass *ic, const char* name, MonoMethodSignature *sig, MonoClass *from_class)
536 {
537         int i;
538         char *qname, *fqname, *class_name;
539         gboolean is_interface;
540         MonoMethod *result = NULL;
541
542         is_interface = MONO_CLASS_IS_INTERFACE (in_class);
543
544         if (ic) {
545                 class_name = mono_type_get_name_full (&ic->byval_arg, MONO_TYPE_NAME_FORMAT_IL);
546
547                 qname = g_strconcat (class_name, ".", name, NULL); 
548                 if (ic->name_space && ic->name_space [0])
549                         fqname = g_strconcat (ic->name_space, ".", class_name, ".", name, NULL);
550                 else
551                         fqname = NULL;
552         } else
553                 class_name = qname = fqname = NULL;
554
555         while (in_class) {
556                 g_assert (from_class);
557                 result = find_method_in_class (in_class, name, qname, fqname, sig, from_class);
558                 if (result)
559                         goto out;
560
561                 if (name [0] == '.' && (!strcmp (name, ".ctor") || !strcmp (name, ".cctor")))
562                         break;
563
564                 g_assert (from_class->interface_count == in_class->interface_count);
565                 for (i = 0; i < in_class->interface_count; i++) {
566                         MonoClass *in_ic = in_class->interfaces [i];
567                         MonoClass *from_ic = from_class->interfaces [i];
568                         char *ic_qname, *ic_fqname, *ic_class_name;
569                         
570                         ic_class_name = mono_type_get_name_full (&in_ic->byval_arg, MONO_TYPE_NAME_FORMAT_IL);
571                         ic_qname = g_strconcat (ic_class_name, ".", name, NULL); 
572                         if (in_ic->name_space && in_ic->name_space [0])
573                                 ic_fqname = g_strconcat (in_ic->name_space, ".", ic_class_name, ".", name, NULL);
574                         else
575                                 ic_fqname = NULL;
576
577                         result = find_method_in_class (in_ic, ic ? name : NULL, ic_qname, ic_fqname, sig, from_ic);
578                         g_free (ic_class_name);
579                         g_free (ic_fqname);
580                         g_free (ic_qname);
581                         if (result)
582                                 goto out;
583                 }
584
585                 in_class = in_class->parent;
586                 from_class = from_class->parent;
587         }
588         g_assert (!in_class == !from_class);
589
590         if (is_interface)
591                 result = find_method_in_class (mono_defaults.object_class, name, qname, fqname, sig, mono_defaults.object_class);
592
593  out:
594         g_free (class_name);
595         g_free (fqname);
596         g_free (qname);
597         return result;
598 }
599
600 static MonoMethodSignature*
601 inflate_generic_signature (MonoImage *image, MonoMethodSignature *sig, MonoGenericContext *context)
602 {
603         MonoMethodSignature *res;
604         gboolean is_open;
605         int i;
606
607         if (!context)
608                 return sig;
609
610         res = g_malloc0 (sizeof (MonoMethodSignature) + ((gint32)sig->param_count - MONO_ZERO_LEN_ARRAY) * sizeof (MonoType*));
611         res->param_count = sig->param_count;
612         res->sentinelpos = -1;
613         res->ret = mono_class_inflate_generic_type (sig->ret, context);
614         is_open = mono_class_is_open_constructed_type (res->ret);
615         for (i = 0; i < sig->param_count; ++i) {
616                 res->params [i] = mono_class_inflate_generic_type (sig->params [i], context);
617                 if (!is_open)
618                         is_open = mono_class_is_open_constructed_type (res->params [i]);
619         }
620         res->hasthis = sig->hasthis;
621         res->explicit_this = sig->explicit_this;
622         res->call_convention = sig->call_convention;
623         res->pinvoke = sig->pinvoke;
624         res->generic_param_count = sig->generic_param_count;
625         res->sentinelpos = sig->sentinelpos;
626         res->has_type_parameters = is_open;
627         res->is_inflated = 1;
628         return res;
629 }
630
631 static MonoMethodHeader*
632 inflate_generic_header (MonoMethodHeader *header, MonoGenericContext *context)
633 {
634         MonoMethodHeader *res;
635         int i;
636         res = g_malloc0 (sizeof (MonoMethodHeader) + sizeof (gpointer) * header->num_locals);
637         res->code = header->code;
638         res->code_size = header->code_size;
639         res->max_stack = header->max_stack;
640         res->num_clauses = header->num_clauses;
641         res->init_locals = header->init_locals;
642         res->num_locals = header->num_locals;
643         res->clauses = header->clauses;
644         for (i = 0; i < header->num_locals; ++i)
645                 res->locals [i] = mono_class_inflate_generic_type (header->locals [i], context);
646         if (res->num_clauses) {
647                 res->clauses = g_memdup (header->clauses, sizeof (MonoExceptionClause) * res->num_clauses);
648                 for (i = 0; i < header->num_clauses; ++i) {
649                         MonoExceptionClause *clause = &res->clauses [i];
650                         MonoType *t;
651                         if (clause->flags != MONO_EXCEPTION_CLAUSE_NONE)
652                                 continue;
653                         t = mono_class_inflate_generic_type (&clause->data.catch_class->byval_arg, context);
654                         clause->data.catch_class = mono_class_from_mono_type (t);
655                         mono_metadata_free_type (t);
656                 }
657         }
658         return res;
659 }
660
661 /*
662  * token is the method_ref or method_def token used in a call IL instruction.
663  */
664 MonoMethodSignature*
665 mono_method_get_signature_full (MonoMethod *method, MonoImage *image, guint32 token, MonoGenericContext *context)
666 {
667         int table = mono_metadata_token_table (token);
668         int idx = mono_metadata_token_index (token);
669         guint32 cols [MONO_MEMBERREF_SIZE];
670         MonoMethodSignature *sig, *prev_sig;
671         const char *ptr;
672
673         /* !table is for wrappers: we should really assign their own token to them */
674         if (!table || table == MONO_TABLE_METHOD)
675                 return mono_method_signature (method);
676
677         if (table == MONO_TABLE_METHODSPEC) {
678                 g_assert (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) &&
679                           mono_method_signature (method));
680                 g_assert (method->is_inflated);
681
682                 return mono_method_signature (method);
683         }
684
685         if (method->klass->generic_class)
686                 return mono_method_signature (method);
687
688         if (image->dynamic)
689                 /* FIXME: This might be incorrect for vararg methods */
690                 return mono_method_signature (method);
691
692         mono_loader_lock ();
693         sig = g_hash_table_lookup (image->memberref_signatures, GUINT_TO_POINTER (token));
694         mono_loader_unlock ();
695         if (!sig) {
696                 mono_metadata_decode_row (&image->tables [MONO_TABLE_MEMBERREF], idx-1, cols, MONO_MEMBERREF_SIZE);
697
698                 ptr = mono_metadata_blob_heap (image, cols [MONO_MEMBERREF_SIGNATURE]);
699                 mono_metadata_decode_blob_size (ptr, &ptr);
700                 sig = mono_metadata_parse_method_signature (image, 0, ptr, NULL);
701
702                 mono_loader_lock ();
703                 prev_sig = g_hash_table_lookup (image->memberref_signatures, GUINT_TO_POINTER (token));
704                 if (prev_sig) {
705                         /* Somebody got in before us */
706                         sig = prev_sig;
707                 }
708                 else
709                         g_hash_table_insert (image->memberref_signatures, GUINT_TO_POINTER (token), sig);
710                 mono_loader_unlock ();
711         }
712
713         if (context) {
714                 MonoMethodSignature *cached;
715
716                 /* This signature is not owned by a MonoMethod, so need to cache */
717                 sig = inflate_generic_signature (image, sig, context);
718                 cached = mono_metadata_get_inflated_signature (sig, context);
719                 if (cached != sig)
720                         mono_metadata_free_inflated_signature (sig);
721                 sig = cached;
722         }
723
724         return sig;
725 }
726
727 MonoMethodSignature*
728 mono_method_get_signature (MonoMethod *method, MonoImage *image, guint32 token)
729 {
730         return mono_method_get_signature_full (method, image, token, NULL);
731 }
732
733 /* this is only for the typespec array methods */
734 static MonoMethod*
735 search_in_array_class (MonoClass *klass, const char *name, MonoMethodSignature *sig)
736 {
737         int i;
738         for (i = 0; i < klass->method.count; ++i) {
739                 MonoMethod *method = klass->methods [i];
740                 if (strcmp (method->name, name) == 0 && sig->param_count == method->signature->param_count)
741                         return method;
742         }
743         return NULL;
744 }
745
746 static MonoMethod *
747 method_from_memberref (MonoImage *image, guint32 idx, MonoGenericContext *typespec_context,
748                        gboolean *used_context)
749 {
750         MonoClass *klass = NULL;
751         MonoMethod *method = NULL;
752         MonoTableInfo *tables = image->tables;
753         guint32 cols[6];
754         guint32 nindex, class;
755         const char *mname;
756         MonoMethodSignature *sig;
757         const char *ptr;
758
759         mono_metadata_decode_row (&tables [MONO_TABLE_MEMBERREF], idx-1, cols, 3);
760         nindex = cols [MONO_MEMBERREF_CLASS] >> MONO_MEMBERREF_PARENT_BITS;
761         class = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
762         /*g_print ("methodref: 0x%x 0x%x %s\n", class, nindex,
763                 mono_metadata_string_heap (m, cols [MONO_MEMBERREF_NAME]));*/
764
765         mname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
766
767         /*
768          * Whether we actually used the `typespec_context' or not.
769          * This is used to tell our caller whether or not it's safe to insert the returned
770          * method into a cache.
771          */
772         if (used_context)
773                 *used_context = class == MONO_MEMBERREF_PARENT_TYPESPEC;
774
775         switch (class) {
776         case MONO_MEMBERREF_PARENT_TYPEREF:
777                 klass = mono_class_from_typeref (image, MONO_TOKEN_TYPE_REF | nindex);
778                 if (!klass) {
779                         char *name = mono_class_name_from_token (image, MONO_TOKEN_TYPE_REF | nindex);
780                         g_warning ("Missing method %s in assembly %s, type %s", mname, image->name, name);
781                         mono_loader_set_error_type_load (name, image->assembly_name);
782                         g_free (name);
783                         return NULL;
784                 }
785                 break;
786         case MONO_MEMBERREF_PARENT_TYPESPEC:
787                 /*
788                  * Parse the TYPESPEC in the parent's context.
789                  */
790                 klass = mono_class_get_full (image, MONO_TOKEN_TYPE_SPEC | nindex, typespec_context);
791                 if (!klass) {
792                         char *name = mono_class_name_from_token (image, MONO_TOKEN_TYPE_SPEC | nindex);
793                         g_warning ("Missing method %s in assembly %s, type %s", mname, image->name, name);
794                         mono_loader_set_error_type_load (name, image->assembly_name);
795                         g_free (name);
796                         return NULL;
797                 }
798                 break;
799         case MONO_MEMBERREF_PARENT_TYPEDEF:
800                 klass = mono_class_get (image, MONO_TOKEN_TYPE_DEF | nindex);
801                 if (!klass) {
802                         char *name = mono_class_name_from_token (image, MONO_TOKEN_TYPE_DEF | nindex);
803                         g_warning ("Missing method %s in assembly %s, type %s", mname, image->name, name);
804                         mono_loader_set_error_type_load (name, image->assembly_name);
805                         g_free (name);
806                         return NULL;
807                 }
808                 break;
809         case MONO_MEMBERREF_PARENT_METHODDEF:
810                 return mono_get_method (image, MONO_TOKEN_METHOD_DEF | nindex, NULL);
811                 
812         default:
813                 {
814                         /* This message leaks */
815                         char *message = g_strdup_printf ("Memberref parent unknown: class: %d, index %d", class, nindex);
816                         mono_loader_set_error_method_load ("", message);
817                         return NULL;
818                 }
819
820         }
821         g_assert (klass);
822         mono_class_init (klass);
823
824         ptr = mono_metadata_blob_heap (image, cols [MONO_MEMBERREF_SIGNATURE]);
825         mono_metadata_decode_blob_size (ptr, &ptr);
826
827         sig = mono_metadata_parse_method_signature (image, 0, ptr, NULL);
828         if (sig == NULL)
829                 return NULL;
830
831         switch (class) {
832         case MONO_MEMBERREF_PARENT_TYPEREF:
833         case MONO_MEMBERREF_PARENT_TYPEDEF:
834                 method = find_method (klass, NULL, mname, sig, klass);
835                 break;
836
837         case MONO_MEMBERREF_PARENT_TYPESPEC: {
838                 MonoType *type;
839                 MonoMethod *result;
840
841                 type = &klass->byval_arg;
842
843                 if (type->type != MONO_TYPE_ARRAY && type->type != MONO_TYPE_SZARRAY) {
844                         MonoClass *in_class = klass->generic_class ? klass->generic_class->container_class : klass;
845                         method = find_method (in_class, NULL, mname, sig, klass);
846                         break;
847                 }
848
849                 /* we're an array and we created these methods already in klass in mono_class_init () */
850                 result = search_in_array_class (klass, mname, sig);
851                 if (result)
852                         return result;
853
854                 g_assert_not_reached ();
855                 break;
856         }
857         default:
858                 g_error ("Memberref parent unknown: class: %d, index %d", class, nindex);
859                 g_assert_not_reached ();
860         }
861
862         if (!method) {
863                 char *msig = mono_signature_get_desc (sig, FALSE);
864                 char * class_name = mono_type_get_name (&klass->byval_arg);
865                 GString *s = g_string_new (mname);
866                 if (sig->generic_param_count)
867                         g_string_append_printf (s, "<[%d]>", sig->generic_param_count);
868                 g_string_append_printf (s, "(%s)", msig);
869                 g_free (msig);
870                 msig = g_string_free (s, FALSE);
871
872                 g_warning (
873                         "Missing method %s::%s in assembly %s, referenced in assembly %s",
874                         class_name, msig, klass->image->name, image->name);
875                 mono_loader_set_error_method_load (class_name, mname);
876                 g_free (msig);
877                 g_free (class_name);
878         }
879         mono_metadata_free_method_signature (sig);
880
881         return method;
882 }
883
884 static MonoMethod *
885 method_from_methodspec (MonoImage *image, MonoGenericContext *context, guint32 idx)
886 {
887         MonoMethod *method;
888         MonoClass *klass;
889         MonoTableInfo *tables = image->tables;
890         MonoGenericContext new_context;
891         MonoGenericInst *inst;
892         const char *ptr;
893         guint32 cols [MONO_METHODSPEC_SIZE];
894         guint32 token, nindex, param_count;
895
896         mono_metadata_decode_row (&tables [MONO_TABLE_METHODSPEC], idx - 1, cols, MONO_METHODSPEC_SIZE);
897         token = cols [MONO_METHODSPEC_METHOD];
898         nindex = token >> MONO_METHODDEFORREF_BITS;
899
900         ptr = mono_metadata_blob_heap (image, cols [MONO_METHODSPEC_SIGNATURE]);
901
902         mono_metadata_decode_value (ptr, &ptr);
903         ptr++;
904         param_count = mono_metadata_decode_value (ptr, &ptr);
905         g_assert (param_count);
906
907         inst = mono_metadata_parse_generic_inst (image, NULL, param_count, ptr, &ptr);
908         if (context && inst->is_open)
909                 inst = mono_metadata_inflate_generic_inst (inst, context);
910
911         if ((token & MONO_METHODDEFORREF_MASK) == MONO_METHODDEFORREF_METHODDEF)
912                 method = mono_get_method_full (image, MONO_TOKEN_METHOD_DEF | nindex, NULL, context);
913         else
914                 method = method_from_memberref (image, nindex, context, NULL);
915
916         if (!method)
917                 return NULL;
918
919         klass = method->klass;
920
921         if (klass->generic_class) {
922                 g_assert (method->is_inflated);
923                 method = ((MonoMethodInflated *) method)->declaring;
924         }
925
926         new_context.class_inst = klass->generic_class ? klass->generic_class->context.class_inst : NULL;
927         new_context.method_inst = inst;
928
929         return mono_class_inflate_generic_method_full (method, klass, &new_context);
930 }
931
932 struct _MonoDllMap {
933         char *dll;
934         char *target;
935         char *func;
936         char *target_func;
937         MonoDllMap *next;
938 };
939
940 static MonoDllMap *global_dll_map;
941
942 static int 
943 mono_dllmap_lookup_list (MonoDllMap *dll_map, const char *dll, const char* func, const char **rdll, const char **rfunc) {
944         int found = 0;
945
946         *rdll = dll;
947
948         if (!dll_map)
949                 return 0;
950
951         mono_loader_lock ();
952
953         /* 
954          * we use the first entry we find that matches, since entries from
955          * the config file are prepended to the list and we document that the
956          * later entries win.
957          */
958         for (; dll_map; dll_map = dll_map->next) {
959                 if (dll_map->dll [0] == 'i' && dll_map->dll [1] == ':') {
960                         if (g_ascii_strcasecmp (dll_map->dll + 2, dll))
961                                 continue;
962                 } else if (strcmp (dll_map->dll, dll)) {
963                         continue;
964                 }
965                 if (!found && dll_map->target) {
966                         *rdll = dll_map->target;
967                         found = 1;
968                         /* we don't quit here, because we could find a full
969                          * entry that matches also function and that has priority.
970                          */
971                 }
972                 if (dll_map->func && strcmp (dll_map->func, func) == 0) {
973                         *rfunc = dll_map->target_func;
974                         break;
975                 }
976         }
977
978         mono_loader_unlock ();
979         return found;
980 }
981
982 static int 
983 mono_dllmap_lookup (MonoImage *assembly, const char *dll, const char* func, const char **rdll, const char **rfunc)
984 {
985         int res;
986         if (assembly && assembly->dll_map) {
987                 res = mono_dllmap_lookup_list (assembly->dll_map, dll, func, rdll, rfunc);
988                 if (res)
989                         return res;
990         }
991         return mono_dllmap_lookup_list (global_dll_map, dll, func, rdll, rfunc);
992 }
993
994 /*
995  * mono_dllmap_insert:
996  *
997  * LOCKING: Acquires the loader lock.
998  *
999  * NOTE: This can be called before the runtime is initialized, for example from
1000  * mono_config_parse ().
1001  */
1002 void
1003 mono_dllmap_insert (MonoImage *assembly, const char *dll, const char *func, const char *tdll, const char *tfunc)
1004 {
1005         MonoDllMap *entry;
1006
1007         mono_loader_init ();
1008
1009         mono_loader_lock ();
1010
1011         if (!assembly) {
1012                 entry = g_malloc0 (sizeof (MonoDllMap));
1013                 entry->dll = dll? g_strdup (dll): NULL;
1014                 entry->target = tdll? g_strdup (tdll): NULL;
1015                 entry->func = func? g_strdup (func): NULL;
1016                 entry->target_func = tfunc? g_strdup (tfunc): NULL;
1017                 entry->next = global_dll_map;
1018                 global_dll_map = entry;
1019         } else {
1020                 entry = mono_image_alloc0 (assembly, sizeof (MonoDllMap));
1021                 entry->dll = dll? mono_image_strdup (assembly, dll): NULL;
1022                 entry->target = tdll? mono_image_strdup (assembly, tdll): NULL;
1023                 entry->func = func? mono_image_strdup (assembly, func): NULL;
1024                 entry->target_func = tfunc? mono_image_strdup (assembly, tfunc): NULL;
1025                 entry->next = assembly->dll_map;
1026                 assembly->dll_map = entry;
1027         }
1028
1029         mono_loader_unlock ();
1030 }
1031
1032 static GHashTable *global_module_map;
1033
1034 static MonoDl*
1035 cached_module_load (const char *name, int flags, char **err)
1036 {
1037         MonoDl *res;
1038         mono_loader_lock ();
1039         if (!global_module_map)
1040                 global_module_map = g_hash_table_new (g_str_hash, g_str_equal);
1041         res = g_hash_table_lookup (global_module_map, name);
1042         if (res) {
1043                 *err = NULL;
1044                 mono_loader_unlock ();
1045                 return res;
1046         }
1047         res = mono_dl_open (name, flags, err);
1048         if (res)
1049                 g_hash_table_insert (global_module_map, g_strdup (name), res);
1050         mono_loader_unlock ();
1051         return res;
1052 }
1053
1054 gpointer
1055 mono_lookup_pinvoke_call (MonoMethod *method, const char **exc_class, const char **exc_arg)
1056 {
1057         MonoImage *image = method->klass->image;
1058         MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)method;
1059         MonoTableInfo *tables = image->tables;
1060         MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
1061         MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
1062         guint32 im_cols [MONO_IMPLMAP_SIZE];
1063         guint32 scope_token;
1064         const char *import = NULL;
1065         const char *orig_scope;
1066         const char *new_scope;
1067         char *error_msg;
1068         char *full_name, *file_name;
1069         int i;
1070         MonoDl *module = NULL;
1071
1072         g_assert (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL);
1073
1074         if (piinfo->addr)
1075                 return piinfo->addr;
1076
1077         if (method->klass->image->dynamic) {
1078                 MonoReflectionMethodAux *method_aux = 
1079                         g_hash_table_lookup (
1080                                 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
1081                 if (!method_aux)
1082                         return NULL;
1083
1084                 import = method_aux->dllentry;
1085                 orig_scope = method_aux->dll;
1086         }
1087         else {
1088                 if (!piinfo->implmap_idx)
1089                         return NULL;
1090
1091                 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
1092
1093                 piinfo->piflags = im_cols [MONO_IMPLMAP_FLAGS];
1094                 import = mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]);
1095                 scope_token = mono_metadata_decode_row_col (mr, im_cols [MONO_IMPLMAP_SCOPE] - 1, MONO_MODULEREF_NAME);
1096                 orig_scope = mono_metadata_string_heap (image, scope_token);
1097         }
1098
1099         mono_dllmap_lookup (image, orig_scope, import, &new_scope, &import);
1100
1101         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1102                         "DllImport attempting to load: '%s'.", new_scope);
1103
1104         if (exc_class) {
1105                 *exc_class = NULL;
1106                 *exc_arg = NULL;
1107         }
1108
1109         /* we allow a special name to dlopen from the running process namespace */
1110         if (strcmp (new_scope, "__Internal") == 0)
1111                 module = mono_dl_open (NULL, MONO_DL_LAZY, &error_msg);
1112
1113         /*
1114          * Try loading the module using a variety of names
1115          */
1116         for (i = 0; i < 4; ++i) {
1117                 switch (i) {
1118                 case 0:
1119                         /* Try the original name */
1120                         file_name = g_strdup (new_scope);
1121                         break;
1122                 case 1:
1123                         /* Try trimming the .dll extension */
1124                         if (strstr (new_scope, ".dll") == (new_scope + strlen (new_scope) - 4)) {
1125                                 file_name = g_strdup (new_scope);
1126                                 file_name [strlen (new_scope) - 4] = '\0';
1127                         }
1128                         else
1129                                 continue;
1130                         break;
1131                 case 2:
1132                         if (strstr (new_scope, "lib") != new_scope) {
1133                                 file_name = g_strdup_printf ("lib%s", new_scope);
1134                         }
1135                         else
1136                                 continue;
1137                         break;
1138                 default:
1139 #ifndef PLATFORM_WIN32
1140                         if (!g_ascii_strcasecmp ("user32.dll", new_scope) ||
1141                             !g_ascii_strcasecmp ("kernel32.dll", new_scope) ||
1142                             !g_ascii_strcasecmp ("user32", new_scope) ||
1143                             !g_ascii_strcasecmp ("kernel", new_scope)) {
1144                                 file_name = g_strdup ("libMonoSupportW.so");
1145                         } else
1146 #endif
1147                                     continue;
1148 #ifndef PLATFORM_WIN32
1149                         break;
1150 #endif
1151                 }
1152
1153                 if (!module) {
1154                         void *iter = NULL;
1155                         while ((full_name = mono_dl_build_path (NULL, file_name, &iter))) {
1156                                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1157                                                 "DllImport loading location: '%s'.", full_name);
1158                                 module = cached_module_load (full_name, MONO_DL_LAZY, &error_msg);
1159                                 if (!module) {
1160                                         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1161                                                         "DllImport error loading library: '%s'.",
1162                                                         error_msg);
1163                                         g_free (error_msg);
1164                                 }
1165                                 g_free (full_name);
1166                                 if (module)
1167                                         break;
1168                         }
1169                 }
1170
1171                 if (!module) {
1172                         void *iter = NULL;
1173                         while ((full_name = mono_dl_build_path (".", file_name, &iter))) {
1174                                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1175                                         "DllImport loading library: '%s'.", full_name);
1176                                 module = cached_module_load (full_name, MONO_DL_LAZY, &error_msg);
1177                                 if (!module) {
1178                                         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1179                                                 "DllImport error loading library '%s'.",
1180                                                 error_msg);
1181                                         g_free (error_msg);
1182                                 }
1183                                 g_free (full_name);
1184                                 if (module)
1185                                         break;
1186                         }
1187                 }
1188
1189                 if (!module) {
1190                         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1191                                         "DllImport loading: '%s'.", file_name);
1192                         module = cached_module_load (file_name, MONO_DL_LAZY, &error_msg);
1193                         if (!module) {
1194                                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1195                                                 "DllImport error loading library '%s'.",
1196                                                 error_msg);
1197                         }
1198                 }
1199
1200                 g_free (file_name);
1201
1202                 if (module)
1203                         break;
1204         }
1205
1206         if (!module) {
1207                 mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_DLLIMPORT,
1208                                 "DllImport unable to load library '%s'.",
1209                                 error_msg);
1210                 g_free (error_msg);
1211
1212                 if (exc_class) {
1213                         *exc_class = "DllNotFoundException";
1214                         *exc_arg = new_scope;
1215                 }
1216                 return NULL;
1217         }
1218
1219         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1220                                 "Searching for '%s'.", import);
1221
1222         if (piinfo->piflags & PINVOKE_ATTRIBUTE_NO_MANGLE) {
1223                 error_msg = mono_dl_symbol (module, import, &piinfo->addr); 
1224         } else {
1225                 char *mangled_name = NULL, *mangled_name2 = NULL;
1226                 int mangle_charset;
1227                 int mangle_stdcall;
1228                 int mangle_param_count;
1229 #ifdef PLATFORM_WIN32
1230                 int param_count;
1231 #endif
1232
1233                 /*
1234                  * Search using a variety of mangled names
1235                  */
1236                 for (mangle_charset = 0; mangle_charset <= 1; mangle_charset ++) {
1237                         for (mangle_stdcall = 0; mangle_stdcall <= 1; mangle_stdcall ++) {
1238                                 gboolean need_param_count = FALSE;
1239 #ifdef PLATFORM_WIN32
1240                                 if (mangle_stdcall > 0)
1241                                         need_param_count = TRUE;
1242 #endif
1243                                 for (mangle_param_count = 0; mangle_param_count <= (need_param_count ? 256 : 0); mangle_param_count += 4) {
1244
1245                                         if (piinfo->addr)
1246                                                 continue;
1247
1248                                         mangled_name = (char*)import;
1249                                         switch (piinfo->piflags & PINVOKE_ATTRIBUTE_CHAR_SET_MASK) {
1250                                         case PINVOKE_ATTRIBUTE_CHAR_SET_UNICODE:
1251                                                 /* Try the mangled name first */
1252                                                 if (mangle_charset == 0)
1253                                                         mangled_name = g_strconcat (import, "W", NULL);
1254                                                 break;
1255                                         case PINVOKE_ATTRIBUTE_CHAR_SET_AUTO:
1256 #ifdef PLATFORM_WIN32
1257                                                 if (mangle_charset == 0)
1258                                                         mangled_name = g_strconcat (import, "W", NULL);
1259 #else
1260                                                 /* Try the mangled name last */
1261                                                 if (mangle_charset == 1)
1262                                                         mangled_name = g_strconcat (import, "A", NULL);
1263 #endif
1264                                                 break;
1265                                         case PINVOKE_ATTRIBUTE_CHAR_SET_ANSI:
1266                                         default:
1267                                                 /* Try the mangled name last */
1268                                                 if (mangle_charset == 1)
1269                                                         mangled_name = g_strconcat (import, "A", NULL);
1270                                                 break;
1271                                         }
1272
1273 #ifdef PLATFORM_WIN32
1274                                         if (mangle_param_count == 0)
1275                                                 param_count = mono_method_signature (method)->param_count * sizeof (gpointer);
1276                                         else
1277                                                 /* Try brute force, since it would be very hard to compute the stack usage correctly */
1278                                                 param_count = mangle_param_count;
1279
1280                                         /* Try the stdcall mangled name */
1281                                         /* 
1282                                          * gcc under windows creates mangled names without the underscore, but MS.NET
1283                                          * doesn't support it, so we doesn't support it either.
1284                                          */
1285                                         if (mangle_stdcall == 1)
1286                                                 mangled_name2 = g_strdup_printf ("_%s@%d", mangled_name, param_count);
1287                                         else
1288                                                 mangled_name2 = mangled_name;
1289 #else
1290                                         mangled_name2 = mangled_name;
1291 #endif
1292
1293                                         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1294                                                                 "Probing '%s'.", mangled_name2);
1295
1296                                         error_msg = mono_dl_symbol (module, mangled_name2, &piinfo->addr);
1297
1298                                         if (piinfo->addr)
1299                                                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1300                                                                         "Found as '%s'.", mangled_name2);
1301
1302                                         if (mangled_name != mangled_name2)
1303                                                 g_free (mangled_name2);
1304                                         if (mangled_name != import)
1305                                                 g_free (mangled_name);
1306                                 }
1307                         }
1308                 }
1309         }
1310
1311         if (!piinfo->addr) {
1312                 g_free (error_msg);
1313                 if (exc_class) {
1314                         *exc_class = "EntryPointNotFoundException";
1315                         *exc_arg = import;
1316                 }
1317                 return NULL;
1318         }
1319         return piinfo->addr;
1320 }
1321
1322 /*
1323  * LOCKING: assumes the loader lock to be taken.
1324  */
1325 static MonoMethod *
1326 mono_get_method_from_token (MonoImage *image, guint32 token, MonoClass *klass,
1327                             MonoGenericContext *context, gboolean *used_context)
1328 {
1329         MonoMethod *result;
1330         int table = mono_metadata_token_table (token);
1331         int idx = mono_metadata_token_index (token);
1332         MonoTableInfo *tables = image->tables;
1333         MonoGenericContainer *generic_container = NULL, *container = NULL;
1334         const char *sig = NULL;
1335         int size, i;
1336         guint32 cols [MONO_TYPEDEF_SIZE];
1337
1338         if (image->dynamic) {
1339                 MonoClass *handle_class;
1340
1341                 result = mono_lookup_dynamic_token_class (image, token, TRUE, &handle_class, context);
1342                 // This checks the memberref type as well
1343                 if (result && handle_class != mono_defaults.methodhandle_class) {
1344                         mono_loader_set_error_bad_image (g_strdup ("Bad method token."));
1345                         return NULL;
1346                 }
1347                 return result;
1348         }
1349
1350         if (table != MONO_TABLE_METHOD) {
1351                 if (table == MONO_TABLE_METHODSPEC) {
1352                         if (used_context) *used_context = TRUE;
1353                         return method_from_methodspec (image, context, idx);
1354                 }
1355                 if (table != MONO_TABLE_MEMBERREF)
1356                         g_print("got wrong token: 0x%08x\n", token);
1357                 g_assert (table == MONO_TABLE_MEMBERREF);
1358                 return method_from_memberref (image, idx, context, used_context);
1359         }
1360
1361         if (used_context) *used_context = FALSE;
1362
1363         if (idx > image->tables [MONO_TABLE_METHOD].rows) {
1364                 mono_loader_set_error_bad_image (g_strdup ("Bad method token."));
1365                 return NULL;
1366         }
1367
1368         mono_metadata_decode_row (&image->tables [MONO_TABLE_METHOD], idx - 1, cols, 6);
1369
1370         if ((cols [2] & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
1371             (cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))
1372                 result = (MonoMethod *)mono_image_alloc0 (image, sizeof (MonoMethodPInvoke));
1373         else
1374                 result = (MonoMethod *)mono_image_alloc0 (image, sizeof (MonoMethodNormal));
1375
1376         mono_stats.method_count ++;
1377
1378         if (!klass) {
1379                 guint32 type = mono_metadata_typedef_from_method (image, token);
1380                 klass = mono_class_get (image, MONO_TOKEN_TYPE_DEF | type);
1381                 if (klass == NULL)
1382                         return NULL;
1383         }
1384
1385         result->slot = -1;
1386         result->klass = klass;
1387         result->flags = cols [2];
1388         result->iflags = cols [1];
1389         result->token = token;
1390         result->name = mono_metadata_string_heap (image, cols [3]);
1391
1392         container = klass->generic_container;
1393         generic_container = mono_metadata_load_generic_params (image, token, container);
1394         if (generic_container) {
1395                 result->is_generic = TRUE;
1396                 generic_container->owner.method = result;
1397
1398                 mono_metadata_load_generic_param_constraints (image, token, generic_container);
1399
1400                 for (i = 0; i < generic_container->type_argc; i++)
1401                         mono_class_from_generic_parameter (&generic_container->type_params [i], image, TRUE);
1402
1403                 container = generic_container;
1404         }
1405
1406
1407         if (!sig) /* already taken from the methodref */
1408                 sig = mono_metadata_blob_heap (image, cols [4]);
1409         size = mono_metadata_decode_blob_size (sig, &sig);
1410
1411         if (cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
1412                 if (result->klass == mono_defaults.string_class && !strcmp (result->name, ".ctor"))
1413                         result->string_ctor = 1;
1414         } else if (cols [2] & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
1415                 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)result;
1416
1417 #ifdef PLATFORM_WIN32
1418                 /* IJW is P/Invoke with a predefined function pointer. */
1419                 if (image->is_module_handle && (cols [1] & METHOD_IMPL_ATTRIBUTE_NATIVE)) {
1420                         piinfo->addr = mono_image_rva_map (image, cols [0]);
1421                         g_assert (piinfo->addr);
1422                 }
1423 #endif
1424                 piinfo->implmap_idx = mono_metadata_implmap_from_method (image, idx - 1);
1425                 /* Native methods can have no map. */
1426                 if (piinfo->implmap_idx)
1427                         piinfo->piflags = mono_metadata_decode_row_col (&tables [MONO_TABLE_IMPLMAP], piinfo->implmap_idx - 1, MONO_IMPLMAP_FLAGS);
1428         }
1429
1430         if (generic_container)
1431                 mono_method_set_generic_container (result, generic_container);
1432
1433         return result;
1434 }
1435
1436 MonoMethod *
1437 mono_get_method (MonoImage *image, guint32 token, MonoClass *klass)
1438 {
1439         return mono_get_method_full (image, token, klass, NULL);
1440 }
1441
1442 static gpointer
1443 get_method_token (gpointer value)
1444 {
1445         MonoMethod *m = (MonoMethod*)value;
1446
1447         return GUINT_TO_POINTER (m->token);
1448 }
1449
1450 MonoMethod *
1451 mono_get_method_full (MonoImage *image, guint32 token, MonoClass *klass,
1452                       MonoGenericContext *context)
1453 {
1454         MonoMethod *result;
1455         gboolean used_context = FALSE;
1456
1457         /* We do everything inside the lock to prevent creation races */
1458
1459         mono_loader_lock ();
1460
1461         if (mono_metadata_token_table (token) == MONO_TABLE_METHOD) {
1462                 if (!image->method_cache)
1463                         image->method_cache = mono_value_hash_table_new (NULL, NULL, get_method_token);
1464                 result = mono_value_hash_table_lookup (image->method_cache, GINT_TO_POINTER (token));
1465         } else {
1466                 if (!image->methodref_cache)
1467                         image->methodref_cache = g_hash_table_new (NULL, NULL);
1468                 result = g_hash_table_lookup (image->methodref_cache, GINT_TO_POINTER (token));
1469         }
1470         if (result) {
1471                 mono_loader_unlock ();
1472                 return result;
1473         }
1474
1475         result = mono_get_method_from_token (image, token, klass, context, &used_context);
1476
1477         //printf ("GET: %s\n", mono_method_full_name (result, TRUE));
1478
1479 #if 0
1480         g_message (G_STRLOC ": %s - %d - %d", mono_method_full_name (result, TRUE),
1481                    result->is_inflated, used_context);
1482 #endif
1483
1484         /*
1485          * `used_context' specifies whether or not mono_get_method_from_token() actually
1486          * used the `context' to get the method.  See bug #80969.
1487          */
1488
1489         if (!used_context && !(result && result->is_inflated) && result) {
1490                 if (mono_metadata_token_table (token) == MONO_TABLE_METHOD) {
1491                         mono_value_hash_table_insert (image->method_cache, GINT_TO_POINTER (token), result);
1492                 } else {
1493                         g_hash_table_insert (image->methodref_cache, GINT_TO_POINTER (token), result);
1494                 }
1495         }
1496
1497         mono_loader_unlock ();
1498
1499         return result;
1500 }
1501
1502 /**
1503  * mono_get_method_constrained:
1504  *
1505  * This is used when JITing the `constrained.' opcode.
1506  *
1507  * This returns two values: the contrained method, which has been inflated
1508  * as the function return value;   And the original CIL-stream method as
1509  * declared in cil_method.  The later is used for verification.
1510  */
1511 MonoMethod *
1512 mono_get_method_constrained (MonoImage *image, guint32 token, MonoClass *constrained_class,
1513                              MonoGenericContext *context, MonoMethod **cil_method)
1514 {
1515         MonoMethod *method, *result;
1516         MonoClass *ic = NULL;
1517         MonoGenericContext *method_context = NULL;
1518         MonoMethodSignature *sig, *original_sig;
1519
1520         mono_loader_lock ();
1521
1522         *cil_method = mono_get_method_from_token (image, token, NULL, context, NULL);
1523         if (!*cil_method) {
1524                 mono_loader_unlock ();
1525                 return NULL;
1526         }
1527
1528         mono_class_init (constrained_class);
1529         method = *cil_method;
1530         original_sig = sig = mono_method_signature (method);
1531
1532         if (method->is_inflated && sig->generic_param_count) {
1533                 MonoMethodInflated *imethod = (MonoMethodInflated *) method;
1534                 sig = mono_method_signature (imethod->declaring);
1535                 method_context = mono_method_get_context (method);
1536
1537                 original_sig = sig;
1538                 /*
1539                  * We must inflate the signature with the class instantiation to work on
1540                  * cases where a class inherit from a generic type and the override replaces
1541                  * and type argument which a concrete type. See #325283.
1542                  */
1543                 if (method_context->class_inst) {
1544                         MonoGenericContext ctx;
1545                         ctx.method_inst = NULL;
1546                         ctx.class_inst = method_context->class_inst;
1547                 
1548                         sig = inflate_generic_signature (method->klass->image, sig, &ctx);
1549                 }
1550         }
1551
1552         if ((constrained_class != method->klass) && (MONO_CLASS_IS_INTERFACE (method->klass)))
1553                 ic = method->klass;
1554
1555         result = find_method (constrained_class, ic, method->name, sig, constrained_class);
1556         if (sig != original_sig)
1557                 mono_metadata_free_inflated_signature (sig);
1558
1559         if (!result) {
1560                 g_warning ("Missing method %s.%s.%s in assembly %s token %x", method->klass->name_space,
1561                            method->klass->name, method->name, image->name, token);
1562                 mono_loader_unlock ();
1563                 return NULL;
1564         }
1565
1566         if (method_context)
1567                 result = mono_class_inflate_generic_method (result, method_context);
1568
1569         mono_loader_unlock ();
1570         return result;
1571 }
1572
1573 void
1574 mono_free_method  (MonoMethod *method)
1575 {
1576         if (mono_profiler_get_events () & MONO_PROFILE_METHOD_EVENTS)
1577                 mono_profiler_method_free (method);
1578         
1579         /* FIXME: This hack will go away when the profiler will support freeing methods */
1580         if (mono_profiler_get_events () != MONO_PROFILE_NONE)
1581                 return;
1582         
1583         if (method->signature) {
1584                 /* 
1585                  * FIXME: This causes crashes because the types inside signatures and
1586                  * locals are shared.
1587                  */
1588                 /* mono_metadata_free_method_signature (method->signature); */
1589                 /* g_free (method->signature); */
1590         }
1591         
1592         if (method->dynamic) {
1593                 MonoMethodWrapper *mw = (MonoMethodWrapper*)method;
1594                 int i;
1595
1596                 mono_loader_lock ();
1597                 mono_property_hash_remove_object (method->klass->image->property_hash, method);
1598                 mono_loader_unlock ();
1599
1600                 g_free ((char*)method->name);
1601                 if (mw->method.header) {
1602                         g_free ((char*)mw->method.header->code);
1603                         for (i = 0; i < mw->method.header->num_locals; ++i)
1604                                 g_free (mw->method.header->locals [i]);
1605                         g_free (mw->method.header->clauses);
1606                         g_free (mw->method.header);
1607                 }
1608                 g_free (mw->method_data);
1609                 g_free (method->signature);
1610                 g_free (method);
1611         }
1612 }
1613
1614 void
1615 mono_method_get_param_names (MonoMethod *method, const char **names)
1616 {
1617         int i, lastp;
1618         MonoClass *klass;
1619         MonoTableInfo *methodt;
1620         MonoTableInfo *paramt;
1621         guint32 idx;
1622
1623         if (method->is_inflated)
1624                 method = ((MonoMethodInflated *) method)->declaring;
1625
1626         if (!mono_method_signature (method)->param_count)
1627                 return;
1628         for (i = 0; i < mono_method_signature (method)->param_count; ++i)
1629                 names [i] = "";
1630
1631         klass = method->klass;
1632         if (klass->rank)
1633                 return;
1634
1635         mono_class_init (klass);
1636
1637         if (klass->image->dynamic) {
1638                 MonoReflectionMethodAux *method_aux = 
1639                         g_hash_table_lookup (
1640                                 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
1641                 if (method_aux && method_aux->param_names) {
1642                         for (i = 0; i < mono_method_signature (method)->param_count; ++i)
1643                                 if (method_aux->param_names [i + 1])
1644                                         names [i] = method_aux->param_names [i + 1];
1645                 }
1646                 return;
1647         }
1648
1649         methodt = &klass->image->tables [MONO_TABLE_METHOD];
1650         paramt = &klass->image->tables [MONO_TABLE_PARAM];
1651         idx = mono_method_get_index (method);
1652         if (idx > 0) {
1653                 guint32 cols [MONO_PARAM_SIZE];
1654                 guint param_index;
1655
1656                 param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
1657
1658                 if (idx < methodt->rows)
1659                         lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
1660                 else
1661                         lastp = paramt->rows + 1;
1662                 for (i = param_index; i < lastp; ++i) {
1663                         mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
1664                         if (cols [MONO_PARAM_SEQUENCE]) /* skip return param spec */
1665                                 names [cols [MONO_PARAM_SEQUENCE] - 1] = mono_metadata_string_heap (klass->image, cols [MONO_PARAM_NAME]);
1666                 }
1667                 return;
1668         }
1669 }
1670
1671 guint32
1672 mono_method_get_param_token (MonoMethod *method, int index)
1673 {
1674         MonoClass *klass = method->klass;
1675         MonoTableInfo *methodt;
1676         guint32 idx;
1677
1678         mono_class_init (klass);
1679
1680         if (klass->image->dynamic) {
1681                 g_assert_not_reached ();
1682         }
1683
1684         methodt = &klass->image->tables [MONO_TABLE_METHOD];
1685         idx = mono_method_get_index (method);
1686         if (idx > 0) {
1687                 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
1688
1689                 if (index == -1)
1690                         /* Return value */
1691                         return mono_metadata_make_token (MONO_TABLE_PARAM, 0);
1692                 else
1693                         return mono_metadata_make_token (MONO_TABLE_PARAM, param_index + index);
1694         }
1695
1696         return 0;
1697 }
1698
1699 void
1700 mono_method_get_marshal_info (MonoMethod *method, MonoMarshalSpec **mspecs)
1701 {
1702         int i, lastp;
1703         MonoClass *klass = method->klass;
1704         MonoTableInfo *methodt;
1705         MonoTableInfo *paramt;
1706         guint32 idx;
1707
1708         for (i = 0; i < mono_method_signature (method)->param_count + 1; ++i)
1709                 mspecs [i] = NULL;
1710
1711         if (method->klass->image->dynamic) {
1712                 MonoReflectionMethodAux *method_aux = 
1713                         g_hash_table_lookup (
1714                                 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
1715                 if (method_aux && method_aux->param_marshall) {
1716                         MonoMarshalSpec **dyn_specs = method_aux->param_marshall;
1717                         for (i = 0; i < mono_method_signature (method)->param_count + 1; ++i)
1718                                 if (dyn_specs [i]) {
1719                                         mspecs [i] = g_new0 (MonoMarshalSpec, 1);
1720                                         memcpy (mspecs [i], dyn_specs [i], sizeof (MonoMarshalSpec));
1721                                 }
1722                 }
1723                 return;
1724         }
1725
1726         mono_class_init (klass);
1727
1728         methodt = &klass->image->tables [MONO_TABLE_METHOD];
1729         paramt = &klass->image->tables [MONO_TABLE_PARAM];
1730         idx = mono_method_get_index (method);
1731         if (idx > 0) {
1732                 guint32 cols [MONO_PARAM_SIZE];
1733                 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
1734
1735                 if (idx < methodt->rows)
1736                         lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
1737                 else
1738                         lastp = paramt->rows + 1;
1739
1740                 for (i = param_index; i < lastp; ++i) {
1741                         mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
1742
1743                         if (cols [MONO_PARAM_FLAGS] & PARAM_ATTRIBUTE_HAS_FIELD_MARSHAL) {
1744                                 const char *tp;
1745                                 tp = mono_metadata_get_marshal_info (klass->image, i - 1, FALSE);
1746                                 g_assert (tp);
1747                                 mspecs [cols [MONO_PARAM_SEQUENCE]]= mono_metadata_parse_marshal_spec (klass->image, tp);
1748                         }
1749                 }
1750
1751                 return;
1752         }
1753 }
1754
1755 gboolean
1756 mono_method_has_marshal_info (MonoMethod *method)
1757 {
1758         int i, lastp;
1759         MonoClass *klass = method->klass;
1760         MonoTableInfo *methodt;
1761         MonoTableInfo *paramt;
1762         guint32 idx;
1763
1764         if (method->klass->image->dynamic) {
1765                 MonoReflectionMethodAux *method_aux = 
1766                         g_hash_table_lookup (
1767                                 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
1768                 MonoMarshalSpec **dyn_specs = method_aux->param_marshall;
1769                 if (dyn_specs) {
1770                         for (i = 0; i < mono_method_signature (method)->param_count + 1; ++i)
1771                                 if (dyn_specs [i])
1772                                         return TRUE;
1773                 }
1774                 return FALSE;
1775         }
1776
1777         mono_class_init (klass);
1778
1779         methodt = &klass->image->tables [MONO_TABLE_METHOD];
1780         paramt = &klass->image->tables [MONO_TABLE_PARAM];
1781         idx = mono_method_get_index (method);
1782         if (idx > 0) {
1783                 guint32 cols [MONO_PARAM_SIZE];
1784                 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
1785
1786                 if (idx + 1 < methodt->rows)
1787                         lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
1788                 else
1789                         lastp = paramt->rows + 1;
1790
1791                 for (i = param_index; i < lastp; ++i) {
1792                         mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
1793
1794                         if (cols [MONO_PARAM_FLAGS] & PARAM_ATTRIBUTE_HAS_FIELD_MARSHAL)
1795                                 return TRUE;
1796                 }
1797                 return FALSE;
1798         }
1799         return FALSE;
1800 }
1801
1802 gpointer
1803 mono_method_get_wrapper_data (MonoMethod *method, guint32 id)
1804 {
1805         void **data;
1806         g_assert (method != NULL);
1807         g_assert (method->wrapper_type != MONO_WRAPPER_NONE);
1808
1809         data = ((MonoMethodWrapper *)method)->method_data;
1810         g_assert (data != NULL);
1811         g_assert (id <= GPOINTER_TO_UINT (*data));
1812         return data [id];
1813 }
1814
1815 static void
1816 default_stack_walk (MonoStackWalk func, gboolean do_il_offset, gpointer user_data) {
1817         g_error ("stack walk not installed");
1818 }
1819
1820 static MonoStackWalkImpl stack_walk = default_stack_walk;
1821
1822 void
1823 mono_stack_walk (MonoStackWalk func, gpointer user_data)
1824 {
1825         stack_walk (func, TRUE, user_data);
1826 }
1827
1828 void
1829 mono_stack_walk_no_il (MonoStackWalk func, gpointer user_data)
1830 {
1831         stack_walk (func, FALSE, user_data);
1832 }
1833
1834 void
1835 mono_install_stack_walk (MonoStackWalkImpl func)
1836 {
1837         stack_walk = func;
1838 }
1839
1840 static gboolean
1841 last_managed (MonoMethod *m, gint no, gint ilo, gboolean managed, gpointer data)
1842 {
1843         MonoMethod **dest = data;
1844         *dest = m;
1845         /*g_print ("In %s::%s [%d] [%d]\n", m->klass->name, m->name, no, ilo);*/
1846
1847         return managed;
1848 }
1849
1850 MonoMethod*
1851 mono_method_get_last_managed (void)
1852 {
1853         MonoMethod *m = NULL;
1854         stack_walk (last_managed, FALSE, &m);
1855         return m;
1856 }
1857
1858 void
1859 mono_loader_lock (void)
1860 {
1861         EnterCriticalSection (&loader_mutex);
1862 }
1863
1864 void
1865 mono_loader_unlock (void)
1866 {
1867         LeaveCriticalSection (&loader_mutex);
1868 }
1869
1870 /**
1871  * mono_method_signature:
1872  *
1873  * Return the signature of the method M. On failure, returns NULL.
1874  */
1875 MonoMethodSignature*
1876 mono_method_signature (MonoMethod *m)
1877 {
1878         int idx;
1879         int size;
1880         MonoImage* img;
1881         const char *sig;
1882         gboolean can_cache_signature;
1883         MonoGenericContainer *container;
1884         MonoMethodSignature *signature = NULL;
1885         int *pattrs;
1886
1887         /* We need memory barriers below because of the double-checked locking pattern */ 
1888
1889         if (m->signature)
1890                 return m->signature;
1891
1892         mono_loader_lock ();
1893
1894         if (m->signature) {
1895                 mono_loader_unlock ();
1896                 return m->signature;
1897         }
1898
1899         if (m->is_inflated) {
1900                 MonoMethodInflated *imethod = (MonoMethodInflated *) m;
1901                 /* the lock is recursive */
1902                 signature = mono_method_signature (imethod->declaring);
1903                 signature = inflate_generic_signature (imethod->declaring->klass->image, signature, mono_method_get_context (m));
1904                 mono_memory_barrier ();
1905                 m->signature = signature;
1906                 mono_loader_unlock ();
1907                 return m->signature;
1908         }
1909
1910         g_assert (mono_metadata_token_table (m->token) == MONO_TABLE_METHOD);
1911         idx = mono_metadata_token_index (m->token);
1912         img = m->klass->image;
1913
1914         sig = mono_metadata_blob_heap (img, mono_metadata_decode_row_col (&img->tables [MONO_TABLE_METHOD], idx - 1, MONO_METHOD_SIGNATURE));
1915
1916         g_assert (!m->klass->generic_class);
1917         container = mono_method_get_generic_container (m);
1918         if (!container)
1919                 container = m->klass->generic_container;
1920
1921         /* Generic signatures depend on the container so they cannot be cached */
1922         /* icall/pinvoke signatures cannot be cached cause we modify them below */
1923         can_cache_signature = !(m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && !(m->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) && !container;
1924
1925         /* If the method has parameter attributes, that can modify the signature */
1926         pattrs = mono_metadata_get_param_attrs (img, idx);
1927         if (pattrs) {
1928                 can_cache_signature = FALSE;
1929                 g_free (pattrs);
1930         }
1931
1932         if (can_cache_signature)
1933                 signature = g_hash_table_lookup (img->method_signatures, sig);
1934
1935         if (!signature) {
1936                 const char *sig_body;
1937
1938                 size = mono_metadata_decode_blob_size (sig, &sig_body);
1939
1940                 signature = mono_metadata_parse_method_signature_full (img, container, idx, sig_body, NULL);
1941                 if (!signature) {
1942                         mono_loader_unlock ();
1943                         return NULL;
1944                 }
1945
1946                 if (can_cache_signature)
1947                         g_hash_table_insert (img->method_signatures, (gpointer)sig, signature);
1948         }
1949
1950         /* Verify metadata consistency */
1951         if (signature->generic_param_count) {
1952                 if (!container || !container->is_method)
1953                         g_error ("Signature claims method has generic parameters, but generic_params table says it doesn't");
1954                 if (container->type_argc != signature->generic_param_count)
1955                         g_error ("Inconsistent generic parameter count.  Signature says %d, generic_params table says %d",
1956                                  signature->generic_param_count, container->type_argc);
1957         } else if (container && container->is_method && container->type_argc)
1958                 g_error ("generic_params table claims method has generic parameters, but signature says it doesn't");
1959
1960         if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
1961                 signature->pinvoke = 1;
1962         else if (m->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
1963                 MonoCallConvention conv = 0;
1964                 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)m;
1965                 signature->pinvoke = 1;
1966
1967                 switch (piinfo->piflags & PINVOKE_ATTRIBUTE_CALL_CONV_MASK) {
1968                 case 0: /* no call conv, so using default */
1969                 case PINVOKE_ATTRIBUTE_CALL_CONV_WINAPI:
1970                         conv = MONO_CALL_DEFAULT;
1971                         break;
1972                 case PINVOKE_ATTRIBUTE_CALL_CONV_CDECL:
1973                         conv = MONO_CALL_C;
1974                         break;
1975                 case PINVOKE_ATTRIBUTE_CALL_CONV_STDCALL:
1976                         conv = MONO_CALL_STDCALL;
1977                         break;
1978                 case PINVOKE_ATTRIBUTE_CALL_CONV_THISCALL:
1979                         conv = MONO_CALL_THISCALL;
1980                         break;
1981                 case PINVOKE_ATTRIBUTE_CALL_CONV_FASTCALL:
1982                         conv = MONO_CALL_FASTCALL;
1983                         break;
1984                 case PINVOKE_ATTRIBUTE_CALL_CONV_GENERIC:
1985                 case PINVOKE_ATTRIBUTE_CALL_CONV_GENERICINST:
1986                 default:
1987                         g_warning ("unsupported calling convention : 0x%04x", piinfo->piflags);
1988                         g_assert_not_reached ();
1989                 }
1990                 signature->call_convention = conv;
1991         }
1992
1993         mono_memory_barrier ();
1994         m->signature = signature;
1995
1996         mono_loader_unlock ();
1997         return m->signature;
1998 }
1999
2000 const char*
2001 mono_method_get_name (MonoMethod *method)
2002 {
2003         return method->name;
2004 }
2005
2006 MonoClass*
2007 mono_method_get_class (MonoMethod *method)
2008 {
2009         return method->klass;
2010 }
2011
2012 guint32
2013 mono_method_get_token (MonoMethod *method)
2014 {
2015         return method->token;
2016 }
2017
2018 MonoMethodHeader*
2019 mono_method_get_header (MonoMethod *method)
2020 {
2021         int idx;
2022         guint32 rva;
2023         MonoImage* img;
2024         gpointer loc;
2025         MonoMethodNormal* mn = (MonoMethodNormal*) method;
2026
2027         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))
2028                 return NULL;
2029
2030 #ifdef G_LIKELY
2031         if (G_LIKELY (mn->header))
2032 #else
2033         if (mn->header)
2034 #endif
2035                 return mn->header;
2036
2037         mono_loader_lock ();
2038
2039         if (mn->header) {
2040                 mono_loader_unlock ();
2041                 return mn->header;
2042         }
2043
2044         if (method->is_inflated) {
2045                 MonoMethodInflated *imethod = (MonoMethodInflated *) method;
2046                 MonoMethodHeader *header;
2047                 /* the lock is recursive */
2048                 header = mono_method_get_header (imethod->declaring);
2049                 mn->header = inflate_generic_header (header, mono_method_get_context (method));
2050                 mono_loader_unlock ();
2051                 return mn->header;
2052         }
2053
2054         g_assert (mono_metadata_token_table (method->token) == MONO_TABLE_METHOD);
2055         idx = mono_metadata_token_index (method->token);
2056         img = method->klass->image;
2057         rva = mono_metadata_decode_row_col (&img->tables [MONO_TABLE_METHOD], idx - 1, MONO_METHOD_RVA);
2058         loc = mono_image_rva_map (img, rva);
2059
2060         g_assert (loc);
2061
2062         mn->header = mono_metadata_parse_mh_full (img, mono_method_get_generic_container (method), loc);
2063
2064         mono_loader_unlock ();
2065         return mn->header;
2066 }
2067
2068 guint32
2069 mono_method_get_flags (MonoMethod *method, guint32 *iflags)
2070 {
2071         if (iflags)
2072                 *iflags = method->iflags;
2073         return method->flags;
2074 }
2075
2076 /*
2077  * Find the method index in the metadata methodDef table.
2078  */
2079 guint32
2080 mono_method_get_index (MonoMethod *method) {
2081         MonoClass *klass = method->klass;
2082         int i;
2083
2084         if (method->token)
2085                 return mono_metadata_token_index (method->token);
2086
2087         mono_class_setup_methods (klass);
2088         for (i = 0; i < klass->method.count; ++i) {
2089                 if (method == klass->methods [i]) {
2090                         if (klass->image->uncompressed_metadata)
2091                                 return mono_metadata_translate_token_index (klass->image, MONO_TABLE_METHOD, klass->method.first + i + 1);
2092                         else
2093                                 return klass->method.first + i + 1;
2094                 }
2095         }
2096         return 0;
2097 }
2098