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