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