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