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