Fri Jan 26 12:00:45 CET 2007 Paolo Molaro <lupus@ximian.com>
[mono.git] / mono / metadata / loader.c
1 /*
2  * loader.c: Image Loader 
3  *
4  * Authors:
5  *   Paolo Molaro (lupus@ximian.com)
6  *   Miguel de Icaza (miguel@ximian.com)
7  *   Patrik Torstensson (patrik.torstensson@labs2.com)
8  *
9  * (C) 2001 Ximian, Inc.
10  * Copyright (C) 2002-2006 Novell, Inc.
11  *
12  * This file is used by the interpreter and the JIT engine to locate
13  * assemblies.  Used to load AssemblyRef and later to resolve various
14  * kinds of `Refs'.
15  *
16  * TODO:
17  *   This should keep track of the assembly versions that we are loading.
18  *
19  */
20 #include <config.h>
21 #include <glib.h>
22 #include <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                 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_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 (image, 0, ptr, NULL);
631
632                 mono_loader_lock ();
633                 prev_sig = g_hash_table_lookup (image->memberref_signatures, GUINT_TO_POINTER (token));
634                 if (prev_sig) {
635                         /* Somebody got in before us */
636                         /* FIXME: Free sig */
637                         sig = prev_sig;
638                 }
639                 else
640                         g_hash_table_insert (image->memberref_signatures, GUINT_TO_POINTER (token), sig);
641                 mono_loader_unlock ();
642         }
643
644         sig = inflate_generic_signature (image, sig, context);
645
646         return sig;
647 }
648
649 MonoMethodSignature*
650 mono_method_get_signature (MonoMethod *method, MonoImage *image, guint32 token)
651 {
652         return mono_method_get_signature_full (method, image, token, NULL);
653 }
654
655 /* this is only for the typespec array methods */
656 static MonoMethod*
657 search_in_array_class (MonoClass *klass, const char *name, MonoMethodSignature *sig)
658 {
659         int i;
660         for (i = 0; i < klass->method.count; ++i) {
661                 MonoMethod *method = klass->methods [i];
662                 if (strcmp (method->name, name) == 0 && sig->param_count == method->signature->param_count)
663                         return method;
664         }
665         return NULL;
666 }
667
668 static MonoMethod *
669 method_from_memberref (MonoImage *image, guint32 idx, MonoGenericContext *typespec_context)
670 {
671         MonoClass *klass = NULL;
672         MonoMethod *method = NULL;
673         MonoTableInfo *tables = image->tables;
674         guint32 cols[6];
675         guint32 nindex, class;
676         const char *mname;
677         MonoMethodSignature *sig;
678         const char *ptr;
679
680         mono_metadata_decode_row (&tables [MONO_TABLE_MEMBERREF], idx-1, cols, 3);
681         nindex = cols [MONO_MEMBERREF_CLASS] >> MONO_MEMBERREF_PARENT_BITS;
682         class = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
683         /*g_print ("methodref: 0x%x 0x%x %s\n", class, nindex,
684                 mono_metadata_string_heap (m, cols [MONO_MEMBERREF_NAME]));*/
685
686         mname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
687
688         switch (class) {
689         case MONO_MEMBERREF_PARENT_TYPEREF:
690                 klass = mono_class_from_typeref (image, MONO_TOKEN_TYPE_REF | nindex);
691                 if (!klass) {
692                         char *name = mono_class_name_from_token (image, MONO_TOKEN_TYPE_REF | nindex);
693                         g_warning ("Missing method %s in assembly %s, type %s", mname, image->name, name);
694                         mono_loader_set_error_method_load (name, mname);
695                         g_free (name);
696                         return NULL;
697                 }
698                 break;
699         case MONO_MEMBERREF_PARENT_TYPESPEC:
700                 /*
701                  * Parse the TYPESPEC in the parent's context.
702                  */
703                 klass = mono_class_get_full (image, MONO_TOKEN_TYPE_SPEC | nindex, typespec_context);
704                 if (!klass) {
705                         char *name = mono_class_name_from_token (image, MONO_TOKEN_TYPE_SPEC | 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_TYPEDEF:
713                 klass = mono_class_get (image, MONO_TOKEN_TYPE_DEF | nindex);
714                 if (!klass) {
715                         char *name = mono_class_name_from_token (image, MONO_TOKEN_TYPE_DEF | nindex);
716                         g_warning ("Missing method %s in assembly %s, type %s", mname, image->name, name);
717                         mono_loader_set_error_method_load (name, mname);
718                         g_free (name);
719                         return NULL;
720                 }
721                 break;
722         case MONO_MEMBERREF_PARENT_METHODDEF:
723                 return mono_get_method (image, MONO_TOKEN_METHOD_DEF | nindex, NULL);
724                 
725         default:
726                 {
727                         /* This message leaks */
728                         char *message = g_strdup_printf ("Memberref parent unknown: class: %d, index %d", class, nindex);
729                         mono_loader_set_error_method_load ("", message);
730                         return NULL;
731                 }
732
733         }
734         g_assert (klass);
735         mono_class_init (klass);
736
737         ptr = mono_metadata_blob_heap (image, cols [MONO_MEMBERREF_SIGNATURE]);
738         mono_metadata_decode_blob_size (ptr, &ptr);
739
740         sig = mono_metadata_parse_method_signature (image, 0, ptr, NULL);
741         if (sig == NULL)
742                 return NULL;
743
744         switch (class) {
745         case MONO_MEMBERREF_PARENT_TYPEREF:
746         case MONO_MEMBERREF_PARENT_TYPEDEF:
747                 method = find_method (klass, NULL, mname, sig, klass);
748                 break;
749
750         case MONO_MEMBERREF_PARENT_TYPESPEC: {
751                 MonoType *type;
752                 MonoMethod *result;
753
754                 type = &klass->byval_arg;
755
756                 if (type->type != MONO_TYPE_ARRAY && type->type != MONO_TYPE_SZARRAY) {
757                         MonoClass *in_class = klass->generic_class ? klass->generic_class->container_class : klass;
758                         method = find_method (in_class, NULL, mname, sig, klass);
759                         break;
760                 }
761
762                 /* we're an array and we created these methods already in klass in mono_class_init () */
763                 result = search_in_array_class (klass, mname, sig);
764                 if (result)
765                         return result;
766
767                 g_assert_not_reached ();
768                 break;
769         }
770         default:
771                 g_error ("Memberref parent unknown: class: %d, index %d", class, nindex);
772                 g_assert_not_reached ();
773         }
774
775         if (!method) {
776                 char *msig = mono_signature_get_desc (sig, FALSE);
777                 char * class_name = mono_type_get_name (&klass->byval_arg);
778                 GString *s = g_string_new (mname);
779                 if (sig->generic_param_count)
780                         g_string_append_printf (s, "<[%d]>", sig->generic_param_count);
781                 g_string_append_printf (s, "(%s)", msig);
782                 g_free (msig);
783                 msig = g_string_free (s, FALSE);
784
785                 g_warning (
786                         "Missing method %s::%s in assembly %s, referenced in assembly %s",
787                         class_name, msig, klass->image->name, image->name);
788                 mono_loader_set_error_method_load (class_name, mname);
789                 g_free (msig);
790                 g_free (class_name);
791         }
792         mono_metadata_free_method_signature (sig);
793
794         return method;
795 }
796
797 static MonoMethod *
798 method_from_methodspec (MonoImage *image, MonoGenericContext *context, guint32 idx)
799 {
800         MonoMethod *method, *inflated;
801         MonoTableInfo *tables = image->tables;
802         MonoGenericContext *new_context = NULL;
803         MonoGenericMethod *gmethod;
804         MonoGenericContainer *container = NULL;
805         const char *ptr;
806         guint32 cols [MONO_METHODSPEC_SIZE];
807         guint32 token, nindex, param_count;
808
809         mono_metadata_decode_row (&tables [MONO_TABLE_METHODSPEC], idx - 1, cols, MONO_METHODSPEC_SIZE);
810         token = cols [MONO_METHODSPEC_METHOD];
811         nindex = token >> MONO_METHODDEFORREF_BITS;
812
813         ptr = mono_metadata_blob_heap (image, cols [MONO_METHODSPEC_SIGNATURE]);
814
815         mono_metadata_decode_value (ptr, &ptr);
816         ptr++;
817         param_count = mono_metadata_decode_value (ptr, &ptr);
818         g_assert (param_count);
819
820         /*
821          * Be careful with the two contexts here:
822          *
823          * ----------------------------------------
824          * class Foo<S> {
825          *   static void Hello<T> (S s, T t) { }
826          *
827          *   static void Test<U> (U u) {
828          *     Foo<U>.Hello<string> (u, "World");
829          *   }
830          * }
831          * ----------------------------------------
832          *
833          * Let's assume we're currently JITing Foo<int>.Test<long>
834          * (ie. `S' is instantiated as `int' and `U' is instantiated as `long').
835          *
836          * The call to Hello() is encoded with a MethodSpec with a TypeSpec as parent
837          * (MONO_MEMBERREF_PARENT_TYPESPEC).
838          *
839          * The TypeSpec is encoded as `Foo<!!0>', so we need to parse it in the current
840          * context (S=int, U=long) to get the correct `Foo<long>'.
841          * 
842          * After that, we parse the memberref signature in the new context
843          * (S=int, T=uninstantiated) and get the open generic method `Foo<long>.Hello<T>'.
844          *
845          */
846         if ((token & MONO_METHODDEFORREF_MASK) == MONO_METHODDEFORREF_METHODDEF)
847                 method = mono_get_method_full (image, MONO_TOKEN_METHOD_DEF | nindex, NULL, context);
848         else
849                 method = method_from_memberref (image, nindex, context);
850
851         method = mono_get_inflated_method (method);
852
853         container = method->generic_container;
854         g_assert (container);
855
856         gmethod = g_new0 (MonoGenericMethod, 1);
857         if (method->klass->generic_class)
858                 gmethod->class_inst = method->klass->generic_class->inst;
859         gmethod->container = container;
860
861         new_context = g_new0 (MonoGenericContext, 1);
862         new_context->gmethod = gmethod;
863         /* FIXME: Is this correct? */
864         if (container->parent)
865                 new_context->class_inst = container->parent->context.class_inst;
866
867         /*
868          * When parsing the methodspec signature, we're in the old context again:
869          *
870          * ----------------------------------------
871          * class Foo {
872          *   static void Hello<T> (T t) { }
873          *
874          *   static void Test<U> (U u) {
875          *     Foo.Hello<U> (u);
876          *   }
877          * }
878          * ----------------------------------------
879          *
880          * Let's assume we're currently JITing "Foo.Test<float>".
881          *
882          * In this case, we already parsed the memberref as "Foo.Hello<T>" and the methodspec
883          * signature is "<!!0>".  This means that we must instantiate the method type parameter
884          * `T' from the new method with the method type parameter `U' from the current context;
885          * ie. instantiate the method as `Foo.Hello<float>.
886          */
887
888         gmethod->inst = mono_metadata_parse_generic_inst (image, NULL, param_count, ptr, &ptr);
889
890         if (context && gmethod->inst->is_open)
891                 gmethod->inst = mono_metadata_inflate_generic_inst (gmethod->inst, context);
892
893         if (!container->method_hash)
894                 container->method_hash = g_hash_table_new (
895                         (GHashFunc)mono_metadata_generic_method_hash, (GEqualFunc)mono_metadata_generic_method_equal);
896
897         inflated = g_hash_table_lookup (container->method_hash, gmethod);
898         if (inflated) {
899                 g_free (gmethod);
900                 g_free (new_context);
901                 return inflated;
902         }
903
904         context = new_context;
905
906         mono_stats.generics_metadata_size += sizeof (MonoGenericMethod) +
907                 sizeof (MonoGenericContext) + param_count * sizeof (MonoType);
908
909         inflated = mono_class_inflate_generic_method_full (method, method->klass, new_context);
910         g_hash_table_insert (container->method_hash, gmethod, inflated);
911
912         return inflated;
913 }
914
915 typedef struct MonoDllMap MonoDllMap;
916
917 struct MonoDllMap {
918         char *name;
919         char *target;
920         char *dll;
921         MonoDllMap *next;
922 };
923
924 static GHashTable *global_dll_map;
925
926 static int 
927 mono_dllmap_lookup_hash (GHashTable *dll_map, const char *dll, const char* func, const char **rdll, const char **rfunc) {
928         MonoDllMap *map, *tmp;
929
930         *rdll = dll;
931
932         if (!dll_map)
933                 return 0;
934
935         mono_loader_lock ();
936
937         map = g_hash_table_lookup (dll_map, dll);
938         if (!map) {
939                 mono_loader_unlock ();
940                 return 0;
941         }
942         *rdll = map->target? map->target: dll;
943
944         for (tmp = map->next; tmp; tmp = tmp->next) {
945                 if (strcmp (func, tmp->name) == 0) {
946                         *rfunc = tmp->name;
947                         if (tmp->dll)
948                                 *rdll = tmp->dll;
949                         mono_loader_unlock ();
950                         return 1;
951                 }
952         }
953         *rfunc = func;
954         mono_loader_unlock ();
955         return 1;
956 }
957
958 static int 
959 mono_dllmap_lookup (MonoImage *assembly, const char *dll, const char* func, const char **rdll, const char **rfunc)
960 {
961         int res;
962         if (assembly && assembly->dll_map) {
963                 res = mono_dllmap_lookup_hash (assembly->dll_map, dll, func, rdll, rfunc);
964                 if (res)
965                         return res;
966         }
967         return mono_dllmap_lookup_hash (global_dll_map, dll, func, rdll, rfunc);
968 }
969
970 void
971 mono_dllmap_insert (MonoImage *assembly, const char *dll, const char *func, const char *tdll, const char *tfunc) {
972         MonoDllMap *map, *entry;
973         GHashTable *dll_map = NULL;
974
975         mono_loader_lock ();
976
977         if (!assembly) {
978                 if (!global_dll_map)
979                         global_dll_map = g_hash_table_new (g_str_hash, g_str_equal);
980                 dll_map = global_dll_map;
981         } else {
982                 if (!assembly->dll_map)
983                         assembly->dll_map = g_hash_table_new (g_str_hash, g_str_equal);
984                 dll_map = assembly->dll_map;
985         }
986
987         map = g_hash_table_lookup (dll_map, dll);
988         if (!map) {
989                 map = g_new0 (MonoDllMap, 1);
990                 map->dll = g_strdup (dll);
991                 if (tdll)
992                         map->target = g_strdup (tdll);
993                 g_hash_table_insert (dll_map, map->dll, map);
994         }
995         if (func) {
996                 entry = g_new0 (MonoDllMap, 1);
997                 entry->name = g_strdup (func);
998                 if (tfunc)
999                         entry->target = g_strdup (tfunc);
1000                 if (tdll && map->target && strcmp (map->target, tdll))
1001                         entry->dll = g_strdup (tdll);
1002                 entry->next = map->next;
1003                 map->next = entry;
1004         }
1005
1006         mono_loader_unlock ();
1007 }
1008
1009 gpointer
1010 mono_lookup_pinvoke_call (MonoMethod *method, const char **exc_class, const char **exc_arg)
1011 {
1012         MonoImage *image = method->klass->image;
1013         MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)method;
1014         MonoTableInfo *tables = image->tables;
1015         MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
1016         MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
1017         guint32 im_cols [MONO_IMPLMAP_SIZE];
1018         guint32 scope_token;
1019         const char *import = NULL;
1020         const char *orig_scope;
1021         const char *new_scope;
1022         char *full_name, *file_name;
1023         int i;
1024         GModule *gmodule = NULL;
1025
1026         g_assert (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL);
1027
1028         if (piinfo->addr)
1029                 return piinfo->addr;
1030
1031         if (method->klass->image->dynamic) {
1032                 MonoReflectionMethodAux *method_aux = 
1033                         g_hash_table_lookup (
1034                                 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
1035                 if (!method_aux)
1036                         return NULL;
1037
1038                 import = method_aux->dllentry;
1039                 orig_scope = method_aux->dll;
1040         }
1041         else {
1042                 if (!piinfo->implmap_idx)
1043                         return NULL;
1044
1045                 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
1046
1047                 piinfo->piflags = im_cols [MONO_IMPLMAP_FLAGS];
1048                 import = mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]);
1049                 scope_token = mono_metadata_decode_row_col (mr, im_cols [MONO_IMPLMAP_SCOPE] - 1, MONO_MODULEREF_NAME);
1050                 orig_scope = mono_metadata_string_heap (image, scope_token);
1051         }
1052
1053         mono_dllmap_lookup (image, orig_scope, import, &new_scope, &import);
1054
1055         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1056                         "DllImport attempting to load: '%s'.", new_scope);
1057
1058         if (exc_class) {
1059                 *exc_class = NULL;
1060                 *exc_arg = NULL;
1061         }
1062
1063         /* we allow a special name to dlopen from the running process namespace */
1064         if (strcmp (new_scope, "__Internal") == 0)
1065                 gmodule = g_module_open (NULL, G_MODULE_BIND_LAZY);
1066
1067         /*
1068          * Try loading the module using a variety of names
1069          */
1070         for (i = 0; i < 4; ++i) {
1071                 switch (i) {
1072                 case 0:
1073                         /* Try the original name */
1074                         file_name = g_strdup (new_scope);
1075                         break;
1076                 case 1:
1077                         /* Try trimming the .dll extension */
1078                         if (strstr (new_scope, ".dll") == (new_scope + strlen (new_scope) - 4)) {
1079                                 file_name = g_strdup (new_scope);
1080                                 file_name [strlen (new_scope) - 4] = '\0';
1081                         }
1082                         else
1083                                 continue;
1084                         break;
1085                 case 2:
1086                         if (strstr (new_scope, "lib") != new_scope) {
1087                                 file_name = g_strdup_printf ("lib%s", new_scope);
1088                         }
1089                         else
1090                                 continue;
1091                         break;
1092                 default:
1093 #ifndef PLATFORM_WIN32
1094                         if (!g_ascii_strcasecmp ("user32.dll", new_scope) ||
1095                             !g_ascii_strcasecmp ("kernel32.dll", new_scope) ||
1096                             !g_ascii_strcasecmp ("user32", new_scope) ||
1097                             !g_ascii_strcasecmp ("kernel", new_scope)) {
1098                                 file_name = g_strdup ("libMonoSupportW.so");
1099                         } else
1100 #endif
1101                                     continue;
1102 #ifndef PLATFORM_WIN32
1103                         break;
1104 #endif
1105                 }
1106
1107                 if (!gmodule) {
1108                         full_name = g_module_build_path (NULL, file_name);
1109                         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1110                                         "DllImport loading location: '%s'.", full_name);
1111                         gmodule = g_module_open (full_name, G_MODULE_BIND_LAZY);
1112                         if (!gmodule) {
1113                                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1114                                                 "DllImport error loading library: '%s'.",
1115                                                 g_module_error ());
1116                         }
1117                         g_free (full_name);
1118                 }
1119
1120                 if (!gmodule) {
1121                         full_name = g_module_build_path (".", file_name);
1122                         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1123                                         "DllImport loading library: '%s'.", full_name);
1124                         gmodule = g_module_open (full_name, G_MODULE_BIND_LAZY);
1125                         if (!gmodule) {
1126                                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1127                                                 "DllImport error loading library '%s'.",
1128                                                 g_module_error ());
1129                         }
1130                         g_free (full_name);
1131                 }
1132
1133                 if (!gmodule) {
1134                         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1135                                         "DllImport loading: '%s'.", file_name);
1136                         gmodule=g_module_open (file_name, G_MODULE_BIND_LAZY);
1137                         if (!gmodule) {
1138                                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1139                                                 "DllImport error loading library '%s'.",
1140                                                 g_module_error ());
1141                         }
1142                 }
1143
1144                 g_free (file_name);
1145
1146                 if (gmodule)
1147                         break;
1148         }
1149
1150         if (!gmodule) {
1151                 mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_DLLIMPORT,
1152                                 "DllImport unable to load library '%s'.",
1153                                 g_module_error ());
1154
1155                 if (exc_class) {
1156                         *exc_class = "DllNotFoundException";
1157                         *exc_arg = new_scope;
1158                 }
1159                 return NULL;
1160         }
1161
1162         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1163                                 "Searching for '%s'.", import);
1164
1165         if (piinfo->piflags & PINVOKE_ATTRIBUTE_NO_MANGLE) {
1166                 g_module_symbol (gmodule, import, &piinfo->addr); 
1167         } else {
1168                 char *mangled_name = NULL, *mangled_name2 = NULL;
1169                 int mangle_charset;
1170                 int mangle_stdcall;
1171                 int mangle_param_count;
1172 #ifdef PLATFORM_WIN32
1173                 int param_count;
1174 #endif
1175
1176                 /*
1177                  * Search using a variety of mangled names
1178                  */
1179                 for (mangle_charset = 0; mangle_charset <= 1; mangle_charset ++) {
1180                         for (mangle_stdcall = 0; mangle_stdcall <= 1; mangle_stdcall ++) {
1181                                 gboolean need_param_count = FALSE;
1182 #ifdef PLATFORM_WIN32
1183                                 if (mangle_stdcall > 0)
1184                                         need_param_count = TRUE;
1185 #endif
1186                                 for (mangle_param_count = 0; mangle_param_count <= (need_param_count ? 256 : 0); mangle_param_count += 4) {
1187
1188                                         if (piinfo->addr)
1189                                                 continue;
1190
1191                                         mangled_name = (char*)import;
1192                                         switch (piinfo->piflags & PINVOKE_ATTRIBUTE_CHAR_SET_MASK) {
1193                                         case PINVOKE_ATTRIBUTE_CHAR_SET_UNICODE:
1194                                                 /* Try the mangled name first */
1195                                                 if (mangle_charset == 0)
1196                                                         mangled_name = g_strconcat (import, "W", NULL);
1197                                                 break;
1198                                         case PINVOKE_ATTRIBUTE_CHAR_SET_AUTO:
1199 #ifdef PLATFORM_WIN32
1200                                                 if (mangle_charset == 0)
1201                                                         mangled_name = g_strconcat (import, "W", NULL);
1202 #else
1203                                                 /* Try the mangled name last */
1204                                                 if (mangle_charset == 1)
1205                                                         mangled_name = g_strconcat (import, "A", NULL);
1206 #endif
1207                                                 break;
1208                                         case PINVOKE_ATTRIBUTE_CHAR_SET_ANSI:
1209                                         default:
1210                                                 /* Try the mangled name last */
1211                                                 if (mangle_charset == 1)
1212                                                         mangled_name = g_strconcat (import, "A", NULL);
1213                                                 break;
1214                                         }
1215
1216 #ifdef PLATFORM_WIN32
1217                                         if (mangle_param_count == 0)
1218                                                 param_count = mono_method_signature (method)->param_count * sizeof (gpointer);
1219                                         else
1220                                                 /* Try brute force, since it would be very hard to compute the stack usage correctly */
1221                                                 param_count = mangle_param_count;
1222
1223                                         /* Try the stdcall mangled name */
1224                                         /* 
1225                                          * gcc under windows creates mangled names without the underscore, but MS.NET
1226                                          * doesn't support it, so we doesn't support it either.
1227                                          */
1228                                         if (mangle_stdcall == 1)
1229                                                 mangled_name2 = g_strdup_printf ("_%s@%d", mangled_name, param_count);
1230                                         else
1231                                                 mangled_name2 = mangled_name;
1232 #else
1233                                         mangled_name2 = mangled_name;
1234 #endif
1235
1236                                         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1237                                                                 "Probing '%s'.", mangled_name2);
1238
1239                                         g_module_symbol (gmodule, mangled_name2, &piinfo->addr);
1240
1241                                         if (piinfo->addr)
1242                                                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1243                                                                         "Found as '%s'.", mangled_name2);
1244
1245                                         if (mangled_name != mangled_name2)
1246                                                 g_free (mangled_name2);
1247                                         if (mangled_name != import)
1248                                                 g_free (mangled_name);
1249                                 }
1250                         }
1251                 }
1252         }
1253
1254         if (!piinfo->addr) {
1255                 if (exc_class) {
1256                         *exc_class = "EntryPointNotFoundException";
1257                         *exc_arg = import;
1258                 }
1259                 return NULL;
1260         }
1261         return piinfo->addr;
1262 }
1263
1264 MonoGenericMethod *
1265 mono_get_shared_generic_method (MonoGenericContainer *container)
1266 {
1267         MonoGenericMethod *gmethod = g_new0 (MonoGenericMethod, 1);
1268         gmethod->container = container;
1269         gmethod->class_inst = container->context.class_inst;
1270         gmethod->inst = mono_get_shared_generic_inst (container);
1271
1272         return gmethod;
1273 }
1274
1275 static MonoMethod *
1276 mono_get_method_from_token (MonoImage *image, guint32 token, MonoClass *klass,
1277                             MonoGenericContext *context)
1278 {
1279         MonoMethod *result;
1280         int table = mono_metadata_token_table (token);
1281         int idx = mono_metadata_token_index (token);
1282         MonoTableInfo *tables = image->tables;
1283         MonoGenericContainer *generic_container = NULL, *container = NULL;
1284         const char *sig = NULL;
1285         int size, i;
1286         guint32 cols [MONO_TYPEDEF_SIZE];
1287
1288         if (image->dynamic)
1289                 return mono_lookup_dynamic_token (image, token);
1290
1291         if (table != MONO_TABLE_METHOD) {
1292                 if (table == MONO_TABLE_METHODSPEC)
1293                         return method_from_methodspec (image, context, idx);
1294                 if (table != MONO_TABLE_MEMBERREF)
1295                         g_print("got wrong token: 0x%08x\n", token);
1296                 g_assert (table == MONO_TABLE_MEMBERREF);
1297                 result = method_from_memberref (image, idx, context);
1298
1299                 return result;
1300         }
1301
1302         mono_metadata_decode_row (&image->tables [MONO_TABLE_METHOD], idx - 1, cols, 6);
1303
1304         if ((cols [2] & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
1305             (cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))
1306                 result = (MonoMethod *)mono_mempool_alloc0 (image->mempool, sizeof (MonoMethodPInvoke));
1307         else
1308                 result = (MonoMethod *)mono_mempool_alloc0 (image->mempool, sizeof (MonoMethodNormal));
1309
1310         mono_stats.method_count ++;
1311
1312         if (!klass) {
1313                 guint32 type = mono_metadata_typedef_from_method (image, token);
1314                 klass = mono_class_get (image, MONO_TOKEN_TYPE_DEF | type);
1315                 if (klass == NULL)
1316                         return NULL;
1317         }
1318
1319         result->slot = -1;
1320         result->klass = klass;
1321         result->flags = cols [2];
1322         result->iflags = cols [1];
1323         result->token = token;
1324         result->name = mono_metadata_string_heap (image, cols [3]);
1325
1326         container = klass->generic_container;
1327         generic_container = mono_metadata_load_generic_params (image, token, container);
1328         if (generic_container) {
1329                 MonoGenericContext *context;
1330
1331                 generic_container->owner.method = result;
1332                 context = &generic_container->context;
1333                 if (container)
1334                         context->class_inst = container->context.class_inst;
1335                 context->gmethod = mono_get_shared_generic_method (generic_container);
1336
1337                 mono_metadata_load_generic_param_constraints (image, token, generic_container);
1338
1339                 for (i = 0; i < generic_container->type_argc; i++)
1340                         mono_class_from_generic_parameter (&generic_container->type_params [i], image, TRUE);
1341
1342                 container = generic_container;
1343         }
1344
1345         if (!sig) /* already taken from the methodref */
1346                 sig = mono_metadata_blob_heap (image, cols [4]);
1347         size = mono_metadata_decode_blob_size (sig, &sig);
1348
1349         if (cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
1350                 if (result->klass == mono_defaults.string_class && !strcmp (result->name, ".ctor"))
1351                         result->string_ctor = 1;
1352         } else if ((cols [2] & METHOD_ATTRIBUTE_PINVOKE_IMPL) && (!(cols [1] & METHOD_IMPL_ATTRIBUTE_NATIVE))) {
1353                 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)result;
1354                 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
1355
1356                 piinfo->implmap_idx = mono_metadata_implmap_from_method (image, idx - 1);
1357                 piinfo->piflags = mono_metadata_decode_row_col (im, piinfo->implmap_idx - 1, MONO_IMPLMAP_FLAGS);
1358         }
1359
1360         /* FIXME: lazyness for generics too, but how? */
1361         if (!(result->flags & METHOD_ATTRIBUTE_ABSTRACT) &&
1362             !(cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) &&
1363             !(result->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) && container) {
1364                 gpointer loc = mono_image_rva_map (image, cols [0]);
1365                 g_assert (loc);
1366                 ((MonoMethodNormal *) result)->header = mono_metadata_parse_mh_full (image, container, loc);
1367         }
1368
1369         result->generic_container = generic_container;
1370
1371         return result;
1372 }
1373
1374 MonoMethod *
1375 mono_get_method (MonoImage *image, guint32 token, MonoClass *klass)
1376 {
1377         return mono_get_method_full (image, token, klass, NULL);
1378 }
1379
1380 MonoMethod *
1381 mono_get_method_full (MonoImage *image, guint32 token, MonoClass *klass,
1382                       MonoGenericContext *context)
1383 {
1384         MonoMethod *result;
1385
1386         /* We do everything inside the lock to prevent creation races */
1387
1388         mono_loader_lock ();
1389
1390         if ((result = g_hash_table_lookup (image->method_cache, GINT_TO_POINTER (token)))) {
1391                 mono_loader_unlock ();
1392                 return result;
1393         }
1394
1395         result = mono_get_method_from_token (image, token, klass, context);
1396
1397         //printf ("GET: %s\n", mono_method_full_name (result, TRUE));
1398
1399         if (!(result && result->is_inflated))
1400                 g_hash_table_insert (image->method_cache, GINT_TO_POINTER (token), result);
1401
1402         mono_loader_unlock ();
1403
1404         return result;
1405 }
1406
1407 /**
1408  * mono_get_method_constrained:
1409  *
1410  * This is used when JITing the `constrained.' opcode.
1411  *
1412  * This returns two values: the contrained method, which has been inflated
1413  * as the function return value;   And the original CIL-stream method as
1414  * declared in cil_method.  The later is used for verification.
1415  */
1416 MonoMethod *
1417 mono_get_method_constrained (MonoImage *image, guint32 token, MonoClass *constrained_class,
1418                              MonoGenericContext *context, MonoMethod **cil_method)
1419 {
1420         MonoMethod *method, *result;
1421         MonoClass *ic = NULL;
1422         MonoGenericContext *class_context = NULL, *method_context = NULL;
1423         MonoMethodSignature *sig;
1424
1425         mono_loader_lock ();
1426
1427         *cil_method = mono_get_method_from_token (image, token, NULL, context);
1428         if (!*cil_method) {
1429                 mono_loader_unlock ();
1430                 return NULL;
1431         }
1432
1433         mono_class_init (constrained_class);
1434         method = mono_get_inflated_method (*cil_method);
1435         sig = mono_method_signature (method);
1436
1437         if (method->is_inflated && sig->generic_param_count) {
1438                 MonoMethodInflated *imethod = (MonoMethodInflated *) method;
1439                 sig = mono_method_signature (imethod->declaring);
1440                 method_context = mono_method_get_context (method);
1441         }
1442
1443         if ((constrained_class != method->klass) && (method->klass->interface_id != 0))
1444                 ic = method->klass;
1445
1446         if (constrained_class->generic_class)
1447                 class_context = mono_class_get_context (constrained_class);
1448
1449         result = find_method (constrained_class, ic, method->name, sig, constrained_class);
1450         if (!result) {
1451                 g_warning ("Missing method %s.%s.%s in assembly %s token %x", method->klass->name_space,
1452                            method->klass->name, method->name, image->name, token);
1453                 mono_loader_unlock ();
1454                 return NULL;
1455         }
1456
1457         if (class_context)
1458                 result = mono_class_inflate_generic_method (result, class_context);
1459         if (method_context)
1460                 result = mono_class_inflate_generic_method (result, method_context);
1461
1462         mono_loader_unlock ();
1463         return result;
1464 }
1465
1466 void
1467 mono_free_method  (MonoMethod *method)
1468 {
1469         if (mono_profiler_get_events () != MONO_PROFILE_NONE)
1470                 return;
1471         
1472         if (method->signature) {
1473                 /* 
1474                  * FIXME: This causes crashes because the types inside signatures and
1475                  * locals are shared.
1476                  */
1477                 /* mono_metadata_free_method_signature (method->signature); */
1478                 /* g_free (method->signature); */
1479         }
1480         
1481         if (method->dynamic) {
1482                 MonoMethodWrapper *mw = (MonoMethodWrapper*)method;
1483                 
1484                 g_free ((char*)method->name);
1485                 if (mw->method.header)
1486                         g_free ((char*)mw->method.header->code);
1487                 g_free (mw->method_data);
1488         }
1489
1490         if (method->dynamic && !(method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && ((MonoMethodNormal *)method)->header) {
1491                 /* FIXME: Ditto */
1492                 /* mono_metadata_free_mh (((MonoMethodNormal *)method)->header); */
1493                 g_free (((MonoMethodNormal*)method)->header);
1494         }
1495
1496         if (method->dynamic)
1497                 g_free (method);
1498 }
1499
1500 void
1501 mono_method_get_param_names (MonoMethod *method, const char **names)
1502 {
1503         int i, lastp;
1504         MonoClass *klass = method->klass;
1505         MonoTableInfo *methodt;
1506         MonoTableInfo *paramt;
1507         guint32 idx;
1508
1509         if (!mono_method_signature (method)->param_count)
1510                 return;
1511         for (i = 0; i < mono_method_signature (method)->param_count; ++i)
1512                 names [i] = "";
1513
1514         if (klass->generic_class || klass->rank) /* copy the names later */
1515                 return;
1516
1517         mono_class_init (klass);
1518
1519         if (klass->image->dynamic) {
1520                 MonoReflectionMethodAux *method_aux = 
1521                         g_hash_table_lookup (
1522                                 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
1523                 if (method_aux && method_aux->param_names) {
1524                         for (i = 0; i < mono_method_signature (method)->param_count; ++i)
1525                                 if (method_aux->param_names [i + 1])
1526                                         names [i] = method_aux->param_names [i + 1];
1527                 }
1528                 return;
1529         }
1530
1531         methodt = &klass->image->tables [MONO_TABLE_METHOD];
1532         paramt = &klass->image->tables [MONO_TABLE_PARAM];
1533         idx = mono_method_get_index (method);
1534         if (idx > 0) {
1535                 guint32 cols [MONO_PARAM_SIZE];
1536                 guint param_index;
1537
1538                 param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
1539
1540                 if (idx < methodt->rows)
1541                         lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
1542                 else
1543                         lastp = paramt->rows + 1;
1544                 for (i = param_index; i < lastp; ++i) {
1545                         mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
1546                         if (cols [MONO_PARAM_SEQUENCE]) /* skip return param spec */
1547                                 names [cols [MONO_PARAM_SEQUENCE] - 1] = mono_metadata_string_heap (klass->image, cols [MONO_PARAM_NAME]);
1548                 }
1549                 return;
1550         }
1551 }
1552
1553 guint32
1554 mono_method_get_param_token (MonoMethod *method, int index)
1555 {
1556         MonoClass *klass = method->klass;
1557         MonoTableInfo *methodt;
1558         guint32 idx;
1559
1560         if (klass->generic_class)
1561                 g_assert_not_reached ();
1562
1563         mono_class_init (klass);
1564
1565         if (klass->image->dynamic) {
1566                 g_assert_not_reached ();
1567         }
1568
1569         methodt = &klass->image->tables [MONO_TABLE_METHOD];
1570         idx = mono_method_get_index (method);
1571         if (idx > 0) {
1572                 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
1573
1574                 return mono_metadata_make_token (MONO_TABLE_PARAM, param_index + index);
1575         }
1576
1577         return 0;
1578 }
1579
1580 void
1581 mono_method_get_marshal_info (MonoMethod *method, MonoMarshalSpec **mspecs)
1582 {
1583         int i, lastp;
1584         MonoClass *klass = method->klass;
1585         MonoTableInfo *methodt;
1586         MonoTableInfo *paramt;
1587         guint32 idx;
1588
1589         for (i = 0; i < mono_method_signature (method)->param_count + 1; ++i)
1590                 mspecs [i] = NULL;
1591
1592         if (method->klass->image->dynamic) {
1593                 MonoReflectionMethodAux *method_aux = 
1594                         g_hash_table_lookup (
1595                                 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
1596                 if (method_aux && method_aux->param_marshall) {
1597                         MonoMarshalSpec **dyn_specs = method_aux->param_marshall;
1598                         for (i = 0; i < mono_method_signature (method)->param_count + 1; ++i)
1599                                 if (dyn_specs [i]) {
1600                                         mspecs [i] = g_new0 (MonoMarshalSpec, 1);
1601                                         memcpy (mspecs [i], dyn_specs [i], sizeof (MonoMarshalSpec));
1602                                 }
1603                 }
1604                 return;
1605         }
1606
1607         mono_class_init (klass);
1608
1609         methodt = &klass->image->tables [MONO_TABLE_METHOD];
1610         paramt = &klass->image->tables [MONO_TABLE_PARAM];
1611         idx = mono_method_get_index (method);
1612         if (idx > 0) {
1613                 guint32 cols [MONO_PARAM_SIZE];
1614                 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
1615
1616                 if (idx < methodt->rows)
1617                         lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
1618                 else
1619                         lastp = paramt->rows + 1;
1620
1621                 for (i = param_index; i < lastp; ++i) {
1622                         mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
1623
1624                         if (cols [MONO_PARAM_FLAGS] & PARAM_ATTRIBUTE_HAS_FIELD_MARSHAL) {
1625                                 const char *tp;
1626                                 tp = mono_metadata_get_marshal_info (klass->image, i - 1, FALSE);
1627                                 g_assert (tp);
1628                                 mspecs [cols [MONO_PARAM_SEQUENCE]]= mono_metadata_parse_marshal_spec (klass->image, tp);
1629                         }
1630                 }
1631
1632                 return;
1633         }
1634 }
1635
1636 gboolean
1637 mono_method_has_marshal_info (MonoMethod *method)
1638 {
1639         int i, lastp;
1640         MonoClass *klass = method->klass;
1641         MonoTableInfo *methodt;
1642         MonoTableInfo *paramt;
1643         guint32 idx;
1644
1645         if (method->klass->image->dynamic) {
1646                 MonoReflectionMethodAux *method_aux = 
1647                         g_hash_table_lookup (
1648                                 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
1649                 MonoMarshalSpec **dyn_specs = method_aux->param_marshall;
1650                 if (dyn_specs) {
1651                         for (i = 0; i < mono_method_signature (method)->param_count + 1; ++i)
1652                                 if (dyn_specs [i])
1653                                         return TRUE;
1654                 }
1655                 return FALSE;
1656         }
1657
1658         mono_class_init (klass);
1659
1660         methodt = &klass->image->tables [MONO_TABLE_METHOD];
1661         paramt = &klass->image->tables [MONO_TABLE_PARAM];
1662         idx = mono_method_get_index (method);
1663         if (idx > 0) {
1664                 guint32 cols [MONO_PARAM_SIZE];
1665                 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
1666
1667                 if (idx + 1 < methodt->rows)
1668                         lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
1669                 else
1670                         lastp = paramt->rows + 1;
1671
1672                 for (i = param_index; i < lastp; ++i) {
1673                         mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
1674
1675                         if (cols [MONO_PARAM_FLAGS] & PARAM_ATTRIBUTE_HAS_FIELD_MARSHAL)
1676                                 return TRUE;
1677                 }
1678                 return FALSE;
1679         }
1680         return FALSE;
1681 }
1682
1683 gpointer
1684 mono_method_get_wrapper_data (MonoMethod *method, guint32 id)
1685 {
1686         void **data;
1687         g_assert (method != NULL);
1688         g_assert (method->wrapper_type != MONO_WRAPPER_NONE);
1689
1690         data = ((MonoMethodWrapper *)method)->method_data;
1691         g_assert (data != NULL);
1692         g_assert (id <= GPOINTER_TO_UINT (*data));
1693         return data [id];
1694 }
1695
1696 static void
1697 default_stack_walk (MonoStackWalk func, gboolean do_il_offset, gpointer user_data) {
1698         g_error ("stack walk not installed");
1699 }
1700
1701 static MonoStackWalkImpl stack_walk = default_stack_walk;
1702
1703 void
1704 mono_stack_walk (MonoStackWalk func, gpointer user_data)
1705 {
1706         stack_walk (func, TRUE, user_data);
1707 }
1708
1709 void
1710 mono_stack_walk_no_il (MonoStackWalk func, gpointer user_data)
1711 {
1712         stack_walk (func, FALSE, user_data);
1713 }
1714
1715 void
1716 mono_install_stack_walk (MonoStackWalkImpl func)
1717 {
1718         stack_walk = func;
1719 }
1720
1721 static gboolean
1722 last_managed (MonoMethod *m, gint no, gint ilo, gboolean managed, gpointer data)
1723 {
1724         MonoMethod **dest = data;
1725         *dest = m;
1726         /*g_print ("In %s::%s [%d] [%d]\n", m->klass->name, m->name, no, ilo);*/
1727
1728         return managed;
1729 }
1730
1731 MonoMethod*
1732 mono_method_get_last_managed (void)
1733 {
1734         MonoMethod *m = NULL;
1735         stack_walk (last_managed, FALSE, &m);
1736         return m;
1737 }
1738
1739 void
1740 mono_loader_lock (void)
1741 {
1742         EnterCriticalSection (&loader_mutex);
1743 }
1744
1745 void
1746 mono_loader_unlock (void)
1747 {
1748         LeaveCriticalSection (&loader_mutex);
1749 }
1750
1751 /**
1752  * mono_method_signature:
1753  *
1754  * Return the signature of the method M. On failure, returns NULL.
1755  */
1756 MonoMethodSignature*
1757 mono_method_signature (MonoMethod *m)
1758 {
1759         int idx;
1760         int size;
1761         MonoImage* img;
1762         const char *sig;
1763         gboolean can_cache_signature;
1764         MonoGenericContainer *container;
1765         int *pattrs;
1766
1767         if (m->signature)
1768                 return m->signature;
1769
1770         mono_loader_lock ();
1771
1772         if (m->signature) {
1773                 mono_loader_unlock ();
1774                 return m->signature;
1775         }
1776
1777         if (m->is_inflated) {
1778                 MonoMethodInflated *imethod = (MonoMethodInflated *) m;
1779                 MonoMethodSignature *signature;
1780                 /* the lock is recursive */
1781                 signature = mono_method_signature (imethod->declaring);
1782                 m->signature = inflate_generic_signature (imethod->declaring->klass->image, signature, mono_method_get_context (m));
1783                 mono_loader_unlock ();
1784                 return m->signature;
1785         }
1786
1787         g_assert (mono_metadata_token_table (m->token) == MONO_TABLE_METHOD);
1788         idx = mono_metadata_token_index (m->token);
1789         img = m->klass->image;
1790
1791         sig = mono_metadata_blob_heap (img, mono_metadata_decode_row_col (&img->tables [MONO_TABLE_METHOD], idx - 1, MONO_METHOD_SIGNATURE));
1792
1793         g_assert (!m->klass->generic_class);
1794         container = m->generic_container;
1795         if (!container)
1796                 container = m->klass->generic_container;
1797
1798         /* Generic signatures depend on the container so they cannot be cached */
1799         /* icall/pinvoke signatures cannot be cached cause we modify them below */
1800         can_cache_signature = !(m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && !(m->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) && !container;
1801
1802         /* If the method has parameter attributes, that can modify the signature */
1803         pattrs = mono_metadata_get_param_attrs (img, idx);
1804         if (pattrs) {
1805                 can_cache_signature = FALSE;
1806                 g_free (pattrs);
1807         }
1808
1809         if (can_cache_signature)
1810                 m->signature = g_hash_table_lookup (img->method_signatures, sig);
1811
1812         if (!m->signature) {
1813                 const char *sig_body;
1814
1815                 size = mono_metadata_decode_blob_size (sig, &sig_body);
1816
1817                 m->signature = mono_metadata_parse_method_signature_full (img, container, idx, sig_body, NULL);
1818                 if (!m->signature) {
1819                         mono_loader_unlock ();
1820                         return NULL;
1821                 }
1822
1823                 if (can_cache_signature)
1824                         g_hash_table_insert (img->method_signatures, (gpointer)sig, m->signature);
1825         }
1826
1827         /* Verify metadata consistency */
1828         if (m->signature->generic_param_count) {
1829                 if (!container || !container->is_method)
1830                         g_error ("Signature claims method has generic parameters, but generic_params table says it doesn't");
1831                 if (container->type_argc != m->signature->generic_param_count)
1832                         g_error ("Inconsistent generic parameter count.  Signature says %d, generic_params table says %d",
1833                                  m->signature->generic_param_count, container->type_argc);
1834         } else if (container && container->is_method && container->type_argc)
1835                 g_error ("generic_params table claims method has generic parameters, but signature says it doesn't");
1836
1837         if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
1838                 m->signature->pinvoke = 1;
1839         else if ((m->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) && (!(m->iflags & METHOD_IMPL_ATTRIBUTE_NATIVE))) {
1840                 MonoCallConvention conv = 0;
1841                 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)m;
1842                 m->signature->pinvoke = 1;
1843
1844                 switch (piinfo->piflags & PINVOKE_ATTRIBUTE_CALL_CONV_MASK) {
1845                 case 0: /* no call conv, so using default */
1846                 case PINVOKE_ATTRIBUTE_CALL_CONV_WINAPI:
1847                         conv = MONO_CALL_DEFAULT;
1848                         break;
1849                 case PINVOKE_ATTRIBUTE_CALL_CONV_CDECL:
1850                         conv = MONO_CALL_C;
1851                         break;
1852                 case PINVOKE_ATTRIBUTE_CALL_CONV_STDCALL:
1853                         conv = MONO_CALL_STDCALL;
1854                         break;
1855                 case PINVOKE_ATTRIBUTE_CALL_CONV_THISCALL:
1856                         conv = MONO_CALL_THISCALL;
1857                         break;
1858                 case PINVOKE_ATTRIBUTE_CALL_CONV_FASTCALL:
1859                         conv = MONO_CALL_FASTCALL;
1860                         break;
1861                 case PINVOKE_ATTRIBUTE_CALL_CONV_GENERIC:
1862                 case PINVOKE_ATTRIBUTE_CALL_CONV_GENERICINST:
1863                 default:
1864                         g_warning ("unsupported calling convention : 0x%04x", piinfo->piflags);
1865                         g_assert_not_reached ();
1866                 }
1867                 m->signature->call_convention = conv;
1868         }
1869
1870         mono_loader_unlock ();
1871         return m->signature;
1872 }
1873
1874 const char*
1875 mono_method_get_name (MonoMethod *method)
1876 {
1877         return method->name;
1878 }
1879
1880 MonoClass*
1881 mono_method_get_class (MonoMethod *method)
1882 {
1883         return method->klass;
1884 }
1885
1886 guint32
1887 mono_method_get_token (MonoMethod *method)
1888 {
1889         return method->token;
1890 }
1891
1892 MonoMethodHeader*
1893 mono_method_get_header (MonoMethod *method)
1894 {
1895         int idx;
1896         guint32 rva;
1897         MonoImage* img;
1898         gpointer loc;
1899         MonoMethodNormal* mn = (MonoMethodNormal*) method;
1900
1901         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))
1902                 return NULL;
1903
1904 #ifdef G_LIKELY
1905         if (G_LIKELY (mn->header))
1906 #else
1907         if (mn->header)
1908 #endif
1909                 return mn->header;
1910
1911         mono_loader_lock ();
1912
1913         if (mn->header) {
1914                 mono_loader_unlock ();
1915                 return mn->header;
1916         }
1917
1918         if (method->is_inflated) {
1919                 MonoMethodInflated *imethod = (MonoMethodInflated *) method;
1920                 MonoMethodHeader *header;
1921                 /* the lock is recursive */
1922                 header = mono_method_get_header (imethod->declaring);
1923                 mn->header = inflate_generic_header (header, mono_method_get_context (method));
1924                 mono_loader_unlock ();
1925                 return mn->header;
1926         }
1927
1928         g_assert (mono_metadata_token_table (method->token) == MONO_TABLE_METHOD);
1929         idx = mono_metadata_token_index (method->token);
1930         img = method->klass->image;
1931         rva = mono_metadata_decode_row_col (&img->tables [MONO_TABLE_METHOD], idx - 1, MONO_METHOD_RVA);
1932         loc = mono_image_rva_map (img, rva);
1933
1934         g_assert (loc);
1935
1936         mn->header = mono_metadata_parse_mh_full (img, method->generic_container, loc);
1937
1938         mono_loader_unlock ();
1939         return mn->header;
1940 }
1941
1942 guint32
1943 mono_method_get_flags (MonoMethod *method, guint32 *iflags)
1944 {
1945         if (iflags)
1946                 *iflags = method->iflags;
1947         return method->flags;
1948 }
1949
1950 /*
1951  * Find the method index in the metadata methodDef table.
1952  */
1953 guint32
1954 mono_method_get_index (MonoMethod *method) {
1955         MonoClass *klass = method->klass;
1956         int i;
1957
1958         if (method->token)
1959                 return mono_metadata_token_index (method->token);
1960
1961         mono_class_setup_methods (klass);
1962         for (i = 0; i < klass->method.count; ++i) {
1963                 if (method == klass->methods [i]) {
1964                         if (klass->image->uncompressed_metadata)
1965                                 return mono_metadata_translate_token_index (klass->image, MONO_TABLE_METHOD, klass->method.first + i + 1);
1966                         else
1967                                 return klass->method.first + i + 1;
1968                 }
1969         }
1970         return 0;
1971 }
1972