Some docs.
[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 (method->addr)
578                 return method->addr;
579
580         if (method->klass->image->dynamic) {
581                 MonoReflectionMethodAux *method_aux = 
582                         mono_g_hash_table_lookup (
583                                 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
584                 if (!method_aux)
585                         return NULL;
586
587                 import = method_aux->dllentry;
588                 orig_scope = method_aux->dll;
589         }
590         else {
591                 if (!piinfo->implmap_idx)
592                         return NULL;
593
594                 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
595
596                 piinfo->piflags = im_cols [MONO_IMPLMAP_FLAGS];
597                 import = mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]);
598                 scope_token = mono_metadata_decode_row_col (mr, im_cols [MONO_IMPLMAP_SCOPE] - 1, MONO_MODULEREF_NAME);
599                 orig_scope = mono_metadata_string_heap (image, scope_token);
600         }
601
602         mono_dllmap_lookup (image, orig_scope, import, &new_scope, &import);
603
604         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
605                         "DllImport attempting to load: '%s'.", new_scope);
606
607         if (exc_class) {
608                 *exc_class = NULL;
609                 *exc_arg = NULL;
610         }
611         
612         /*
613          * Try loading the module using a variety of names
614          */
615         for (i = 0; i < 2; ++i) {
616                 if (i == 0)
617                         /* Try the original name */
618                         file_name = g_strdup (new_scope);
619                 else {
620                         /* Try trimming the .dll extension */
621                         if (strstr (new_scope, ".dll") == (new_scope + strlen (new_scope) - 4)) {
622                                 file_name = g_strdup (new_scope);
623                                 file_name [strlen (new_scope) - 4] = '\0';
624                         }
625                         else
626                                 break;
627                 }
628
629                 if (!gmodule) {
630                         full_name = g_module_build_path (NULL, file_name);
631                         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
632                                         "DllImport loading location: '%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                         full_name = g_module_build_path (".", file_name);
644                         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
645                                         "DllImport loading library: '%s'.", full_name);
646                         gmodule = g_module_open (full_name, G_MODULE_BIND_LAZY);
647                         if (!gmodule) {
648                                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
649                                                 "DllImport error loading library '%s'.",
650                                                 g_module_error ());
651                         }
652                         g_free (full_name);
653                 }
654
655                 if (!gmodule) {
656                         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
657                                         "DllImport loading: '%s'.", file_name);
658                         gmodule=g_module_open (file_name, G_MODULE_BIND_LAZY);
659                         if (!gmodule) {
660                                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_DLLIMPORT,
661                                                 "DllImport error loading library '%s'.",
662                                                 g_module_error ());
663                         }
664                 }
665
666                 g_free (file_name);
667
668                 if (gmodule)
669                         break;
670         }
671
672         if (!gmodule) {
673                 mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_DLLIMPORT,
674                                 "DllImport unable to load library '%s'.",
675                                 g_module_error ());
676
677                 if (exc_class) {
678                         *exc_class = "DllNotFoundException";
679                         *exc_arg = orig_scope;
680                 }
681                 return NULL;
682         }
683
684         if (piinfo->piflags & PINVOKE_ATTRIBUTE_NO_MANGLE) {
685                 g_module_symbol (gmodule, import, &method->addr); 
686         } else {
687                 char *mangled_name;
688
689                 switch (piinfo->piflags & PINVOKE_ATTRIBUTE_CHAR_SET_MASK) {
690                 case PINVOKE_ATTRIBUTE_CHAR_SET_UNICODE:
691                         mangled_name = g_strconcat (import, "W", NULL);
692                         g_module_symbol (gmodule, mangled_name, &method->addr); 
693                         g_free (mangled_name);
694
695                         if (!method->addr)
696                                 g_module_symbol (gmodule, import, &method->addr); 
697                         break;
698                 case PINVOKE_ATTRIBUTE_CHAR_SET_AUTO:
699                         g_module_symbol (gmodule, import, &method->addr); 
700                         break;
701                 case PINVOKE_ATTRIBUTE_CHAR_SET_ANSI:
702                 default:
703                         mangled_name = g_strconcat (import, "A", NULL);
704                         g_module_symbol (gmodule, mangled_name, &method->addr); 
705                         g_free (mangled_name);
706
707                         if (!method->addr)
708                                 g_module_symbol (gmodule, import, &method->addr); 
709                                
710                         break;                                  
711                 }
712         }
713
714         if (!method->addr) {
715                 if (exc_class) {
716                         *exc_class = "EntryPointNotFoundException";
717                         *exc_arg = import;
718                 }
719                 return NULL;
720         }
721         return method->addr;
722 }
723
724 static MonoMethod *
725 mono_get_method_from_token (MonoImage *image, guint32 token, MonoClass *klass,
726                             MonoGenericContext *context)
727 {
728         MonoMethod *result;
729         int table = mono_metadata_token_table (token);
730         int idx = mono_metadata_token_index (token);
731         MonoTableInfo *tables = image->tables;
732         const char *loc, *sig = NULL;
733         int size, i;
734         guint32 cols [MONO_TYPEDEF_SIZE];
735
736         if (image->dynamic)
737                 return mono_lookup_dynamic_token (image, token);
738
739         if (table != MONO_TABLE_METHOD) {
740                 if (table == MONO_TABLE_METHODSPEC)
741                         return method_from_methodspec (image, idx);
742                 if (table != MONO_TABLE_MEMBERREF)
743                         g_print("got wrong token: 0x%08x\n", token);
744                 g_assert (table == MONO_TABLE_MEMBERREF);
745                 result = method_from_memberref (image, idx, context);
746
747                 return result;
748         }
749
750         mono_metadata_decode_row (&tables [table], idx - 1, cols, 6);
751
752         if ((cols [2] & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
753             (cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))
754                 result = (MonoMethod *)g_new0 (MonoMethodPInvoke, 1);
755         else 
756                 result = (MonoMethod *)g_new0 (MonoMethodNormal, 1);
757         
758         result->slot = -1;
759         result->klass = klass;
760         result->flags = cols [2];
761         result->iflags = cols [1];
762         result->token = token;
763         result->name = mono_metadata_string_heap (image, cols [3]);
764
765         if (!sig) /* already taken from the methodref */
766                 sig = mono_metadata_blob_heap (image, cols [4]);
767         size = mono_metadata_decode_blob_size (sig, &sig);
768         result->signature = mono_metadata_parse_method_signature (image, idx, sig, NULL);
769
770         if (!result->klass) {
771                 guint32 type = mono_metadata_typedef_from_method (image, token);
772                 result->klass = mono_class_get (image, MONO_TOKEN_TYPE_DEF | type);
773         }
774
775         if (cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
776                 if (result->klass == mono_defaults.string_class && !strcmp (result->name, ".ctor"))
777                         result->string_ctor = 1;
778
779                 result->signature->pinvoke = 1;
780         } else if ((cols [2] & METHOD_ATTRIBUTE_PINVOKE_IMPL) && (!(cols [1] & METHOD_IMPL_ATTRIBUTE_NATIVE))) {
781                 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)result;
782                 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
783                 MonoCallConvention conv = 0;
784
785                 result->signature->pinvoke = 1;
786                 piinfo->implmap_idx = mono_metadata_implmap_from_method (image, idx - 1);
787                 piinfo->piflags = mono_metadata_decode_row_col (im, piinfo->implmap_idx - 1, MONO_IMPLMAP_FLAGS);
788
789                 switch (piinfo->piflags & PINVOKE_ATTRIBUTE_CALL_CONV_MASK) {
790                 case PINVOKE_ATTRIBUTE_CALL_CONV_WINAPI:
791                         conv = MONO_CALL_DEFAULT;
792                         break;
793                 case PINVOKE_ATTRIBUTE_CALL_CONV_CDECL:
794                         conv = MONO_CALL_C;
795                         break;
796                 case PINVOKE_ATTRIBUTE_CALL_CONV_STDCALL:
797                         conv = MONO_CALL_STDCALL;
798                         break;
799                 case PINVOKE_ATTRIBUTE_CALL_CONV_THISCALL:
800                         conv = MONO_CALL_THISCALL;
801                         break;
802                 case PINVOKE_ATTRIBUTE_CALL_CONV_FASTCALL:
803                         conv = MONO_CALL_FASTCALL;
804                         break;
805                 case PINVOKE_ATTRIBUTE_CALL_CONV_GENERIC:
806                 case PINVOKE_ATTRIBUTE_CALL_CONV_GENERICINST:
807                 default:
808                         g_warning ("unsupported calling convention");
809                         g_assert_not_reached ();
810                 }       
811                 result->signature->call_convention = conv;
812         } else {
813                 MonoMethodNormal *mn = (MonoMethodNormal *) result;
814                 MonoGenericParam *gen_params = NULL;
815
816                 /* if this is a methodref from another module/assembly, this fails */
817                 loc = mono_image_rva_map (image, cols [0]);
818
819                 if (result->signature->generic_param_count) {
820                         MonoMethodSignature *sig = result->signature;
821
822                         gen_params = mono_metadata_load_generic_params (image, token, NULL);
823
824                         for (i = 0; i < sig->generic_param_count; i++) {
825                                 gen_params [i].method = result;
826
827                                 mono_class_from_generic_parameter (
828                                         &gen_params [i], image, TRUE);
829                         }
830
831                         if (sig->ret->type == MONO_TYPE_MVAR) {
832                                 int num = sig->ret->data.generic_param->num;
833                                 sig->ret->data.generic_param = &gen_params [num];
834                         }
835
836                         for (i = 0; i < sig->param_count; i++) {
837                                 MonoType *t = sig->params [i];
838                                 if (t->type == MONO_TYPE_MVAR) {
839                                         int num = t->data.generic_param->num;
840                                         sig->params [i]->data.generic_param = &gen_params [num];
841                                 }
842                         }
843                 }
844
845                 if (!result->klass->dummy && !(result->flags & METHOD_ATTRIBUTE_ABSTRACT) &&
846                     !(result->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME)) {
847                         g_assert (loc);
848                         mn->header = mono_metadata_parse_mh (image, loc);
849                 }
850
851                 mn->gen_params = gen_params;
852         }
853
854         return result;
855 }
856
857 MonoMethod *
858 mono_get_method (MonoImage *image, guint32 token, MonoClass *klass)
859 {
860         return mono_get_method_full (image, token, klass, NULL);
861 }
862
863 MonoMethod *
864 mono_get_method_full (MonoImage *image, guint32 token, MonoClass *klass,
865                       MonoGenericContext *context)
866 {
867         MonoMethod *result;
868
869         /* We do everything inside the lock to prevent creation races */
870
871         mono_loader_lock ();
872
873         if ((result = g_hash_table_lookup (image->method_cache, GINT_TO_POINTER (token)))) {
874                 mono_loader_unlock ();
875                 return result;
876         }
877
878         result = mono_get_method_from_token (image, token, klass, context);
879
880         if (!(result && result->signature->is_inflated))
881                 g_hash_table_insert (image->method_cache, GINT_TO_POINTER (token), result);
882
883         mono_loader_unlock ();
884
885         return result;
886 }
887
888 MonoMethod *
889 mono_get_method_constrained (MonoImage *image, guint32 token, MonoClass *constrained_class,
890                              MonoGenericContext *context)
891 {
892         MonoMethod *method, *result;
893         MonoClass *ic = NULL;
894
895         mono_loader_lock ();
896
897         method = mono_get_method_from_token (image, token, NULL, context);
898         if (!method) {
899                 mono_loader_unlock ();
900                 return NULL;
901         }
902
903         mono_class_init (constrained_class);
904
905         if ((constrained_class != method->klass) && (method->klass->interface_id != 0))
906                 ic = method->klass;
907
908         result = find_method (constrained_class, ic, method->name, method->signature);
909         if (!result)
910                 g_warning ("Missing method %s in assembly %s token %x", method->name,
911                            image->name, token);
912
913         mono_loader_unlock ();
914         return result;
915 }
916
917 void
918 mono_free_method  (MonoMethod *method)
919 {
920         mono_metadata_free_method_signature (method->signature);
921         if (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
922                 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)method;
923                 g_free (piinfo->code);
924         } else if (!(method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
925                 mono_metadata_free_mh (((MonoMethodNormal *)method)->header);
926         }
927
928         g_free (method);
929 }
930
931 void
932 mono_method_get_param_names (MonoMethod *method, const char **names)
933 {
934         int i, lastp;
935         MonoClass *klass = method->klass;
936         MonoTableInfo *methodt;
937         MonoTableInfo *paramt;
938
939         if (!method->signature->param_count)
940                 return;
941         for (i = 0; i < method->signature->param_count; ++i)
942                 names [i] = "";
943
944         if (klass->generic_inst) /* copy the names later */
945                 return;
946
947         mono_class_init (klass);
948
949         if (klass->image->dynamic) {
950                 MonoReflectionMethodAux *method_aux = 
951                         mono_g_hash_table_lookup (
952                                 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
953                 if (method_aux && method_aux->param_names) {
954                         for (i = 0; i < method->signature->param_count; ++i)
955                                 if (method_aux->param_names [i + 1])
956                                         names [i] = method_aux->param_names [i + 1];
957                 }
958                 return;
959         }
960
961         methodt = &klass->image->tables [MONO_TABLE_METHOD];
962         paramt = &klass->image->tables [MONO_TABLE_PARAM];
963         for (i = 0; i < klass->method.count; ++i) {
964                 if (method == klass->methods [i]) {
965                         guint32 idx = klass->method.first + i;
966                         guint32 cols [MONO_PARAM_SIZE];
967                         guint param_index = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
968
969                         if (idx + 1 < methodt->rows)
970                                 lastp = mono_metadata_decode_row_col (methodt, idx + 1, MONO_METHOD_PARAMLIST);
971                         else
972                                 lastp = paramt->rows + 1;
973                         for (i = param_index; i < lastp; ++i) {
974                                 mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
975                                 if (cols [MONO_PARAM_SEQUENCE]) /* skip return param spec */
976                                         names [cols [MONO_PARAM_SEQUENCE] - 1] = mono_metadata_string_heap (klass->image, cols [MONO_PARAM_NAME]);
977                         }
978                         return;
979                 }
980         }
981 }
982
983 void
984 mono_method_get_marshal_info (MonoMethod *method, MonoMarshalSpec **mspecs)
985 {
986         int i, lastp;
987         MonoClass *klass = method->klass;
988         MonoTableInfo *methodt;
989         MonoTableInfo *paramt;
990
991         for (i = 0; i < method->signature->param_count + 1; ++i)
992                 mspecs [i] = NULL;
993
994         if (method->klass->image->dynamic) {
995                 MonoReflectionMethodAux *method_aux = 
996                         mono_g_hash_table_lookup (
997                                 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
998                 if (method_aux && method_aux->param_marshall) {
999                         MonoMarshalSpec **dyn_specs = method_aux->param_marshall;
1000                         for (i = 0; i < method->signature->param_count + 1; ++i)
1001                                 if (dyn_specs [i]) {
1002                                         mspecs [i] = g_new0 (MonoMarshalSpec, 1);
1003                                         memcpy (mspecs [i], dyn_specs [i], sizeof (MonoMarshalSpec));
1004                                 }
1005                 }
1006                 return;
1007         }
1008
1009         mono_class_init (klass);
1010
1011         methodt = &klass->image->tables [MONO_TABLE_METHOD];
1012         paramt = &klass->image->tables [MONO_TABLE_PARAM];
1013
1014         for (i = 0; i < klass->method.count; ++i) {
1015                 if (method == klass->methods [i]) {
1016                         guint32 idx = klass->method.first + i;
1017                         guint32 cols [MONO_PARAM_SIZE];
1018                         guint param_index = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
1019
1020                         if (idx + 1 < methodt->rows)
1021                                 lastp = mono_metadata_decode_row_col (methodt, idx + 1, MONO_METHOD_PARAMLIST);
1022                         else
1023                                 lastp = paramt->rows + 1;
1024
1025                         for (i = param_index; i < lastp; ++i) {
1026                                 mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
1027
1028                                 if (cols [MONO_PARAM_FLAGS] & PARAM_ATTRIBUTE_HAS_FIELD_MARSHAL) {
1029                                         const char *tp;
1030                                         tp = mono_metadata_get_marshal_info (klass->image, i - 1, FALSE);
1031                                         g_assert (tp);
1032                                         mspecs [cols [MONO_PARAM_SEQUENCE]]= mono_metadata_parse_marshal_spec (klass->image, tp);
1033                                 }
1034                         }
1035
1036                         return;
1037                 }
1038         }
1039 }
1040
1041 gboolean
1042 mono_method_has_marshal_info (MonoMethod *method)
1043 {
1044         int i, lastp;
1045         MonoClass *klass = method->klass;
1046         MonoTableInfo *methodt;
1047         MonoTableInfo *paramt;
1048
1049         if (method->klass->image->dynamic) {
1050                 MonoReflectionMethodAux *method_aux = 
1051                         mono_g_hash_table_lookup (
1052                                 ((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
1053                 MonoMarshalSpec **dyn_specs = method_aux->param_marshall;
1054                 if (dyn_specs) {
1055                         for (i = 0; i < method->signature->param_count + 1; ++i)
1056                                 if (dyn_specs [i])
1057                                         return TRUE;
1058                 }
1059                 return FALSE;
1060         }
1061
1062         mono_class_init (klass);
1063
1064         methodt = &klass->image->tables [MONO_TABLE_METHOD];
1065         paramt = &klass->image->tables [MONO_TABLE_PARAM];
1066
1067         for (i = 0; i < klass->method.count; ++i) {
1068                 if (method == klass->methods [i]) {
1069                         guint32 idx = klass->method.first + i;
1070                         guint32 cols [MONO_PARAM_SIZE];
1071                         guint param_index = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
1072
1073                         if (idx + 1 < methodt->rows)
1074                                 lastp = mono_metadata_decode_row_col (methodt, idx + 1, MONO_METHOD_PARAMLIST);
1075                         else
1076                                 lastp = paramt->rows + 1;
1077
1078                         for (i = param_index; i < lastp; ++i) {
1079                                 mono_metadata_decode_row (paramt, i -1, cols, MONO_PARAM_SIZE);
1080
1081                                 if (cols [MONO_PARAM_FLAGS] & PARAM_ATTRIBUTE_HAS_FIELD_MARSHAL)
1082                                         return TRUE;
1083                         }
1084                         return FALSE;
1085                 }
1086         }
1087         return FALSE;
1088 }
1089
1090 gpointer
1091 mono_method_get_wrapper_data (MonoMethod *method, guint32 id)
1092 {
1093         GList *l;
1094         g_assert (method != NULL);
1095         g_assert (method->wrapper_type != MONO_WRAPPER_NONE);
1096
1097         if (!(l = g_list_nth (((MonoMethodWrapper *)method)->data, id - 1)))
1098                 g_assert_not_reached ();
1099
1100         return l->data;
1101 }
1102
1103 static void
1104 default_stack_walk (MonoStackWalk func, gpointer user_data) {
1105         g_error ("stack walk not installed");
1106 }
1107
1108 static MonoStackWalkImpl stack_walk = default_stack_walk;
1109
1110 void
1111 mono_stack_walk (MonoStackWalk func, gpointer user_data)
1112 {
1113         stack_walk (func, user_data);
1114 }
1115
1116 void
1117 mono_install_stack_walk (MonoStackWalkImpl func)
1118 {
1119         stack_walk = func;
1120 }
1121
1122 static gboolean
1123 last_managed (MonoMethod *m, gint no, gint ilo, gboolean managed, gpointer data)
1124 {
1125         MonoMethod **dest = data;
1126         *dest = m;
1127         /*g_print ("In %s::%s [%d] [%d]\n", m->klass->name, m->name, no, ilo);*/
1128
1129         return managed;
1130 }
1131
1132 MonoMethod*
1133 mono_method_get_last_managed (void)
1134 {
1135         MonoMethod *m = NULL;
1136         stack_walk (last_managed, &m);
1137         return m;
1138 }
1139
1140 void
1141 mono_loader_lock (void)
1142 {
1143         EnterCriticalSection (&loader_mutex);
1144 }
1145
1146 void
1147 mono_loader_unlock (void)
1148 {
1149         LeaveCriticalSection (&loader_mutex);
1150 }
1151
1152 MonoMethodSignature* 
1153 mono_method_signature (MonoMethod *method)
1154 {
1155         return method->signature;
1156 }
1157
1158 const char*
1159 mono_method_get_name (MonoMethod *method)
1160 {
1161         return method->name;
1162 }
1163
1164 MonoClass*
1165 mono_method_get_class (MonoMethod *method)
1166 {
1167         return method->klass;
1168 }
1169
1170 guint32
1171 mono_method_get_token (MonoMethod *method)
1172 {
1173         return method->token;
1174 }
1175
1176 guint32
1177 mono_method_get_flags (MonoMethod *method, guint32 *iflags)
1178 {
1179         if (iflags)
1180                 *iflags = method->iflags;
1181         return method->flags;
1182 }
1183
1184