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