merge -r 53370:58178
[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                 container = generic_container;
1158         }
1159
1160         if (!sig) /* already taken from the methodref */
1161                 sig = mono_metadata_blob_heap (image, cols [4]);
1162         size = mono_metadata_decode_blob_size (sig, &sig);
1163         
1164         /* there are generic params, or a container. FIXME: be lazy here for generics*/
1165         if (* sig & 0x10 || container) {
1166                 result->signature = mono_metadata_parse_method_signature_full (
1167                         image, container, idx, sig, NULL);
1168
1169                 if (cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
1170                         result->signature->pinvoke = 1;
1171         }
1172
1173         if (!result->klass) {
1174                 guint32 type = mono_metadata_typedef_from_method (image, token);
1175                 result->klass = mono_class_get (image, MONO_TOKEN_TYPE_DEF | type);
1176         }
1177
1178         if (cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
1179                 if (result->klass == mono_defaults.string_class && !strcmp (result->name, ".ctor"))
1180                         result->string_ctor = 1;
1181         } else if ((cols [2] & METHOD_ATTRIBUTE_PINVOKE_IMPL) && (!(cols [1] & METHOD_IMPL_ATTRIBUTE_NATIVE))) {
1182                 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)result;
1183                 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
1184                 
1185                 piinfo->implmap_idx = mono_metadata_implmap_from_method (image, idx - 1);
1186                 piinfo->piflags = mono_metadata_decode_row_col (im, piinfo->implmap_idx - 1, MONO_IMPLMAP_FLAGS);
1187         }
1188
1189         if (result->signature && result->signature->generic_param_count) {
1190                 MonoMethodSignature *sig = result->signature;
1191
1192                 for (i = 0; i < sig->generic_param_count; i++) {
1193                         generic_container->type_params [i].method = result;
1194
1195                         mono_class_from_generic_parameter (
1196                                 &generic_container->type_params [i], image, TRUE);
1197                 }
1198
1199                 if (sig->ret->type == MONO_TYPE_MVAR) {
1200                         int num = sig->ret->data.generic_param->num;
1201                         sig->ret->data.generic_param = &generic_container->type_params [num];
1202                 }
1203
1204                 for (i = 0; i < sig->param_count; i++) {
1205                         MonoType *t = sig->params [i];
1206                         if (t->type == MONO_TYPE_MVAR) {
1207                                 int num = t->data.generic_param->num;
1208                                 sig->params [i]->data.generic_param = &generic_container->type_params [num];
1209                         }
1210                 }
1211         }
1212                 
1213         /* FIXME: lazyness for generics too, but how? */
1214         if (!result->klass->dummy && !(result->flags & METHOD_ATTRIBUTE_ABSTRACT) &&
1215             !(cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) &&
1216             !(result->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) && container) {
1217                 gpointer loc = mono_image_rva_map (image, cols [0]);
1218                 g_assert (loc);
1219                 ((MonoMethodNormal *) result)->header = mono_metadata_parse_mh_full (
1220                         image, (MonoGenericContext *) container, loc);
1221         }
1222                 
1223         result->generic_container = generic_container;
1224
1225         return result;
1226 }
1227
1228 MonoMethod *
1229 mono_get_method (MonoImage *image, guint32 token, MonoClass *klass)
1230 {
1231         return mono_get_method_full (image, token, klass, NULL);
1232 }
1233
1234 MonoMethod *
1235 mono_get_method_full (MonoImage *image, guint32 token, MonoClass *klass,
1236                       MonoGenericContext *context)
1237 {
1238         MonoMethod *result;
1239
1240         /* We do everything inside the lock to prevent creation races */
1241
1242         mono_loader_lock ();
1243
1244         if ((result = g_hash_table_lookup (image->method_cache, GINT_TO_POINTER (token)))) {
1245                 mono_loader_unlock ();
1246                 return result;
1247         }
1248
1249         result = mono_get_method_from_token (image, token, klass, context);
1250
1251         //printf ("GET: %s\n", mono_method_full_name (result, TRUE));
1252
1253         if (!(result && result->is_inflated))
1254                 g_hash_table_insert (image->method_cache, GINT_TO_POINTER (token), result);
1255
1256         mono_loader_unlock ();
1257
1258         return result;
1259 }
1260
1261 /**
1262  * mono_get_method_constrained:
1263  *
1264  * This is used when JITing the `constrained.' opcode.
1265  */
1266 MonoMethod *
1267 mono_get_method_constrained (MonoImage *image, guint32 token, MonoClass *constrained_class,
1268                              MonoGenericContext *context)
1269 {
1270         MonoMethod *method, *result;
1271         MonoClass *ic = NULL;
1272         MonoGenericClass *gclass = NULL;
1273
1274         mono_loader_lock ();
1275
1276         method = mono_get_method_from_token (image, token, NULL, context);
1277         if (!method) {
1278                 mono_loader_unlock ();
1279                 return NULL;
1280         }
1281
1282         mono_class_init (constrained_class);
1283         method = mono_get_inflated_method (method);
1284
1285         if ((constrained_class != method->klass) && (method->klass->interface_id != 0))
1286                 ic = method->klass;
1287
1288         if (constrained_class->generic_class)
1289                 gclass = constrained_class->generic_class;
1290
1291         result = find_method (
1292                 constrained_class, ic, method->name, mono_method_signature (method),
1293                 context ? context->container : NULL);
1294         if (!result)
1295                 g_warning ("Missing method %s in assembly %s token %x", method->name,
1296                            image->name, token);
1297
1298         if (gclass)
1299                 result = mono_class_inflate_generic_method (result, gclass->context);
1300
1301         mono_loader_unlock ();
1302         return result;
1303 }
1304
1305 void
1306 mono_free_method  (MonoMethod *method)
1307 {
1308         if (method->signature) {
1309                 /* 
1310                  * FIXME: This causes crashes because the types inside signatures and
1311                  * locals are shared.
1312                  */
1313                 /* mono_metadata_free_method_signature (method->signature); */
1314                 g_free (method->signature);
1315         }
1316
1317         if (method->dynamic) {
1318                 MonoMethodWrapper *mw = (MonoMethodWrapper*)method;
1319
1320                 g_free ((char*)method->name);
1321                 if (mw->method.header)
1322                         g_free ((char*)mw->method.header->code);
1323                 g_free (mw->method_data);
1324         }
1325
1326         if (!(method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && ((MonoMethodNormal *)method)->header) {
1327                 /* FIXME: Ditto */
1328                 /* mono_metadata_free_mh (((MonoMethodNormal *)method)->header); */
1329                 g_free (((MonoMethodNormal*)method)->header);
1330         }
1331
1332         g_free (method);
1333 }
1334
1335 void
1336 mono_method_get_param_names (MonoMethod *method, const char **names)
1337 {
1338         int i, lastp;
1339         MonoClass *klass = method->klass;
1340         MonoTableInfo *methodt;
1341         MonoTableInfo *paramt;
1342         guint32 idx;
1343
1344         if (!mono_method_signature (method)->param_count)
1345                 return;
1346         for (i = 0; i < mono_method_signature (method)->param_count; ++i)
1347                 names [i] = "";
1348
1349         if (klass->generic_class) /* copy the names later */
1350                 return;
1351
1352         mono_class_init (klass);
1353
1354         if (klass->image->dynamic) {
1355                 MonoReflectionMethodAux *method_aux = 
1356                         g_hash_table_lookup (
1357                                 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
1358                 if (method_aux && method_aux->param_names) {
1359                         for (i = 0; i < mono_method_signature (method)->param_count; ++i)
1360                                 if (method_aux->param_names [i + 1])
1361                                         names [i] = method_aux->param_names [i + 1];
1362                 }
1363                 return;
1364         }
1365
1366         methodt = &klass->image->tables [MONO_TABLE_METHOD];
1367         paramt = &klass->image->tables [MONO_TABLE_PARAM];
1368         idx = mono_method_get_index (method);
1369         if (idx > 0) {
1370                 guint32 cols [MONO_PARAM_SIZE];
1371                 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
1372
1373                 if (idx < methodt->rows)
1374                         lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
1375                 else
1376                         lastp = paramt->rows + 1;
1377                 for (i = param_index; i < lastp; ++i) {
1378                         mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
1379                         if (cols [MONO_PARAM_SEQUENCE]) /* skip return param spec */
1380                                 names [cols [MONO_PARAM_SEQUENCE] - 1] = mono_metadata_string_heap (klass->image, cols [MONO_PARAM_NAME]);
1381                 }
1382                 return;
1383         }
1384 }
1385
1386 guint32
1387 mono_method_get_param_token (MonoMethod *method, int index)
1388 {
1389         MonoClass *klass = method->klass;
1390         MonoTableInfo *methodt;
1391         guint32 idx;
1392
1393         if (klass->generic_class)
1394                 g_assert_not_reached ();
1395
1396         mono_class_init (klass);
1397
1398         if (klass->image->dynamic) {
1399                 g_assert_not_reached ();
1400         }
1401
1402         methodt = &klass->image->tables [MONO_TABLE_METHOD];
1403         idx = mono_method_get_index (method);
1404         if (idx > 0) {
1405                 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
1406
1407                 return mono_metadata_make_token (MONO_TABLE_PARAM, param_index + index);
1408         }
1409
1410         return 0;
1411 }
1412
1413 void
1414 mono_method_get_marshal_info (MonoMethod *method, MonoMarshalSpec **mspecs)
1415 {
1416         int i, lastp;
1417         MonoClass *klass = method->klass;
1418         MonoTableInfo *methodt;
1419         MonoTableInfo *paramt;
1420         guint32 idx;
1421
1422         for (i = 0; i < mono_method_signature (method)->param_count + 1; ++i)
1423                 mspecs [i] = NULL;
1424
1425         if (method->klass->image->dynamic) {
1426                 MonoReflectionMethodAux *method_aux = 
1427                         g_hash_table_lookup (
1428                                 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
1429                 if (method_aux && method_aux->param_marshall) {
1430                         MonoMarshalSpec **dyn_specs = method_aux->param_marshall;
1431                         for (i = 0; i < mono_method_signature (method)->param_count + 1; ++i)
1432                                 if (dyn_specs [i]) {
1433                                         mspecs [i] = g_new0 (MonoMarshalSpec, 1);
1434                                         memcpy (mspecs [i], dyn_specs [i], sizeof (MonoMarshalSpec));
1435                                 }
1436                 }
1437                 return;
1438         }
1439
1440         mono_class_init (klass);
1441
1442         methodt = &klass->image->tables [MONO_TABLE_METHOD];
1443         paramt = &klass->image->tables [MONO_TABLE_PARAM];
1444         idx = mono_method_get_index (method);
1445         if (idx > 0) {
1446                 guint32 cols [MONO_PARAM_SIZE];
1447                 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
1448
1449                 if (idx < methodt->rows)
1450                         lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
1451                 else
1452                         lastp = paramt->rows + 1;
1453
1454                 for (i = param_index; i < lastp; ++i) {
1455                         mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
1456
1457                         if (cols [MONO_PARAM_FLAGS] & PARAM_ATTRIBUTE_HAS_FIELD_MARSHAL) {
1458                                 const char *tp;
1459                                 tp = mono_metadata_get_marshal_info (klass->image, i - 1, FALSE);
1460                                 g_assert (tp);
1461                                 mspecs [cols [MONO_PARAM_SEQUENCE]]= mono_metadata_parse_marshal_spec (klass->image, tp);
1462                         }
1463                 }
1464
1465                 return;
1466         }
1467 }
1468
1469 gboolean
1470 mono_method_has_marshal_info (MonoMethod *method)
1471 {
1472         int i, lastp;
1473         MonoClass *klass = method->klass;
1474         MonoTableInfo *methodt;
1475         MonoTableInfo *paramt;
1476         guint32 idx;
1477
1478         if (method->klass->image->dynamic) {
1479                 MonoReflectionMethodAux *method_aux = 
1480                         g_hash_table_lookup (
1481                                 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
1482                 MonoMarshalSpec **dyn_specs = method_aux->param_marshall;
1483                 if (dyn_specs) {
1484                         for (i = 0; i < mono_method_signature (method)->param_count + 1; ++i)
1485                                 if (dyn_specs [i])
1486                                         return TRUE;
1487                 }
1488                 return FALSE;
1489         }
1490
1491         mono_class_init (klass);
1492
1493         methodt = &klass->image->tables [MONO_TABLE_METHOD];
1494         paramt = &klass->image->tables [MONO_TABLE_PARAM];
1495         idx = mono_method_get_index (method);
1496         if (idx > 0) {
1497                 guint32 cols [MONO_PARAM_SIZE];
1498                 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
1499                 
1500                 if (idx + 1 < methodt->rows)
1501                         lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
1502                 else
1503                         lastp = paramt->rows + 1;
1504
1505                 for (i = param_index; i < lastp; ++i) {
1506                         mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
1507
1508                         if (cols [MONO_PARAM_FLAGS] & PARAM_ATTRIBUTE_HAS_FIELD_MARSHAL)
1509                                 return TRUE;
1510                 }
1511                 return FALSE;
1512         }
1513         return FALSE;
1514 }
1515
1516 gpointer
1517 mono_method_get_wrapper_data (MonoMethod *method, guint32 id)
1518 {
1519         void **data;
1520         g_assert (method != NULL);
1521         g_assert (method->wrapper_type != MONO_WRAPPER_NONE);
1522
1523         data = ((MonoMethodWrapper *)method)->method_data;
1524         g_assert (data != NULL);
1525         g_assert (id <= GPOINTER_TO_UINT (*data));
1526         return data [id];
1527 }
1528
1529 static void
1530 default_stack_walk (MonoStackWalk func, gboolean do_il_offset, gpointer user_data) {
1531         g_error ("stack walk not installed");
1532 }
1533
1534 static MonoStackWalkImpl stack_walk = default_stack_walk;
1535
1536 void
1537 mono_stack_walk (MonoStackWalk func, gpointer user_data)
1538 {
1539         stack_walk (func, TRUE, user_data);
1540 }
1541
1542 void
1543 mono_stack_walk_no_il (MonoStackWalk func, gpointer user_data)
1544 {
1545         stack_walk (func, FALSE, user_data);
1546 }
1547
1548 void
1549 mono_install_stack_walk (MonoStackWalkImpl func)
1550 {
1551         stack_walk = func;
1552 }
1553
1554 static gboolean
1555 last_managed (MonoMethod *m, gint no, gint ilo, gboolean managed, gpointer data)
1556 {
1557         MonoMethod **dest = data;
1558         *dest = m;
1559         /*g_print ("In %s::%s [%d] [%d]\n", m->klass->name, m->name, no, ilo);*/
1560
1561         return managed;
1562 }
1563
1564 MonoMethod*
1565 mono_method_get_last_managed (void)
1566 {
1567         MonoMethod *m = NULL;
1568         stack_walk (last_managed, FALSE, &m);
1569         return m;
1570 }
1571
1572 void
1573 mono_loader_lock (void)
1574 {
1575         EnterCriticalSection (&loader_mutex);
1576 }
1577
1578 void
1579 mono_loader_unlock (void)
1580 {
1581         LeaveCriticalSection (&loader_mutex);
1582 }
1583
1584 MonoMethodSignature* 
1585 mono_method_signature (MonoMethod *m)
1586 {
1587         m = mono_get_inflated_method (m);
1588         return mono_method_signature_full (m, NULL);
1589 }
1590
1591 MonoMethodSignature* 
1592 mono_method_signature_full (MonoMethod *m, MonoGenericContainer *container)
1593 {
1594         int idx;
1595         int size;
1596         MonoImage* img;
1597         const char *sig;
1598         
1599         if (m->signature)
1600                 return m->signature;
1601                 
1602         mono_loader_lock ();
1603         
1604         if (m->signature) {
1605                 mono_loader_unlock ();
1606                 return m->signature;
1607         }
1608         
1609         g_assert (mono_metadata_token_table (m->token) == MONO_TABLE_METHOD);
1610         idx = mono_metadata_token_index (m->token);
1611         img = m->klass->image;
1612         
1613         sig = mono_metadata_blob_heap (img, mono_metadata_decode_row_col (&img->tables [MONO_TABLE_METHOD], idx - 1, MONO_METHOD_SIGNATURE));
1614         size = mono_metadata_decode_blob_size (sig, &sig);
1615         
1616         m->signature = mono_metadata_parse_method_signature_full (img, container, idx, sig, NULL);
1617         
1618         if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
1619                 m->signature->pinvoke = 1;
1620         else if ((m->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) && (!(m->iflags & METHOD_IMPL_ATTRIBUTE_NATIVE))) {
1621                 MonoCallConvention conv = 0;
1622                 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)m;
1623                 m->signature->pinvoke = 1;
1624                 
1625                 switch (piinfo->piflags & PINVOKE_ATTRIBUTE_CALL_CONV_MASK) {
1626                 case 0: /* no call conv, so using default */
1627                 case PINVOKE_ATTRIBUTE_CALL_CONV_WINAPI:
1628                         conv = MONO_CALL_DEFAULT;
1629                         break;
1630                 case PINVOKE_ATTRIBUTE_CALL_CONV_CDECL:
1631                         conv = MONO_CALL_C;
1632                         break;
1633                 case PINVOKE_ATTRIBUTE_CALL_CONV_STDCALL:
1634                         conv = MONO_CALL_STDCALL;
1635                         break;
1636                 case PINVOKE_ATTRIBUTE_CALL_CONV_THISCALL:
1637                         conv = MONO_CALL_THISCALL;
1638                         break;
1639                 case PINVOKE_ATTRIBUTE_CALL_CONV_FASTCALL:
1640                         conv = MONO_CALL_FASTCALL;
1641                         break;
1642                 case PINVOKE_ATTRIBUTE_CALL_CONV_GENERIC:
1643                 case PINVOKE_ATTRIBUTE_CALL_CONV_GENERICINST:
1644                 default:
1645                         g_warning ("unsupported calling convention : 0x%04x", piinfo->piflags);
1646                         g_assert_not_reached ();
1647                 }       
1648                 m->signature->call_convention = conv;
1649         }
1650         
1651         mono_loader_unlock ();
1652         return m->signature;
1653 }
1654
1655 const char*
1656 mono_method_get_name (MonoMethod *method)
1657 {
1658         return method->name;
1659 }
1660
1661 MonoClass*
1662 mono_method_get_class (MonoMethod *method)
1663 {
1664         return method->klass;
1665 }
1666
1667 guint32
1668 mono_method_get_token (MonoMethod *method)
1669 {
1670         return method->token;
1671 }
1672
1673 MonoMethodHeader* 
1674 mono_method_get_header (MonoMethod *method)
1675 {
1676         int idx;
1677         guint32 rva;
1678         MonoImage* img;
1679         gpointer loc;
1680         MonoMethodNormal* mn = (MonoMethodNormal*) method;
1681         
1682         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))
1683                 return NULL;
1684         
1685 #ifdef G_LIKELY
1686         if (G_LIKELY (mn->header))
1687 #else
1688         if (mn->header)
1689 #endif
1690                 return mn->header;
1691         
1692         mono_loader_lock ();
1693         
1694         if (mn->header) {
1695                 mono_loader_unlock ();
1696                 return mn->header;
1697         }
1698         
1699         g_assert (mono_metadata_token_table (method->token) == MONO_TABLE_METHOD);
1700         idx = mono_metadata_token_index (method->token);
1701         img = method->klass->image;
1702         rva = mono_metadata_decode_row_col (&img->tables [MONO_TABLE_METHOD], idx - 1, MONO_METHOD_RVA);
1703         loc = mono_image_rva_map (img, rva);
1704         
1705         g_assert (loc);
1706         
1707         mn->header = mono_metadata_parse_mh_full (img, (MonoGenericContext *) method->generic_container, loc);
1708         
1709         mono_loader_unlock ();
1710         return mn->header;
1711 }
1712
1713 guint32
1714 mono_method_get_flags (MonoMethod *method, guint32 *iflags)
1715 {
1716         if (iflags)
1717                 *iflags = method->iflags;
1718         return method->flags;
1719 }
1720
1721 /*
1722  * Find the method index in the metadata methodDef table.
1723  */
1724 guint32
1725 mono_method_get_index (MonoMethod *method) {
1726         MonoClass *klass = method->klass;
1727         int i;
1728
1729         if (method->token)
1730                 return mono_metadata_token_index (method->token);
1731
1732         mono_class_setup_methods (klass);
1733         for (i = 0; i < klass->method.count; ++i) {
1734                 if (method == klass->methods [i])
1735                         return klass->method.first + 1 + i;
1736         }
1737         return 0;
1738 }
1739