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