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