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