2003-11-24 Zoltan Varga <vargaz@freemail.hu>
[mono.git] / mono / metadata / assembly.c
1 /*
2  * assembly.c: Routines for loading assemblies.
3  * 
4  * Author:
5  *   Miguel de Icaza (miguel@ximian.com)
6  *
7  * (C) 2001 Ximian, Inc.  http://www.ximian.com
8  *
9  * TODO:
10  *   Implement big-endian versions of the reading routines.
11  */
12 #include <config.h>
13 #include <stdio.h>
14 #include <glib.h>
15 #include <errno.h>
16 #include <string.h>
17 #include <stdlib.h>
18 #include "assembly.h"
19 #include "image.h"
20 #include "cil-coff.h"
21 #include "rawbuffer.h"
22 #ifdef WITH_BUNDLE
23 #include "mono-bundle.h"
24 #endif
25 #include <mono/io-layer/io-layer.h>
26
27 /* the default search path is just MONO_ASSEMBLIES */
28 static const char*
29 default_path [] = {
30         MONO_ASSEMBLIES,
31         NULL
32 };
33
34 static char **assemblies_path = NULL;
35
36 /*
37  * keeps track of loaded assemblies
38  */
39 static GList *loaded_assemblies = NULL;
40 static MonoAssembly *corlib;
41
42 /* This protects loaded_assemblies and image->references */
43 static CRITICAL_SECTION assemblies_mutex;
44
45 /* A hastable of thread->assembly list mappings */
46 static GHashTable *assemblies_loading;
47
48 #ifdef PLATFORM_WIN32
49
50 static void
51 init_default_path (void)
52 {
53         int i;
54
55         default_path [0] = g_strdup (MONO_ASSEMBLIES);
56         for (i = strlen (MONO_ASSEMBLIES) - 1; i >= 0; i--) {
57                 if (default_path [0][i] == '/')
58                         ((char*) default_path [0])[i] = '\\';
59         }
60 }
61 #endif
62
63 static void
64 check_env (void) {
65         const char *path;
66         char **splitted;
67         
68         path = getenv ("MONO_PATH");
69         if (!path)
70                 return;
71         splitted = g_strsplit (path, G_SEARCHPATH_SEPARATOR_S, 1000);
72         if (assemblies_path)
73                 g_strfreev (assemblies_path);
74         assemblies_path = splitted;
75 }
76
77 /* assemblies_mutex must be held by the caller */
78 static MonoAssembly*
79 search_loaded (MonoAssemblyName* aname)
80 {
81         GList *tmp;
82         MonoAssembly *ass;
83         GList *loading;
84         
85         for (tmp = loaded_assemblies; tmp; tmp = tmp->next) {
86                 ass = tmp->data;
87                 if (!ass->aname.name)
88                         continue;
89                 /* we just compare the name, but later we'll do all the checks */
90                 /* g_print ("compare %s %s\n", aname->name, ass->aname.name); */
91                 if (strcmp (aname->name, ass->aname.name))
92                         continue;
93                 /* g_print ("success\n"); */
94
95                 return ass;
96         }
97
98         /*
99          * The assembly might be under load by this thread. In this case, it is
100          * safe to return an incomplete instance to prevent loops.
101          */
102         loading = g_hash_table_lookup (assemblies_loading, GetCurrentThread ());
103         for (tmp = loading; tmp; tmp = tmp->next) {
104                 ass = tmp->data;
105                 if (!ass->aname.name)
106                         continue;
107                 if (strcmp (aname->name, ass->aname.name))
108                         continue;
109
110                 return ass;
111         }
112
113         return NULL;
114 }
115
116 static MonoAssembly *
117 load_in_path (const char *basename, const char** search_path, MonoImageOpenStatus *status)
118 {
119         int i;
120         char *fullpath;
121         MonoAssembly *result;
122
123         for (i = 0; search_path [i]; ++i) {
124                 fullpath = g_build_filename (search_path [i], basename, NULL);
125                 result = mono_assembly_open (fullpath, status);
126                 g_free (fullpath);
127                 if (result)
128                         return result;
129         }
130         return NULL;
131 }
132
133 /**
134  * mono_assembly_setrootdir:
135  * @root_dir: The pathname of the root directory where we will locate assemblies
136  *
137  * This routine sets the internal default root directory for looking up
138  * assemblies.  This is used by Windows installations to compute dynamically
139  * the place where the Mono assemblies are located.
140  *
141  */
142 void
143 mono_assembly_setrootdir (const char *root_dir)
144 {
145         /*
146          * Override the MONO_ASSEMBLIES directory configured at compile time.
147          */
148         /* Leak if called more than once */
149         default_path [0] = g_strdup (root_dir);
150 }
151
152 /**
153  * mono_assemblies_init:
154  *
155  *  Initialize global variables used by this module.
156  */
157 void
158 mono_assemblies_init (void)
159 {
160 #ifdef PLATFORM_WIN32
161         init_default_path ();
162 #endif
163
164         check_env ();
165
166         InitializeCriticalSection (&assemblies_mutex);
167
168         assemblies_loading = g_hash_table_new (NULL, NULL);
169 }
170
171 gboolean
172 mono_assembly_fill_assembly_name (MonoImage *image, MonoAssemblyName *aname)
173 {
174         MonoTableInfo *t = &image->tables [MONO_TABLE_ASSEMBLY];
175         guint32 cols [MONO_ASSEMBLY_SIZE];
176
177         if (!t->rows)
178                 return FALSE;
179
180         mono_metadata_decode_row (t, 0, cols, MONO_ASSEMBLY_SIZE);
181
182         aname->hash_len = 0;
183         aname->hash_value = NULL;
184         aname->name = mono_metadata_string_heap (image, cols [MONO_ASSEMBLY_NAME]);
185         aname->culture = mono_metadata_string_heap (image, cols [MONO_ASSEMBLY_CULTURE]);
186         aname->flags = cols [MONO_ASSEMBLY_FLAGS];
187         aname->major = cols [MONO_ASSEMBLY_MAJOR_VERSION];
188         aname->minor = cols [MONO_ASSEMBLY_MINOR_VERSION];
189         aname->build = cols [MONO_ASSEMBLY_BUILD_NUMBER];
190         aname->revision = cols [MONO_ASSEMBLY_REV_NUMBER];
191         aname->hash_alg = cols [MONO_ASSEMBLY_HASH_ALG];
192         if (cols [MONO_ASSEMBLY_PUBLIC_KEY])
193                 aname->public_key = mono_metadata_blob_heap (image, cols [MONO_ASSEMBLY_PUBLIC_KEY]);
194         else
195                 aname->public_key = 0;
196
197         return TRUE;
198 }
199
200 static void
201 mono_assembly_load_references (MonoImage *image, MonoImageOpenStatus *status)
202 {
203         MonoTableInfo *t;
204         guint32 cols [MONO_ASSEMBLYREF_SIZE];
205         const char *hash;
206         int i;
207
208         *status = MONO_IMAGE_OK;
209
210         t = &image->tables [MONO_TABLE_ASSEMBLYREF];
211
212         image->references = g_new0 (MonoAssembly *, t->rows + 1);
213
214         /*
215          * Load any assemblies this image references
216          */
217         for (i = 0; i < t->rows; i++) {
218                 MonoAssemblyName aname;
219
220                 mono_metadata_decode_row (t, i, cols, MONO_ASSEMBLYREF_SIZE);
221                 
222                 hash = mono_metadata_blob_heap (image, cols [MONO_ASSEMBLYREF_HASH_VALUE]);
223                 aname.hash_len = mono_metadata_decode_blob_size (hash, &hash);
224                 aname.hash_value = hash;
225                 aname.name = mono_metadata_string_heap (image, cols [MONO_ASSEMBLYREF_NAME]);
226                 aname.culture = mono_metadata_string_heap (image, cols [MONO_ASSEMBLYREF_CULTURE]);
227                 aname.flags = cols [MONO_ASSEMBLYREF_FLAGS];
228                 aname.major = cols [MONO_ASSEMBLYREF_MAJOR_VERSION];
229                 aname.minor = cols [MONO_ASSEMBLYREF_MINOR_VERSION];
230                 aname.build = cols [MONO_ASSEMBLYREF_BUILD_NUMBER];
231                 aname.revision = cols [MONO_ASSEMBLYREF_REV_NUMBER];
232
233                 image->references [i] = mono_assembly_load (&aname, image->assembly->basedir, status);
234
235                 if (image->references [i] == NULL){
236                         int j;
237                         
238                         for (j = 0; j < i; j++)
239                                 mono_assembly_close (image->references [j]);
240                         g_free (image->references);
241
242                         g_warning ("Could not find assembly %s", aname.name);
243                         *status = MONO_IMAGE_MISSING_ASSEMBLYREF;
244                         return;
245                 }
246
247                 /* 
248                  * This check is disabled since lots of people seem to have an older
249                  * corlib which triggers this.
250                  */
251                 /* 
252                 if (image->references [i]->image == image)
253                         g_error ("Error: Assembly %s references itself", image->name);
254                 */
255         }
256         image->references [i] = NULL;
257
258         /* resolve assembly references for modules */
259         t = &image->tables [MONO_TABLE_MODULEREF];
260         for (i = 0; i < t->rows; i++){
261                 if (image->modules [i]) {
262                         image->modules [i]->assembly = image->assembly;
263                         mono_assembly_load_references (image->modules [i], status);
264                 }
265         }
266 }
267
268 typedef struct AssemblyLoadHook AssemblyLoadHook;
269 struct AssemblyLoadHook {
270         AssemblyLoadHook *next;
271         MonoAssemblyLoadFunc func;
272         gpointer user_data;
273 };
274
275 AssemblyLoadHook *assembly_load_hook = NULL;
276
277 void
278 mono_assembly_invoke_load_hook (MonoAssembly *ass)
279 {
280         AssemblyLoadHook *hook;
281
282         for (hook = assembly_load_hook; hook; hook = hook->next) {
283                 hook->func (ass, hook->user_data);
284         }
285 }
286
287 void
288 mono_install_assembly_load_hook (MonoAssemblyLoadFunc func, gpointer user_data)
289 {
290         AssemblyLoadHook *hook;
291         
292         g_return_if_fail (func != NULL);
293
294         hook = g_new0 (AssemblyLoadHook, 1);
295         hook->func = func;
296         hook->user_data = user_data;
297         hook->next = assembly_load_hook;
298         assembly_load_hook = hook;
299 }
300
301 typedef struct AssemblyPreLoadHook AssemblyPreLoadHook;
302 struct AssemblyPreLoadHook {
303         AssemblyPreLoadHook *next;
304         MonoAssemblyPreLoadFunc func;
305         gpointer user_data;
306 };
307
308 AssemblyPreLoadHook *assembly_preload_hook = NULL;
309
310 static MonoAssembly *
311 invoke_assembly_preload_hook (MonoAssemblyName *aname, gchar **assemblies_path)
312 {
313         AssemblyPreLoadHook *hook;
314         MonoAssembly *assembly;
315
316         for (hook = assembly_preload_hook; hook; hook = hook->next) {
317                 assembly = hook->func (aname, assemblies_path, hook->user_data);
318                 if (assembly != NULL)
319                         return assembly;
320         }
321
322         return NULL;
323 }
324
325 void
326 mono_install_assembly_preload_hook (MonoAssemblyPreLoadFunc func, gpointer user_data)
327 {
328         AssemblyPreLoadHook *hook;
329         
330         g_return_if_fail (func != NULL);
331
332         hook = g_new0 (AssemblyPreLoadHook, 1);
333         hook->func = func;
334         hook->user_data = user_data;
335         hook->next = assembly_preload_hook;
336         assembly_preload_hook = hook;
337 }
338
339 static gchar *
340 absolute_dir (const gchar *filename)
341 {
342         gchar *cwd;
343         gchar *mixed;
344         gchar **parts;
345         gchar *part;
346         GList *list, *tmp;
347         GString *result;
348         gchar *res;
349         gint i;
350
351         if (g_path_is_absolute (filename))
352                 return g_path_get_dirname (filename);
353
354         cwd = g_get_current_dir ();
355         mixed = g_build_filename (cwd, filename, NULL);
356         parts = g_strsplit (mixed, G_DIR_SEPARATOR_S, 0);
357         g_free (mixed);
358         g_free (cwd);
359
360         list = NULL;
361         for (i = 0; (part = parts [i]) != NULL; i++) {
362                 if (!strcmp (part, "."))
363                         continue;
364
365                 if (!strcmp (part, "..")) {
366                         if (list && list->next) /* Don't remove root */
367                                 list = g_list_delete_link (list, list);
368                 } else {
369                         list = g_list_prepend (list, part);
370                 }
371         }
372
373         result = g_string_new ("");
374         list = g_list_reverse (list);
375
376         /* Ignores last data pointer, which should be the filename */
377         for (tmp = list; tmp && tmp->next != NULL; tmp = tmp->next)
378                 if (tmp->data)
379                         g_string_append_printf (result, "%s%c", (char *) tmp->data,
380                                                                 G_DIR_SEPARATOR);
381         
382         res = result->str;
383         g_string_free (result, FALSE);
384         g_list_free (list);
385         g_strfreev (parts);
386         if (*res == '\0') {
387                 g_free (res);
388                 return g_strdup (".");
389         }
390
391         return res;
392 }
393
394 static MonoImage*
395 do_mono_assembly_open (const char *filename, MonoImageOpenStatus *status)
396 {
397         MonoImage *image = NULL;
398 #ifdef WITH_BUNDLE
399         int i;
400         char *name = g_path_get_basename (filename);
401         char *dot = strrchr (name, '.');
402         GList *tmp;
403         MonoAssembly *ass;
404         
405         if (dot)
406                 *dot = 0;
407         if (strcmp (name, "corlib") == 0) {
408                 g_free (name);
409                 name = g_strdup ("mscorlib");
410         }
411         /* we do a very simple search for bundled assemblies: it's not a general 
412          * purpose assembly loading mechanism.
413          */
414         EnterCriticalSection (&assemblies_mutex);
415         for (tmp = loaded_assemblies; tmp; tmp = tmp->next) {
416                 ass = tmp->data;
417                 if (!ass->aname.name)
418                         continue;
419                 if (strcmp (name, ass->aname.name))
420                         continue;
421                 image = ass->image;
422                 break;
423         }
424         LeaveCriticalSection (&assemblies_mutex);
425         for (i = 0; !image && bundled_assemblies [i]; ++i) {
426                 if (strcmp (bundled_assemblies [i]->name, name) == 0) {
427                         image = mono_image_open_from_data ((char*)bundled_assemblies [i]->data, bundled_assemblies [i]->size, FALSE, status);
428                         break;
429                 }
430         }
431         g_free (name);
432         if (image) {
433                 InterlockedIncrement (&image->ref_count);
434                 return image;
435         }
436 #endif
437         image = mono_image_open (filename, status);
438         return image;
439 }
440
441 /**
442  * mono_assembly_open:
443  * @filename: Opens the assembly pointed out by this name
444  * @status: where a status code can be returned
445  *
446  * mono_assembly_open opens the PE-image pointed by @filename, and
447  * loads any external assemblies referenced by it.
448  *
449  * NOTE: we could do lazy loading of the assemblies.  Or maybe not worth
450  * it. 
451  */
452 MonoAssembly *
453 mono_assembly_open (const char *filename, MonoImageOpenStatus *status)
454 {
455         MonoAssembly *ass, *ass2;
456         MonoImage *image;
457         char *base_dir;
458         MonoImageOpenStatus def_status;
459         gchar *fname;
460         GList *loading;
461         
462         g_return_val_if_fail (filename != NULL, NULL);
463
464         if (!status)
465                 status = &def_status;
466         *status = MONO_IMAGE_OK;
467
468         if (strncmp (filename, "file://", 7) == 0) {
469                 GError *error = NULL;
470                 gchar *uri = (gchar *) filename;
471
472                 /*
473                  * MS allows file://c:/... and fails on file://localhost/c:/... 
474                  * They also throw an IndexOutOfRangeException if "file://"
475                  */
476                 if (uri [7] != '/')
477                         uri = g_strdup_printf ("file:///%s", uri + 7);
478         
479                 fname = g_filename_from_uri (uri, NULL, &error);
480                 if (uri != filename)
481                         g_free (uri);
482
483                 if (error != NULL) {
484                         g_warning ("%s\n", error->message);
485                         g_error_free (error);
486                         fname = g_strdup (filename);
487                 }
488         } else {
489                 fname = g_strdup (filename);
490         }
491
492         /* g_print ("file loading %s\n", fname); */
493         image = do_mono_assembly_open (fname, status);
494
495         if (!image){
496                 *status = MONO_IMAGE_ERROR_ERRNO;
497                 g_free (fname);
498                 return NULL;
499         }
500
501 #if defined (PLATFORM_WIN32)
502         {
503                 gchar *tmp_fn;
504                 int i;
505
506                 tmp_fn = g_strdup (fname);
507                 for (i = strlen (tmp_fn) - 1; i >= 0; i--) {
508                         if (tmp_fn [i] == '/')
509                                 tmp_fn [i] = '\\';
510                 }
511
512                 base_dir = absolute_dir (tmp_fn);
513                 g_free (tmp_fn);
514         }
515 #else
516         base_dir = absolute_dir (fname);
517 #endif
518
519         /*
520          * Create assembly struct, and enter it into the assembly cache
521          */
522         ass = g_new0 (MonoAssembly, 1);
523         ass->basedir = base_dir;
524         ass->image = image;
525
526
527         g_free (fname);
528
529         mono_assembly_fill_assembly_name (image, &ass->aname);
530
531         /* 
532          * Atomically search the loaded list and add ourselves to it if necessary.
533          */
534         EnterCriticalSection (&assemblies_mutex);
535         if (ass->aname.name)
536                 /* avoid loading the same assembly twice for now... */
537                 if ((ass2 = search_loaded (&ass->aname))) {
538                         g_free (ass);
539                         g_free (base_dir);
540                         mono_image_close (image);
541                         *status = MONO_IMAGE_OK;
542                         LeaveCriticalSection (&assemblies_mutex);
543                         return ass2;
544                 }
545         loading = g_hash_table_lookup (assemblies_loading, GetCurrentThread ());
546         loading = g_list_prepend (loading, ass);
547         g_hash_table_insert (assemblies_loading, GetCurrentThread (), loading);
548         LeaveCriticalSection (&assemblies_mutex);
549
550         image->assembly = ass;
551
552         /*
553          * We load referenced assemblies outside the lock to prevent deadlocks
554          * with regards to preload hooks.
555          */
556         mono_assembly_load_references (image, status);
557
558         EnterCriticalSection (&assemblies_mutex);
559
560         loading = g_hash_table_lookup (assemblies_loading, GetCurrentThread ());
561         loading = g_list_remove (loading, ass);
562         if (loading == NULL)
563                 /* Prevent memory leaks */
564                 g_hash_table_remove (assemblies_loading, GetCurrentThread ());
565         else
566                 g_hash_table_insert (assemblies_loading, GetCurrentThread (), loading);
567         if (*status != MONO_IMAGE_OK) {
568                 LeaveCriticalSection (&assemblies_mutex);
569                 mono_assembly_close (ass);
570                 return NULL;
571         }
572
573         if (ass->aname.name) {
574                 ass2 = search_loaded (&ass->aname);
575                 if (ass2) {
576                         /* Somebody else has loaded the assembly before us */
577                         LeaveCriticalSection (&assemblies_mutex);
578                         mono_assembly_close (ass);
579                         return ass2;
580                 }
581         }
582
583         loaded_assemblies = g_list_prepend (loaded_assemblies, ass);
584         LeaveCriticalSection (&assemblies_mutex);
585
586         mono_assembly_invoke_load_hook (ass);
587
588         return ass;
589 }
590
591 MonoAssembly*
592 mono_assembly_load (MonoAssemblyName *aname, const char *basedir, MonoImageOpenStatus *status)
593 {
594         MonoAssembly *result;
595         char *fullpath, *filename;
596
597         result = invoke_assembly_preload_hook (aname, assemblies_path);
598         if (result)
599                 return result;
600
601         /* g_print ("loading %s\n", aname->name); */
602         /* special case corlib */
603         if ((strcmp (aname->name, "mscorlib") == 0) || (strcmp (aname->name, "corlib") == 0)) {
604                 if (corlib) {
605                         /* g_print ("corlib already loaded\n"); */
606                         return corlib;
607                 }
608                 /* g_print ("corlib load\n"); */
609                 if (assemblies_path) {
610                         corlib = load_in_path ("mscorlib.dll", (const char**)assemblies_path, status);
611                         if (corlib)
612                                 return corlib;
613                         corlib = load_in_path ("corlib.dll", (const char**)assemblies_path, status);
614                         if (corlib)
615                                 return corlib;
616                 }
617                 corlib = load_in_path ("mscorlib.dll", default_path, status);
618                 if (!corlib)
619                         corlib = load_in_path ("corlib.dll", default_path, status);
620                 return corlib;
621         }
622         result = search_loaded (aname);
623         if (result)
624                 return result;
625         /* g_print ("%s not found in cache\n", aname->name); */
626         if (strstr (aname->name, ".dll"))
627                 filename = g_strdup (aname->name);
628         else
629                 filename = g_strconcat (aname->name, ".dll", NULL);
630         if (basedir) {
631                 fullpath = g_build_filename (basedir, filename, NULL);
632                 result = mono_assembly_open (fullpath, status);
633                 g_free (fullpath);
634                 if (result) {
635                         g_free (filename);
636                         return result;
637                 }
638         }
639         if (assemblies_path) {
640                 result = load_in_path (filename, (const char**)assemblies_path, status);
641                 if (result) {
642                         g_free (filename);
643                         return result;
644                 }
645         }
646         result = load_in_path (filename, default_path, status);
647         g_free (filename);
648         return result;
649 }
650
651 void
652 mono_assembly_close (MonoAssembly *assembly)
653 {
654         MonoImage *image;
655         int i;
656         
657         g_return_if_fail (assembly != NULL);
658
659         EnterCriticalSection (&assemblies_mutex);
660         if (--assembly->ref_count != 0) {
661                 LeaveCriticalSection (&assemblies_mutex);
662                 return;
663         }
664         loaded_assemblies = g_list_remove (loaded_assemblies, assembly);
665         LeaveCriticalSection (&assemblies_mutex);
666         image = assembly->image;
667         if (image->references) {
668                 for (i = 0; image->references [i] != NULL; i++)
669                         mono_image_close (image->references [i]->image);
670                 g_free (image->references);
671         }
672
673         mono_image_close (assembly->image);
674
675         g_free (assembly->basedir);
676         g_free (assembly);
677 }
678
679 MonoImage*
680 mono_assembly_load_module (MonoAssembly *assembly, guint32 idx)
681 {
682         MonoImageOpenStatus status;
683         MonoImage *module;
684
685         module = mono_image_load_file_for_image (assembly->image, idx);
686         if (module)
687                 mono_assembly_load_references (module, &status);
688
689         return module;
690 }
691
692 void
693 mono_assembly_foreach (GFunc func, gpointer user_data)
694 {
695         GList *copy;
696
697         /*
698      * We make a copy of the list to avoid calling the callback inside the 
699          * lock, which could lead to deadlocks.
700          */
701         EnterCriticalSection (&assemblies_mutex);
702         copy = g_list_copy (loaded_assemblies);
703         LeaveCriticalSection (&assemblies_mutex);
704
705         g_list_foreach (loaded_assemblies, func, user_data);
706
707         g_list_free (copy);
708 }
709
710 /* Holds the assembly of the application, for
711  * System.Diagnostics.Process::MainModule
712  */
713 static MonoAssembly *main_assembly=NULL;
714
715 void
716 mono_assembly_set_main (MonoAssembly *assembly)
717 {
718         main_assembly=assembly;
719 }
720
721 MonoAssembly *
722 mono_assembly_get_main (void)
723 {
724         return(main_assembly);
725 }