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