2001-08-20 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 "cli.h"
30
31
32 static char *dll_map[] = {
33         "libc", "libc.so.6",
34         "libm", "libm.so.6",
35         "cygwin1.dll", "libc.so.6", 
36         NULL, NULL
37 };
38
39 static const char *
40 mono_map_dll (const char *name)
41 {
42         int i = 0;
43
44         while (dll_map [i]) {
45                 if (!strcmp (dll_map [i], name))
46                         return  dll_map [i + 1];
47                 i += 2;
48         }
49
50         return name;
51 }
52
53 guint32
54 mono_typedef_from_name (MonoImage *image, const char *name, 
55                         const char *nspace, guint32 *mlist)
56 {
57         MonoMetadata *m = &image->metadata;
58         MonoTableInfo *t = &m->tables [MONO_TABLE_TYPEDEF];
59         guint32 i;
60         guint32 cols [MONO_TYPEDEF_SIZE];
61
62         for (i=0; i < t->rows; ++i) {
63                 mono_metadata_decode_row (t, i, cols, MONO_TYPEDEF_SIZE);
64                 if (strcmp (name, mono_metadata_string_heap (m, cols [MONO_TYPEDEF_NAME])) == 0 
65                                 && strcmp (nspace, mono_metadata_string_heap (m, cols [MONO_TYPEDEF_NAMESPACE])) == 0) {
66                         if (mlist)
67                                 *mlist = cols [MONO_TYPEDEF_METHOD_LIST];
68                         return MONO_TOKEN_TYPE_DEF | (i + 1);
69                 }
70         }
71         g_assert_not_reached ();
72         return 0;
73 }
74
75 MonoImage *
76 mono_get_corlib ()
77 {
78         static MonoImage *corlib = NULL;
79         MonoAssembly *ass;
80         enum MonoImageOpenStatus status = MONO_IMAGE_OK;
81
82         if (!corlib) {
83                 ass = mono_assembly_open (CORLIB_NAME, NULL, &status);
84                 g_assert (status == MONO_IMAGE_OK);
85                 g_assert (ass != NULL);
86                 g_assert (ass->image != NULL);
87                 
88                 corlib = ass->image;
89         }
90
91         return corlib;
92 }
93
94 /**
95  * mono_get_array_class_info:
96  * @ttoken: pointer to location to store type definition token
97  * @cl: pointer where image will be stored
98  *
99  * This routine locates information about the System.Array class. A reference
100  * to the image containing the class is returned in @cl. The type definition 
101  * token is returned in @ttoken. 
102  */
103 void
104 mono_get_array_class_info (guint *ttoken, MonoImage **cl)
105 {
106         static guint32 arr_token = 0;
107         static MonoImage *corlib;
108
109         if (!arr_token) {
110                 corlib = mono_get_corlib ();            
111                 arr_token = mono_typedef_from_name (corlib, "Array", "System", NULL);
112                 g_assert (arr_token != 0);
113         }
114
115         *ttoken = arr_token;
116         *cl = corlib;
117 }
118
119 /**
120  * mono_get_string_class_info:
121  * @ttoken: pointer to location to store type definition token
122  * @cl: pointer where image will be stored
123  *
124  * This routine locates information about the System.String class. A reference
125  * to the image containing the class is returned in @cl. The type definition 
126  * token is returned in @ttoken. 
127  *
128  * Returns: the method definition token for System.String::.ctor (char *)
129  */
130
131 guint32
132 mono_get_string_class_info (guint *ttoken, MonoImage **cl)
133 {
134         static guint32 ctor = 0, tt = 0;
135         static MonoImage *corlib;
136         MonoMetadata *m;
137         MonoTableInfo *t;
138         guint32 cols [MAX (MONO_TYPEDEF_SIZE, MONO_METHOD_SIZE)];
139         guint32 ncols [MONO_TYPEDEF_SIZE];
140         guint32 i, first = 0, last = 0;
141         const char *name, *nspace;
142
143         if (ctor) {
144                 *ttoken = tt;
145                 *cl = corlib;
146                 return ctor;
147         }
148
149         *cl = corlib = mono_get_corlib ();              
150         
151         m = &corlib->metadata;
152         t = &m->tables [MONO_TABLE_TYPEDEF];
153
154         for (i = 0; i < t->rows; i++) {
155                 mono_metadata_decode_row (t, i, cols, MONO_TYPEDEF_SIZE);
156                 name = mono_metadata_string_heap (m, cols[1]);
157                 nspace = mono_metadata_string_heap (m, cols[2]);
158
159                 if (((cols [0] & TYPE_ATTRIBUTE_CLASS_SEMANTIC_MASK) == TYPE_ATTRIBUTE_CLASS) &&
160                     !strcmp (nspace, "System") && !strcmp (name, "String")) {
161
162                         *ttoken = tt = MONO_TOKEN_TYPE_DEF | (i + 1);
163
164                         first = cols [5] - 1;
165
166                         if (i + 1 < t->rows) {
167                                 mono_metadata_decode_row (t, i + 1, ncols, 
168                                                           MONO_TYPEDEF_SIZE);
169                                 last =  ncols [5] - 1;
170                         } else
171                                 last = m->tables [MONO_TABLE_METHOD].rows;
172                         break;
173                 }
174         }
175
176         g_assert (last - first > 0);
177
178         t = &m->tables [MONO_TABLE_METHOD];
179         g_assert (last < t->rows);
180
181         for (i = first; i < last; i++) {
182                 const char *ptr;
183                 int len;
184                 guint8 sig[] = { 0x20, 0x01, 0x01, 0x0f, 0x03 };
185                 mono_metadata_decode_row (t, i, cols, MONO_METHOD_SIZE);
186
187                 if (!strcmp (mono_metadata_string_heap (m, cols [3]), 
188                              ".ctor") &&
189                     (cols [2] & METHOD_ATTRIBUTE_SPECIAL_NAME)) {
190
191                         ptr = mono_metadata_blob_heap (m, cols [4]);
192                         len = mono_metadata_decode_value (ptr, &ptr);
193
194                         if (len == 5 && !memcmp (ptr, sig, len)) {
195                                 ctor = MONO_TOKEN_METHOD_DEF | (i + 1);
196                                 break;
197                         }
198                 } 
199
200         }
201
202         return ctor;
203 }
204
205 static MonoMethod *
206 method_from_memberref (MonoImage *image, guint32 index)
207 {
208         MonoImage *mimage;
209         MonoMetadata *m = &image->metadata;
210         MonoTableInfo *tables = m->tables;
211         guint32 cols[6];
212         guint32 nindex, class, i;
213         const char *mname, *name, *nspace;
214         MonoMethodSignature *sig, *msig;
215         const char *ptr;
216
217         mono_metadata_decode_row (&tables [MONO_TABLE_MEMBERREF], index-1, cols, 3);
218         nindex = cols [MONO_MEMBERREF_CLASS] >> MEMBERREF_PARENT_BITS;
219         class = cols [MONO_MEMBERREF_CLASS] & MEMBERREF_PARENT_MASK;
220         /*g_print ("methodref: 0x%x 0x%x %s\n", class, nindex,
221                 mono_metadata_string_heap (m, cols [MONO_MEMBERREF_NAME]));*/
222
223         mname = mono_metadata_string_heap (m, cols [MONO_MEMBERREF_NAME]);
224         
225         ptr = mono_metadata_blob_heap (m, cols [MONO_MEMBERREF_SIGNATURE]);
226         mono_metadata_decode_blob_size (ptr, &ptr);
227         sig = mono_metadata_parse_method_signature (m, 0, ptr, NULL);
228
229         switch (class) {
230         case MEMBERREF_PARENT_TYPEREF: {
231                 guint32 scopeindex, scopetable;
232
233                 mono_metadata_decode_row (&tables [MONO_TABLE_TYPEREF], nindex-1, cols, MONO_TYPEREF_SIZE);
234                 scopeindex = cols [MONO_TYPEREF_SCOPE] >> RESOLTION_SCOPE_BITS;
235                 scopetable = cols [MONO_TYPEREF_SCOPE] & RESOLTION_SCOPE_MASK;
236                 /*g_print ("typeref: 0x%x 0x%x %s.%s\n", scopetable, scopeindex,
237                         mono_metadata_string_heap (m, cols [MONO_TYPEREF_NAMESPACE]),
238                         mono_metadata_string_heap (m, cols [MONO_TYPEREF_NAME]));*/
239                 switch (scopetable) {
240                 case RESOLTION_SCOPE_ASSEMBLYREF:
241                         /*
242                          * To find the method we have the following info:
243                          * *) name and namespace of the class from the TYPEREF table
244                          * *) name and signature of the method from the MEMBERREF table
245                          */
246                         nspace = mono_metadata_string_heap (m, cols [MONO_TYPEREF_NAMESPACE]);
247                         name = mono_metadata_string_heap (m, cols [MONO_TYPEREF_NAME]);
248
249                         /* this will triggered by references to mscorlib */
250                         g_assert (image->references [scopeindex-1] != NULL);
251
252                         mimage = image->references [scopeindex-1]->image;
253
254                         m = &mimage->metadata;
255                         tables = &m->tables [MONO_TABLE_METHOD];
256                         mono_typedef_from_name (mimage, name, nspace, &i);
257                         /* mostly dumb search for now */
258                         for (i--; i < tables->rows; ++i) {
259
260                                 mono_metadata_decode_row (tables, i, cols, MONO_METHOD_SIZE);
261
262                                 if (!strcmp (mname, mono_metadata_string_heap (m, cols [MONO_METHOD_NAME]))) {
263                                         
264                                         ptr = mono_metadata_blob_heap (m, cols [MONO_METHOD_SIGNATURE]);
265                                         mono_metadata_decode_blob_size (ptr, &ptr);
266                                         msig = mono_metadata_parse_method_signature (m, 1, ptr, NULL);
267
268                                         if (mono_metadata_signature_equal (&image->metadata, sig, 
269                                                                            &mimage->metadata, msig)) {
270                                                 mono_metadata_free_method_signature (sig);
271                                                 mono_metadata_free_method_signature (msig);
272                                                 return mono_get_method (mimage, MONO_TOKEN_METHOD_DEF | (i + 1));
273                                         }
274                                 }
275                         }
276                         g_warning ("cant find method %s.%s::%s",nspace, name, mname);
277                         g_assert_not_reached ();
278                         break;
279                 default:
280                         g_assert_not_reached ();
281                 }
282                 break;
283         }
284         case MEMBERREF_PARENT_TYPESPEC: {
285                 guint32 bcols [MONO_TYPESPEC_SIZE];
286                 guint32 len;
287                 MonoType *type;
288                 MonoMethod *result;
289
290                 mono_metadata_decode_row (&tables [MONO_TABLE_TYPESPEC], nindex - 1, 
291                                           bcols, MONO_TYPESPEC_SIZE);
292                 ptr = mono_metadata_blob_heap (m, bcols [MONO_TYPESPEC_SIGNATURE]);
293                 len = mono_metadata_decode_value (ptr, &ptr);   
294                 type = mono_metadata_parse_type (m, ptr, &ptr);
295
296                 if (type->type != MONO_TYPE_ARRAY)
297                         g_assert_not_reached ();                
298
299                 result = (MonoMethod *)g_new0 (MonoMethod, 1);
300                 result->image = image;
301                 result->iflags = METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL;
302                 result->signature = sig;
303                 
304                 if (!strcmp (mname, ".ctor")) { 
305                         g_assert (sig->hasthis);
306                         if (type->data.array->rank == sig->param_count) {
307                                 result->addr = mono_lookup_internal_call ("__array_ctor");
308                                 return result;
309                         } else if ((type->data.array->rank * 2) == sig->param_count) {
310                                 result->addr = mono_lookup_internal_call ("__array_bound_ctor");
311                                 return result;                  
312                         } else 
313                                 g_assert_not_reached ();
314                 }
315
316                 if (!strcmp (mname, "Set")) {
317                         g_assert (sig->hasthis);
318                         g_assert (type->data.array->rank + 1 == sig->param_count);
319
320                         result->addr = mono_lookup_internal_call ("__array_Set");
321                         return result;
322                 }
323
324                 if (!strcmp (mname, "Get")) {
325                         g_assert (sig->hasthis);
326                         g_assert (type->data.array->rank == sig->param_count);
327
328                         result->addr = mono_lookup_internal_call ("__array_Get");
329                         return result;
330                 }
331
332                 g_assert_not_reached ();
333                 break;
334         }
335         default:
336                 g_assert_not_reached ();
337         }
338
339         return NULL;
340 }
341
342 static ffi_type *
343 ves_map_ffi_type (MonoType *type)
344 {
345         ffi_type *rettype;
346
347         switch (type->type) {
348         case MONO_TYPE_I1:
349                 rettype = &ffi_type_sint8;
350                 break;
351         case MONO_TYPE_BOOLEAN:
352         case MONO_TYPE_U1:
353                 rettype = &ffi_type_uint8;
354                 break;
355         case MONO_TYPE_I2:
356                 rettype = &ffi_type_sint16;
357                 break;
358         case MONO_TYPE_U2:
359         case MONO_TYPE_CHAR:
360                 rettype = &ffi_type_uint16;
361                 break;
362         case MONO_TYPE_I4:
363                 rettype = &ffi_type_sint32;
364                 break;
365         case MONO_TYPE_U4:
366                 rettype = &ffi_type_sint32;
367                 break;
368         case MONO_TYPE_R4:
369                 rettype = &ffi_type_float;
370                 break;
371         case MONO_TYPE_R8:
372                 rettype = &ffi_type_double;
373                 break;
374         case MONO_TYPE_STRING:
375                 rettype = &ffi_type_pointer;
376                 break;
377         case MONO_TYPE_VOID:
378                 rettype = &ffi_type_void;
379                 break;
380         default:
381                 g_warning ("not implemented");
382                 g_assert_not_reached ();
383         }
384
385         return rettype;
386 }
387
388 static void
389 fill_pinvoke_info (MonoImage *image, MonoMethodPInvoke *piinfo, int index)
390 {
391         MonoMethod *mh = &piinfo->method;
392         MonoTableInfo *tables = image->metadata.tables;
393         MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
394         MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
395         guint32 im_cols [4];
396         guint32 mr_cols [1];
397         const char *import = NULL;
398         const char *scope = NULL;
399         char *full_name;
400         GModule *gmodule;
401         ffi_type **args, *rettype;
402         int i, acount;
403
404         for (i = 0; i < im->rows; i++) {
405                         
406                 mono_metadata_decode_row (im, i, im_cols, 4);
407
408                 if ((im_cols[1] >> 1) == index + 1) {
409
410                         import = mono_metadata_string_heap (&image->metadata, 
411                                                             im_cols [2]);
412
413                         mono_metadata_decode_row (mr, im_cols [3] - 1, mr_cols,
414                                                   1);
415                         
416                         scope = mono_metadata_string_heap (&image->metadata, 
417                                                            mr_cols [0]);
418                 }
419         }
420
421         g_assert (import && scope);
422
423         scope = mono_map_dll (scope);
424         full_name = g_module_build_path (NULL, scope);
425         gmodule = g_module_open (full_name, G_MODULE_BIND_LAZY);
426         g_free (full_name);
427
428         g_assert (gmodule);
429
430         piinfo->cif = g_new (ffi_cif , 1);
431         piinfo->piflags = im_cols [0];
432
433         g_module_symbol (gmodule, import, &mh->addr); 
434
435         g_assert (mh->addr);
436
437         acount = mh->signature->param_count;
438
439         args = g_new (ffi_type *, acount);
440
441         for (i = 0; i < acount; i++)
442                 args[i] = ves_map_ffi_type (mh->signature->params [i]->type);
443
444         rettype = ves_map_ffi_type (mh->signature->ret->type);
445         
446         if (!ffi_prep_cif (piinfo->cif, FFI_DEFAULT_ABI, acount, rettype, 
447                            args) == FFI_OK) {
448                 g_warning ("prepare pinvoke failed");
449                 g_assert_not_reached ();
450         }
451 }
452
453 MonoMethod *
454 mono_get_method (MonoImage *image, guint32 token)
455 {
456         MonoMethod *result;
457         MonoMetadata *m = &image->metadata;
458         int table = mono_metadata_token_table (token);
459         int index = mono_metadata_token_index (token);
460         MonoTableInfo *tables = m->tables;
461         const char *loc, *sig = NULL;
462         char *name;
463         int size;
464         guint32 cols[MONO_TYPEDEF_SIZE];
465
466         if (table == MONO_TABLE_METHOD && (result = g_hash_table_lookup (image->method_cache, GINT_TO_POINTER (token))))
467                         return result;
468
469         if (table != MONO_TABLE_METHOD) {
470                 g_assert (table == MONO_TABLE_MEMBERREF);
471                 return method_from_memberref (image, index);
472         }
473
474         mono_metadata_decode_row (&tables [table], index - 1, cols, 6);
475
476         if (cols [1] & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
477                 MonoTableInfo *t = &m->tables [MONO_TABLE_TYPEDEF];
478                 MonoAssembly *corlib;
479                 guint32 tdef;
480                 guint32 tdcols [MONO_TYPEDEF_SIZE];
481
482                 tdef = mono_metadata_typedef_from_method (m, index - 1) - 1;
483
484                 mono_metadata_decode_row (t, tdef, tdcols, MONO_TYPEDEF_SIZE);
485
486                 name = g_strconcat (mono_metadata_string_heap (m, tdcols [MONO_TYPEDEF_NAMESPACE]), ".",
487                                     mono_metadata_string_heap (m, tdcols [MONO_TYPEDEF_NAME]), "::", 
488                                     mono_metadata_string_heap (m, cols [MONO_METHOD_NAME]), NULL);
489
490                 corlib = mono_assembly_open (CORLIB_NAME, NULL, NULL);
491
492                 /* all internal calls must be inside corlib */
493                 g_assert (corlib->image == image);
494
495                 result = (MonoMethod *)g_new0 (MonoMethod, 1);
496
497                 result->addr = mono_lookup_internal_call (name);
498
499                 g_free (name);
500
501                 g_assert (result->addr != NULL);
502
503         } else if (cols [2] & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
504
505                 result = (MonoMethod *)g_new0 (MonoMethodPInvoke, 1);
506         } else {
507
508                 result = (MonoMethod *)g_new0 (MonoMethodNormal, 1);
509         }
510
511         result->image = image;
512         result->flags = cols [2];
513         result->iflags = cols [1];
514         result->name = mono_metadata_string_heap (m, cols [3]);
515
516         if (!sig) /* already taken from the methodref */
517                 sig = mono_metadata_blob_heap (m, cols [4]);
518         size = mono_metadata_decode_blob_size (sig, &sig);
519         result->signature = mono_metadata_parse_method_signature (m, 0, sig, NULL);
520
521         if (result->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
522                 fill_pinvoke_info (image, (MonoMethodPInvoke *)result, 
523                                    index - 1);
524         } else if (!(result->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
525                 /* if this is a methodref from another module/assembly, this fails */
526                 loc = mono_cli_rva_map ((MonoCLIImageInfo *)image->image_info, cols [0]);
527                 g_assert (loc);
528                 ((MonoMethodNormal *)result)->header = 
529                         mono_metadata_parse_mh (m, loc);
530         }
531
532         g_hash_table_insert (image->method_cache, GINT_TO_POINTER (token), result);
533
534         return result;
535 }
536
537 void
538 mono_free_method  (MonoMethod *method)
539 {
540         mono_metadata_free_method_signature (method->signature);
541         if (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
542                 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *)method;
543                 g_free (piinfo->cif->arg_types);
544                 g_free (piinfo->cif);
545         } else if (!(method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
546                 mono_metadata_free_mh (((MonoMethodNormal *)method)->header);
547         }
548
549         g_free (method);
550 }
551