2005-09-13 Sureshkumar T <tsureshkumar@novell.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)
322 {
323         MonoGenericContext *context = NULL;
324         int i;
325
326         if (klass->generic_container)
327                 context = &klass->generic_container->context;
328         else if (klass->generic_class)
329                 context = klass->generic_class->context;
330
331         mono_class_setup_methods (klass);
332         for (i = 0; i < klass->method.count; ++i) {
333                 MonoMethod *m = klass->methods [i];
334
335                 if (!((fqname && !strcmp (m->name, fqname)) ||
336                       (qname && !strcmp (m->name, qname)) || !strcmp (m->name, name)))
337                         continue;
338
339                 if (sig->call_convention == MONO_CALL_VARARG) {
340                         if (mono_metadata_signature_vararg_match (sig, mono_method_signature (m)))
341                                 return m;
342                 } else {
343                         MonoMethodSignature *msig = mono_method_signature_full (m, context);
344                         if (mono_metadata_signature_equal (sig, msig))
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 (image, context, 0, ptr, NULL);
443
444                 mono_loader_lock ();
445                 prev_sig = g_hash_table_lookup (image->memberref_signatures, GUINT_TO_POINTER (token));
446                 if (prev_sig) {
447                         /* Somebody got in before us */
448                         /* FIXME: Free sig */
449                         sig = prev_sig;
450                 }
451                 else
452                         g_hash_table_insert (image->memberref_signatures, GUINT_TO_POINTER (token), sig);
453                 mono_loader_unlock ();
454         }
455
456         sig = mono_class_inflate_generic_signature (image, sig, context);
457
458         return sig;
459 }
460
461 MonoMethodSignature*
462 mono_method_get_signature (MonoMethod *method, MonoImage *image, guint32 token)
463 {
464         return mono_method_get_signature_full (method, image, token, NULL);
465 }
466
467 static MonoMethod *
468 method_from_memberref (MonoImage *image, guint32 idx, MonoGenericContext *context)
469 {
470         MonoClass *klass = NULL;
471         MonoMethod *method = NULL;
472         MonoTableInfo *tables = image->tables;
473         guint32 cols[6];
474         guint32 nindex, class;
475         MonoGenericClass *gclass = NULL;
476         MonoGenericContainer *container = NULL;
477         const char *mname;
478         MonoMethodSignature *sig;
479         const char *ptr;
480
481         mono_metadata_decode_row (&tables [MONO_TABLE_MEMBERREF], idx-1, cols, 3);
482         nindex = cols [MONO_MEMBERREF_CLASS] >> MONO_MEMBERREF_PARENT_BITS;
483         class = cols [MONO_MEMBERREF_CLASS] & MONO_MEMBERREF_PARENT_MASK;
484         /*g_print ("methodref: 0x%x 0x%x %s\n", class, nindex,
485                 mono_metadata_string_heap (m, cols [MONO_MEMBERREF_NAME]));*/
486
487         mname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
488
489         switch (class) {
490         case MONO_MEMBERREF_PARENT_TYPEREF:
491                 klass = mono_class_from_typeref (image, MONO_TOKEN_TYPE_REF | nindex);
492                 if (!klass) {
493                         char *name = mono_class_name_from_token (image, MONO_TOKEN_TYPE_REF | nindex, context);
494                         g_warning ("Missing method %s in assembly %s, type %s", mname, image->name, name);
495                         g_free (name);
496                         return NULL;
497                 }
498                 break;
499         case MONO_MEMBERREF_PARENT_TYPESPEC:
500                 klass = mono_class_get_full (image, MONO_TOKEN_TYPE_SPEC | nindex, context);
501                 if (!klass) {
502                         char *name = mono_class_name_from_token (image, MONO_TOKEN_TYPE_SPEC | nindex, context);
503                         g_warning ("Missing method %s in assembly %s, type %s", mname, image->name, name);
504                         g_free (name);
505                         return NULL;
506                 }
507                 break;
508         case MONO_MEMBERREF_PARENT_TYPEDEF:
509                 klass = mono_class_get (image, MONO_TOKEN_TYPE_DEF | nindex);
510                 if (!klass) {
511                         char *name = mono_class_name_from_token (image, MONO_TOKEN_TYPE_DEF | nindex, context);
512                         g_warning ("Missing method %s in assembly %s, type %s", mname, image->name, name);
513                         g_free (name);
514                         return NULL;
515                 }
516                 break;
517         case MONO_MEMBERREF_PARENT_METHODDEF:
518                 return mono_get_method (image, MONO_TOKEN_METHOD_DEF | nindex, NULL);
519         default:
520                 g_error ("Memberref parent unknown: class: %d, index %d", class, nindex);
521                 g_assert_not_reached ();
522         }
523         g_assert (klass);
524
525         if (klass->generic_class) {
526                 gclass = klass->generic_class;
527                 klass = gclass->container_class;
528         }
529         if (klass->generic_container)
530                 container = klass->generic_container;
531         mono_class_init (klass);
532
533         ptr = mono_metadata_blob_heap (image, cols [MONO_MEMBERREF_SIGNATURE]);
534         mono_metadata_decode_blob_size (ptr, &ptr);
535         sig = mono_metadata_parse_method_signature_full (image, (MonoGenericContext *) container, 0, ptr, NULL);
536
537         switch (class) {
538         case MONO_MEMBERREF_PARENT_TYPEREF:
539                 method = find_method (klass, NULL, mname, sig);
540                 if (!method)
541                         mono_loader_set_error_method_load (klass, mname);
542                 mono_metadata_free_method_signature (sig);
543                 break;
544         case MONO_MEMBERREF_PARENT_TYPESPEC: {
545                 MonoType *type;
546                 MonoMethod *result;
547
548                 type = &klass->byval_arg;
549
550                 if (type->type != MONO_TYPE_ARRAY && type->type != MONO_TYPE_SZARRAY) {
551                         method = find_method (klass, NULL, mname, sig);
552                         if (!method)
553                                 g_warning ("Missing method %s in assembly %s, type %s", mname, image->name, mono_class_get_name (klass));
554                         else if (klass->generic_class && (klass != method->klass))
555                                 method = mono_class_inflate_generic_method (
556                                         method, klass->generic_class->context);
557                         mono_metadata_free_method_signature (sig);
558                         break;
559                 }
560
561                 result = (MonoMethod *)g_new0 (MonoMethodPInvoke, 1);
562                 result->klass = mono_class_get (image, MONO_TOKEN_TYPE_SPEC | nindex);
563                 result->iflags = METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL;
564                 result->signature = sig;
565                 result->name = mname;
566
567                 if (!strcmp (mname, ".ctor")) {
568                         /* we special-case this in the runtime. */
569                         return result;
570                 }
571                 
572                 if (!strcmp (mname, "Set")) {
573                         g_assert (sig->hasthis);
574                         g_assert (type->data.array->rank + 1 == sig->param_count);
575                         result->iflags |= METHOD_IMPL_ATTRIBUTE_RUNTIME;
576                         return result;
577                 }
578
579                 if (!strcmp (mname, "Get")) {
580                         g_assert (sig->hasthis);
581                         g_assert (type->data.array->rank == sig->param_count);
582                         result->iflags |= METHOD_IMPL_ATTRIBUTE_RUNTIME;
583                         return result;
584                 }
585
586                 if (!strcmp (mname, "Address")) {
587                         g_assert (sig->hasthis);
588                         g_assert (type->data.array->rank == sig->param_count);
589                         result->iflags |= METHOD_IMPL_ATTRIBUTE_RUNTIME;
590                         return result;
591                 }
592
593                 g_assert_not_reached ();
594                 break;
595         }
596         case MONO_MEMBERREF_PARENT_TYPEDEF:
597                 method = find_method (klass, NULL, mname, sig);
598                 if (!method)
599                         g_warning ("Missing method %s in assembly %s, type %s", mname, image->name, mono_class_get_name (klass));
600                 mono_metadata_free_method_signature (sig);
601                 break;
602         default:
603                 g_error ("Memberref parent unknown: class: %d, index %d", class, nindex);
604                 g_assert_not_reached ();
605         }
606
607         if (gclass)
608                 method = mono_class_inflate_generic_method (method, gclass->context);
609
610         return method;
611 }
612
613 static MonoMethod *
614 method_from_methodspec (MonoImage *image, MonoGenericContext *context, guint32 idx)
615 {
616         MonoMethod *method, *inflated;
617         MonoTableInfo *tables = image->tables;
618         MonoGenericContext *new_context = NULL;
619         MonoGenericMethod *gmethod;
620         MonoGenericContainer *container = NULL;
621         const char *ptr;
622         guint32 cols [MONO_METHODSPEC_SIZE];
623         guint32 token, param_count;
624
625         mono_metadata_decode_row (&tables [MONO_TABLE_METHODSPEC], idx - 1, cols, MONO_METHODSPEC_SIZE);
626         token = cols [MONO_METHODSPEC_METHOD];
627         if ((token & MONO_METHODDEFORREF_MASK) == MONO_METHODDEFORREF_METHODDEF)
628                 token = MONO_TOKEN_METHOD_DEF | (token >> MONO_METHODDEFORREF_BITS);
629         else
630                 token = MONO_TOKEN_MEMBER_REF | (token >> MONO_METHODDEFORREF_BITS);
631
632         method = mono_get_method (image, token, NULL);
633         method = mono_get_inflated_method (method);
634
635         ptr = mono_metadata_blob_heap (image, cols [MONO_METHODSPEC_SIGNATURE]);
636         
637         mono_metadata_decode_value (ptr, &ptr);
638         ptr++;
639         param_count = mono_metadata_decode_value (ptr, &ptr);
640
641         g_assert (param_count);
642         if (method->is_inflated)
643                 container = ((MonoMethodNormal *) ((MonoMethodInflated *) method)->declaring)->generic_container;
644         else
645                 container = ((MonoMethodNormal *) method)->generic_container;
646         g_assert (container && container->is_method);
647
648         if (context) {
649                 g_assert (context->container);
650                 container->parent = context->container;
651                 if (container->parent->is_method)
652                         container->parent = container->parent->parent;
653         }
654
655         gmethod = g_new0 (MonoGenericMethod, 1);
656         gmethod->generic_class = method->klass->generic_class;
657         gmethod->container = container;
658
659         if (context && context->gmethod)
660                 new_context = &context->gmethod->container->context;
661         else if (context && context->gclass)
662                 new_context = &context->gclass->container_class->generic_container->context;
663         else
664                 new_context = context ? &context->container->context : NULL;
665
666         gmethod->inst = mono_metadata_parse_generic_inst (
667                 image, new_context, param_count, ptr, &ptr);
668
669         if (context)
670                 gmethod->inst = mono_metadata_inflate_generic_inst (gmethod->inst, context);
671
672         if (!container->method_hash)
673                 container->method_hash = g_hash_table_new (
674                         (GHashFunc)mono_metadata_generic_method_hash, (GEqualFunc)mono_metadata_generic_method_equal);
675
676         inflated = g_hash_table_lookup (container->method_hash, gmethod);
677         if (inflated) {
678                 g_free (gmethod);
679                 return inflated;
680         }
681
682         if (!context) {
683                 new_context = g_new0 (MonoGenericContext, 1);
684                 new_context->container = container;
685                 new_context->gmethod = gmethod;
686
687                 context = new_context;
688         } else {
689                 new_context = g_new0 (MonoGenericContext, 1);
690                 new_context->container = container;
691                 new_context->gmethod = gmethod;
692                 new_context->gclass = context->gclass;
693
694                 context = new_context;
695         }
696
697         mono_stats.generics_metadata_size += sizeof (MonoGenericMethod) +
698                 sizeof (MonoGenericContext) + param_count * sizeof (MonoType);
699
700         inflated = mono_class_inflate_generic_method (method, context);
701         g_hash_table_insert (container->method_hash, gmethod, inflated);
702
703         if (new_context)
704                 context->gclass = inflated->klass->generic_class;
705         return inflated;
706 }
707
708 typedef struct MonoDllMap MonoDllMap;
709
710 struct MonoDllMap {
711         char *name;
712         char *target;
713         char *dll;
714         MonoDllMap *next;
715 };
716
717 static GHashTable *global_dll_map;
718
719 static int 
720 mono_dllmap_lookup_hash (GHashTable *dll_map, const char *dll, const char* func, const char **rdll, const char **rfunc) {
721         MonoDllMap *map, *tmp;
722
723         *rdll = dll;
724
725         if (!dll_map)
726                 return 0;
727
728         mono_loader_lock ();
729
730         map = g_hash_table_lookup (dll_map, dll);
731         if (!map) {
732                 mono_loader_unlock ();
733                 return 0;
734         }
735         *rdll = map->target? map->target: dll;
736                 
737         for (tmp = map->next; tmp; tmp = tmp->next) {
738                 if (strcmp (func, tmp->name) == 0) {
739                         *rfunc = tmp->name;
740                         if (tmp->dll)
741                                 *rdll = tmp->dll;
742                         mono_loader_unlock ();
743                         return 1;
744                 }
745         }
746         *rfunc = func;
747         mono_loader_unlock ();
748         return 1;
749 }
750
751 static int 
752 mono_dllmap_lookup (MonoImage *assembly, const char *dll, const char* func, const char **rdll, const char **rfunc)
753 {
754         int res;
755         if (assembly && assembly->dll_map) {
756                 res = mono_dllmap_lookup_hash (assembly->dll_map, dll, func, rdll, rfunc);
757                 if (res)
758                         return res;
759         }
760         return mono_dllmap_lookup_hash (global_dll_map, dll, func, rdll, rfunc);
761 }
762
763 void
764 mono_dllmap_insert (MonoImage *assembly, const char *dll, const char *func, const char *tdll, const char *tfunc) {
765         MonoDllMap *map, *entry;
766         GHashTable *dll_map = NULL;
767
768         mono_loader_lock ();
769
770         if (!assembly) {
771                 if (!global_dll_map)
772                         global_dll_map = g_hash_table_new (g_str_hash, g_str_equal);
773                 dll_map = global_dll_map;
774         } else {
775                 if (!assembly->dll_map)
776                         assembly->dll_map = g_hash_table_new (g_str_hash, g_str_equal);
777                 dll_map = assembly->dll_map;
778         }
779
780         map = g_hash_table_lookup (dll_map, dll);
781         if (!map) {
782                 map = g_new0 (MonoDllMap, 1);
783                 map->dll = g_strdup (dll);
784                 if (tdll)
785                         map->target = g_strdup (tdll);
786                 g_hash_table_insert (dll_map, map->dll, map);
787         }
788         if (func) {
789                 entry = g_new0 (MonoDllMap, 1);
790                 entry->name = g_strdup (func);
791                 if (tfunc)
792                         entry->target = g_strdup (tfunc);
793                 if (tdll && map->target && strcmp (map->target, tdll))
794                         entry->dll = g_strdup (tdll);
795                 entry->next = map->next;
796                 map->next = entry;
797         }
798
799         mono_loader_unlock ();
800 }
801
802 gpointer
803 mono_lookup_pinvoke_call (MonoMethod *method, const char **exc_class, const char **exc_arg)
804 {
805         MonoImage *image = method->klass->image;
806         MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)method;
807         MonoTableInfo *tables = image->tables;
808         MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
809         MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
810         guint32 im_cols [MONO_IMPLMAP_SIZE];
811         guint32 scope_token;
812         const char *import = NULL;
813         const char *orig_scope;
814         const char *new_scope;
815         char *full_name, *file_name;
816         int i;
817         GModule *gmodule = NULL;
818
819         g_assert (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL);
820
821         if (piinfo->addr)
822                 return piinfo->addr;
823
824         if (method->klass->image->dynamic) {
825                 MonoReflectionMethodAux *method_aux = 
826                         g_hash_table_lookup (
827                                 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
828                 if (!method_aux)
829                         return NULL;
830
831                 import = method_aux->dllentry;
832                 orig_scope = method_aux->dll;
833         }
834         else {
835                 if (!piinfo->implmap_idx)
836                         return NULL;
837
838                 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
839
840                 piinfo->piflags = im_cols [MONO_IMPLMAP_FLAGS];
841                 import = mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]);
842                 scope_token = mono_metadata_decode_row_col (mr, im_cols [MONO_IMPLMAP_SCOPE] - 1, MONO_MODULEREF_NAME);
843                 orig_scope = mono_metadata_string_heap (image, scope_token);
844         }
845
846         mono_dllmap_lookup (image, orig_scope, import, &new_scope, &import);
847
848         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
849                         "DllImport attempting to load: '%s'.", new_scope);
850
851         if (exc_class) {
852                 *exc_class = NULL;
853                 *exc_arg = NULL;
854         }
855
856         /* we allow a special name to dlopen from the running process namespace */
857         if (strcmp (new_scope, "__Internal") == 0)
858                 gmodule = g_module_open (NULL, G_MODULE_BIND_LAZY);
859                 
860         /*
861          * Try loading the module using a variety of names
862          */
863         for (i = 0; i < 4; ++i) {
864                 switch (i) {
865                 case 0:
866                         /* Try the original name */
867                         file_name = g_strdup (new_scope);
868                         break;
869                 case 1:
870                         /* Try trimming the .dll extension */
871                         if (strstr (new_scope, ".dll") == (new_scope + strlen (new_scope) - 4)) {
872                                 file_name = g_strdup (new_scope);
873                                 file_name [strlen (new_scope) - 4] = '\0';
874                         }
875                         else
876                                 continue;
877                         break;
878                 case 2:
879                         if (strstr (new_scope, "lib") != new_scope) {
880                                 file_name = g_strdup_printf ("lib%s", new_scope);
881                         }
882                         else
883                                 continue;
884                         break;
885                 default:
886 #ifndef PLATFORM_WIN32
887                         if (!g_ascii_strcasecmp ("user32.dll", new_scope) ||
888                             !g_ascii_strcasecmp ("kernel32.dll", new_scope) ||
889                             !g_ascii_strcasecmp ("user32", new_scope) ||
890                             !g_ascii_strcasecmp ("kernel", new_scope)) {
891                                 file_name = g_strdup ("libMonoSupportW.so");
892                         } else
893 #endif
894                                     continue;
895 #ifndef PLATFORM_WIN32
896                         break;
897 #endif
898                 }
899
900                 if (!gmodule) {
901                         full_name = g_module_build_path (NULL, file_name);
902                         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
903                                         "DllImport loading location: '%s'.", full_name);
904                         gmodule = g_module_open (full_name, G_MODULE_BIND_LAZY);
905                         if (!gmodule) {
906                                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
907                                                 "DllImport error loading library: '%s'.",
908                                                 g_module_error ());
909                         }
910                         g_free (full_name);
911                 }
912
913                 if (!gmodule) {
914                         full_name = g_module_build_path (".", file_name);
915                         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
916                                         "DllImport loading library: '%s'.", full_name);
917                         gmodule = g_module_open (full_name, G_MODULE_BIND_LAZY);
918                         if (!gmodule) {
919                                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
920                                                 "DllImport error loading library '%s'.",
921                                                 g_module_error ());
922                         }
923                         g_free (full_name);
924                 }
925
926                 if (!gmodule) {
927                         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
928                                         "DllImport loading: '%s'.", file_name);
929                         gmodule=g_module_open (file_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                 }
936
937                 g_free (file_name);
938
939                 if (gmodule)
940                         break;
941         }
942
943         if (!gmodule) {
944                 mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_DLLIMPORT,
945                                 "DllImport unable to load library '%s'.",
946                                 g_module_error ());
947
948                 if (exc_class) {
949                         *exc_class = "DllNotFoundException";
950                         *exc_arg = new_scope;
951                 }
952                 return NULL;
953         }
954
955         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
956                                 "Searching for '%s'.", import);
957
958         if (piinfo->piflags & PINVOKE_ATTRIBUTE_NO_MANGLE) {
959                 g_module_symbol (gmodule, import, &piinfo->addr); 
960         } else {
961                 char *mangled_name = NULL, *mangled_name2 = NULL;
962                 int mangle_charset;
963                 int mangle_stdcall;
964                 int mangle_param_count;
965 #ifdef PLATFORM_WIN32
966                 int param_count;
967 #endif
968
969                 /*
970                  * Search using a variety of mangled names
971                  */
972                 for (mangle_charset = 0; mangle_charset <= 1; mangle_charset ++) {
973                         for (mangle_stdcall = 0; mangle_stdcall <= 1; mangle_stdcall ++) {
974                                 gboolean need_param_count = FALSE;
975 #ifdef PLATFORM_WIN32
976                                 if (mangle_stdcall > 0)
977                                         need_param_count = TRUE;
978 #endif
979                                 for (mangle_param_count = 0; mangle_param_count <= (need_param_count ? 256 : 0); mangle_param_count += 4) {
980
981                                         if (piinfo->addr)
982                                                 continue;
983
984                                         mangled_name = (char*)import;
985                                         switch (piinfo->piflags & PINVOKE_ATTRIBUTE_CHAR_SET_MASK) {
986                                         case PINVOKE_ATTRIBUTE_CHAR_SET_UNICODE:
987                                                 /* Try the mangled name first */
988                                                 if (mangle_charset == 0)
989                                                         mangled_name = g_strconcat (import, "W", NULL);
990                                                 break;
991                                         case PINVOKE_ATTRIBUTE_CHAR_SET_AUTO:
992 #ifdef PLATFORM_WIN32
993                                                 if (mangle_charset == 0)
994                                                         mangled_name = g_strconcat (import, "W", NULL);
995 #endif
996                                                 break;
997                                         case PINVOKE_ATTRIBUTE_CHAR_SET_ANSI:
998                                         default:
999                                                 /* Try the mangled name last */
1000                                                 if (mangle_charset == 1)
1001                                                         mangled_name = g_strconcat (import, "A", NULL);
1002                                                 break;
1003                                         }
1004
1005 #ifdef PLATFORM_WIN32
1006                                         if (mangle_param_count == 0)
1007                                                 param_count = mono_method_signature (method)->param_count * sizeof (gpointer);
1008                                         else
1009                                                 /* Try brute force, since it would be very hard to compute the stack usage correctly */
1010                                                 param_count = mangle_param_count;
1011
1012                                         /* Try the stdcall mangled name */
1013                                         /* 
1014                                          * gcc under windows creates mangled names without the underscore, but MS.NET
1015                                          * doesn't support it, so we doesn't support it either.
1016                                          */
1017                                         if (mangle_stdcall == 1)
1018                                                 mangled_name2 = g_strdup_printf ("_%s@%d", mangled_name, param_count);
1019                                         else
1020                                                 mangled_name2 = mangled_name;
1021 #else
1022                                         mangled_name2 = mangled_name;
1023 #endif
1024
1025                                         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1026                                                                 "Probing '%s'.", mangled_name2);
1027
1028                                         g_module_symbol (gmodule, mangled_name2, &piinfo->addr);
1029
1030                                         if (piinfo->addr)
1031                                                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
1032                                                                         "Found as '%s'.", mangled_name2);
1033
1034                                         if (mangled_name != mangled_name2)
1035                                                 g_free (mangled_name2);
1036                                         if (mangled_name != import)
1037                                                 g_free (mangled_name);
1038                                 }
1039                         }
1040                 }
1041         }
1042
1043         if (!piinfo->addr) {
1044                 if (exc_class) {
1045                         *exc_class = "EntryPointNotFoundException";
1046                         *exc_arg = import;
1047                 }
1048                 return NULL;
1049         }
1050         return piinfo->addr;
1051 }
1052
1053 static MonoMethod *
1054 mono_get_method_from_token (MonoImage *image, guint32 token, MonoClass *klass,
1055                             MonoGenericContext *context)
1056 {
1057         MonoMethod *result;
1058         int table = mono_metadata_token_table (token);
1059         int idx = mono_metadata_token_index (token);
1060         MonoTableInfo *tables = image->tables;
1061         MonoGenericContainer *generic_container = NULL, *container = NULL;
1062         const char *sig = NULL;
1063         int size, i;
1064         guint32 cols [MONO_TYPEDEF_SIZE];
1065
1066         if (image->dynamic)
1067                 return mono_lookup_dynamic_token (image, token);
1068
1069         if (table != MONO_TABLE_METHOD) {
1070                 MonoGenericContainer *generic_container = NULL;
1071                 if (context) {
1072                         g_assert (context->container);
1073                         generic_container = context->container;
1074                 }
1075                 if (table == MONO_TABLE_METHODSPEC)
1076                         return method_from_methodspec (image, context, idx);
1077                 if (table != MONO_TABLE_MEMBERREF)
1078                         g_print("got wrong token: 0x%08x\n", token);
1079                 g_assert (table == MONO_TABLE_MEMBERREF);
1080                 result = method_from_memberref (image, idx, context);
1081
1082                 return result;
1083         }
1084
1085         mono_metadata_decode_row (&tables [table], idx - 1, cols, 6);
1086
1087         if ((cols [2] & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
1088             (cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))
1089                 result = (MonoMethod *)g_new0 (MonoMethodPInvoke, 1);
1090         else 
1091                 result = (MonoMethod *)g_new0 (MonoMethodNormal, 1);
1092         
1093         result->slot = -1;
1094         result->klass = klass;
1095         result->flags = cols [2];
1096         result->iflags = cols [1];
1097         result->token = token;
1098         result->name = mono_metadata_string_heap (image, cols [3]);
1099
1100         if (klass)
1101                 container = klass->generic_container;
1102
1103         if (!(cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) &&
1104             (!(cols [2] & METHOD_ATTRIBUTE_PINVOKE_IMPL) || cols [1] & METHOD_IMPL_ATTRIBUTE_NATIVE)) {
1105                 generic_container = mono_metadata_load_generic_params (image, token, container);
1106                 if (generic_container)
1107                         container = generic_container;
1108         }
1109
1110         if (!sig) /* already taken from the methodref */
1111                 sig = mono_metadata_blob_heap (image, cols [4]);
1112         size = mono_metadata_decode_blob_size (sig, &sig);
1113         
1114         /* there are generic params, or a container. FIXME: be lazy here for generics*/
1115         if (* sig & 0x10 || container) {
1116                 result->signature = mono_metadata_parse_method_signature_full (
1117                         image, (MonoGenericContext *) container, idx, sig, NULL);
1118
1119                 if (cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
1120                         result->signature->pinvoke = 1;
1121         }
1122
1123         if (!result->klass) {
1124                 guint32 type = mono_metadata_typedef_from_method (image, token);
1125                 result->klass = mono_class_get (image, MONO_TOKEN_TYPE_DEF | type);
1126         }
1127
1128         if (cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
1129                 if (result->klass == mono_defaults.string_class && !strcmp (result->name, ".ctor"))
1130                         result->string_ctor = 1;
1131         } else if ((cols [2] & METHOD_ATTRIBUTE_PINVOKE_IMPL) && (!(cols [1] & METHOD_IMPL_ATTRIBUTE_NATIVE))) {
1132                 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)result;
1133                 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
1134                 
1135                 piinfo->implmap_idx = mono_metadata_implmap_from_method (image, idx - 1);
1136                 piinfo->piflags = mono_metadata_decode_row_col (im, piinfo->implmap_idx - 1, MONO_IMPLMAP_FLAGS);
1137         } else {
1138                 if (result->signature && result->signature->generic_param_count) {
1139                         MonoMethodSignature *sig = result->signature;
1140
1141                         for (i = 0; i < sig->generic_param_count; i++) {
1142                                 generic_container->type_params [i].method = result;
1143
1144                                 mono_class_from_generic_parameter (
1145                                         &generic_container->type_params [i], image, TRUE);
1146                         }
1147
1148                         if (sig->ret->type == MONO_TYPE_MVAR) {
1149                                 int num = sig->ret->data.generic_param->num;
1150                                 sig->ret->data.generic_param = &generic_container->type_params [num];
1151                         }
1152
1153                         for (i = 0; i < sig->param_count; i++) {
1154                                 MonoType *t = sig->params [i];
1155                                 if (t->type == MONO_TYPE_MVAR) {
1156                                         int num = t->data.generic_param->num;
1157                                         sig->params [i]->data.generic_param = &generic_container->type_params [num];
1158                                 }
1159                         }
1160                 }
1161                 
1162                 /* FIXME: lazyness for generics too, but how? */
1163                 if (!result->klass->dummy && !(result->flags & METHOD_ATTRIBUTE_ABSTRACT) &&
1164                     !(result->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) && container) {
1165                         gpointer loc = mono_image_rva_map (image, cols [0]);
1166                         g_assert (loc);
1167                         ((MonoMethodNormal *) result)->header = mono_metadata_parse_mh_full (
1168                                 image, (MonoGenericContext *) container, loc);
1169                 }
1170                 
1171                 ((MonoMethodNormal *) result)->generic_container = generic_container;
1172         }
1173
1174         return result;
1175 }
1176
1177 MonoMethod *
1178 mono_get_method (MonoImage *image, guint32 token, MonoClass *klass)
1179 {
1180         return mono_get_method_full (image, token, klass, NULL);
1181 }
1182
1183 MonoMethod *
1184 mono_get_method_full (MonoImage *image, guint32 token, MonoClass *klass,
1185                       MonoGenericContext *context)
1186 {
1187         MonoMethod *result;
1188
1189         /* We do everything inside the lock to prevent creation races */
1190
1191         mono_loader_lock ();
1192
1193         if ((result = g_hash_table_lookup (image->method_cache, GINT_TO_POINTER (token)))) {
1194                 mono_loader_unlock ();
1195                 return result;
1196         }
1197
1198         result = mono_get_method_from_token (image, token, klass, context);
1199
1200         //printf ("GET: %s\n", mono_method_full_name (result, TRUE));
1201
1202         if (!(result && result->is_inflated))
1203                 g_hash_table_insert (image->method_cache, GINT_TO_POINTER (token), result);
1204
1205         mono_loader_unlock ();
1206
1207         return result;
1208 }
1209
1210 MonoMethod *
1211 mono_get_method_constrained (MonoImage *image, guint32 token, MonoClass *constrained_class,
1212                              MonoGenericContext *context)
1213 {
1214         MonoMethod *method, *result;
1215         MonoClass *ic = NULL;
1216         MonoGenericClass *gclass = NULL;
1217
1218         mono_loader_lock ();
1219
1220         method = mono_get_method_from_token (image, token, NULL, context);
1221         if (!method) {
1222                 mono_loader_unlock ();
1223                 return NULL;
1224         }
1225
1226         mono_class_init (constrained_class);
1227         method = mono_get_inflated_method (method);
1228
1229         if ((constrained_class != method->klass) && (method->klass->interface_id != 0))
1230                 ic = method->klass;
1231
1232         if (constrained_class->generic_class)
1233                 gclass = constrained_class->generic_class;
1234
1235         result = find_method (constrained_class, ic, method->name, mono_method_signature (method));
1236         if (!result)
1237                 g_warning ("Missing method %s in assembly %s token %x", method->name,
1238                            image->name, token);
1239
1240         if (gclass)
1241                 result = mono_class_inflate_generic_method (result, gclass->context);
1242
1243         mono_loader_unlock ();
1244         return result;
1245 }
1246
1247 void
1248 mono_free_method  (MonoMethod *method)
1249 {
1250         if (method->signature) {
1251                 /* 
1252                  * FIXME: This causes crashes because the types inside signatures and
1253                  * locals are shared.
1254                  */
1255                 /* mono_metadata_free_method_signature (method->signature); */
1256                 g_free (method->signature);
1257         }
1258
1259         if (method->dynamic) {
1260                 MonoMethodWrapper *mw = (MonoMethodWrapper*)method;
1261
1262                 g_free ((char*)method->name);
1263                 if (mw->method.header)
1264                         g_free ((char*)mw->method.header->code);
1265                 g_free (mw->method_data);
1266         }
1267
1268         if (!(method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && ((MonoMethodNormal *)method)->header) {
1269                 /* FIXME: Ditto */
1270                 /* mono_metadata_free_mh (((MonoMethodNormal *)method)->header); */
1271                 g_free (((MonoMethodNormal*)method)->header);
1272         }
1273
1274         g_free (method);
1275 }
1276
1277 void
1278 mono_method_get_param_names (MonoMethod *method, const char **names)
1279 {
1280         int i, lastp;
1281         MonoClass *klass = method->klass;
1282         MonoTableInfo *methodt;
1283         MonoTableInfo *paramt;
1284         guint32 idx;
1285
1286         if (!mono_method_signature (method)->param_count)
1287                 return;
1288         for (i = 0; i < mono_method_signature (method)->param_count; ++i)
1289                 names [i] = "";
1290
1291         if (klass->generic_class) /* copy the names later */
1292                 return;
1293
1294         mono_class_init (klass);
1295
1296         if (klass->image->dynamic) {
1297                 MonoReflectionMethodAux *method_aux = 
1298                         g_hash_table_lookup (
1299                                 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
1300                 if (method_aux && method_aux->param_names) {
1301                         for (i = 0; i < mono_method_signature (method)->param_count; ++i)
1302                                 if (method_aux->param_names [i + 1])
1303                                         names [i] = method_aux->param_names [i + 1];
1304                 }
1305                 return;
1306         }
1307
1308         methodt = &klass->image->tables [MONO_TABLE_METHOD];
1309         paramt = &klass->image->tables [MONO_TABLE_PARAM];
1310         idx = mono_method_get_index (method);
1311         if (idx > 0) {
1312                 guint32 cols [MONO_PARAM_SIZE];
1313                 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
1314
1315                 if (idx < methodt->rows)
1316                         lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
1317                 else
1318                         lastp = paramt->rows + 1;
1319                 for (i = param_index; i < lastp; ++i) {
1320                         mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
1321                         if (cols [MONO_PARAM_SEQUENCE]) /* skip return param spec */
1322                                 names [cols [MONO_PARAM_SEQUENCE] - 1] = mono_metadata_string_heap (klass->image, cols [MONO_PARAM_NAME]);
1323                 }
1324                 return;
1325         }
1326 }
1327
1328 guint32
1329 mono_method_get_param_token (MonoMethod *method, int index)
1330 {
1331         MonoClass *klass = method->klass;
1332         MonoTableInfo *methodt;
1333         guint32 idx;
1334
1335         if (klass->generic_class)
1336                 g_assert_not_reached ();
1337
1338         mono_class_init (klass);
1339
1340         if (klass->image->dynamic) {
1341                 g_assert_not_reached ();
1342         }
1343
1344         methodt = &klass->image->tables [MONO_TABLE_METHOD];
1345         idx = mono_method_get_index (method);
1346         if (idx > 0) {
1347                 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
1348
1349                 return mono_metadata_make_token (MONO_TABLE_PARAM, param_index + index);
1350         }
1351
1352         return 0;
1353 }
1354
1355 void
1356 mono_method_get_marshal_info (MonoMethod *method, MonoMarshalSpec **mspecs)
1357 {
1358         int i, lastp;
1359         MonoClass *klass = method->klass;
1360         MonoTableInfo *methodt;
1361         MonoTableInfo *paramt;
1362         guint32 idx;
1363
1364         for (i = 0; i < mono_method_signature (method)->param_count + 1; ++i)
1365                 mspecs [i] = NULL;
1366
1367         if (method->klass->image->dynamic) {
1368                 MonoReflectionMethodAux *method_aux = 
1369                         g_hash_table_lookup (
1370                                 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
1371                 if (method_aux && method_aux->param_marshall) {
1372                         MonoMarshalSpec **dyn_specs = method_aux->param_marshall;
1373                         for (i = 0; i < mono_method_signature (method)->param_count + 1; ++i)
1374                                 if (dyn_specs [i]) {
1375                                         mspecs [i] = g_new0 (MonoMarshalSpec, 1);
1376                                         memcpy (mspecs [i], dyn_specs [i], sizeof (MonoMarshalSpec));
1377                                 }
1378                 }
1379                 return;
1380         }
1381
1382         mono_class_init (klass);
1383
1384         methodt = &klass->image->tables [MONO_TABLE_METHOD];
1385         paramt = &klass->image->tables [MONO_TABLE_PARAM];
1386         idx = mono_method_get_index (method);
1387         if (idx > 0) {
1388                 guint32 cols [MONO_PARAM_SIZE];
1389                 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
1390
1391                 if (idx < methodt->rows)
1392                         lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
1393                 else
1394                         lastp = paramt->rows + 1;
1395
1396                 for (i = param_index; i < lastp; ++i) {
1397                         mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
1398
1399                         if (cols [MONO_PARAM_FLAGS] & PARAM_ATTRIBUTE_HAS_FIELD_MARSHAL) {
1400                                 const char *tp;
1401                                 tp = mono_metadata_get_marshal_info (klass->image, i - 1, FALSE);
1402                                 g_assert (tp);
1403                                 mspecs [cols [MONO_PARAM_SEQUENCE]]= mono_metadata_parse_marshal_spec (klass->image, tp);
1404                         }
1405                 }
1406
1407                 return;
1408         }
1409 }
1410
1411 gboolean
1412 mono_method_has_marshal_info (MonoMethod *method)
1413 {
1414         int i, lastp;
1415         MonoClass *klass = method->klass;
1416         MonoTableInfo *methodt;
1417         MonoTableInfo *paramt;
1418         guint32 idx;
1419
1420         if (method->klass->image->dynamic) {
1421                 MonoReflectionMethodAux *method_aux = 
1422                         g_hash_table_lookup (
1423                                 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
1424                 MonoMarshalSpec **dyn_specs = method_aux->param_marshall;
1425                 if (dyn_specs) {
1426                         for (i = 0; i < mono_method_signature (method)->param_count + 1; ++i)
1427                                 if (dyn_specs [i])
1428                                         return TRUE;
1429                 }
1430                 return FALSE;
1431         }
1432
1433         mono_class_init (klass);
1434
1435         methodt = &klass->image->tables [MONO_TABLE_METHOD];
1436         paramt = &klass->image->tables [MONO_TABLE_PARAM];
1437         idx = mono_method_get_index (method);
1438         if (idx > 0) {
1439                 guint32 cols [MONO_PARAM_SIZE];
1440                 guint param_index = mono_metadata_decode_row_col (methodt, idx - 1, MONO_METHOD_PARAMLIST);
1441                 
1442                 if (idx + 1 < methodt->rows)
1443                         lastp = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
1444                 else
1445                         lastp = paramt->rows + 1;
1446
1447                 for (i = param_index; i < lastp; ++i) {
1448                         mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
1449
1450                         if (cols [MONO_PARAM_FLAGS] & PARAM_ATTRIBUTE_HAS_FIELD_MARSHAL)
1451                                 return TRUE;
1452                 }
1453                 return FALSE;
1454         }
1455         return FALSE;
1456 }
1457
1458 gpointer
1459 mono_method_get_wrapper_data (MonoMethod *method, guint32 id)
1460 {
1461         void **data;
1462         g_assert (method != NULL);
1463         g_assert (method->wrapper_type != MONO_WRAPPER_NONE);
1464
1465         data = ((MonoMethodWrapper *)method)->method_data;
1466         g_assert (data != NULL);
1467         g_assert (id <= GPOINTER_TO_UINT (*data));
1468         return data [id];
1469 }
1470
1471 static void
1472 default_stack_walk (MonoStackWalk func, gboolean do_il_offset, gpointer user_data) {
1473         g_error ("stack walk not installed");
1474 }
1475
1476 static MonoStackWalkImpl stack_walk = default_stack_walk;
1477
1478 void
1479 mono_stack_walk (MonoStackWalk func, gpointer user_data)
1480 {
1481         stack_walk (func, TRUE, user_data);
1482 }
1483
1484 void
1485 mono_stack_walk_no_il (MonoStackWalk func, gpointer user_data)
1486 {
1487         stack_walk (func, FALSE, user_data);
1488 }
1489
1490 void
1491 mono_install_stack_walk (MonoStackWalkImpl func)
1492 {
1493         stack_walk = func;
1494 }
1495
1496 static gboolean
1497 last_managed (MonoMethod *m, gint no, gint ilo, gboolean managed, gpointer data)
1498 {
1499         MonoMethod **dest = data;
1500         *dest = m;
1501         /*g_print ("In %s::%s [%d] [%d]\n", m->klass->name, m->name, no, ilo);*/
1502
1503         return managed;
1504 }
1505
1506 MonoMethod*
1507 mono_method_get_last_managed (void)
1508 {
1509         MonoMethod *m = NULL;
1510         stack_walk (last_managed, FALSE, &m);
1511         return m;
1512 }
1513
1514 void
1515 mono_loader_lock (void)
1516 {
1517         EnterCriticalSection (&loader_mutex);
1518 }
1519
1520 void
1521 mono_loader_unlock (void)
1522 {
1523         LeaveCriticalSection (&loader_mutex);
1524 }
1525
1526 MonoMethodSignature* 
1527 mono_method_signature (MonoMethod *m)
1528 {
1529         m = mono_get_inflated_method (m);
1530         return mono_method_signature_full (m, NULL);
1531 }
1532
1533 MonoMethodSignature* 
1534 mono_method_signature_full (MonoMethod *m, MonoGenericContext *context)
1535 {
1536         int idx;
1537         int size;
1538         MonoImage* img;
1539         const char *sig;
1540         
1541         if (m->signature)
1542                 return m->signature;
1543                 
1544         mono_loader_lock ();
1545         
1546         if (m->signature) {
1547                 mono_loader_unlock ();
1548                 return m->signature;
1549         }
1550         
1551         g_assert (mono_metadata_token_table (m->token) == MONO_TABLE_METHOD);
1552         idx = mono_metadata_token_index (m->token);
1553         img = m->klass->image;
1554         
1555         sig = mono_metadata_blob_heap (img, mono_metadata_decode_row_col (&img->tables [MONO_TABLE_METHOD], idx - 1, MONO_METHOD_SIGNATURE));
1556         size = mono_metadata_decode_blob_size (sig, &sig);
1557         
1558         m->signature = mono_metadata_parse_method_signature_full (img, context, idx, sig, NULL);
1559         
1560         if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
1561                 m->signature->pinvoke = 1;
1562         else if ((m->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) && (!(m->iflags & METHOD_IMPL_ATTRIBUTE_NATIVE))) {
1563                 MonoCallConvention conv = 0;
1564                 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)m;
1565                 m->signature->pinvoke = 1;
1566                 
1567                 switch (piinfo->piflags & PINVOKE_ATTRIBUTE_CALL_CONV_MASK) {
1568                 case 0: /* no call conv, so using default */
1569                 case PINVOKE_ATTRIBUTE_CALL_CONV_WINAPI:
1570                         conv = MONO_CALL_DEFAULT;
1571                         break;
1572                 case PINVOKE_ATTRIBUTE_CALL_CONV_CDECL:
1573                         conv = MONO_CALL_C;
1574                         break;
1575                 case PINVOKE_ATTRIBUTE_CALL_CONV_STDCALL:
1576                         conv = MONO_CALL_STDCALL;
1577                         break;
1578                 case PINVOKE_ATTRIBUTE_CALL_CONV_THISCALL:
1579                         conv = MONO_CALL_THISCALL;
1580                         break;
1581                 case PINVOKE_ATTRIBUTE_CALL_CONV_FASTCALL:
1582                         conv = MONO_CALL_FASTCALL;
1583                         break;
1584                 case PINVOKE_ATTRIBUTE_CALL_CONV_GENERIC:
1585                 case PINVOKE_ATTRIBUTE_CALL_CONV_GENERICINST:
1586                 default:
1587                         g_warning ("unsupported calling convention : 0x%04x", piinfo->piflags);
1588                         g_assert_not_reached ();
1589                 }       
1590                 m->signature->call_convention = conv;
1591         }
1592         
1593         mono_loader_unlock ();
1594         return m->signature;
1595 }
1596
1597 const char*
1598 mono_method_get_name (MonoMethod *method)
1599 {
1600         return method->name;
1601 }
1602
1603 MonoClass*
1604 mono_method_get_class (MonoMethod *method)
1605 {
1606         return method->klass;
1607 }
1608
1609 guint32
1610 mono_method_get_token (MonoMethod *method)
1611 {
1612         return method->token;
1613 }
1614
1615 MonoMethodHeader* 
1616 mono_method_get_header (MonoMethod *method)
1617 {
1618         int idx;
1619         guint32 rva;
1620         MonoImage* img;
1621         gpointer loc;
1622         MonoMethodNormal* mn = (MonoMethodNormal*) method;
1623         
1624 #ifdef G_LIKELY
1625         if (G_LIKELY (mn->header))
1626 #else
1627         if (mn->header)
1628 #endif
1629                 return mn->header;
1630         
1631         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))
1632                 return NULL;
1633         
1634         mono_loader_lock ();
1635         
1636         if (mn->header) {
1637                 mono_loader_unlock ();
1638                 return mn->header;
1639         }
1640         
1641         g_assert (mono_metadata_token_table (method->token) == MONO_TABLE_METHOD);
1642         idx = mono_metadata_token_index (method->token);
1643         img = method->klass->image;
1644         rva = mono_metadata_decode_row_col (&img->tables [MONO_TABLE_METHOD], idx - 1, MONO_METHOD_RVA);
1645         loc = mono_image_rva_map (img, rva);
1646         
1647         g_assert (loc);
1648         
1649         mn->header = mono_metadata_parse_mh_full (img, (MonoGenericContext *) mn->generic_container, loc);
1650         
1651         mono_loader_unlock ();
1652         return mn->header;
1653 }
1654
1655 guint32
1656 mono_method_get_flags (MonoMethod *method, guint32 *iflags)
1657 {
1658         if (iflags)
1659                 *iflags = method->iflags;
1660         return method->flags;
1661 }
1662
1663 /*
1664  * Find the method index in the metadata methodDef table.
1665  */
1666 guint32
1667 mono_method_get_index (MonoMethod *method) {
1668         MonoClass *klass = method->klass;
1669         int i;
1670
1671         if (method->token)
1672                 return mono_metadata_token_index (method->token);
1673
1674         mono_class_setup_methods (klass);
1675         for (i = 0; i < klass->method.count; ++i) {
1676                 if (method == klass->methods [i])
1677                         return klass->method.first + 1 + i;
1678         }
1679         return 0;
1680 }
1681