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