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