* appdomain.c: Increment version number.
[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/loader.h>
32 #include <mono/metadata/class.h>
33 #include <mono/metadata/debug-helpers.h>
34 #include <mono/metadata/reflection.h>
35
36 MonoDefaults mono_defaults;
37
38 CRITICAL_SECTION loader_mutex;
39
40 void
41 mono_loader_init ()
42 {
43         InitializeCriticalSection (&loader_mutex);
44 }
45
46 static MonoClassField*
47 field_from_memberref (MonoImage *image, guint32 token, MonoClass **retklass,
48                       MonoGenericContext *context)
49 {
50         MonoClass *klass;
51         MonoTableInfo *tables = image->tables;
52         guint32 cols[6];
53         guint32 nindex, class;
54         const char *fname;
55         const char *ptr;
56         guint32 idx = mono_metadata_token_index (token);
57
58         if (image->dynamic) {
59                 MonoClassField *result = mono_lookup_dynamic_token (image, token);
60                 *retklass = result->parent;
61                 return result;
62         }
63
64         mono_metadata_decode_row (&tables [MONO_TABLE_MEMBERREF], idx-1, cols, MONO_MEMBERREF_SIZE);
65         nindex = cols [MONO_MEMBERREF_CLASS] >> MEMBERREF_PARENT_BITS;
66         class = cols [MONO_MEMBERREF_CLASS] & MEMBERREF_PARENT_MASK;
67
68         fname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
69         
70         ptr = mono_metadata_blob_heap (image, cols [MONO_MEMBERREF_SIGNATURE]);
71         mono_metadata_decode_blob_size (ptr, &ptr);
72         /* we may want to check the signature here... */
73
74         switch (class) {
75         case MEMBERREF_PARENT_TYPEREF:
76                 klass = mono_class_from_typeref (image, MONO_TOKEN_TYPE_REF | nindex);
77                 if (!klass) {
78                         g_warning ("Missing field %s in typeref index %d", fname, nindex);
79                         return NULL;
80                 }
81                 mono_class_init (klass);
82                 if (retklass)
83                         *retklass = klass;
84                 return mono_class_get_field_from_name (klass, fname);
85         case MEMBERREF_PARENT_TYPESPEC: {
86                 /*guint32 bcols [MONO_TYPESPEC_SIZE];
87                 guint32 len;
88                 MonoType *type;
89
90                 mono_metadata_decode_row (&tables [MONO_TABLE_TYPESPEC], nindex - 1, 
91                                           bcols, MONO_TYPESPEC_SIZE);
92                 ptr = mono_metadata_blob_heap (image, bcols [MONO_TYPESPEC_SIGNATURE]);
93                 len = mono_metadata_decode_value (ptr, &ptr);   
94                 type = mono_metadata_parse_type (image, MONO_PARSE_TYPE, 0, ptr, &ptr);
95
96                 klass = mono_class_from_mono_type (type);
97                 mono_class_init (klass);
98                 g_print ("type in sig: %s\n", klass->name);*/
99                 klass = mono_class_get_full (image, MONO_TOKEN_TYPE_SPEC | nindex, context);
100                 mono_class_init (klass);
101                 if (retklass)
102                         *retklass = klass;
103                 return mono_class_get_field_from_name (klass, fname);
104         }
105         default:
106                 g_warning ("field load from %x", class);
107                 return NULL;
108         }
109 }
110
111 MonoClassField*
112 mono_field_from_token (MonoImage *image, guint32 token, MonoClass **retklass,
113                        MonoGenericContext *context)
114 {
115         MonoClass *k;
116         guint32 type;
117         MonoClassField *field;
118
119         if (image->dynamic) {
120                 MonoClassField *result = mono_lookup_dynamic_token (image, token);
121                 *retklass = result->parent;
122                 return result;
123         }
124
125         mono_loader_lock ();
126         if ((field = g_hash_table_lookup (image->field_cache, GUINT_TO_POINTER (token)))) {
127                 *retklass = field->parent;
128                 mono_loader_unlock ();
129                 return field;
130         }
131         mono_loader_unlock ();
132
133         if (mono_metadata_token_table (token) == MONO_TABLE_MEMBERREF)
134                 field = field_from_memberref (image, token, retklass, context);
135         else {
136                 type = mono_metadata_typedef_from_field (image, mono_metadata_token_index (token));
137                 if (!type)
138                         return NULL;
139                 k = mono_class_get (image, MONO_TOKEN_TYPE_DEF | type);
140                 mono_class_init (k);
141                 if (!k)
142                         return NULL;
143                 if (retklass)
144                         *retklass = k;
145                 field = mono_class_get_field (k, token);
146         }
147
148         mono_loader_lock ();
149         if (!field->parent->generic_inst)
150                 g_hash_table_insert (image->field_cache, GUINT_TO_POINTER (token), field);
151         mono_loader_unlock ();
152         return field;
153 }
154
155 static gboolean
156 mono_metadata_signature_vararg_match (MonoMethodSignature *sig1, MonoMethodSignature *sig2)
157 {
158         int i;
159
160         if (sig1->hasthis != sig2->hasthis ||
161             sig1->sentinelpos != sig2->sentinelpos)
162                 return FALSE;
163
164         for (i = 0; i < sig1->sentinelpos; i++) { 
165                 MonoType *p1 = sig1->params[i];
166                 MonoType *p2 = sig2->params[i];
167                 
168                 //if (p1->attrs != p2->attrs)
169                 //      return FALSE;
170                 
171                 if (!mono_metadata_type_equal (p1, p2))
172                         return FALSE;
173         }
174
175         if (!mono_metadata_type_equal (sig1->ret, sig2->ret))
176                 return FALSE;
177         return TRUE;
178 }
179
180 static MonoMethod *
181 find_method (MonoClass *klass, MonoClass *ic, const char* name, MonoMethodSignature *sig)
182 {
183         int i;
184         MonoClass *sclass = klass;
185         char *qname, *fqname;
186
187         if (ic) {
188                 qname = g_strconcat (ic->name, ".", name, NULL); 
189                 if (ic->name_space && ic->name_space [0])
190                         fqname = g_strconcat (ic->name_space, ".", ic->name, ".", name, NULL);
191                 else
192                         fqname = NULL;
193         } else
194                 qname = fqname = NULL;
195
196         while (klass) {
197                 for (i = 0; i < klass->method.count; ++i) {
198                         MonoMethod *m = klass->methods [i];
199
200                         if (!((fqname && !strcmp (m->name, fqname)) ||
201                               (qname && !strcmp (m->name, qname)) || !strcmp (m->name, name)))
202                                 continue;
203
204                         if (sig->call_convention == MONO_CALL_VARARG) {
205                                 if (mono_metadata_signature_vararg_match (sig, m->signature))
206                                         return m;
207                         } else {
208                                 if (mono_metadata_signature_equal (sig, m->signature))
209                                         return m;
210                         }
211                 }
212
213                 if (name [0] == '.' && (strcmp (name, ".ctor") == 0 || strcmp (name, ".cctor") == 0))
214                         break;
215
216                 klass = klass->parent;
217         }
218
219         if (sclass->generic_inst) {
220                 MonoClass *gclass;
221                 MonoMethod *res;
222
223                 gclass = mono_class_from_mono_type (sclass->generic_inst->generic_type);
224                 mono_class_init (gclass);
225
226                 res = find_method (gclass, ic, name, sig);
227                 if (!res)
228                         return NULL;
229                 for (i = 0; i < res->klass->method.count; ++i) {
230                         if (res == res->klass->methods [i]) {
231                                 return sclass->methods [i];
232                         }
233                 }
234         }
235
236         return NULL;
237 }
238
239 /*
240  * token is the method_ref or method_def token used in a call IL instruction.
241  */
242 MonoMethodSignature*
243 mono_method_get_signature (MonoMethod *method, MonoImage *image, guint32 token)
244 {
245         int table = mono_metadata_token_table (token);
246         int idx = mono_metadata_token_index (token);
247         guint32 cols [MONO_MEMBERREF_SIZE];
248         MonoMethodSignature *sig;
249         const char *ptr;
250
251         /* !table is for wrappers: we should really assign their own token to them */
252         if (!table || table == MONO_TABLE_METHOD)
253                 return method->signature;
254
255         if (table == MONO_TABLE_METHODSPEC) {
256                 g_assert (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) &&
257                           !(method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) &&
258                           method->signature);
259                 g_assert (method->signature->is_inflated);
260
261                 return method->signature;
262         }
263
264         if (method->klass->generic_inst)
265                 return method->signature;
266
267         if (image->dynamic)
268                 /* FIXME: This might be incorrect for vararg methods */
269                 return method->signature;
270
271         mono_metadata_decode_row (&image->tables [MONO_TABLE_MEMBERREF], idx-1, cols, MONO_MEMBERREF_SIZE);
272         
273         ptr = mono_metadata_blob_heap (image, cols [MONO_MEMBERREF_SIGNATURE]);
274         mono_metadata_decode_blob_size (ptr, &ptr);
275         sig = mono_metadata_parse_method_signature (image, 0, ptr, NULL);
276
277         return sig;
278 }
279
280 static MonoMethod *
281 method_from_memberref (MonoImage *image, guint32 idx, MonoGenericContext *context)
282 {
283         MonoClass *klass;
284         MonoMethod *method;
285         MonoTableInfo *tables = image->tables;
286         guint32 cols[6];
287         guint32 nindex, class;
288         const char *mname;
289         MonoMethodSignature *sig;
290         const char *ptr;
291
292         mono_metadata_decode_row (&tables [MONO_TABLE_MEMBERREF], idx-1, cols, 3);
293         nindex = cols [MONO_MEMBERREF_CLASS] >> MEMBERREF_PARENT_BITS;
294         class = cols [MONO_MEMBERREF_CLASS] & MEMBERREF_PARENT_MASK;
295         /*g_print ("methodref: 0x%x 0x%x %s\n", class, nindex,
296                 mono_metadata_string_heap (m, cols [MONO_MEMBERREF_NAME]));*/
297
298         mname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
299         
300         ptr = mono_metadata_blob_heap (image, cols [MONO_MEMBERREF_SIGNATURE]);
301         mono_metadata_decode_blob_size (ptr, &ptr);
302         sig = mono_metadata_parse_method_signature (image, 0, ptr, NULL);
303
304         switch (class) {
305         case MEMBERREF_PARENT_TYPEREF:
306                 klass = mono_class_from_typeref (image, MONO_TOKEN_TYPE_REF | nindex);
307                 if (!klass) {
308                         g_warning ("Missing method %s in assembly %s typeref index %d", mname, image->name, nindex);
309                         mono_metadata_free_method_signature (sig);
310                         return NULL;
311                 }
312                 mono_class_init (klass);
313                 method = find_method (klass, NULL, mname, sig);
314                 if (!method)
315                         g_warning ("Missing method %s in assembly %s typeref index %d", mname, image->name, nindex);
316                 mono_metadata_free_method_signature (sig);
317                 return method;
318         case MEMBERREF_PARENT_TYPESPEC: {
319                 guint32 bcols [MONO_TYPESPEC_SIZE];
320                 guint32 len;
321                 MonoType *type;
322                 MonoMethod *result;
323                 MonoClass *klass;
324
325                 klass = mono_class_get_full (image, MONO_TOKEN_TYPE_SPEC | nindex, context);
326                 type = &klass->byval_arg;
327
328                 if (type->type != MONO_TYPE_ARRAY && type->type != MONO_TYPE_SZARRAY) {
329                         mono_class_init (klass);
330                         method = find_method (klass, NULL, mname, sig);
331                         if (!method)
332                                 g_warning ("Missing method %s in assembly %s typeref index %d", mname, image->name, nindex);
333                         else if (klass->generic_inst && (klass != method->klass))
334                                 method = mono_class_inflate_generic_method (
335                                         method, klass->generic_inst->context, klass);
336                         mono_metadata_free_method_signature (sig);
337                         return method;
338                 }
339
340                 result = (MonoMethod *)g_new0 (MonoMethodPInvoke, 1);
341                 result->klass = mono_class_get (image, MONO_TOKEN_TYPE_SPEC | nindex);
342                 result->iflags = METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL;
343                 result->signature = sig;
344                 result->name = mname;
345
346                 if (!strcmp (mname, ".ctor")) {
347                         /* we special-case this in the runtime. */
348                         result->addr = NULL;
349                         return result;
350                 }
351                 
352                 if (!strcmp (mname, "Set")) {
353                         g_assert (sig->hasthis);
354                         g_assert (type->data.array->rank + 1 == sig->param_count);
355                         result->iflags |= METHOD_IMPL_ATTRIBUTE_RUNTIME;
356                         result->addr = NULL;
357                         return result;
358                 }
359
360                 if (!strcmp (mname, "Get")) {
361                         g_assert (sig->hasthis);
362                         g_assert (type->data.array->rank == sig->param_count);
363                         result->iflags |= METHOD_IMPL_ATTRIBUTE_RUNTIME;
364                         result->addr = NULL;
365                         return result;
366                 }
367
368                 if (!strcmp (mname, "Address")) {
369                         g_assert (sig->hasthis);
370                         g_assert (type->data.array->rank == sig->param_count);
371                         result->iflags |= METHOD_IMPL_ATTRIBUTE_RUNTIME;
372                         result->addr = NULL;
373                         return result;
374                 }
375
376                 g_assert_not_reached ();
377                 break;
378         }
379         case MEMBERREF_PARENT_TYPEDEF:
380                 klass = mono_class_get (image, MONO_TOKEN_TYPE_DEF | nindex);
381                 if (!klass) {
382                         g_warning ("Missing method %s in assembly %s typedef index %d", mname, image->name, nindex);
383                         mono_metadata_free_method_signature (sig);
384                         return NULL;
385                 }
386                 mono_class_init (klass);
387                 method = find_method (klass, NULL, mname, sig);
388                 if (!method)
389                         g_warning ("Missing method %s in assembly %s typeref index %d", mname, image->name, nindex);
390                 mono_metadata_free_method_signature (sig);
391                 return method;
392         case MEMBERREF_PARENT_METHODDEF:
393                 method = mono_get_method (image, MONO_TOKEN_METHOD_DEF | nindex, NULL);
394                 return method;
395         default:
396                 g_error ("Memberref parent unknown: class: %d, index %d", class, nindex);
397                 g_assert_not_reached ();
398         }
399
400         return NULL;
401 }
402
403 static MonoMethod *
404 method_from_methodspec (MonoImage *image, guint32 idx)
405 {
406         MonoMethod *method, *inflated;
407         MonoTableInfo *tables = image->tables;
408         MonoGenericContext *context;
409         MonoGenericMethod *gmethod;
410         const char *ptr;
411         guint32 cols [MONO_METHODSPEC_SIZE];
412         guint32 token, param_count, i;
413
414         mono_metadata_decode_row (&tables [MONO_TABLE_METHODSPEC], idx - 1, cols, MONO_METHODSPEC_SIZE);
415         token = cols [MONO_METHODSPEC_METHOD];
416         if ((token & METHODDEFORREF_MASK) == METHODDEFORREF_METHODDEF)
417                 token = MONO_TOKEN_METHOD_DEF | (token >> METHODDEFORREF_BITS);
418         else
419                 token = MONO_TOKEN_MEMBER_REF | (token >> METHODDEFORREF_BITS);
420
421         method = mono_get_method (image, token, NULL);
422
423         ptr = mono_metadata_blob_heap (image, cols [MONO_METHODSPEC_SIGNATURE]);
424         
425         mono_metadata_decode_value (ptr, &ptr);
426         ptr++;
427         param_count = mono_metadata_decode_value (ptr, &ptr);
428
429         gmethod = g_new0 (MonoGenericMethod, 1);
430         gmethod->mtype_argc = param_count;
431         gmethod->mtype_argv = g_new0 (MonoType *, param_count);
432         
433         for (i = 0; i < param_count; i++) {
434                 gmethod->mtype_argv [i] = mono_metadata_parse_type (image, MONO_PARSE_TYPE, 0, ptr, &ptr);
435
436                 if (!gmethod->is_open)
437                         gmethod->is_open = mono_class_is_open_constructed_type (gmethod->mtype_argv [i]);
438         }
439
440         context = g_new0 (MonoGenericContext, 1);
441         context->gmethod = gmethod;
442
443         mono_stats.generics_metadata_size += sizeof (MonoGenericMethod) +
444                 sizeof (MonoGenericContext) + param_count * sizeof (MonoType);
445
446         inflated = mono_class_inflate_generic_method (method, context, NULL);
447
448         context->ginst = inflated->klass->generic_inst;
449         return inflated;
450 }
451
452 typedef struct MonoDllMap MonoDllMap;
453
454 struct MonoDllMap {
455         char *name;
456         char *target;
457         char *dll;
458         MonoDllMap *next;
459 };
460
461 static GHashTable *global_dll_map;
462
463 static int 
464 mono_dllmap_lookup_hash (GHashTable *dll_map, const char *dll, const char* func, const char **rdll, const char **rfunc) {
465         MonoDllMap *map, *tmp;
466
467         *rdll = dll;
468
469         if (!dll_map)
470                 return 0;
471
472         mono_loader_lock ();
473
474         map = g_hash_table_lookup (dll_map, dll);
475         if (!map) {
476                 mono_loader_unlock ();
477                 return 0;
478         }
479         *rdll = map->target? map->target: dll;
480                 
481         for (tmp = map->next; tmp; tmp = tmp->next) {
482                 if (strcmp (func, tmp->name) == 0) {
483                         *rfunc = tmp->name;
484                         if (tmp->dll)
485                                 *rdll = tmp->dll;
486                         mono_loader_unlock ();
487                         return 1;
488                 }
489         }
490         *rfunc = func;
491         mono_loader_unlock ();
492         return 1;
493 }
494
495 static int 
496 mono_dllmap_lookup (MonoImage *assembly, const char *dll, const char* func, const char **rdll, const char **rfunc)
497 {
498         int res;
499         if (assembly && assembly->dll_map) {
500                 res = mono_dllmap_lookup_hash (assembly->dll_map, dll, func, rdll, rfunc);
501                 if (res)
502                         return res;
503         }
504         return mono_dllmap_lookup_hash (global_dll_map, dll, func, rdll, rfunc);
505 }
506
507 void
508 mono_dllmap_insert (MonoImage *assembly, const char *dll, const char *func, const char *tdll, const char *tfunc) {
509         MonoDllMap *map, *entry;
510         GHashTable *dll_map = NULL;
511
512         mono_loader_lock ();
513
514         if (!assembly) {
515                 if (!global_dll_map)
516                         global_dll_map = g_hash_table_new (g_str_hash, g_str_equal);
517                 dll_map = global_dll_map;
518         } else {
519                 if (!assembly->dll_map)
520                         assembly->dll_map = g_hash_table_new (g_str_hash, g_str_equal);
521                 dll_map = assembly->dll_map;
522         }
523
524         map = g_hash_table_lookup (dll_map, dll);
525         if (!map) {
526                 map = g_new0 (MonoDllMap, 1);
527                 map->dll = g_strdup (dll);
528                 if (tdll)
529                         map->target = g_strdup (tdll);
530                 g_hash_table_insert (dll_map, map->dll, map);
531         }
532         if (func) {
533                 entry = g_new0 (MonoDllMap, 1);
534                 entry->name = g_strdup (func);
535                 if (tfunc)
536                         entry->target = g_strdup (tfunc);
537                 if (tdll && map->target && strcmp (map->target, tdll))
538                         entry->dll = g_strdup (tdll);
539                 entry->next = map->next;
540                 map->next = entry;
541         }
542
543         mono_loader_unlock ();
544 }
545
546 static void
547 mono_dllmap_free (GHashTable *dll_map)
548 {
549 }
550
551 static int wine_test_needed = 1;
552
553 gpointer
554 mono_lookup_pinvoke_call (MonoMethod *method, const char **exc_class, const char **exc_arg)
555 {
556         MonoImage *image = method->klass->image;
557         MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)method;
558         MonoTableInfo *tables = image->tables;
559         MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
560         MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
561         guint32 im_cols [MONO_IMPLMAP_SIZE];
562         guint32 scope_token;
563         const char *import = NULL;
564         const char *orig_scope;
565         const char *new_scope;
566         char *full_name, *file_name;
567         int i;
568         GModule *gmodule = NULL;
569
570         g_assert (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL);
571
572         if (exc_class) {
573                 *exc_class = NULL;
574                 *exc_arg = NULL;
575         }
576
577         if (method->addr)
578                 return method->addr;
579         if (!piinfo->implmap_idx)
580                 return NULL;
581         
582         mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
583
584         piinfo->piflags = im_cols [MONO_IMPLMAP_FLAGS];
585         import = mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]);
586         scope_token = mono_metadata_decode_row_col (mr, im_cols [MONO_IMPLMAP_SCOPE] - 1, MONO_MODULEREF_NAME);
587         orig_scope = mono_metadata_string_heap (image, scope_token);
588
589         mono_dllmap_lookup (image, orig_scope, import, &new_scope, &import);
590
591 #ifndef PLATFORM_WIN32
592         /*
593          * If we are P/Invoking a library from System.Windows.Forms, load Wine
594          */
595         if (wine_test_needed && strcmp (image->assembly_name, "System.Windows.Forms") == 0){
596                 mono_loader_wine_init ();
597                 wine_test_needed = 0;
598         }
599 #endif
600         
601         /*
602          * Try loading the module using a variety of names
603          */
604         for (i = 0; i < 2; ++i) {
605                 if (i == 0)
606                         /* Try the original name */
607                         file_name = g_strdup (new_scope);
608                 else {
609                         /* Try trimming the .dll extension */
610                         if (strstr (new_scope, ".dll") == (new_scope + strlen (new_scope) - 4)) {
611                                 file_name = g_strdup (new_scope);
612                                 file_name [strlen (new_scope) - 4] = '\0';
613                         }
614                         else
615                                 break;
616                 }
617
618                 if (!gmodule) {
619                         full_name = g_module_build_path (NULL, file_name);
620                         gmodule = g_module_open (full_name, G_MODULE_BIND_LAZY);
621                         g_free (full_name);
622                 }
623
624                 if (!gmodule) {
625                         full_name = g_module_build_path (".", file_name);
626                         gmodule = g_module_open (full_name, G_MODULE_BIND_LAZY);
627                         g_free (full_name);
628                 }
629
630                 if (!gmodule) {
631                         gmodule=g_module_open (file_name, G_MODULE_BIND_LAZY);
632                 }
633
634                 g_free (file_name);
635
636                 if (gmodule)
637                         break;
638         }
639
640         if (!gmodule) {
641                 if (g_getenv ("MONO_DEBUG")) {
642                         gchar *error = g_strdup (g_module_error ());
643                         g_message ("Error loading '%s': %s\n", orig_scope, error);
644                         g_free (error);
645                 }
646
647                 if (exc_class) {
648                         *exc_class = "DllNotFoundException";
649                         *exc_arg = orig_scope;
650                 }
651                 return NULL;
652         }
653
654         if (piinfo->piflags & PINVOKE_ATTRIBUTE_NO_MANGLE) {
655                 g_module_symbol (gmodule, import, &method->addr); 
656         } else {
657                 char *mangled_name;
658
659                 switch (piinfo->piflags & PINVOKE_ATTRIBUTE_CHAR_SET_MASK) {
660                 case PINVOKE_ATTRIBUTE_CHAR_SET_UNICODE:
661                         mangled_name = g_strconcat (import, "W", NULL);
662                         g_module_symbol (gmodule, mangled_name, &method->addr); 
663                         g_free (mangled_name);
664
665                         if (!method->addr)
666                                 g_module_symbol (gmodule, import, &method->addr); 
667                         break;
668                 case PINVOKE_ATTRIBUTE_CHAR_SET_AUTO:
669                         g_module_symbol (gmodule, import, &method->addr); 
670                         break;
671                 case PINVOKE_ATTRIBUTE_CHAR_SET_ANSI:
672                 default:
673                         mangled_name = g_strconcat (import, "A", NULL);
674                         g_module_symbol (gmodule, mangled_name, &method->addr); 
675                         g_free (mangled_name);
676
677                         if (!method->addr)
678                                 g_module_symbol (gmodule, import, &method->addr); 
679                                
680                         break;                                  
681                 }
682         }
683
684         if (!method->addr) {
685                 if (exc_class) {
686                         *exc_class = "EntryPointNotFoundException";
687                         *exc_arg = import;
688                 }
689                 return NULL;
690         }
691         return method->addr;
692 }
693
694 static MonoMethod *
695 mono_get_method_from_token (MonoImage *image, guint32 token, MonoClass *klass,
696                             MonoGenericContext *context)
697 {
698         MonoMethod *result;
699         int table = mono_metadata_token_table (token);
700         int idx = mono_metadata_token_index (token);
701         MonoTableInfo *tables = image->tables;
702         const char *loc, *sig = NULL;
703         int size, i;
704         guint32 cols [MONO_TYPEDEF_SIZE];
705
706         if (image->dynamic)
707                 return mono_lookup_dynamic_token (image, token);
708
709         if (table != MONO_TABLE_METHOD) {
710                 if (table == MONO_TABLE_METHODSPEC)
711                         return method_from_methodspec (image, idx);
712                 if (table != MONO_TABLE_MEMBERREF)
713                         g_print("got wrong token: 0x%08x\n", token);
714                 g_assert (table == MONO_TABLE_MEMBERREF);
715                 result = method_from_memberref (image, idx, context);
716
717                 return result;
718         }
719
720         mono_metadata_decode_row (&tables [table], idx - 1, cols, 6);
721
722         if ((cols [2] & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
723             (cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))
724                 result = (MonoMethod *)g_new0 (MonoMethodPInvoke, 1);
725         else 
726                 result = (MonoMethod *)g_new0 (MonoMethodNormal, 1);
727         
728         result->slot = -1;
729         result->klass = klass;
730         result->flags = cols [2];
731         result->iflags = cols [1];
732         result->token = token;
733         result->name = mono_metadata_string_heap (image, cols [3]);
734
735         if (!sig) /* already taken from the methodref */
736                 sig = mono_metadata_blob_heap (image, cols [4]);
737         size = mono_metadata_decode_blob_size (sig, &sig);
738         result->signature = mono_metadata_parse_method_signature (image, idx, sig, NULL);
739
740         if (!result->klass) {
741                 guint32 type = mono_metadata_typedef_from_method (image, token);
742                 result->klass = mono_class_get (image, MONO_TOKEN_TYPE_DEF | type);
743         }
744
745         if (cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
746                 if (result->klass == mono_defaults.string_class && !strcmp (result->name, ".ctor"))
747                         result->string_ctor = 1;
748
749                 result->signature->pinvoke = 1;
750         } else if ((cols [2] & METHOD_ATTRIBUTE_PINVOKE_IMPL) && (!(cols [1] & METHOD_IMPL_ATTRIBUTE_NATIVE))) {
751                 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)result;
752                 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
753                 MonoCallConvention conv = 0;
754
755                 result->signature->pinvoke = 1;
756                 piinfo->implmap_idx = mono_metadata_implmap_from_method (image, idx - 1);
757                 piinfo->piflags = mono_metadata_decode_row_col (im, piinfo->implmap_idx - 1, MONO_IMPLMAP_FLAGS);
758
759                 switch (piinfo->piflags & PINVOKE_ATTRIBUTE_CALL_CONV_MASK) {
760                 case PINVOKE_ATTRIBUTE_CALL_CONV_WINAPI:
761                         conv = MONO_CALL_DEFAULT;
762                         break;
763                 case PINVOKE_ATTRIBUTE_CALL_CONV_CDECL:
764                         conv = MONO_CALL_C;
765                         break;
766                 case PINVOKE_ATTRIBUTE_CALL_CONV_STDCALL:
767                         conv = MONO_CALL_STDCALL;
768                         break;
769                 case PINVOKE_ATTRIBUTE_CALL_CONV_THISCALL:
770                         conv = MONO_CALL_THISCALL;
771                         break;
772                 case PINVOKE_ATTRIBUTE_CALL_CONV_FASTCALL:
773                         conv = MONO_CALL_FASTCALL;
774                         break;
775                 case PINVOKE_ATTRIBUTE_CALL_CONV_GENERIC:
776                 case PINVOKE_ATTRIBUTE_CALL_CONV_GENERICINST:
777                 default:
778                         g_warning ("unsupported calling convention");
779                         g_assert_not_reached ();
780                 }       
781                 result->signature->call_convention = conv;
782         } else {
783                 MonoGenericParam *gen_params = NULL;
784
785                 /* if this is a methodref from another module/assembly, this fails */
786                 loc = mono_cli_rva_map ((MonoCLIImageInfo *)image->image_info, cols [0]);
787
788                 if (result->signature->generic_param_count) {
789                         MonoMethodSignature *sig = result->signature;
790
791                         gen_params = mono_metadata_load_generic_params (image, token, NULL);
792
793                         for (i = 0; i < sig->generic_param_count; i++) {
794                                 gen_params [i].method = result;
795
796                                 mono_class_from_generic_parameter (
797                                         &gen_params [i], image, TRUE);
798                         }
799
800                         if (sig->ret->type == MONO_TYPE_MVAR) {
801                                 int num = sig->ret->data.generic_param->num;
802                                 sig->ret->data.generic_param = &gen_params [num];
803                         }
804
805                         for (i = 0; i < sig->param_count; i++) {
806                                 MonoType *t = sig->params [i];
807                                 if (t->type == MONO_TYPE_MVAR) {
808                                         int num = t->data.generic_param->num;
809                                         sig->params [i]->data.generic_param = &gen_params [num];
810                                 }
811                         }
812                 }
813
814                 if (!result->klass->dummy && !(result->flags & METHOD_ATTRIBUTE_ABSTRACT) &&
815                                         !(result->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME)) {
816                         MonoMethodNormal *mn = (MonoMethodNormal *) result;
817
818                         g_assert (loc);
819                         mn->header = mono_metadata_parse_mh (image, loc);
820                         mn->header->gen_params = gen_params;
821                 }
822         }
823
824         return result;
825 }
826
827 MonoMethod *
828 mono_get_method (MonoImage *image, guint32 token, MonoClass *klass)
829 {
830         return mono_get_method_full (image, token, klass, NULL);
831 }
832
833 MonoMethod *
834 mono_get_method_full (MonoImage *image, guint32 token, MonoClass *klass,
835                       MonoGenericContext *context)
836 {
837         MonoMethod *result;
838
839         /* We do everything inside the lock to prevent creation races */
840
841         mono_loader_lock ();
842
843         if ((result = g_hash_table_lookup (image->method_cache, GINT_TO_POINTER (token)))) {
844                 mono_loader_unlock ();
845                 return result;
846         }
847
848         result = mono_get_method_from_token (image, token, klass, context);
849
850         if (!(result && result->signature->is_inflated))
851                 g_hash_table_insert (image->method_cache, GINT_TO_POINTER (token), result);
852
853         mono_loader_unlock ();
854
855         return result;
856 }
857
858 MonoMethod *
859 mono_get_method_constrained (MonoImage *image, guint32 token, MonoClass *constrained_class,
860                              MonoGenericContext *context)
861 {
862         MonoMethod *method, *result;
863         MonoClass *ic = NULL;
864         int i;
865
866         mono_loader_lock ();
867
868         method = mono_get_method_from_token (image, token, NULL, context);
869         if (!method) {
870                 mono_loader_unlock ();
871                 return NULL;
872         }
873
874         if ((constrained_class != method->klass) && (method->klass->interface_id != 0))
875                 ic = method->klass;
876
877         result = find_method (constrained_class, ic, method->name, method->signature);
878         if (!result)
879                 g_warning ("Missing method %s in assembly %s token %x", method->name,
880                            image->name, token);
881
882         mono_loader_unlock ();
883         return result;
884 }
885
886 void
887 mono_free_method  (MonoMethod *method)
888 {
889         mono_metadata_free_method_signature (method->signature);
890         if (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
891                 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)method;
892                 g_free (piinfo->code);
893         } else if (!(method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
894                 mono_metadata_free_mh (((MonoMethodNormal *)method)->header);
895         }
896
897         g_free (method);
898 }
899
900 void
901 mono_method_get_param_names (MonoMethod *method, const char **names)
902 {
903         int i, lastp;
904         MonoClass *klass = method->klass;
905         MonoTableInfo *methodt;
906         MonoTableInfo *paramt;
907
908         if (!method->signature->param_count)
909                 return;
910         for (i = 0; i < method->signature->param_count; ++i)
911                 names [i] = "";
912
913         if (klass->generic_inst) /* copy the names later */
914                 return;
915
916         mono_class_init (klass);
917
918         if (klass->image->dynamic) {
919                 MonoReflectionMethodAux *method_aux = 
920                         mono_g_hash_table_lookup (
921                                 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
922                 if (method_aux && method_aux->param_names) {
923                         for (i = 0; i < method->signature->param_count; ++i)
924                                 if (method_aux->param_names [i + 1])
925                                         names [i] = method_aux->param_names [i + 1];
926                 }
927                 return;
928         }
929
930         methodt = &klass->image->tables [MONO_TABLE_METHOD];
931         paramt = &klass->image->tables [MONO_TABLE_PARAM];
932         for (i = 0; i < klass->method.count; ++i) {
933                 if (method == klass->methods [i]) {
934                         guint32 idx = klass->method.first + i;
935                         guint32 cols [MONO_PARAM_SIZE];
936                         guint param_index = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
937
938                         if (idx + 1 < methodt->rows)
939                                 lastp = mono_metadata_decode_row_col (methodt, idx + 1, MONO_METHOD_PARAMLIST);
940                         else
941                                 lastp = paramt->rows + 1;
942                         for (i = param_index; i < lastp; ++i) {
943                                 mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
944                                 if (cols [MONO_PARAM_SEQUENCE]) /* skip return param spec */
945                                         names [cols [MONO_PARAM_SEQUENCE] - 1] = mono_metadata_string_heap (klass->image, cols [MONO_PARAM_NAME]);
946                         }
947                         return;
948                 }
949         }
950 }
951
952 void
953 mono_method_get_marshal_info (MonoMethod *method, MonoMarshalSpec **mspecs)
954 {
955         int i, lastp;
956         MonoClass *klass = method->klass;
957         MonoTableInfo *methodt;
958         MonoTableInfo *paramt;
959
960         for (i = 0; i < method->signature->param_count + 1; ++i)
961                 mspecs [i] = NULL;
962
963         if (method->klass->image->dynamic) {
964                 MonoReflectionMethodAux *method_aux = 
965                         mono_g_hash_table_lookup (
966                                 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
967                 if (method_aux && method_aux->param_marshall) {
968                         MonoMarshalSpec **dyn_specs = method_aux->param_marshall;
969                         for (i = 0; i < method->signature->param_count + 1; ++i)
970                                 if (dyn_specs [i]) {
971                                         mspecs [i] = g_new0 (MonoMarshalSpec, 1);
972                                         memcpy (mspecs [i], dyn_specs [i], sizeof (MonoMarshalSpec));
973                                 }
974                 }
975                 return;
976         }
977
978         mono_class_init (klass);
979
980         methodt = &klass->image->tables [MONO_TABLE_METHOD];
981         paramt = &klass->image->tables [MONO_TABLE_PARAM];
982
983         for (i = 0; i < klass->method.count; ++i) {
984                 if (method == klass->methods [i]) {
985                         guint32 idx = klass->method.first + i;
986                         guint32 cols [MONO_PARAM_SIZE];
987                         guint param_index = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
988
989                         if (idx + 1 < methodt->rows)
990                                 lastp = mono_metadata_decode_row_col (methodt, idx + 1, MONO_METHOD_PARAMLIST);
991                         else
992                                 lastp = paramt->rows + 1;
993
994                         for (i = param_index; i < lastp; ++i) {
995                                 mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
996
997                                 if (cols [MONO_PARAM_FLAGS] & PARAM_ATTRIBUTE_HAS_FIELD_MARSHAL) {
998                                         const char *tp;
999                                         tp = mono_metadata_get_marshal_info (klass->image, i - 1, FALSE);
1000                                         g_assert (tp);
1001                                         mspecs [cols [MONO_PARAM_SEQUENCE]]= mono_metadata_parse_marshal_spec (klass->image, tp);
1002                                 }
1003                         }
1004
1005                         return;
1006                 }
1007         }
1008 }
1009
1010 gboolean
1011 mono_method_has_marshal_info (MonoMethod *method)
1012 {
1013         int i, lastp;
1014         MonoClass *klass = method->klass;
1015         MonoTableInfo *methodt;
1016         MonoTableInfo *paramt;
1017
1018         if (method->klass->image->dynamic) {
1019                 MonoReflectionMethodAux *method_aux = 
1020                         mono_g_hash_table_lookup (
1021                                 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
1022                 MonoMarshalSpec **dyn_specs = method_aux->param_marshall;
1023                 if (dyn_specs) {
1024                         for (i = 0; i < method->signature->param_count + 1; ++i)
1025                                 if (dyn_specs [i])
1026                                         return TRUE;
1027                 }
1028                 return FALSE;
1029         }
1030
1031         mono_class_init (klass);
1032
1033         methodt = &klass->image->tables [MONO_TABLE_METHOD];
1034         paramt = &klass->image->tables [MONO_TABLE_PARAM];
1035
1036         for (i = 0; i < klass->method.count; ++i) {
1037                 if (method == klass->methods [i]) {
1038                         guint32 idx = klass->method.first + i;
1039                         guint32 cols [MONO_PARAM_SIZE];
1040                         guint param_index = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
1041
1042                         if (idx + 1 < methodt->rows)
1043                                 lastp = mono_metadata_decode_row_col (methodt, idx + 1, MONO_METHOD_PARAMLIST);
1044                         else
1045                                 lastp = paramt->rows + 1;
1046
1047                         for (i = param_index; i < lastp; ++i) {
1048                                 mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
1049
1050                                 if (cols [MONO_PARAM_FLAGS] & PARAM_ATTRIBUTE_HAS_FIELD_MARSHAL)
1051                                         return TRUE;
1052                         }
1053                         return FALSE;
1054                 }
1055         }
1056         return FALSE;
1057 }
1058
1059 gpointer
1060 mono_method_get_wrapper_data (MonoMethod *method, guint32 id)
1061 {
1062         GList *l;
1063         g_assert (method != NULL);
1064         g_assert (method->wrapper_type != MONO_WRAPPER_NONE);
1065
1066         if (!(l = g_list_nth (((MonoMethodWrapper *)method)->data, id - 1)))
1067                 g_assert_not_reached ();
1068
1069         return l->data;
1070 }
1071
1072 static void
1073 default_stack_walk (MonoStackWalk func, gpointer user_data) {
1074         g_error ("stack walk not installed");
1075 }
1076
1077 static MonoStackWalkImpl stack_walk = default_stack_walk;
1078
1079 void
1080 mono_stack_walk (MonoStackWalk func, gpointer user_data)
1081 {
1082         stack_walk (func, user_data);
1083 }
1084
1085 void
1086 mono_install_stack_walk (MonoStackWalkImpl func)
1087 {
1088         stack_walk = func;
1089 }
1090
1091 static gboolean
1092 last_managed (MonoMethod *m, gint no, gint ilo, gboolean managed, gpointer data)
1093 {
1094         MonoMethod **dest = data;
1095         *dest = m;
1096         /*g_print ("In %s::%s [%d] [%d]\n", m->klass->name, m->name, no, ilo);*/
1097
1098         return managed;
1099 }
1100
1101 MonoMethod*
1102 mono_method_get_last_managed (void)
1103 {
1104         MonoMethod *m = NULL;
1105         stack_walk (last_managed, &m);
1106         return m;
1107 }
1108
1109 #ifndef PLATFORM_WIN32
1110 /*
1111  * This routine exists to load and init Wine due to the special Wine
1112  * requirements: basically the SharedWineInit must be called before
1113  * any modules are dlopened or they will fail to work.
1114  */
1115 void
1116 mono_loader_wine_init ()
1117 {
1118         GModule *module = g_module_open ("winelib.exe.so", G_MODULE_BIND_LAZY);
1119         int (*shared_wine_init)();
1120
1121         if (module == NULL){
1122                 fprintf (stderr, "Could not load winelib.exe.so");
1123                 return;
1124         }
1125
1126         g_module_symbol (module, "SharedWineInit", &shared_wine_init);
1127         if (shared_wine_init == NULL)
1128                 return;
1129
1130         shared_wine_init ();
1131
1132         return;
1133 }
1134 #endif
1135