2001-08-24 Dietmar Maurer <dietmar@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  *
8  * (C) 2001 Ximian, Inc.
9  *
10  * This file is used by the interpreter and the JIT engine to locate
11  * assemblies.  Used to load AssemblyRef and later to resolve various
12  * kinds of `Refs'.
13  *
14  * TODO:
15  *   This should keep track of the assembly versions that we are loading.
16  *
17  */
18 #include <config.h>
19 #include <glib.h>
20 #include <gmodule.h>
21 #include <stdio.h>
22 #include <string.h>
23 #include <mono/metadata/metadata.h>
24 #include <mono/metadata/image.h>
25 #include <mono/metadata/assembly.h>
26 #include <mono/metadata/tokentype.h>
27 #include <mono/metadata/cil-coff.h>
28 #include <mono/metadata/tabledefs.h>
29 #include <mono/metadata/loader.h>
30 #include <mono/metadata/class.h>
31
32 MonoDefaults mono_defaults;
33
34 static char *dll_map[] = {
35         "libc", "libc.so.6",
36         "libm", "libm.so.6",
37         "cygwin1.dll", "libc.so.6", 
38         NULL, NULL
39 };
40
41 static const char *
42 mono_map_dll (const char *name)
43 {
44         int i = 0;
45
46         while (dll_map [i]) {
47                 if (!strcmp (dll_map [i], name))
48                         return  dll_map [i + 1];
49                 i += 2;
50         }
51
52         return name;
53 }
54
55 void
56 mono_init ()
57 {
58         static gboolean initialized = FALSE;
59         MonoAssembly *ass;
60         enum MonoImageOpenStatus status = MONO_IMAGE_OK;
61
62         if (initialized)
63                 return;
64
65         /* find the corlib */
66         ass = mono_assembly_open (CORLIB_NAME, NULL, &status);
67         g_assert (status == MONO_IMAGE_OK);
68         g_assert (ass != NULL);
69         mono_defaults.corlib = ass->image;
70
71         mono_defaults.object_class = mono_class_from_name (
72                 mono_defaults.corlib, "System", "Object");
73         g_assert (mono_defaults.object_class != 0);
74
75         mono_defaults.boolean_class = mono_class_from_name (
76                 mono_defaults.corlib, "System", "Boolean");
77         g_assert (mono_defaults.boolean_class != 0);
78
79         mono_defaults.byte_class = mono_class_from_name (
80                 mono_defaults.corlib, "System", "Byte");
81         g_assert (mono_defaults.byte_class != 0);
82
83         mono_defaults.sbyte_class = mono_class_from_name (
84                 mono_defaults.corlib, "System", "SByte");
85         g_assert (mono_defaults.sbyte_class != 0);
86
87         mono_defaults.int16_class = mono_class_from_name (
88                 mono_defaults.corlib, "System", "Int16");
89         g_assert (mono_defaults.int16_class != 0);
90
91         mono_defaults.uint16_class = mono_class_from_name (
92                 mono_defaults.corlib, "System", "UInt16");
93         g_assert (mono_defaults.uint16_class != 0);
94
95         mono_defaults.int32_class = mono_class_from_name (
96                 mono_defaults.corlib, "System", "Int32");
97         g_assert (mono_defaults.int32_class != 0);
98
99         mono_defaults.uint32_class = mono_class_from_name (
100                 mono_defaults.corlib, "System", "UInt32");
101         g_assert (mono_defaults.uint32_class != 0);
102
103         mono_defaults.int64_class = mono_class_from_name (
104                 mono_defaults.corlib, "System", "Int64");
105         g_assert (mono_defaults.int64_class != 0);
106
107         mono_defaults.uint64_class = mono_class_from_name (
108                 mono_defaults.corlib, "System", "UInt64");
109         g_assert (mono_defaults.uint64_class != 0);
110
111         mono_defaults.single_class = mono_class_from_name (
112                 mono_defaults.corlib, "System", "Single");
113         g_assert (mono_defaults.single_class != 0);
114
115         mono_defaults.double_class = mono_class_from_name (
116                 mono_defaults.corlib, "System", "Double");
117         g_assert (mono_defaults.double_class != 0);
118
119         mono_defaults.char_class = mono_class_from_name (
120                 mono_defaults.corlib, "System", "Char");
121         g_assert (mono_defaults.char_class != 0);
122
123         mono_defaults.string_class = mono_class_from_name (
124                 mono_defaults.corlib, "System", "String");
125         g_assert (mono_defaults.string_class != 0);
126
127         mono_defaults.enum_class = mono_class_from_name (
128                 mono_defaults.corlib, "System", "Enum");
129         g_assert (mono_defaults.enum_class != 0);
130
131         mono_defaults.array_class = mono_class_from_name (
132                 mono_defaults.corlib, "System", "Array");
133         g_assert (mono_defaults.array_class != 0);
134 }
135
136 static GHashTable *icall_hash = NULL;
137
138 void
139 mono_add_internal_call (const char *name, gpointer method)
140 {
141         if (!icall_hash)
142                 icall_hash = g_hash_table_new (g_str_hash , g_str_equal);
143         
144         g_hash_table_insert (icall_hash, g_strdup (name), method);
145 }
146
147 gpointer
148 mono_lookup_internal_call (const char *name)
149 {
150         gpointer res;
151
152         if (!icall_hash) {
153                 g_warning ("icall_hash not initialized");
154                 g_assert_not_reached ();
155         }
156
157         if (!(res = g_hash_table_lookup (icall_hash, name))) {
158                 g_warning ("cant resolve internal call to \"%s\"", name);
159                 g_assert_not_reached ();
160         }
161
162         return res;
163 }
164
165 static MonoMethod *
166 method_from_memberref (MonoImage *image, guint32 index)
167 {
168         MonoImage *mimage;
169         MonoClass *klass;
170         MonoTableInfo *tables = image->tables;
171         guint32 cols[6];
172         guint32 nindex, class, i;
173         const char *mname, *name, *nspace;
174         MonoMethodSignature *sig;
175         const char *ptr;
176
177         mono_metadata_decode_row (&tables [MONO_TABLE_MEMBERREF], index-1, cols, 3);
178         nindex = cols [MONO_MEMBERREF_CLASS] >> MEMBERREF_PARENT_BITS;
179         class = cols [MONO_MEMBERREF_CLASS] & MEMBERREF_PARENT_MASK;
180         /*g_print ("methodref: 0x%x 0x%x %s\n", class, nindex,
181                 mono_metadata_string_heap (m, cols [MONO_MEMBERREF_NAME]));*/
182
183         mname = mono_metadata_string_heap (image, cols [MONO_MEMBERREF_NAME]);
184         
185         ptr = mono_metadata_blob_heap (image, cols [MONO_MEMBERREF_SIGNATURE]);
186         mono_metadata_decode_blob_size (ptr, &ptr);
187         sig = mono_metadata_parse_method_signature (image, 0, ptr, NULL);
188
189         switch (class) {
190         case MEMBERREF_PARENT_TYPEREF: {
191                 guint32 scopeindex, scopetable;
192
193                 mono_metadata_decode_row (&tables [MONO_TABLE_TYPEREF], nindex-1, cols, MONO_TYPEREF_SIZE);
194                 scopeindex = cols [MONO_TYPEREF_SCOPE] >> RESOLTION_SCOPE_BITS;
195                 scopetable = cols [MONO_TYPEREF_SCOPE] & RESOLTION_SCOPE_MASK;
196                 /*g_print ("typeref: 0x%x 0x%x %s.%s\n", scopetable, scopeindex,
197                         mono_metadata_string_heap (m, cols [MONO_TYPEREF_NAMESPACE]),
198                         mono_metadata_string_heap (m, cols [MONO_TYPEREF_NAME]));*/
199                 switch (scopetable) {
200                 case RESOLTION_SCOPE_ASSEMBLYREF:
201                         /*
202                          * To find the method we have the following info:
203                          * *) name and namespace of the class from the TYPEREF table
204                          * *) name and signature of the method from the MEMBERREF table
205                          */
206                         nspace = mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAMESPACE]);
207                         name = mono_metadata_string_heap (image, cols [MONO_TYPEREF_NAME]);
208
209                         /* this will triggered by references to mscorlib */
210                         g_assert (image->references [scopeindex-1] != NULL);
211
212                         mimage = image->references [scopeindex-1]->image;
213
214                         klass = mono_class_from_name (mimage, nspace, name);
215                         mono_class_metadata_init (klass);
216
217                         /* mostly dumb search for now */
218                         for (i = 0; i < klass->method.count; ++i) {
219                                 MonoMethod *m = klass->methods [i];
220                                 if (!strcmp (mname, m->name)) {
221                                         if (mono_metadata_signature_equal (image, sig, mimage, m->signature)) {
222                                                 mono_metadata_free_method_signature (sig);
223                                                 return m;
224                                         }
225                                 }
226                         }
227                         g_warning ("can't find method %s.%s::%s", nspace, name, mname);
228                         g_assert_not_reached ();
229                         break;
230                 default:
231                         g_assert_not_reached ();
232                 }
233                 break;
234         }
235         case MEMBERREF_PARENT_TYPESPEC: {
236                 guint32 bcols [MONO_TYPESPEC_SIZE];
237                 guint32 len;
238                 MonoType *type;
239                 MonoMethod *result;
240
241                 mono_metadata_decode_row (&tables [MONO_TABLE_TYPESPEC], nindex - 1, 
242                                           bcols, MONO_TYPESPEC_SIZE);
243                 ptr = mono_metadata_blob_heap (image, bcols [MONO_TYPESPEC_SIGNATURE]);
244                 len = mono_metadata_decode_value (ptr, &ptr);   
245                 type = mono_metadata_parse_type (image, ptr, &ptr);
246
247                 if (type->type != MONO_TYPE_ARRAY)
248                         g_assert_not_reached ();                
249
250                 result = (MonoMethod *)g_new0 (MonoMethod, 1);
251                 result->klass = mono_defaults.array_class;
252                 result->iflags = METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL;
253                 result->signature = sig;
254                 
255                 if (!strcmp (mname, ".ctor")) { 
256                         g_assert (sig->hasthis);
257                         if (type->data.array->rank == sig->param_count) {
258                                 result->addr = mono_lookup_internal_call ("__array_ctor");
259                                 return result;
260                         } else if ((type->data.array->rank * 2) == sig->param_count) {
261                                 result->addr = mono_lookup_internal_call ("__array_bound_ctor");
262                                 return result;                  
263                         } else 
264                                 g_assert_not_reached ();
265                 }
266
267                 if (!strcmp (mname, "Set")) {
268                         g_assert (sig->hasthis);
269                         g_assert (type->data.array->rank + 1 == sig->param_count);
270
271                         result->addr = mono_lookup_internal_call ("__array_Set");
272                         return result;
273                 }
274
275                 if (!strcmp (mname, "Get")) {
276                         g_assert (sig->hasthis);
277                         g_assert (type->data.array->rank == sig->param_count);
278
279                         result->addr = mono_lookup_internal_call ("__array_Get");
280                         return result;
281                 }
282
283                 g_assert_not_reached ();
284                 break;
285         }
286         default:
287                 g_assert_not_reached ();
288         }
289
290         return NULL;
291 }
292
293 static ffi_type *
294 ves_map_ffi_type (MonoType *type)
295 {
296         ffi_type *rettype;
297
298         switch (type->type) {
299         case MONO_TYPE_I1:
300                 rettype = &ffi_type_sint8;
301                 break;
302         case MONO_TYPE_BOOLEAN:
303         case MONO_TYPE_U1:
304                 rettype = &ffi_type_uint8;
305                 break;
306         case MONO_TYPE_I2:
307                 rettype = &ffi_type_sint16;
308                 break;
309         case MONO_TYPE_U2:
310         case MONO_TYPE_CHAR:
311                 rettype = &ffi_type_uint16;
312                 break;
313         case MONO_TYPE_I4:
314                 rettype = &ffi_type_sint32;
315                 break;
316         case MONO_TYPE_U4:
317                 rettype = &ffi_type_sint32;
318                 break;
319         case MONO_TYPE_R4:
320                 rettype = &ffi_type_float;
321                 break;
322         case MONO_TYPE_R8:
323                 rettype = &ffi_type_double;
324                 break;
325         case MONO_TYPE_STRING:
326                 rettype = &ffi_type_pointer;
327                 break;
328         case MONO_TYPE_VOID:
329                 rettype = &ffi_type_void;
330                 break;
331         default:
332                 g_warning ("not implemented");
333                 g_assert_not_reached ();
334         }
335
336         return rettype;
337 }
338
339 static void
340 fill_pinvoke_info (MonoImage *image, MonoMethodPInvoke *piinfo, int index)
341 {
342         MonoMethod *mh = &piinfo->method;
343         MonoTableInfo *tables = image->tables;
344         MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
345         MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
346         guint32 im_cols [4];
347         guint32 mr_cols [1];
348         const char *import = NULL;
349         const char *scope = NULL;
350         char *full_name;
351         GModule *gmodule;
352         ffi_type **args, *rettype;
353         int i, acount;
354
355         for (i = 0; i < im->rows; i++) {
356                         
357                 mono_metadata_decode_row (im, i, im_cols, 4);
358
359                 if ((im_cols[1] >> 1) == index + 1) {
360
361                         import = mono_metadata_string_heap (image, im_cols [2]);
362
363                         mono_metadata_decode_row (mr, im_cols [3] - 1, mr_cols,
364                                                   1);
365                         
366                         scope = mono_metadata_string_heap (image, mr_cols [0]);
367                 }
368         }
369
370         g_assert (import && scope);
371
372         scope = mono_map_dll (scope);
373         full_name = g_module_build_path (NULL, scope);
374         gmodule = g_module_open (full_name, G_MODULE_BIND_LAZY);
375         g_free (full_name);
376
377         g_assert (gmodule);
378
379         piinfo->cif = g_new (ffi_cif , 1);
380         piinfo->piflags = im_cols [0];
381
382         g_module_symbol (gmodule, import, &mh->addr); 
383
384         g_assert (mh->addr);
385
386         acount = mh->signature->param_count;
387
388         args = g_new (ffi_type *, acount);
389
390         for (i = 0; i < acount; i++)
391                 args[i] = ves_map_ffi_type (mh->signature->params [i]->type);
392
393         rettype = ves_map_ffi_type (mh->signature->ret->type);
394         
395         if (!ffi_prep_cif (piinfo->cif, FFI_DEFAULT_ABI, acount, rettype, 
396                            args) == FFI_OK) {
397                 g_warning ("prepare pinvoke failed");
398                 g_assert_not_reached ();
399         }
400 }
401
402 MonoMethod *
403 mono_get_method (MonoImage *image, guint32 token, MonoClass *klass)
404 {
405         MonoMethod *result;
406         int table = mono_metadata_token_table (token);
407         int index = mono_metadata_token_index (token);
408         MonoTableInfo *tables = image->tables;
409         const char *loc, *sig = NULL;
410         char *name;
411         int size;
412         guint32 cols [MONO_TYPEDEF_SIZE];
413
414         if (table == MONO_TABLE_METHOD && (result = g_hash_table_lookup (image->method_cache, GINT_TO_POINTER (token))))
415                         return result;
416
417         if (table != MONO_TABLE_METHOD) {
418                 g_assert (table == MONO_TABLE_MEMBERREF);
419                 return method_from_memberref (image, index);
420         }
421
422         mono_metadata_decode_row (&tables [table], index - 1, cols, 6);
423
424         if (cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
425                 MonoTableInfo *t = &image->tables [MONO_TABLE_TYPEDEF];
426                 MonoAssembly *corlib;
427                 guint32 tdef;
428                 guint32 tdcols [MONO_TYPEDEF_SIZE];
429
430                 tdef = mono_metadata_typedef_from_method (image, index - 1) - 1;
431
432                 mono_metadata_decode_row (t, tdef, tdcols, MONO_TYPEDEF_SIZE);
433
434                 name = g_strconcat (mono_metadata_string_heap (image, tdcols [MONO_TYPEDEF_NAMESPACE]), ".",
435                                     mono_metadata_string_heap (image, tdcols [MONO_TYPEDEF_NAME]), "::", 
436                                     mono_metadata_string_heap (image, cols [MONO_METHOD_NAME]), NULL);
437
438                 corlib = mono_assembly_open (CORLIB_NAME, NULL, NULL);
439
440                 /* all internal calls must be inside corlib */
441                 g_assert (corlib->image == image);
442
443                 result = (MonoMethod *)g_new0 (MonoMethod, 1);
444
445                 result->addr = mono_lookup_internal_call (name);
446
447                 g_free (name);
448
449                 g_assert (result->addr != NULL);
450
451         } else if (cols [2] & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
452
453                 result = (MonoMethod *)g_new0 (MonoMethodPInvoke, 1);
454         } else {
455
456                 result = (MonoMethod *)g_new0 (MonoMethodNormal, 1);
457         }
458
459         result->klass = klass;
460         result->flags = cols [2];
461         result->iflags = cols [1];
462         result->name = mono_metadata_string_heap (image, cols [3]);
463
464         if (!sig) /* already taken from the methodref */
465                 sig = mono_metadata_blob_heap (image, cols [4]);
466         size = mono_metadata_decode_blob_size (sig, &sig);
467         result->signature = mono_metadata_parse_method_signature (image, 0, sig, NULL);
468
469         if (result->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
470                 fill_pinvoke_info (image, (MonoMethodPInvoke *)result, 
471                                    index - 1);
472         } else if (!(result->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
473                 /* if this is a methodref from another module/assembly, this fails */
474                 loc = mono_cli_rva_map ((MonoCLIImageInfo *)image->image_info, cols [0]);
475
476                 if (!result->klass) {
477                         guint32 type = mono_metadata_typedef_from_method (image, token);
478                         result->klass = mono_class_get (image, MONO_TOKEN_TYPE_DEF | type);
479                 }
480
481                 g_assert (loc);
482
483                 ((MonoMethodNormal *)result)->header = mono_metadata_parse_mh (image, loc);
484         }
485
486         g_hash_table_insert (image->method_cache, GINT_TO_POINTER (token), result);
487
488         return result;
489 }
490
491 void
492 mono_free_method  (MonoMethod *method)
493 {
494         mono_metadata_free_method_signature (method->signature);
495         if (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
496                 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)method;
497                 g_free (piinfo->cif->arg_types);
498                 g_free (piinfo->cif);
499         } else if (!(method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
500                 mono_metadata_free_mh (((MonoMethodNormal *)method)->header);
501         }
502
503         g_free (method);
504 }
505