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