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