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