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