Use 2.0 instead of 1.0 when probing install dirs.
[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  * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
8  * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
9  */
10 #include <config.h>
11 #include <stdio.h>
12 #include <glib.h>
13 #include <errno.h>
14 #include <string.h>
15 #include <stdlib.h>
16 #include "assembly.h"
17 #include "image.h"
18 #include "object-internals.h"
19 #include <mono/metadata/loader.h>
20 #include <mono/metadata/tabledefs.h>
21 #include <mono/metadata/metadata-internals.h>
22 #include <mono/metadata/profiler-private.h>
23 #include <mono/metadata/class-internals.h>
24 #include <mono/metadata/domain-internals.h>
25 #include <mono/metadata/mono-endian.h>
26 #include <mono/metadata/mono-debug.h>
27 #include <mono/io-layer/io-layer.h>
28 #include <mono/utils/mono-uri.h>
29 #include <mono/metadata/mono-config.h>
30 #include <mono/utils/mono-digest.h>
31 #include <mono/utils/mono-logger-internal.h>
32 #include <mono/utils/mono-path.h>
33 #include <mono/metadata/reflection.h>
34 #include <mono/metadata/coree.h>
35
36 #ifndef HOST_WIN32
37 #include <sys/types.h>
38 #include <unistd.h>
39 #include <sys/stat.h>
40 #endif
41
42 #ifdef PLATFORM_MACOSX
43 #include <mach-o/dyld.h>
44 #endif
45
46 /* AssemblyVersionMap: an assembly name and the assembly version set on which it is based */
47 typedef struct  {
48         const char* assembly_name;
49         guint8 version_set_index;
50 } AssemblyVersionMap;
51
52 /* the default search path is empty, the first slot is replaced with the computed value */
53 static const char*
54 default_path [] = {
55         NULL,
56         NULL
57 };
58
59 /* Contains the list of directories to be searched for assemblies (MONO_PATH) */
60 static char **assemblies_path = NULL;
61
62 /* Contains the list of directories that point to auxiliary GACs */
63 static char **extra_gac_paths = NULL;
64
65 #ifndef DISABLE_ASSEMBLY_REMAPPING
66 /* The list of system assemblies what will be remapped to the running
67  * runtime version. WARNING: this list must be sorted.
68  */
69 static const AssemblyVersionMap framework_assemblies [] = {
70         {"Accessibility", 0},
71         {"Commons.Xml.Relaxng", 0},
72         {"I18N", 0},
73         {"I18N.CJK", 0},
74         {"I18N.MidEast", 0},
75         {"I18N.Other", 0},
76         {"I18N.Rare", 0},
77         {"I18N.West", 0},
78         {"Microsoft.VisualBasic", 1},
79         {"Microsoft.VisualC", 1},
80         {"Mono.Cairo", 0},
81         {"Mono.CompilerServices.SymbolWriter", 0},
82         {"Mono.Data", 0},
83         {"Mono.Data.SybaseClient", 0},
84         {"Mono.Data.Tds", 0},
85         {"Mono.Data.TdsClient", 0},
86         {"Mono.GetOptions", 0},
87         {"Mono.Http", 0},
88         {"Mono.Posix", 0},
89         {"Mono.Security", 0},
90         {"Mono.Security.Win32", 0},
91         {"Mono.Xml.Ext", 0},
92         {"Novell.Directory.Ldap", 0},
93         {"Npgsql", 0},
94         {"PEAPI", 0},
95         {"System", 0},
96         {"System.ComponentModel.DataAnnotations", 2},
97         {"System.Configuration", 0},
98         {"System.Configuration.Install", 0},
99         {"System.Core", 2},
100         {"System.Data", 0},
101         {"System.Data.Linq", 2},
102         {"System.Data.OracleClient", 0},
103         {"System.Data.SqlXml", 0},
104         {"System.Design", 0},
105         {"System.DirectoryServices", 0},
106         {"System.Drawing", 0},
107         {"System.Drawing.Design", 0},
108         {"System.EnterpriseServices", 0},
109         {"System.Management", 0},
110         {"System.Messaging", 0},
111         {"System.Runtime.Remoting", 0},
112         {"System.Runtime.Serialization.Formatters.Soap", 0},
113         {"System.Security", 0},
114         {"System.ServiceProcess", 0},
115         {"System.Web", 0},
116         {"System.Web.Abstractions", 2},
117         {"System.Web.Mobile", 0},
118         {"System.Web.Routing", 2},
119         {"System.Web.Services", 0},
120         {"System.Windows.Forms", 0},
121         {"System.Xml", 0},
122         {"mscorlib", 0}
123 };
124 #endif
125
126 /*
127  * keeps track of loaded assemblies
128  */
129 static GList *loaded_assemblies = NULL;
130 static MonoAssembly *corlib;
131
132 #if defined(__native_client__)
133
134 /* On Native Client, allow mscorlib to be loaded from memory  */
135 /* instead of loaded off disk.  If these are not set, default */
136 /* mscorlib loading will take place                           */
137
138 /* NOTE: If mscorlib data is passed to mono in this way then */
139 /* it needs to remain allocated during the use of mono.      */
140
141 static void *corlibData = NULL;
142 static size_t corlibSize = 0;
143
144 void
145 mono_set_corlib_data (void *data, size_t size)
146 {
147   corlibData = data;
148   corlibSize = size;
149 }
150
151 #endif
152
153 /* This protects loaded_assemblies and image->references */
154 #define mono_assemblies_lock() EnterCriticalSection (&assemblies_mutex)
155 #define mono_assemblies_unlock() LeaveCriticalSection (&assemblies_mutex)
156 static CRITICAL_SECTION assemblies_mutex;
157
158 /* If defined, points to the bundled assembly information */
159 const MonoBundledAssembly **bundles;
160
161 /* Loaded assembly binding info */
162 static GSList *loaded_assembly_bindings = NULL;
163
164 static MonoAssembly*
165 mono_assembly_invoke_search_hook_internal (MonoAssemblyName *aname, gboolean refonly, gboolean postload);
166 static MonoBoolean
167 mono_assembly_is_in_gac (const gchar *filanem);
168
169 static gchar*
170 encode_public_tok (const guchar *token, gint32 len)
171 {
172         const static gchar allowed [] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
173         gchar *res;
174         int i;
175
176         res = g_malloc (len * 2 + 1);
177         for (i = 0; i < len; i++) {
178                 res [i * 2] = allowed [token [i] >> 4];
179                 res [i * 2 + 1] = allowed [token [i] & 0xF];
180         }
181         res [len * 2] = 0;
182         return res;
183 }
184
185 /**
186  * mono_public_tokens_are_equal:
187  * @pubt1: first public key token
188  * @pubt2: second public key token
189  *
190  * Compare two public key tokens and return #TRUE is they are equal and #FALSE
191  * otherwise.
192  */
193 gboolean
194 mono_public_tokens_are_equal (const unsigned char *pubt1, const unsigned char *pubt2)
195 {
196         return memcmp (pubt1, pubt2, 16) == 0;
197 }
198
199 static void
200 check_path_env (void)
201 {
202         const char *path;
203         char **splitted, **dest;
204         
205         path = g_getenv ("MONO_PATH");
206         if (!path)
207                 return;
208
209         splitted = g_strsplit (path, G_SEARCHPATH_SEPARATOR_S, 1000);
210         if (assemblies_path)
211                 g_strfreev (assemblies_path);
212         assemblies_path = dest = splitted;
213         while (*splitted){
214                 if (**splitted)
215                         *dest++ = *splitted;
216                 splitted++;
217         }
218         *dest = *splitted;
219         
220         if (g_getenv ("MONO_DEBUG") == NULL)
221                 return;
222
223         splitted = assemblies_path;
224         while (*splitted) {
225                 if (**splitted && !g_file_test (*splitted, G_FILE_TEST_IS_DIR))
226                         g_warning ("'%s' in MONO_PATH doesn't exist or has wrong permissions.", *splitted);
227
228                 splitted++;
229         }
230 }
231
232 static void
233 check_extra_gac_path_env (void) {
234         const char *path;
235         char **splitted, **dest;
236         
237         path = g_getenv ("MONO_GAC_PREFIX");
238         if (!path)
239                 return;
240
241         splitted = g_strsplit (path, G_SEARCHPATH_SEPARATOR_S, 1000);
242         if (extra_gac_paths)
243                 g_strfreev (extra_gac_paths);
244         extra_gac_paths = dest = splitted;
245         while (*splitted){
246                 if (**splitted)
247                         *dest++ = *splitted;
248                 splitted++;
249         }
250         *dest = *splitted;
251         
252         if (g_getenv ("MONO_DEBUG") == NULL)
253                 return;
254
255         while (*splitted) {
256                 if (**splitted && !g_file_test (*splitted, G_FILE_TEST_IS_DIR))
257                         g_warning ("'%s' in MONO_GAC_PREFIX doesn't exist or has wrong permissions.", *splitted);
258
259                 splitted++;
260         }
261 }
262
263 static gboolean
264 assembly_binding_maps_name (MonoAssemblyBindingInfo *info, MonoAssemblyName *aname)
265 {
266         if (!info || !info->name)
267                 return FALSE;
268
269         if (strcmp (info->name, aname->name))
270                 return FALSE;
271
272         if (info->major != aname->major || info->minor != aname->minor)
273                 return FALSE;
274
275         if ((info->culture != NULL && info->culture [0]) != (aname->culture != NULL && aname->culture [0])) 
276                 return FALSE;
277         
278         if (info->culture && aname->culture && strcmp (info->culture, aname->culture))
279                 return FALSE;
280         
281         if (!mono_public_tokens_are_equal (info->public_key_token, aname->public_key_token))
282                 return FALSE;
283
284         return TRUE;
285 }
286
287 static void
288 mono_assembly_binding_info_free (MonoAssemblyBindingInfo *info)
289 {
290         if (!info)
291                 return;
292
293         g_free (info->name);
294         g_free (info->culture);
295 }
296
297 static void
298 get_publisher_policy_info (MonoImage *image, MonoAssemblyName *aname, MonoAssemblyBindingInfo *binding_info)
299 {
300         MonoTableInfo *t;
301         guint32 cols [MONO_MANIFEST_SIZE];
302         const gchar *filename;
303         gchar *subpath, *fullpath;
304
305         t = &image->tables [MONO_TABLE_MANIFESTRESOURCE];
306         /* MS Impl. accepts policy assemblies with more than
307          * one manifest resource, and only takes the first one */
308         if (t->rows < 1) {
309                 binding_info->is_valid = FALSE;
310                 return;
311         }
312         
313         mono_metadata_decode_row (t, 0, cols, MONO_MANIFEST_SIZE);
314         if ((cols [MONO_MANIFEST_IMPLEMENTATION] & MONO_IMPLEMENTATION_MASK) != MONO_IMPLEMENTATION_FILE) {
315                 binding_info->is_valid = FALSE;
316                 return;
317         }
318         
319         filename = mono_metadata_string_heap (image, cols [MONO_MANIFEST_NAME]);
320         g_assert (filename != NULL);
321         
322         subpath = g_path_get_dirname (image->name);
323         fullpath = g_build_path (G_DIR_SEPARATOR_S, subpath, filename, NULL);
324         mono_config_parse_publisher_policy (fullpath, binding_info);
325         g_free (subpath);
326         g_free (fullpath);
327         
328         /* Define the optional elements/attributes before checking */
329         if (!binding_info->culture)
330                 binding_info->culture = g_strdup ("");
331         
332         /* Check that the most important elements/attributes exist */
333         if (!binding_info->name || !binding_info->public_key_token [0] || !binding_info->has_old_version_bottom ||
334                         !binding_info->has_new_version || !assembly_binding_maps_name (binding_info, aname)) {
335                 mono_assembly_binding_info_free (binding_info);
336                 binding_info->is_valid = FALSE;
337                 return;
338         }
339
340         binding_info->is_valid = TRUE;
341 }
342
343 static int
344 compare_versions (AssemblyVersionSet *v, MonoAssemblyName *aname)
345 {
346         if (v->major > aname->major)
347                 return 1;
348         else if (v->major < aname->major)
349                 return -1;
350
351         if (v->minor > aname->minor)
352                 return 1;
353         else if (v->minor < aname->minor)
354                 return -1;
355
356         if (v->build > aname->build)
357                 return 1;
358         else if (v->build < aname->build)
359                 return -1;
360
361         if (v->revision > aname->revision)
362                 return 1;
363         else if (v->revision < aname->revision)
364                 return -1;
365
366         return 0;
367 }
368
369 static gboolean
370 check_policy_versions (MonoAssemblyBindingInfo *info, MonoAssemblyName *name)
371 {
372         if (!info->is_valid)
373                 return FALSE;
374         
375         /* If has_old_version_top doesn't exist, we don't have an interval */
376         if (!info->has_old_version_top) {
377                 if (compare_versions (&info->old_version_bottom, name) == 0)
378                         return TRUE;
379
380                 return FALSE;
381         }
382
383         /* Check that the version defined by name is valid for the interval */
384         if (compare_versions (&info->old_version_top, name) < 0)
385                 return FALSE;
386
387         /* We should be greater or equal than the small version */
388         if (compare_versions (&info->old_version_bottom, name) > 0)
389                 return FALSE;
390
391         return TRUE;
392 }
393
394 /**
395  * mono_assembly_names_equal:
396  * @l: first assembly
397  * @r: second assembly.
398  *
399  * Compares two MonoAssemblyNames and returns whether they are equal.
400  *
401  * This compares the names, the cultures, the release version and their
402  * public tokens.
403  *
404  * Returns: TRUE if both assembly names are equal.
405  */
406 gboolean
407 mono_assembly_names_equal (MonoAssemblyName *l, MonoAssemblyName *r)
408 {
409         if (!l->name || !r->name)
410                 return FALSE;
411
412         if (strcmp (l->name, r->name))
413                 return FALSE;
414
415         if (l->culture && r->culture && strcmp (l->culture, r->culture))
416                 return FALSE;
417
418         if (l->major != r->major || l->minor != r->minor ||
419                         l->build != r->build || l->revision != r->revision)
420                 if (! ((l->major == 0 && l->minor == 0 && l->build == 0 && l->revision == 0) || (r->major == 0 && r->minor == 0 && r->build == 0 && r->revision == 0)))
421                         return FALSE;
422
423         if (!l->public_key_token [0] || !r->public_key_token [0])
424                 return TRUE;
425
426         if (!mono_public_tokens_are_equal (l->public_key_token, r->public_key_token))
427                 return FALSE;
428
429         return TRUE;
430 }
431
432 static MonoAssembly *
433 load_in_path (const char *basename, const char** search_path, MonoImageOpenStatus *status, MonoBoolean refonly)
434 {
435         int i;
436         char *fullpath;
437         MonoAssembly *result;
438
439         for (i = 0; search_path [i]; ++i) {
440                 fullpath = g_build_filename (search_path [i], basename, NULL);
441                 result = mono_assembly_open_full (fullpath, status, refonly);
442                 g_free (fullpath);
443                 if (result)
444                         return result;
445         }
446         return NULL;
447 }
448
449 /**
450  * mono_assembly_setrootdir:
451  * @root_dir: The pathname of the root directory where we will locate assemblies
452  *
453  * This routine sets the internal default root directory for looking up
454  * assemblies.
455  *
456  * This is used by Windows installations to compute dynamically the
457  * place where the Mono assemblies are located.
458  *
459  */
460 void
461 mono_assembly_setrootdir (const char *root_dir)
462 {
463         /*
464          * Override the MONO_ASSEMBLIES directory configured at compile time.
465          */
466         /* Leak if called more than once */
467         default_path [0] = g_strdup (root_dir);
468 }
469
470 /**
471  * mono_assembly_getrootdir:
472  * 
473  * Obtains the root directory used for looking up assemblies.
474  *
475  * Returns: a string with the directory, this string should not be freed.
476  */
477 G_CONST_RETURN gchar *
478 mono_assembly_getrootdir (void)
479 {
480         return default_path [0];
481 }
482
483 /**
484  * mono_set_dirs:
485  * @assembly_dir: the base directory for assemblies
486  * @config_dir: the base directory for configuration files
487  *
488  * This routine is used internally and by developers embedding
489  * the runtime into their own applications.
490  *
491  * There are a number of cases to consider: Mono as a system-installed
492  * package that is available on the location preconfigured or Mono in
493  * a relocated location.
494  *
495  * If you are using a system-installed Mono, you can pass NULL
496  * to both parameters.  If you are not, you should compute both
497  * directory values and call this routine.
498  *
499  * The values for a given PREFIX are:
500  *
501  *    assembly_dir: PREFIX/lib
502  *    config_dir:   PREFIX/etc
503  *
504  * Notice that embedders that use Mono in a relocated way must
505  * compute the location at runtime, as they will be in control
506  * of where Mono is installed.
507  */
508 void
509 mono_set_dirs (const char *assembly_dir, const char *config_dir)
510 {
511 #if defined (MONO_ASSEMBLIES)
512         if (assembly_dir == NULL)
513                 assembly_dir = MONO_ASSEMBLIES;
514 #endif
515 #if defined (MONO_CFG_DIR)
516         if (config_dir == NULL)
517                 config_dir = MONO_CFG_DIR;
518 #endif
519         mono_assembly_setrootdir (assembly_dir);
520         mono_set_config_dir (config_dir);
521 }
522
523 #ifndef HOST_WIN32
524
525 static char *
526 compute_base (char *path)
527 {
528         char *p = strrchr (path, '/');
529         if (p == NULL)
530                 return NULL;
531
532         /* Not a well known Mono executable, we are embedded, cant guess the base  */
533         if (strcmp (p, "/mono") && strcmp (p, "/monodis") && strcmp (p, "/mint") && strcmp (p, "/monodiet"))
534                 return NULL;
535             
536         *p = 0;
537         p = strrchr (path, '/');
538         if (p == NULL)
539                 return NULL;
540         
541         if (strcmp (p, "/bin") != 0)
542                 return NULL;
543         *p = 0;
544         return path;
545 }
546
547 static void
548 fallback (void)
549 {
550         mono_set_dirs (MONO_ASSEMBLIES, MONO_CFG_DIR);
551 }
552
553 static void
554 set_dirs (char *exe)
555 {
556         char *base;
557         char *config, *lib, *mono;
558         struct stat buf;
559         
560         /*
561          * Only /usr prefix is treated specially
562          */
563         if (strncmp (exe, MONO_BINDIR, strlen (MONO_BINDIR)) == 0 || (base = compute_base (exe)) == NULL){
564                 fallback ();
565                 return;
566         }
567
568         config = g_build_filename (base, "etc", NULL);
569         lib = g_build_filename (base, "lib", NULL);
570         mono = g_build_filename (lib, "mono/2.0", NULL);
571         if (stat (mono, &buf) == -1)
572                 fallback ();
573         else {
574                 mono_set_dirs (lib, config);
575         }
576         
577         g_free (config);
578         g_free (lib);
579         g_free (mono);
580 }
581
582 #endif /* HOST_WIN32 */
583
584 /**
585  * mono_set_rootdir:
586  *
587  * Registers the root directory for the Mono runtime, for Linux and Solaris 10,
588  * this auto-detects the prefix where Mono was installed. 
589  */
590 void
591 mono_set_rootdir (void)
592 {
593 #if defined(HOST_WIN32) || (defined(PLATFORM_MACOSX) && !defined(TARGET_ARM))
594         gchar *bindir, *installdir, *root, *name, *resolvedname, *config;
595
596 #ifdef HOST_WIN32
597         name = mono_get_module_file_name ((HMODULE) &__ImageBase);
598 #else
599         {
600                 /* 
601                  * _NSGetExecutablePath may return -1 to indicate buf is not large
602                  *  enough, but we ignore that case to avoid having to do extra dynamic
603                  *  allocation for the path and hope that 4096 is enough - this is 
604                  *  ok in the Linux/Solaris case below at least...
605                  */
606                 
607                 gchar buf[4096];
608                 guint buf_size = sizeof (buf);
609  
610                 if (_NSGetExecutablePath (buf, &buf_size) == 0)
611                         name = g_strdup (buf);
612  
613                 if (name == NULL) {
614                         fallback ();
615                         return;
616                 }
617         }
618 #endif
619
620         resolvedname = mono_path_resolve_symlinks (name);
621
622         bindir = g_path_get_dirname (resolvedname);
623         installdir = g_path_get_dirname (bindir);
624         root = g_build_path (G_DIR_SEPARATOR_S, installdir, "lib", NULL);
625
626         config = g_build_filename (root, "..", "etc", NULL);
627 #ifdef HOST_WIN32
628         mono_set_dirs (root, config);
629 #else
630         if (g_file_test (root, G_FILE_TEST_EXISTS) && g_file_test (config, G_FILE_TEST_EXISTS))
631                 mono_set_dirs (root, config);
632         else
633                 fallback ();
634 #endif
635
636         g_free (config);
637         g_free (root);
638         g_free (installdir);
639         g_free (bindir);
640         g_free (name);
641         g_free (resolvedname);
642 #elif defined(DISABLE_MONO_AUTODETECTION)
643         fallback ();
644 #else
645         char buf [4096];
646         int  s;
647         char *str;
648
649         /* Linux style */
650         s = readlink ("/proc/self/exe", buf, sizeof (buf)-1);
651
652         if (s != -1){
653                 buf [s] = 0;
654                 set_dirs (buf);
655                 return;
656         }
657
658         /* Solaris 10 style */
659         str = g_strdup_printf ("/proc/%d/path/a.out", getpid ());
660         s = readlink (str, buf, sizeof (buf)-1);
661         g_free (str);
662         if (s != -1){
663                 buf [s] = 0;
664                 set_dirs (buf);
665                 return;
666         } 
667         fallback ();
668 #endif
669 }
670
671 /**
672  * mono_assemblies_init:
673  *
674  *  Initialize global variables used by this module.
675  */
676 void
677 mono_assemblies_init (void)
678 {
679         /*
680          * Initialize our internal paths if we have not been initialized yet.
681          * This happens when embedders use Mono.
682          */
683         if (mono_assembly_getrootdir () == NULL)
684                 mono_set_rootdir ();
685
686         check_path_env ();
687         check_extra_gac_path_env ();
688
689         InitializeCriticalSection (&assemblies_mutex);
690 }
691
692 gboolean
693 mono_assembly_fill_assembly_name (MonoImage *image, MonoAssemblyName *aname)
694 {
695         MonoTableInfo *t = &image->tables [MONO_TABLE_ASSEMBLY];
696         guint32 cols [MONO_ASSEMBLY_SIZE];
697
698         if (!t->rows)
699                 return FALSE;
700
701         mono_metadata_decode_row (t, 0, cols, MONO_ASSEMBLY_SIZE);
702
703         aname->hash_len = 0;
704         aname->hash_value = NULL;
705         aname->name = mono_metadata_string_heap (image, cols [MONO_ASSEMBLY_NAME]);
706         aname->culture = mono_metadata_string_heap (image, cols [MONO_ASSEMBLY_CULTURE]);
707         aname->flags = cols [MONO_ASSEMBLY_FLAGS];
708         aname->major = cols [MONO_ASSEMBLY_MAJOR_VERSION];
709         aname->minor = cols [MONO_ASSEMBLY_MINOR_VERSION];
710         aname->build = cols [MONO_ASSEMBLY_BUILD_NUMBER];
711         aname->revision = cols [MONO_ASSEMBLY_REV_NUMBER];
712         aname->hash_alg = cols [MONO_ASSEMBLY_HASH_ALG];
713         if (cols [MONO_ASSEMBLY_PUBLIC_KEY]) {
714                 guchar* token = g_malloc (8);
715                 gchar* encoded;
716                 const gchar* pkey;
717                 int len;
718
719                 pkey = mono_metadata_blob_heap (image, cols [MONO_ASSEMBLY_PUBLIC_KEY]);
720                 len = mono_metadata_decode_blob_size (pkey, &pkey);
721                 aname->public_key = (guchar*)pkey;
722
723                 mono_digest_get_public_token (token, aname->public_key, len);
724                 encoded = encode_public_tok (token, 8);
725                 g_strlcpy ((char*)aname->public_key_token, encoded, MONO_PUBLIC_KEY_TOKEN_LENGTH);
726
727                 g_free (encoded);
728                 g_free (token);
729         }
730         else {
731                 aname->public_key = NULL;
732                 memset (aname->public_key_token, 0, MONO_PUBLIC_KEY_TOKEN_LENGTH);
733         }
734
735         if (cols [MONO_ASSEMBLY_PUBLIC_KEY]) {
736                 aname->public_key = (guchar*)mono_metadata_blob_heap (image, cols [MONO_ASSEMBLY_PUBLIC_KEY]);
737         }
738         else
739                 aname->public_key = 0;
740
741         return TRUE;
742 }
743
744 /**
745  * mono_stringify_assembly_name:
746  * @aname: the assembly name.
747  *
748  * Convert @aname into its string format. The returned string is dynamically
749  * allocated and should be freed by the caller.
750  *
751  * Returns: a newly allocated string with a string representation of
752  * the assembly name.
753  */
754 char*
755 mono_stringify_assembly_name (MonoAssemblyName *aname)
756 {
757         const char *quote = (aname->name && g_ascii_isspace (aname->name [0])) ? "\"" : "";
758
759         return g_strdup_printf (
760                 "%s%s%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
761                 quote, aname->name, quote,
762                 aname->major, aname->minor, aname->build, aname->revision,
763                 aname->culture && *aname->culture? aname->culture: "neutral",
764                 aname->public_key_token [0] ? (char *)aname->public_key_token : "null",
765                 (aname->flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
766 }
767
768 static gchar*
769 assemblyref_public_tok (MonoImage *image, guint32 key_index, guint32 flags)
770 {
771         const gchar *public_tok;
772         int len;
773
774         public_tok = mono_metadata_blob_heap (image, key_index);
775         len = mono_metadata_decode_blob_size (public_tok, &public_tok);
776
777         if (flags & ASSEMBLYREF_FULL_PUBLIC_KEY_FLAG) {
778                 guchar token [8];
779                 mono_digest_get_public_token (token, (guchar*)public_tok, len);
780                 return encode_public_tok (token, 8);
781         }
782
783         return encode_public_tok ((guchar*)public_tok, len);
784 }
785
786 /**
787  * mono_assembly_addref:
788  * @assemnly: the assembly to reference
789  *
790  * This routine increments the reference count on a MonoAssembly.
791  * The reference count is reduced every time the method mono_assembly_close() is
792  * invoked.
793  */
794 void
795 mono_assembly_addref (MonoAssembly *assembly)
796 {
797         InterlockedIncrement (&assembly->ref_count);
798 }
799
800 #ifndef DISABLE_ASSEMBLY_REMAPPING
801 static MonoAssemblyName *
802 mono_assembly_remap_version (MonoAssemblyName *aname, MonoAssemblyName *dest_aname)
803 {
804         const MonoRuntimeInfo *current_runtime;
805         int pos, first, last;
806
807         if (aname->name == NULL) return aname;
808         current_runtime = mono_get_runtime_info ();
809
810         first = 0;
811         last = G_N_ELEMENTS (framework_assemblies) - 1;
812         
813         while (first <= last) {
814                 int res;
815                 pos = first + (last - first) / 2;
816                 res = strcmp (aname->name, framework_assemblies[pos].assembly_name);
817                 if (res == 0) {
818                         const AssemblyVersionSet* vset;
819                         int index = framework_assemblies[pos].version_set_index;
820                         g_assert (index < G_N_ELEMENTS (current_runtime->version_sets));
821                         vset = &current_runtime->version_sets [index];
822
823                         if (aname->major == vset->major && aname->minor == vset->minor &&
824                                 aname->build == vset->build && aname->revision == vset->revision)
825                                 return aname;
826                 
827                         if ((aname->major | aname->minor | aname->build | aname->revision) != 0)
828                                 mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_ASSEMBLY,
829                                         "The request to load the assembly %s v%d.%d.%d.%d was remapped to v%d.%d.%d.%d",
830                                                         aname->name,
831                                                         aname->major, aname->minor, aname->build, aname->revision,
832                                                         vset->major, vset->minor, vset->build, vset->revision
833                                                         );
834                         
835                         memcpy (dest_aname, aname, sizeof(MonoAssemblyName));
836                         dest_aname->major = vset->major;
837                         dest_aname->minor = vset->minor;
838                         dest_aname->build = vset->build;
839                         dest_aname->revision = vset->revision;
840                         return dest_aname;
841                 } else if (res < 0) {
842                         last = pos - 1;
843                 } else {
844                         first = pos + 1;
845                 }
846         }
847         return aname;
848 }
849 #endif
850
851 /*
852  * mono_assembly_get_assemblyref:
853  *
854  *   Fill out ANAME with the assembly name of the INDEXth assembly reference in IMAGE.
855  */
856 void
857 mono_assembly_get_assemblyref (MonoImage *image, int index, MonoAssemblyName *aname)
858 {
859         MonoTableInfo *t;
860         guint32 cols [MONO_ASSEMBLYREF_SIZE];
861         const char *hash;
862
863         t = &image->tables [MONO_TABLE_ASSEMBLYREF];
864
865         mono_metadata_decode_row (t, index, cols, MONO_ASSEMBLYREF_SIZE);
866                 
867         hash = mono_metadata_blob_heap (image, cols [MONO_ASSEMBLYREF_HASH_VALUE]);
868         aname->hash_len = mono_metadata_decode_blob_size (hash, &hash);
869         aname->hash_value = hash;
870         aname->name = mono_metadata_string_heap (image, cols [MONO_ASSEMBLYREF_NAME]);
871         aname->culture = mono_metadata_string_heap (image, cols [MONO_ASSEMBLYREF_CULTURE]);
872         aname->flags = cols [MONO_ASSEMBLYREF_FLAGS];
873         aname->major = cols [MONO_ASSEMBLYREF_MAJOR_VERSION];
874         aname->minor = cols [MONO_ASSEMBLYREF_MINOR_VERSION];
875         aname->build = cols [MONO_ASSEMBLYREF_BUILD_NUMBER];
876         aname->revision = cols [MONO_ASSEMBLYREF_REV_NUMBER];
877
878         if (cols [MONO_ASSEMBLYREF_PUBLIC_KEY]) {
879                 gchar *token = assemblyref_public_tok (image, cols [MONO_ASSEMBLYREF_PUBLIC_KEY], aname->flags);
880                 g_strlcpy ((char*)aname->public_key_token, token, MONO_PUBLIC_KEY_TOKEN_LENGTH);
881                 g_free (token);
882         } else {
883                 memset (aname->public_key_token, 0, MONO_PUBLIC_KEY_TOKEN_LENGTH);
884         }
885 }
886
887 void
888 mono_assembly_load_reference (MonoImage *image, int index)
889 {
890         MonoAssembly *reference;
891         MonoAssemblyName aname;
892         MonoImageOpenStatus status;
893
894         /*
895          * image->references is shared between threads, so we need to access
896          * it inside a critical section.
897          */
898         mono_assemblies_lock ();
899         if (!image->references) {
900                 MonoTableInfo *t = &image->tables [MONO_TABLE_ASSEMBLYREF];
901         
902                 image->references = g_new0 (MonoAssembly *, t->rows + 1);
903         }
904         reference = image->references [index];
905         mono_assemblies_unlock ();
906         if (reference)
907                 return;
908
909         mono_assembly_get_assemblyref (image, index, &aname);
910
911         if (image->assembly && image->assembly->ref_only) {
912                 /* We use the loaded corlib */
913                 if (!strcmp (aname.name, "mscorlib"))
914                         reference = mono_assembly_load_full (&aname, image->assembly->basedir, &status, FALSE);
915                 else {
916                         reference = mono_assembly_loaded_full (&aname, TRUE);
917                         if (!reference)
918                                 /* Try a postload search hook */
919                                 reference = mono_assembly_invoke_search_hook_internal (&aname, TRUE, TRUE);
920                 }
921
922                 /*
923                  * Here we must advice that the error was due to
924                  * a non loaded reference using the ReflectionOnly api
925                 */
926                 if (!reference)
927                         reference = REFERENCE_MISSING;
928         } else
929                 reference = mono_assembly_load (&aname, image->assembly? image->assembly->basedir: NULL, &status);
930
931         if (reference == NULL){
932                 char *extra_msg;
933
934                 if (status == MONO_IMAGE_ERROR_ERRNO && errno == ENOENT) {
935                         extra_msg = g_strdup_printf ("The assembly was not found in the Global Assembly Cache, a path listed in the MONO_PATH environment variable, or in the location of the executing assembly (%s).\n", image->assembly != NULL ? image->assembly->basedir : "" );
936                 } else if (status == MONO_IMAGE_ERROR_ERRNO) {
937                         extra_msg = g_strdup_printf ("System error: %s\n", strerror (errno));
938                 } else if (status == MONO_IMAGE_MISSING_ASSEMBLYREF) {
939                         extra_msg = g_strdup ("Cannot find an assembly referenced from this one.\n");
940                 } else if (status == MONO_IMAGE_IMAGE_INVALID) {
941                         extra_msg = g_strdup ("The file exists but is not a valid assembly.\n");
942                 } else {
943                         extra_msg = g_strdup ("");
944                 }
945                 
946                 mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_ASSEMBLY, "The following assembly referenced from %s could not be loaded:\n"
947                                    "     Assembly:   %s    (assemblyref_index=%d)\n"
948                                    "     Version:    %d.%d.%d.%d\n"
949                                    "     Public Key: %s\n%s",
950                                    image->name, aname.name, index,
951                                    aname.major, aname.minor, aname.build, aname.revision,
952                                    strlen ((char*)aname.public_key_token) == 0 ? "(none)" : (char*)aname.public_key_token, extra_msg);
953                 g_free (extra_msg);
954         }
955
956         mono_assemblies_lock ();
957         if (reference == NULL) {
958                 /* Flag as not found */
959                 reference = REFERENCE_MISSING;
960         }       
961
962         if (!image->references [index]) {
963                 if (reference != REFERENCE_MISSING){
964                         mono_assembly_addref (reference);
965                         if (image->assembly)
966                                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_ASSEMBLY, "Assembly Ref addref %s[%p] -> %s[%p]: %d",
967                                     image->assembly->aname.name, image->assembly, reference->aname.name, reference, reference->ref_count);
968                 } else {
969                         if (image->assembly)
970                                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_ASSEMBLY, "Failed to load assembly %s[%p]\n",
971                                     image->assembly->aname.name, image->assembly);
972                 }
973                 
974                 image->references [index] = reference;
975         }
976         mono_assemblies_unlock ();
977
978         if (image->references [index] != reference) {
979                 /* Somebody loaded it before us */
980                 mono_assembly_close (reference);
981         }
982 }
983
984 void
985 mono_assembly_load_references (MonoImage *image, MonoImageOpenStatus *status)
986 {
987         /* This is a no-op now but it is part of the embedding API so we can't remove it */
988         *status = MONO_IMAGE_OK;
989 }
990
991 typedef struct AssemblyLoadHook AssemblyLoadHook;
992 struct AssemblyLoadHook {
993         AssemblyLoadHook *next;
994         MonoAssemblyLoadFunc func;
995         gpointer user_data;
996 };
997
998 AssemblyLoadHook *assembly_load_hook = NULL;
999
1000 void
1001 mono_assembly_invoke_load_hook (MonoAssembly *ass)
1002 {
1003         AssemblyLoadHook *hook;
1004
1005         for (hook = assembly_load_hook; hook; hook = hook->next) {
1006                 hook->func (ass, hook->user_data);
1007         }
1008 }
1009
1010 void
1011 mono_install_assembly_load_hook (MonoAssemblyLoadFunc func, gpointer user_data)
1012 {
1013         AssemblyLoadHook *hook;
1014         
1015         g_return_if_fail (func != NULL);
1016
1017         hook = g_new0 (AssemblyLoadHook, 1);
1018         hook->func = func;
1019         hook->user_data = user_data;
1020         hook->next = assembly_load_hook;
1021         assembly_load_hook = hook;
1022 }
1023
1024 static void
1025 free_assembly_load_hooks (void)
1026 {
1027         AssemblyLoadHook *hook, *next;
1028
1029         for (hook = assembly_load_hook; hook; hook = next) {
1030                 next = hook->next;
1031                 g_free (hook);
1032         }
1033 }
1034
1035 typedef struct AssemblySearchHook AssemblySearchHook;
1036 struct AssemblySearchHook {
1037         AssemblySearchHook *next;
1038         MonoAssemblySearchFunc func;
1039         gboolean refonly;
1040         gboolean postload;
1041         gpointer user_data;
1042 };
1043
1044 AssemblySearchHook *assembly_search_hook = NULL;
1045
1046 static MonoAssembly*
1047 mono_assembly_invoke_search_hook_internal (MonoAssemblyName *aname, gboolean refonly, gboolean postload)
1048 {
1049         AssemblySearchHook *hook;
1050
1051         for (hook = assembly_search_hook; hook; hook = hook->next) {
1052                 if ((hook->refonly == refonly) && (hook->postload == postload)) {
1053                         MonoAssembly *ass = hook->func (aname, hook->user_data);
1054                         if (ass)
1055                                 return ass;
1056                 }
1057         }
1058
1059         return NULL;
1060 }
1061
1062 MonoAssembly*
1063 mono_assembly_invoke_search_hook (MonoAssemblyName *aname)
1064 {
1065         return mono_assembly_invoke_search_hook_internal (aname, FALSE, FALSE);
1066 }
1067
1068 static void
1069 mono_install_assembly_search_hook_internal (MonoAssemblySearchFunc func, gpointer user_data, gboolean refonly, gboolean postload)
1070 {
1071         AssemblySearchHook *hook;
1072         
1073         g_return_if_fail (func != NULL);
1074
1075         hook = g_new0 (AssemblySearchHook, 1);
1076         hook->func = func;
1077         hook->user_data = user_data;
1078         hook->refonly = refonly;
1079         hook->postload = postload;
1080         hook->next = assembly_search_hook;
1081         assembly_search_hook = hook;
1082 }
1083
1084 void          
1085 mono_install_assembly_search_hook (MonoAssemblySearchFunc func, gpointer user_data)
1086 {
1087         mono_install_assembly_search_hook_internal (func, user_data, FALSE, FALSE);
1088 }       
1089
1090 static void
1091 free_assembly_search_hooks (void)
1092 {
1093         AssemblySearchHook *hook, *next;
1094
1095         for (hook = assembly_search_hook; hook; hook = next) {
1096                 next = hook->next;
1097                 g_free (hook);
1098         }
1099 }
1100
1101 void
1102 mono_install_assembly_refonly_search_hook (MonoAssemblySearchFunc func, gpointer user_data)
1103 {
1104         mono_install_assembly_search_hook_internal (func, user_data, TRUE, FALSE);
1105 }
1106
1107 void          
1108 mono_install_assembly_postload_search_hook (MonoAssemblySearchFunc func, gpointer user_data)
1109 {
1110         mono_install_assembly_search_hook_internal (func, user_data, FALSE, TRUE);
1111 }       
1112
1113 void
1114 mono_install_assembly_postload_refonly_search_hook (MonoAssemblySearchFunc func, gpointer user_data)
1115 {
1116         mono_install_assembly_search_hook_internal (func, user_data, TRUE, TRUE);
1117 }
1118
1119 typedef struct AssemblyPreLoadHook AssemblyPreLoadHook;
1120 struct AssemblyPreLoadHook {
1121         AssemblyPreLoadHook *next;
1122         MonoAssemblyPreLoadFunc func;
1123         gpointer user_data;
1124 };
1125
1126 static AssemblyPreLoadHook *assembly_preload_hook = NULL;
1127 static AssemblyPreLoadHook *assembly_refonly_preload_hook = NULL;
1128
1129 static MonoAssembly *
1130 invoke_assembly_preload_hook (MonoAssemblyName *aname, gchar **assemblies_path)
1131 {
1132         AssemblyPreLoadHook *hook;
1133         MonoAssembly *assembly;
1134
1135         for (hook = assembly_preload_hook; hook; hook = hook->next) {
1136                 assembly = hook->func (aname, assemblies_path, hook->user_data);
1137                 if (assembly != NULL)
1138                         return assembly;
1139         }
1140
1141         return NULL;
1142 }
1143
1144 static MonoAssembly *
1145 invoke_assembly_refonly_preload_hook (MonoAssemblyName *aname, gchar **assemblies_path)
1146 {
1147         AssemblyPreLoadHook *hook;
1148         MonoAssembly *assembly;
1149
1150         for (hook = assembly_refonly_preload_hook; hook; hook = hook->next) {
1151                 assembly = hook->func (aname, assemblies_path, hook->user_data);
1152                 if (assembly != NULL)
1153                         return assembly;
1154         }
1155
1156         return NULL;
1157 }
1158
1159 void
1160 mono_install_assembly_preload_hook (MonoAssemblyPreLoadFunc func, gpointer user_data)
1161 {
1162         AssemblyPreLoadHook *hook;
1163         
1164         g_return_if_fail (func != NULL);
1165
1166         hook = g_new0 (AssemblyPreLoadHook, 1);
1167         hook->func = func;
1168         hook->user_data = user_data;
1169         hook->next = assembly_preload_hook;
1170         assembly_preload_hook = hook;
1171 }
1172
1173 void
1174 mono_install_assembly_refonly_preload_hook (MonoAssemblyPreLoadFunc func, gpointer user_data)
1175 {
1176         AssemblyPreLoadHook *hook;
1177         
1178         g_return_if_fail (func != NULL);
1179
1180         hook = g_new0 (AssemblyPreLoadHook, 1);
1181         hook->func = func;
1182         hook->user_data = user_data;
1183         hook->next = assembly_refonly_preload_hook;
1184         assembly_refonly_preload_hook = hook;
1185 }
1186
1187 static void
1188 free_assembly_preload_hooks (void)
1189 {
1190         AssemblyPreLoadHook *hook, *next;
1191
1192         for (hook = assembly_preload_hook; hook; hook = next) {
1193                 next = hook->next;
1194                 g_free (hook);
1195         }
1196
1197         for (hook = assembly_refonly_preload_hook; hook; hook = next) {
1198                 next = hook->next;
1199                 g_free (hook);
1200         }
1201 }
1202
1203 static gchar *
1204 absolute_dir (const gchar *filename)
1205 {
1206         gchar *cwd;
1207         gchar *mixed;
1208         gchar **parts;
1209         gchar *part;
1210         GList *list, *tmp;
1211         GString *result;
1212         gchar *res;
1213         gint i;
1214
1215         if (g_path_is_absolute (filename)) {
1216                 part = g_path_get_dirname (filename);
1217                 res = g_strconcat (part, G_DIR_SEPARATOR_S, NULL);
1218                 g_free (part);
1219                 return res;
1220         }
1221
1222         cwd = g_get_current_dir ();
1223         mixed = g_build_filename (cwd, filename, NULL);
1224         parts = g_strsplit (mixed, G_DIR_SEPARATOR_S, 0);
1225         g_free (mixed);
1226         g_free (cwd);
1227
1228         list = NULL;
1229         for (i = 0; (part = parts [i]) != NULL; i++) {
1230                 if (!strcmp (part, "."))
1231                         continue;
1232
1233                 if (!strcmp (part, "..")) {
1234                         if (list && list->next) /* Don't remove root */
1235                                 list = g_list_delete_link (list, list);
1236                 } else {
1237                         list = g_list_prepend (list, part);
1238                 }
1239         }
1240
1241         result = g_string_new ("");
1242         list = g_list_reverse (list);
1243
1244         /* Ignores last data pointer, which should be the filename */
1245         for (tmp = list; tmp && tmp->next != NULL; tmp = tmp->next){
1246                 if (tmp->data)
1247                         g_string_append_printf (result, "%s%c", (char *) tmp->data,
1248                                                                 G_DIR_SEPARATOR);
1249         }
1250
1251         res = result->str;
1252         g_string_free (result, FALSE);
1253         g_list_free (list);
1254         g_strfreev (parts);
1255         if (*res == '\0') {
1256                 g_free (res);
1257                 return g_strdup (".");
1258         }
1259
1260         return res;
1261 }
1262
1263 /** 
1264  * mono_assembly_open_from_bundle:
1265  * @filename: Filename requested
1266  * @status: return value
1267  *
1268  * This routine tries to open the assembly specified by `filename' from the
1269  * defined bundles, if found, returns the MonoImage for it, if not found
1270  * returns NULL
1271  */
1272 MonoImage *
1273 mono_assembly_open_from_bundle (const char *filename, MonoImageOpenStatus *status, gboolean refonly)
1274 {
1275         int i;
1276         char *name;
1277         MonoImage *image = NULL;
1278
1279         /*
1280          * we do a very simple search for bundled assemblies: it's not a general 
1281          * purpose assembly loading mechanism.
1282          */
1283
1284         if (!bundles)
1285                 return NULL;
1286
1287         name = g_path_get_basename (filename);
1288
1289         mono_assemblies_lock ();
1290         for (i = 0; !image && bundles [i]; ++i) {
1291                 if (strcmp (bundles [i]->name, name) == 0) {
1292                         image = mono_image_open_from_data_with_name ((char*)bundles [i]->data, bundles [i]->size, FALSE, status, refonly, name);
1293                         break;
1294                 }
1295         }
1296         mono_assemblies_unlock ();
1297         g_free (name);
1298         if (image) {
1299                 mono_image_addref (image);
1300                 return image;
1301         }
1302         return NULL;
1303 }
1304
1305 MonoAssembly *
1306 mono_assembly_open_full (const char *filename, MonoImageOpenStatus *status, gboolean refonly)
1307 {
1308         MonoImage *image;
1309         MonoAssembly *ass;
1310         MonoImageOpenStatus def_status;
1311         gchar *fname;
1312         gchar *new_fname;
1313         
1314         g_return_val_if_fail (filename != NULL, NULL);
1315
1316         if (!status)
1317                 status = &def_status;
1318         *status = MONO_IMAGE_OK;
1319
1320         if (strncmp (filename, "file://", 7) == 0) {
1321                 GError *error = NULL;
1322                 gchar *uri = (gchar *) filename;
1323                 gchar *tmpuri;
1324
1325                 /*
1326                  * MS allows file://c:/... and fails on file://localhost/c:/... 
1327                  * They also throw an IndexOutOfRangeException if "file://"
1328                  */
1329                 if (uri [7] != '/')
1330                         uri = g_strdup_printf ("file:///%s", uri + 7);
1331         
1332                 tmpuri = uri;
1333                 uri = mono_escape_uri_string (tmpuri);
1334                 fname = g_filename_from_uri (uri, NULL, &error);
1335                 g_free (uri);
1336
1337                 if (tmpuri != filename)
1338                         g_free (tmpuri);
1339
1340                 if (error != NULL) {
1341                         g_warning ("%s\n", error->message);
1342                         g_error_free (error);
1343                         fname = g_strdup (filename);
1344                 }
1345         } else {
1346                 fname = g_strdup (filename);
1347         }
1348
1349         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_ASSEMBLY,
1350                         "Assembly Loader probing location: '%s'.", fname);
1351
1352         new_fname = NULL;
1353         if (!mono_assembly_is_in_gac (fname))
1354                 new_fname = mono_make_shadow_copy (fname);
1355         if (new_fname && new_fname != fname) {
1356                 g_free (fname);
1357                 fname = new_fname;
1358                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_ASSEMBLY,
1359                             "Assembly Loader shadow-copied assembly to: '%s'.", fname);
1360         }
1361         
1362         image = NULL;
1363
1364         if (bundles != NULL)
1365                 image = mono_assembly_open_from_bundle (fname, status, refonly);
1366
1367         if (!image)
1368                 image = mono_image_open_full (fname, status, refonly);
1369
1370         if (!image){
1371                 if (*status == MONO_IMAGE_OK)
1372                         *status = MONO_IMAGE_ERROR_ERRNO;
1373                 g_free (fname);
1374                 return NULL;
1375         }
1376
1377         if (image->assembly) {
1378                 /* Already loaded by another appdomain */
1379                 mono_assembly_invoke_load_hook (image->assembly);
1380                 mono_image_close (image);
1381                 g_free (fname);
1382                 return image->assembly;
1383         }
1384
1385         ass = mono_assembly_load_from_full (image, fname, status, refonly);
1386
1387         if (ass) {
1388                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_ASSEMBLY,
1389                                 "Assembly Loader loaded assembly from location: '%s'.", filename);
1390                 if (!refonly)
1391                         mono_config_for_assembly (ass->image);
1392         }
1393
1394         /* Clear the reference added by mono_image_open */
1395         mono_image_close (image);
1396         
1397         g_free (fname);
1398
1399         return ass;
1400 }
1401
1402 static void
1403 free_item (gpointer val, gpointer user_data)
1404 {
1405         g_free (val);
1406 }
1407
1408 /*
1409  * mono_assembly_load_friends:
1410  * @ass: an assembly
1411  *
1412  * Load the list of friend assemblies that are allowed to access
1413  * the assembly's internal types and members. They are stored as assembly
1414  * names in custom attributes.
1415  *
1416  * This is an internal method, we need this because when we load mscorlib
1417  * we do not have the mono_defaults.internals_visible_class loaded yet,
1418  * so we need to load these after we initialize the runtime. 
1419  *
1420  * LOCKING: Acquires the assemblies lock plus the loader lock.
1421  */
1422 void
1423 mono_assembly_load_friends (MonoAssembly* ass)
1424 {
1425         int i;
1426         MonoCustomAttrInfo* attrs;
1427         GSList *list;
1428
1429         if (ass->friend_assembly_names_inited)
1430                 return;
1431
1432         attrs = mono_custom_attrs_from_assembly (ass);
1433         if (!attrs) {
1434                 mono_assemblies_lock ();
1435                 ass->friend_assembly_names_inited = TRUE;
1436                 mono_assemblies_unlock ();
1437                 return;
1438         }
1439
1440         mono_assemblies_lock ();
1441         if (ass->friend_assembly_names_inited) {
1442                 mono_assemblies_unlock ();
1443                 return;
1444         }
1445         mono_assemblies_unlock ();
1446
1447         list = NULL;
1448         /* 
1449          * We build the list outside the assemblies lock, the worse that can happen
1450          * is that we'll need to free the allocated list.
1451          */
1452         for (i = 0; i < attrs->num_attrs; ++i) {
1453                 MonoCustomAttrEntry *attr = &attrs->attrs [i];
1454                 MonoAssemblyName *aname;
1455                 const gchar *data;
1456                 guint slen;
1457                 /* Do some sanity checking */
1458                 if (!attr->ctor || attr->ctor->klass != mono_defaults.internals_visible_class)
1459                         continue;
1460                 if (attr->data_size < 4)
1461                         continue;
1462                 data = (const char*)attr->data;
1463                 /* 0xFF means null string, see custom attr format */
1464                 if (data [0] != 1 || data [1] != 0 || (data [2] & 0xFF) == 0xFF)
1465                         continue;
1466                 slen = mono_metadata_decode_value (data + 2, &data);
1467                 aname = g_new0 (MonoAssemblyName, 1);
1468                 /*g_print ("friend ass: %s\n", data);*/
1469                 if (mono_assembly_name_parse_full (data, aname, TRUE, NULL, NULL)) {
1470                         list = g_slist_prepend (list, aname);
1471                 } else {
1472                         g_free (aname);
1473                 }
1474         }
1475         mono_custom_attrs_free (attrs);
1476
1477         mono_assemblies_lock ();
1478         if (ass->friend_assembly_names_inited) {
1479                 mono_assemblies_unlock ();
1480                 g_slist_foreach (list, free_item, NULL);
1481                 g_slist_free (list);
1482                 return;
1483         }
1484         ass->friend_assembly_names = list;
1485
1486         /* Because of the double checked locking pattern above */
1487         mono_memory_barrier ();
1488         ass->friend_assembly_names_inited = TRUE;
1489         mono_assemblies_unlock ();
1490 }
1491
1492 /**
1493  * mono_assembly_open:
1494  * @filename: Opens the assembly pointed out by this name
1495  * @status: where a status code can be returned
1496  *
1497  * mono_assembly_open opens the PE-image pointed by @filename, and
1498  * loads any external assemblies referenced by it.
1499  *
1500  * Return: a pointer to the MonoAssembly if @filename contains a valid
1501  * assembly or NULL on error.  Details about the error are stored in the
1502  * @status variable.
1503  */
1504 MonoAssembly *
1505 mono_assembly_open (const char *filename, MonoImageOpenStatus *status)
1506 {
1507         return mono_assembly_open_full (filename, status, FALSE);
1508 }
1509
1510 MonoAssembly *
1511 mono_assembly_load_from_full (MonoImage *image, const char*fname, 
1512                               MonoImageOpenStatus *status, gboolean refonly)
1513 {
1514         MonoAssembly *ass, *ass2;
1515         char *base_dir;
1516
1517         if (!image->tables [MONO_TABLE_ASSEMBLY].rows) {
1518                 /* 'image' doesn't have a manifest -- maybe someone is trying to Assembly.Load a .netmodule */
1519                 *status = MONO_IMAGE_IMAGE_INVALID;
1520                 return NULL;
1521         }
1522
1523 #if defined (HOST_WIN32)
1524         {
1525                 gchar *tmp_fn;
1526                 int i;
1527
1528                 tmp_fn = g_strdup (fname);
1529                 for (i = strlen (tmp_fn) - 1; i >= 0; i--) {
1530                         if (tmp_fn [i] == '/')
1531                                 tmp_fn [i] = '\\';
1532                 }
1533
1534                 base_dir = absolute_dir (tmp_fn);
1535                 g_free (tmp_fn);
1536         }
1537 #else
1538         base_dir = absolute_dir (fname);
1539 #endif
1540
1541         /*
1542          * Create assembly struct, and enter it into the assembly cache
1543          */
1544         ass = g_new0 (MonoAssembly, 1);
1545         ass->basedir = base_dir;
1546         ass->ref_only = refonly;
1547         ass->image = image;
1548
1549         mono_profiler_assembly_event (ass, MONO_PROFILE_START_LOAD);
1550
1551         mono_assembly_fill_assembly_name (image, &ass->aname);
1552
1553         if (mono_defaults.corlib && strcmp (ass->aname.name, "mscorlib") == 0) {
1554                 // MS.NET doesn't support loading other mscorlibs
1555                 g_free (ass);
1556                 g_free (base_dir);
1557                 mono_image_addref (mono_defaults.corlib);
1558                 *status = MONO_IMAGE_OK;
1559                 return mono_defaults.corlib->assembly;
1560         }
1561
1562         /* Add a non-temporary reference because of ass->image */
1563         mono_image_addref (image);
1564
1565         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_ASSEMBLY, "Image addref %s[%p] -> %s[%p]: %d", ass->aname.name, ass, image->name, image, image->ref_count);
1566
1567         /* 
1568          * The load hooks might take locks so we can't call them while holding the
1569          * assemblies lock.
1570          */
1571         if (ass->aname.name) {
1572                 ass2 = mono_assembly_invoke_search_hook_internal (&ass->aname, refonly, FALSE);
1573                 if (ass2) {
1574                         g_free (ass);
1575                         g_free (base_dir);
1576                         mono_image_close (image);
1577                         *status = MONO_IMAGE_OK;
1578                         return ass2;
1579                 }
1580         }
1581
1582         mono_assemblies_lock ();
1583
1584         if (image->assembly) {
1585                 /* 
1586                  * This means another thread has already loaded the assembly, but not yet
1587                  * called the load hooks so the search hook can't find the assembly.
1588                  */
1589                 mono_assemblies_unlock ();
1590                 ass2 = image->assembly;
1591                 g_free (ass);
1592                 g_free (base_dir);
1593                 mono_image_close (image);
1594                 *status = MONO_IMAGE_OK;
1595                 return ass2;
1596         }
1597
1598         image->assembly = ass;
1599
1600         loaded_assemblies = g_list_prepend (loaded_assemblies, ass);
1601         mono_assemblies_unlock ();
1602
1603 #ifdef HOST_WIN32
1604         if (image->is_module_handle)
1605                 mono_image_fixup_vtable (image);
1606 #endif
1607
1608         mono_assembly_invoke_load_hook (ass);
1609
1610         mono_profiler_assembly_loaded (ass, MONO_PROFILE_OK);
1611         
1612         return ass;
1613 }
1614
1615 MonoAssembly *
1616 mono_assembly_load_from (MonoImage *image, const char *fname,
1617                          MonoImageOpenStatus *status)
1618 {
1619         return mono_assembly_load_from_full (image, fname, status, FALSE);
1620 }
1621
1622 /**
1623  * mono_assembly_name_free:
1624  * @aname: assembly name to free
1625  * 
1626  * Frees the provided assembly name object.
1627  * (it does not frees the object itself, only the name members).
1628  */
1629 void
1630 mono_assembly_name_free (MonoAssemblyName *aname)
1631 {
1632         if (aname == NULL)
1633                 return;
1634
1635         g_free ((void *) aname->name);
1636         g_free ((void *) aname->culture);
1637         g_free ((void *) aname->hash_value);
1638 }
1639
1640 static gboolean
1641 parse_public_key (const gchar *key, gchar** pubkey)
1642 {
1643         const gchar *pkey;
1644         gchar header [16], val, *arr;
1645         gint i, j, offset, bitlen, keylen, pkeylen;
1646         
1647         keylen = strlen (key) >> 1;
1648         if (keylen < 1)
1649                 return FALSE;
1650         
1651         val = g_ascii_xdigit_value (key [0]) << 4;
1652         val |= g_ascii_xdigit_value (key [1]);
1653         switch (val) {
1654                 case 0x00:
1655                         if (keylen < 13)
1656                                 return FALSE;
1657                         val = g_ascii_xdigit_value (key [24]);
1658                         val |= g_ascii_xdigit_value (key [25]);
1659                         if (val != 0x06)
1660                                 return FALSE;
1661                         pkey = key + 24;
1662                         break;
1663                 case 0x06:
1664                         pkey = key;
1665                         break;
1666                 default:
1667                         return FALSE;
1668         }
1669                 
1670         /* We need the first 16 bytes
1671         * to check whether this key is valid or not */
1672         pkeylen = strlen (pkey) >> 1;
1673         if (pkeylen < 16)
1674                 return FALSE;
1675                 
1676         for (i = 0, j = 0; i < 16; i++) {
1677                 header [i] = g_ascii_xdigit_value (pkey [j++]) << 4;
1678                 header [i] |= g_ascii_xdigit_value (pkey [j++]);
1679         }
1680
1681         if (header [0] != 0x06 || /* PUBLICKEYBLOB (0x06) */
1682                         header [1] != 0x02 || /* Version (0x02) */
1683                         header [2] != 0x00 || /* Reserved (word) */
1684                         header [3] != 0x00 ||
1685                         (guint)(read32 (header + 8)) != 0x31415352) /* DWORD magic = RSA1 */
1686                 return FALSE;
1687
1688         /* Based on this length, we _should_ be able to know if the length is right */
1689         bitlen = read32 (header + 12) >> 3;
1690         if ((bitlen + 16 + 4) != pkeylen)
1691                 return FALSE;
1692
1693         /* parsing is OK and the public key itself is not requested back */
1694         if (!pubkey)
1695                 return TRUE;
1696                 
1697         /* Encode the size of the blob */
1698         offset = 0;
1699         if (keylen <= 127) {
1700                 arr = g_malloc (keylen + 1);
1701                 arr [offset++] = keylen;
1702         } else {
1703                 arr = g_malloc (keylen + 2);
1704                 arr [offset++] = 0x80; /* 10bs */
1705                 arr [offset++] = keylen;
1706         }
1707                 
1708         for (i = offset, j = 0; i < keylen + offset; i++) {
1709                 arr [i] = g_ascii_xdigit_value (key [j++]) << 4;
1710                 arr [i] |= g_ascii_xdigit_value (key [j++]);
1711         }
1712
1713         *pubkey = arr;
1714
1715         return TRUE;
1716 }
1717
1718 static gboolean
1719 build_assembly_name (const char *name, const char *version, const char *culture, const char *token, const char *key, guint32 flags, guint32 arch, MonoAssemblyName *aname, gboolean save_public_key)
1720 {
1721         gint major, minor, build, revision;
1722         gint len;
1723         gint version_parts;
1724         gchar *pkey, *pkeyptr, *encoded, tok [8];
1725
1726         memset (aname, 0, sizeof (MonoAssemblyName));
1727
1728         if (version) {
1729                 version_parts = sscanf (version, "%u.%u.%u.%u", &major, &minor, &build, &revision);
1730                 if (version_parts < 2 || version_parts > 4)
1731                         return FALSE;
1732
1733                 /* FIXME: we should set build & revision to -1 (instead of 0)
1734                 if these are not set in the version string. That way, later on,
1735                 we can still determine if these were specified. */
1736                 aname->major = major;
1737                 aname->minor = minor;
1738                 if (version_parts >= 3)
1739                         aname->build = build;
1740                 else
1741                         aname->build = 0;
1742                 if (version_parts == 4)
1743                         aname->revision = revision;
1744                 else
1745                         aname->revision = 0;
1746         }
1747         
1748         aname->flags = flags;
1749         aname->arch = arch;
1750         aname->name = g_strdup (name);
1751         
1752         if (culture) {
1753                 if (g_ascii_strcasecmp (culture, "neutral") == 0)
1754                         aname->culture = g_strdup ("");
1755                 else
1756                         aname->culture = g_strdup (culture);
1757         }
1758         
1759         if (token && strncmp (token, "null", 4) != 0) {
1760                 char *lower;
1761
1762                 /* the constant includes the ending NULL, hence the -1 */
1763                 if (strlen (token) != (MONO_PUBLIC_KEY_TOKEN_LENGTH - 1)) {
1764                         mono_assembly_name_free (aname);
1765                         return FALSE;
1766                 }
1767                 lower = g_ascii_strdown (token, MONO_PUBLIC_KEY_TOKEN_LENGTH);
1768                 g_strlcpy ((char*)aname->public_key_token, lower, MONO_PUBLIC_KEY_TOKEN_LENGTH);
1769                 g_free (lower);
1770         }
1771
1772         if (key) {
1773                 if (strcmp (key, "null") == 0 || !parse_public_key (key, &pkey)) {
1774                         mono_assembly_name_free (aname);
1775                         return FALSE;
1776                 }
1777                 
1778                 len = mono_metadata_decode_blob_size ((const gchar *) pkey, (const gchar **) &pkeyptr);
1779                 // We also need to generate the key token
1780                 mono_digest_get_public_token ((guchar*) tok, (guint8*) pkeyptr, len);
1781                 encoded = encode_public_tok ((guchar*) tok, 8);
1782                 g_strlcpy ((gchar*)aname->public_key_token, encoded, MONO_PUBLIC_KEY_TOKEN_LENGTH);
1783                 g_free (encoded);
1784
1785                 if (save_public_key)
1786                         aname->public_key = (guint8*) pkey;
1787                 else
1788                         g_free (pkey);
1789         }
1790
1791         return TRUE;
1792 }
1793
1794 static gboolean
1795 parse_assembly_directory_name (const char *name, const char *dirname, MonoAssemblyName *aname)
1796 {
1797         gchar **parts;
1798         gboolean res;
1799         
1800         parts = g_strsplit (dirname, "_", 3);
1801         if (!parts || !parts[0] || !parts[1] || !parts[2]) {
1802                 g_strfreev (parts);
1803                 return FALSE;
1804         }
1805         
1806         res = build_assembly_name (name, parts[0], parts[1], parts[2], NULL, 0, 0, aname, FALSE);
1807         g_strfreev (parts);
1808         return res;
1809 }
1810
1811 gboolean
1812 mono_assembly_name_parse_full (const char *name, MonoAssemblyName *aname, gboolean save_public_key, gboolean *is_version_defined, gboolean *is_token_defined)
1813 {
1814         gchar *dllname;
1815         gchar *version = NULL;
1816         gchar *culture = NULL;
1817         gchar *token = NULL;
1818         gchar *key = NULL;
1819         gchar *retargetable = NULL;
1820         gboolean res;
1821         gchar *value;
1822         gchar **parts;
1823         gchar **tmp;
1824         gboolean version_defined;
1825         gboolean token_defined;
1826         guint32 flags = 0;
1827         guint32 arch = PROCESSOR_ARCHITECTURE_NONE;
1828
1829         if (!is_version_defined)
1830                 is_version_defined = &version_defined;
1831         *is_version_defined = FALSE;
1832         if (!is_token_defined)
1833                 is_token_defined = &token_defined;
1834         *is_token_defined = FALSE;
1835         
1836         parts = tmp = g_strsplit (name, ",", 6);
1837         if (!tmp || !*tmp) {
1838                 g_strfreev (tmp);
1839                 return FALSE;
1840         }
1841
1842         dllname = g_strstrip (*tmp);
1843         
1844         tmp++;
1845
1846         while (*tmp) {
1847                 value = g_strstrip (*tmp);
1848                 if (!g_ascii_strncasecmp (value, "Version=", 8)) {
1849                         *is_version_defined = TRUE;
1850                         version = g_strstrip (value + 8);
1851                         if (strlen (version) == 0) {
1852                                 goto cleanup_and_fail;
1853                         }
1854                         tmp++;
1855                         continue;
1856                 }
1857
1858                 if (!g_ascii_strncasecmp (value, "Culture=", 8)) {
1859                         culture = g_strstrip (value + 8);
1860                         if (strlen (culture) == 0) {
1861                                 goto cleanup_and_fail;
1862                         }
1863                         tmp++;
1864                         continue;
1865                 }
1866
1867                 if (!g_ascii_strncasecmp (value, "PublicKeyToken=", 15)) {
1868                         *is_token_defined = TRUE;
1869                         token = g_strstrip (value + 15);
1870                         if (strlen (token) == 0) {
1871                                 goto cleanup_and_fail;
1872                         }
1873                         tmp++;
1874                         continue;
1875                 }
1876
1877                 if (!g_ascii_strncasecmp (value, "PublicKey=", 10)) {
1878                         key = g_strstrip (value + 10);
1879                         if (strlen (key) == 0) {
1880                                 goto cleanup_and_fail;
1881                         }
1882                         tmp++;
1883                         continue;
1884                 }
1885
1886                 if (!g_ascii_strncasecmp (value, "Retargetable=", 13)) {
1887                         retargetable = g_strstrip (value + 13);
1888                         if (strlen (retargetable) == 0) {
1889                                 goto cleanup_and_fail;
1890                         }
1891                         if (!g_ascii_strcasecmp (retargetable, "yes")) {
1892                                 flags |= ASSEMBLYREF_RETARGETABLE_FLAG;
1893                         } else if (g_ascii_strcasecmp (retargetable, "no")) {
1894                                 goto cleanup_and_fail;
1895                         }
1896                         tmp++;
1897                         continue;
1898                 }
1899
1900                 if (!g_ascii_strncasecmp (value, "ProcessorArchitecture=", 22)) {
1901                         char *s = g_strstrip (value + 22);
1902                         if (!g_ascii_strcasecmp (s, "None"))
1903                                 arch = PROCESSOR_ARCHITECTURE_NONE;
1904                         else if (!g_ascii_strcasecmp (s, "MSIL"))
1905                                 arch = PROCESSOR_ARCHITECTURE_MSIL;
1906                         else if (!g_ascii_strcasecmp (s, "X86"))
1907                                 arch = PROCESSOR_ARCHITECTURE_X86;
1908                         else if (!g_ascii_strcasecmp (s, "IA64"))
1909                                 arch = PROCESSOR_ARCHITECTURE_IA64;
1910                         else if (!g_ascii_strcasecmp (s, "AMD64"))
1911                                 arch = PROCESSOR_ARCHITECTURE_AMD64;
1912                         else
1913                                 goto cleanup_and_fail;
1914                         tmp++;
1915                         continue;
1916                 }
1917
1918                 g_strfreev (parts);
1919                 return FALSE;
1920         }
1921
1922         /* if retargetable flag is set, then we must have a fully qualified name */
1923         if (retargetable != NULL && (version == NULL || culture == NULL || (key == NULL && token == NULL))) {
1924                 goto cleanup_and_fail;
1925         }
1926
1927         res = build_assembly_name (dllname, version, culture, token, key, flags, arch,
1928                 aname, save_public_key);
1929         g_strfreev (parts);
1930         return res;
1931
1932 cleanup_and_fail:
1933         g_strfreev (parts);
1934         return FALSE;
1935 }
1936
1937 /**
1938  * mono_assembly_name_parse:
1939  * @name: name to parse
1940  * @aname: the destination assembly name
1941  * 
1942  * Parses an assembly qualified type name and assigns the name,
1943  * version, culture and token to the provided assembly name object.
1944  *
1945  * Returns: true if the name could be parsed.
1946  */
1947 gboolean
1948 mono_assembly_name_parse (const char *name, MonoAssemblyName *aname)
1949 {
1950         return mono_assembly_name_parse_full (name, aname, FALSE, NULL, NULL);
1951 }
1952
1953 /**
1954  * mono_assembly_name_new:
1955  * @name: name to parse
1956  *
1957  * Allocate a new MonoAssemblyName and fill its values from the
1958  * passed @name.
1959  *
1960  * Returns: a newly allocated structure or NULL if there was any failure.
1961  */
1962 MonoAssemblyName*
1963 mono_assembly_name_new (const char *name)
1964 {
1965         MonoAssemblyName *aname = g_new0 (MonoAssemblyName, 1);
1966         if (mono_assembly_name_parse (name, aname))
1967                 return aname;
1968         g_free (aname);
1969         return NULL;
1970 }
1971
1972 const char*
1973 mono_assembly_name_get_name (MonoAssemblyName *aname)
1974 {
1975         return aname->name;
1976 }
1977
1978 const char*
1979 mono_assembly_name_get_culture (MonoAssemblyName *aname)
1980 {
1981         return aname->culture;
1982 }
1983
1984 mono_byte*
1985 mono_assembly_name_get_pubkeytoken (MonoAssemblyName *aname)
1986 {
1987         if (aname->public_key_token [0])
1988                 return aname->public_key_token;
1989         return NULL;
1990 }
1991
1992 uint16_t
1993 mono_assembly_name_get_version (MonoAssemblyName *aname, uint16_t *minor, uint16_t *build, uint16_t *revision)
1994 {
1995         if (minor)
1996                 *minor = aname->minor;
1997         if (build)
1998                 *build = aname->build;
1999         if (revision)
2000                 *revision = aname->revision;
2001         return aname->major;
2002 }
2003
2004 static MonoAssembly*
2005 probe_for_partial_name (const char *basepath, const char *fullname, MonoAssemblyName *aname, MonoImageOpenStatus *status)
2006 {
2007         gchar *fullpath = NULL;
2008         GDir *dirhandle;
2009         const char* direntry;
2010         MonoAssemblyName gac_aname;
2011         gint major=-1, minor=0, build=0, revision=0;
2012         gboolean exact_version;
2013         
2014         dirhandle = g_dir_open (basepath, 0, NULL);
2015         if (!dirhandle)
2016                 return NULL;
2017                 
2018         exact_version = (aname->major | aname->minor | aname->build | aname->revision) != 0;
2019
2020         while ((direntry = g_dir_read_name (dirhandle))) {
2021                 gboolean match = TRUE;
2022                 
2023                 if(!parse_assembly_directory_name (aname->name, direntry, &gac_aname))
2024                         continue;
2025                 
2026                 if (aname->culture != NULL && strcmp (aname->culture, gac_aname.culture) != 0)
2027                         match = FALSE;
2028                         
2029                 if (match && strlen ((char*)aname->public_key_token) > 0 && 
2030                                 !mono_public_tokens_are_equal (aname->public_key_token, gac_aname.public_key_token))
2031                         match = FALSE;
2032                 
2033                 if (match) {
2034                         if (exact_version) {
2035                                 match = (aname->major == gac_aname.major && aname->minor == gac_aname.minor &&
2036                                                  aname->build == gac_aname.build && aname->revision == gac_aname.revision); 
2037                         }
2038                         else if (gac_aname.major < major)
2039                                 match = FALSE;
2040                         else if (gac_aname.major == major) {
2041                                 if (gac_aname.minor < minor)
2042                                         match = FALSE;
2043                                 else if (gac_aname.minor == minor) {
2044                                         if (gac_aname.build < build)
2045                                                 match = FALSE;
2046                                         else if (gac_aname.build == build && gac_aname.revision <= revision)
2047                                                 match = FALSE; 
2048                                 }
2049                         }
2050                 }
2051                 
2052                 if (match) {
2053                         major = gac_aname.major;
2054                         minor = gac_aname.minor;
2055                         build = gac_aname.build;
2056                         revision = gac_aname.revision;
2057                         g_free (fullpath);
2058                         fullpath = g_build_path (G_DIR_SEPARATOR_S, basepath, direntry, fullname, NULL);
2059                 }
2060
2061                 mono_assembly_name_free (&gac_aname);
2062         }
2063         
2064         g_dir_close (dirhandle);
2065         
2066         if (fullpath == NULL)
2067                 return NULL;
2068         else {
2069                 MonoAssembly *res = mono_assembly_open (fullpath, status);
2070                 g_free (fullpath);
2071                 return res;
2072         }
2073 }
2074
2075 MonoAssembly*
2076 mono_assembly_load_with_partial_name (const char *name, MonoImageOpenStatus *status)
2077 {
2078         MonoAssembly *res;
2079         MonoAssemblyName *aname, base_name;
2080 #ifndef DISABLE_ASSEMBLY_REMAPPING
2081         MonoAssemblyName maped_aname;
2082 #endif
2083         gchar *fullname, *gacpath;
2084         gchar **paths;
2085
2086         memset (&base_name, 0, sizeof (MonoAssemblyName));
2087         aname = &base_name;
2088
2089         if (!mono_assembly_name_parse (name, aname))
2090                 return NULL;
2091
2092 #ifndef DISABLE_ASSEMBLY_REMAPPING
2093         /* 
2094          * If no specific version has been requested, make sure we load the
2095          * correct version for system assemblies.
2096          */ 
2097         if ((aname->major | aname->minor | aname->build | aname->revision) == 0)
2098                 aname = mono_assembly_remap_version (aname, &maped_aname);
2099 #endif
2100         
2101         res = mono_assembly_loaded (aname);
2102         if (res) {
2103                 mono_assembly_name_free (aname);
2104                 return res;
2105         }
2106
2107         res = invoke_assembly_preload_hook (aname, assemblies_path);
2108         if (res) {
2109                 res->in_gac = FALSE;
2110                 mono_assembly_name_free (aname);
2111                 return res;
2112         }
2113
2114         fullname = g_strdup_printf ("%s.dll", aname->name);
2115
2116         if (extra_gac_paths) {
2117                 paths = extra_gac_paths;
2118                 while (!res && *paths) {
2119                         gacpath = g_build_path (G_DIR_SEPARATOR_S, *paths, "lib", "mono", "gac", aname->name, NULL);
2120                         res = probe_for_partial_name (gacpath, fullname, aname, status);
2121                         g_free (gacpath);
2122                         paths++;
2123                 }
2124         }
2125
2126         if (res) {
2127                 res->in_gac = TRUE;
2128                 g_free (fullname);
2129                 mono_assembly_name_free (aname);
2130                 return res;
2131         }
2132
2133         gacpath = g_build_path (G_DIR_SEPARATOR_S, mono_assembly_getrootdir (), "mono", "gac", aname->name, NULL);
2134         res = probe_for_partial_name (gacpath, fullname, aname, status);
2135         g_free (gacpath);
2136
2137         if (res)
2138                 res->in_gac = TRUE;
2139         else {
2140                 MonoDomain *domain = mono_domain_get ();
2141                 MonoReflectionAssembly *refasm = mono_try_assembly_resolve (domain, mono_string_new (domain, name), FALSE);
2142                 if (refasm)
2143                         res = refasm->assembly;
2144         }
2145         
2146         g_free (fullname);
2147         mono_assembly_name_free (aname);
2148
2149         return res;
2150 }
2151
2152 static MonoBoolean
2153 mono_assembly_is_in_gac (const gchar *filename)
2154 {
2155         const gchar *rootdir;
2156         gchar *gp;
2157         gchar **paths;
2158
2159         if (filename == NULL)
2160                 return FALSE;
2161
2162         for (paths = extra_gac_paths; paths && *paths; paths++) {
2163                 if (strstr (*paths, filename) != *paths)
2164                         continue;
2165
2166                 gp = (gchar *) (filename + strlen (*paths));
2167                 if (*gp != G_DIR_SEPARATOR)
2168                         continue;
2169                 gp++;
2170                 if (strncmp (gp, "lib", 3))
2171                         continue;
2172                 gp += 3;
2173                 if (*gp != G_DIR_SEPARATOR)
2174                         continue;
2175                 gp++;
2176                 if (strncmp (gp, "mono", 4))
2177                         continue;
2178                 gp += 4;
2179                 if (*gp != G_DIR_SEPARATOR)
2180                         continue;
2181                 gp++;
2182                 if (strncmp (gp, "gac", 3))
2183                         continue;
2184                 gp += 3;
2185                 if (*gp != G_DIR_SEPARATOR)
2186                         continue;
2187
2188                 return TRUE;
2189         }
2190
2191         rootdir = mono_assembly_getrootdir ();
2192         if (strstr (filename, rootdir) != filename)
2193                 return FALSE;
2194
2195         gp = (gchar *) (filename + strlen (rootdir));
2196         if (*gp != G_DIR_SEPARATOR)
2197                 return FALSE;
2198         gp++;
2199         if (strncmp (gp, "mono", 4))
2200                 return FALSE;
2201         gp += 4;
2202         if (*gp != G_DIR_SEPARATOR)
2203                 return FALSE;
2204         gp++;
2205         if (strncmp (gp, "gac", 3))
2206                 return FALSE;
2207         gp += 3;
2208         if (*gp != G_DIR_SEPARATOR)
2209                 return FALSE;
2210         return TRUE;
2211 }
2212
2213 static MonoImage*
2214 mono_assembly_load_publisher_policy (MonoAssemblyName *aname)
2215 {
2216         MonoImage *image;
2217         gchar *filename, *pname, *name, *culture, *version, *fullpath, *subpath;
2218         gchar **paths;
2219         gint32 len;
2220
2221         if (strstr (aname->name, ".dll")) {
2222                 len = strlen (aname->name) - 4;
2223                 name = g_malloc (len);
2224                 strncpy (name, aname->name, len);
2225         } else
2226                 name = g_strdup (aname->name);
2227         
2228         if (aname->culture)
2229                 culture = g_utf8_strdown (aname->culture, -1);
2230         else
2231                 culture = g_strdup ("");
2232         
2233         pname = g_strdup_printf ("policy.%d.%d.%s", aname->major, aname->minor, name);
2234         version = g_strdup_printf ("0.0.0.0_%s_%s", culture, aname->public_key_token);
2235         g_free (name);
2236         g_free (culture);
2237         
2238         filename = g_strconcat (pname, ".dll", NULL);
2239         subpath = g_build_path (G_DIR_SEPARATOR_S, pname, version, filename, NULL);
2240         g_free (pname);
2241         g_free (version);
2242         g_free (filename);
2243
2244         image = NULL;
2245         if (extra_gac_paths) {
2246                 paths = extra_gac_paths;
2247                 while (!image && *paths) {
2248                         fullpath = g_build_path (G_DIR_SEPARATOR_S, *paths,
2249                                         "lib", "mono", "gac", subpath, NULL);
2250                         image = mono_image_open (fullpath, NULL);
2251                         g_free (fullpath);
2252                         paths++;
2253                 }
2254         }
2255
2256         if (image) {
2257                 g_free (subpath);
2258                 return image;
2259         }
2260
2261         fullpath = g_build_path (G_DIR_SEPARATOR_S, mono_assembly_getrootdir (), 
2262                         "mono", "gac", subpath, NULL);
2263         image = mono_image_open (fullpath, NULL);
2264         g_free (subpath);
2265         g_free (fullpath);
2266         
2267         return image;
2268 }
2269
2270 static MonoAssemblyName*
2271 mono_assembly_bind_version (MonoAssemblyBindingInfo *info, MonoAssemblyName *aname, MonoAssemblyName *dest_name)
2272 {
2273         memcpy (dest_name, aname, sizeof (MonoAssemblyName));
2274         dest_name->major = info->new_version.major;
2275         dest_name->minor = info->new_version.minor;
2276         dest_name->build = info->new_version.build;
2277         dest_name->revision = info->new_version.revision;
2278         
2279         return dest_name;
2280 }
2281
2282 /* LOCKING: Assumes that we are already locked */
2283 static MonoAssemblyBindingInfo*
2284 search_binding_loaded (MonoAssemblyName *aname)
2285 {
2286         GSList *tmp;
2287
2288         for (tmp = loaded_assembly_bindings; tmp; tmp = tmp->next) {
2289                 MonoAssemblyBindingInfo *info = tmp->data;
2290                 if (assembly_binding_maps_name (info, aname))
2291                         return info;
2292         }
2293
2294         return NULL;
2295 }
2296
2297 static inline gboolean
2298 info_compare_versions (AssemblyVersionSet *left, AssemblyVersionSet *right)
2299 {
2300         if (left->major != right->major || left->minor != right->minor ||
2301             left->build != right->build || left->revision != right->revision)
2302                 return FALSE;
2303
2304         return TRUE;
2305 }
2306
2307 static inline gboolean
2308 info_versions_equal (MonoAssemblyBindingInfo *left, MonoAssemblyBindingInfo *right)
2309 {
2310         if (left->has_old_version_bottom != right->has_old_version_bottom)
2311                 return FALSE;
2312
2313         if (left->has_old_version_top != right->has_old_version_top)
2314                 return FALSE;
2315
2316         if (left->has_new_version != right->has_new_version)
2317                 return FALSE;
2318
2319         if (left->has_old_version_bottom && !info_compare_versions (&left->old_version_bottom, &right->old_version_bottom))
2320                 return FALSE;
2321
2322         if (left->has_old_version_top && !info_compare_versions (&left->old_version_top, &right->old_version_top))
2323                 return FALSE;
2324
2325         if (left->has_new_version && !info_compare_versions (&left->new_version, &right->new_version))
2326                 return FALSE;
2327
2328         return TRUE;
2329 }
2330
2331 /* LOCKING: assumes all the necessary locks are held */
2332 static void
2333 assembly_binding_info_parsed (MonoAssemblyBindingInfo *info, void *user_data)
2334 {
2335         MonoAssemblyBindingInfo *info_copy;
2336         GSList *tmp;
2337         MonoAssemblyBindingInfo *info_tmp;
2338         MonoDomain *domain = (MonoDomain*)user_data;
2339
2340         if (!domain)
2341                 return;
2342
2343         for (tmp = domain->assembly_bindings; tmp; tmp = tmp->next) {
2344                 info_tmp = tmp->data;
2345                 if (strcmp (info->name, info_tmp->name) == 0 && info_versions_equal (info, info_tmp))
2346                         return;
2347         }
2348
2349         info_copy = mono_mempool_alloc0 (domain->mp, sizeof (MonoAssemblyBindingInfo));
2350         memcpy (info_copy, info, sizeof (MonoAssemblyBindingInfo));
2351         if (info->name)
2352                 info_copy->name = mono_mempool_strdup (domain->mp, info->name);
2353         if (info->culture)
2354                 info_copy->culture = mono_mempool_strdup (domain->mp, info->culture);
2355
2356         domain->assembly_bindings = g_slist_append_mempool (domain->mp, domain->assembly_bindings, info_copy);
2357 }
2358
2359 static inline gboolean
2360 info_major_minor_in_range (MonoAssemblyBindingInfo *info, MonoAssemblyName *aname)
2361 {
2362         if (!info->has_old_version_bottom)
2363                 return FALSE;
2364
2365         if (info->old_version_bottom.major > aname->major || info->old_version_bottom.minor > aname->minor)
2366                 return FALSE;
2367
2368         if (info->has_old_version_top && (info->old_version_top.major < aname->major || info->old_version_top.minor < aname->minor))
2369                 return FALSE;
2370
2371         /* This is not the nicest way to do it, but it's a by-product of the way parsing is done */
2372         info->major = aname->major;
2373         info->minor = aname->minor;
2374
2375         return TRUE;
2376 }
2377
2378 /* LOCKING: Assumes that we are already locked - both loader and domain locks */
2379 static MonoAssemblyBindingInfo*
2380 get_per_domain_assembly_binding_info (MonoDomain *domain, MonoAssemblyName *aname)
2381 {
2382         MonoAssemblyBindingInfo *info;
2383         GSList *list;
2384
2385         if (!domain->assembly_bindings)
2386                 return NULL;
2387
2388         info = NULL;
2389         for (list = domain->assembly_bindings; list; list = list->next) {
2390                 info = list->data;
2391                 if (info && !strcmp (aname->name, info->name) && info_major_minor_in_range (info, aname))
2392                         break;
2393                 info = NULL;
2394         }
2395
2396         if (info) {
2397                 if (info->name && info->public_key_token [0] && info->has_old_version_bottom &&
2398                     info->has_new_version && assembly_binding_maps_name (info, aname))
2399                         info->is_valid = TRUE;
2400                 else
2401                         info->is_valid = FALSE;
2402         }
2403
2404         return info;
2405 }
2406
2407 static MonoAssemblyName*
2408 mono_assembly_apply_binding (MonoAssemblyName *aname, MonoAssemblyName *dest_name)
2409 {
2410         MonoAssemblyBindingInfo *info, *info2;
2411         MonoImage *ppimage;
2412         MonoDomain *domain;
2413
2414         if (aname->public_key_token [0] == 0)
2415                 return aname;
2416
2417         domain = mono_domain_get ();
2418         mono_loader_lock ();
2419         info = search_binding_loaded (aname);
2420         if (!info) {
2421                 mono_domain_lock (domain);
2422                 info = get_per_domain_assembly_binding_info (domain, aname);
2423                 mono_domain_unlock (domain);
2424         }
2425
2426         mono_loader_unlock ();
2427         if (info) {
2428                 if (!check_policy_versions (info, aname))
2429                         return aname;
2430                 
2431                 mono_assembly_bind_version (info, aname, dest_name);
2432                 return dest_name;
2433         }
2434
2435         if (domain && domain->setup && domain->setup->configuration_file) {
2436                 mono_domain_lock (domain);
2437                 if (!domain->assembly_bindings_parsed) {
2438                         gchar *domain_config_file = mono_string_to_utf8 (domain->setup->configuration_file);
2439
2440                         mono_config_parse_assembly_bindings (domain_config_file, aname->major, aname->minor, domain, assembly_binding_info_parsed);
2441                         domain->assembly_bindings_parsed = TRUE;
2442                         g_free (domain_config_file);
2443                 }
2444                 mono_domain_unlock (domain);
2445
2446                 mono_loader_lock ();
2447                 mono_domain_lock (domain);
2448                 info = get_per_domain_assembly_binding_info (domain, aname);
2449                 mono_domain_unlock (domain);
2450                 mono_loader_unlock ();
2451         }
2452
2453         if (!info) {
2454                 info = g_new0 (MonoAssemblyBindingInfo, 1);
2455                 info->major = aname->major;
2456                 info->minor = aname->minor;
2457         }
2458
2459         if (!info->is_valid) {
2460                 ppimage = mono_assembly_load_publisher_policy (aname);
2461                 if (ppimage) {
2462                         get_publisher_policy_info (ppimage, aname, info);
2463                         mono_image_close (ppimage);
2464                 }
2465         }
2466
2467         /* Define default error value if needed */
2468         if (!info->is_valid) {
2469                 info->name = g_strdup (aname->name);
2470                 info->culture = g_strdup (aname->culture);
2471                 g_strlcpy ((char *)info->public_key_token, (const char *)aname->public_key_token, MONO_PUBLIC_KEY_TOKEN_LENGTH);
2472         }
2473         
2474         mono_loader_lock ();
2475         info2 = search_binding_loaded (aname);
2476         if (info2) {
2477                 /* This binding was added by another thread 
2478                  * before us */
2479                 mono_assembly_binding_info_free (info);
2480                 g_free (info);
2481                 
2482                 info = info2;
2483         } else
2484                 loaded_assembly_bindings = g_slist_prepend (loaded_assembly_bindings, info);
2485                 
2486         mono_loader_unlock ();
2487         
2488         if (!info->is_valid || !check_policy_versions (info, aname))
2489                 return aname;
2490
2491         mono_assembly_bind_version (info, aname, dest_name);
2492         return dest_name;
2493 }
2494
2495 /**
2496  * mono_assembly_load_from_gac
2497  *
2498  * @aname: The assembly name object
2499  */
2500 static MonoAssembly*
2501 mono_assembly_load_from_gac (MonoAssemblyName *aname,  gchar *filename, MonoImageOpenStatus *status, MonoBoolean refonly)
2502 {
2503         MonoAssembly *result = NULL;
2504         gchar *name, *version, *culture, *fullpath, *subpath;
2505         gint32 len;
2506         gchar **paths;
2507         char *pubtok;
2508
2509         if (aname->public_key_token [0] == 0) {
2510                 return NULL;
2511         }
2512
2513         if (strstr (aname->name, ".dll")) {
2514                 len = strlen (filename) - 4;
2515                 name = g_malloc (len);
2516                 strncpy (name, aname->name, len);
2517         } else {
2518                 name = g_strdup (aname->name);
2519         }
2520
2521         if (aname->culture) {
2522                 culture = g_utf8_strdown (aname->culture, -1);
2523         } else {
2524                 culture = g_strdup ("");
2525         }
2526
2527         pubtok = g_ascii_strdown ((char*)aname->public_key_token, MONO_PUBLIC_KEY_TOKEN_LENGTH);
2528         version = g_strdup_printf ("%d.%d.%d.%d_%s_%s", aname->major,
2529                         aname->minor, aname->build, aname->revision,
2530                         culture, pubtok);
2531         g_free (pubtok);
2532         
2533         subpath = g_build_path (G_DIR_SEPARATOR_S, name, version, filename, NULL);
2534         g_free (name);
2535         g_free (version);
2536         g_free (culture);
2537
2538         if (extra_gac_paths) {
2539                 paths = extra_gac_paths;
2540                 while (!result && *paths) {
2541                         fullpath = g_build_path (G_DIR_SEPARATOR_S, *paths, "lib", "mono", "gac", subpath, NULL);
2542                         result = mono_assembly_open_full (fullpath, status, refonly);
2543                         g_free (fullpath);
2544                         paths++;
2545                 }
2546         }
2547
2548         if (result) {
2549                 result->in_gac = TRUE;
2550                 g_free (subpath);
2551                 return result;
2552         }
2553
2554         fullpath = g_build_path (G_DIR_SEPARATOR_S, mono_assembly_getrootdir (),
2555                         "mono", "gac", subpath, NULL);
2556         result = mono_assembly_open_full (fullpath, status, refonly);
2557         g_free (fullpath);
2558
2559         if (result)
2560                 result->in_gac = TRUE;
2561         
2562         g_free (subpath);
2563
2564         return result;
2565 }
2566
2567 MonoAssembly*
2568 mono_assembly_load_corlib (const MonoRuntimeInfo *runtime, MonoImageOpenStatus *status)
2569 {
2570         char *corlib_file;
2571         MonoAssemblyName *aname;
2572
2573         if (corlib) {
2574                 /* g_print ("corlib already loaded\n"); */
2575                 return corlib;
2576         }
2577
2578 #if defined(__native_client__)
2579         if (corlibData != NULL && corlibSize != 0) {
2580                 int status = 0;
2581                 /* First "FALSE" instructs mono not to make a copy. */
2582                 /* Second "FALSE" says this is not just a ref.      */
2583                 MonoImage* image = mono_image_open_from_data_full (corlibData, corlibSize, FALSE, &status, FALSE);
2584                 if (image == NULL || status != 0)
2585                         g_print("mono_image_open_from_data_full failed: %d\n", status);
2586                 corlib = mono_assembly_load_from_full (image, "mscorlib", &status, FALSE);
2587                 if (corlib == NULL || status != 0)
2588                         g_print ("mono_assembly_load_from_full failed: %d\n", status);
2589                 if (corlib)
2590                         return corlib;
2591         }
2592 #endif
2593
2594         aname = mono_assembly_name_new ("mscorlib.dll");
2595         corlib = invoke_assembly_preload_hook (aname, assemblies_path);
2596         mono_assembly_name_free (aname);
2597         g_free (aname);
2598         if (corlib != NULL)
2599                 return corlib;
2600
2601         if (assemblies_path) {
2602                 corlib = load_in_path ("mscorlib.dll", (const char**)assemblies_path, status, FALSE);
2603                 if (corlib)
2604                         return corlib;
2605         }
2606
2607         /* Load corlib from mono/<version> */
2608         
2609         corlib_file = g_build_filename ("mono", runtime->framework_version, "mscorlib.dll", NULL);
2610         if (assemblies_path) {
2611                 corlib = load_in_path (corlib_file, (const char**)assemblies_path, status, FALSE);
2612                 if (corlib) {
2613                         g_free (corlib_file);
2614                         return corlib;
2615                 }
2616         }
2617         corlib = load_in_path (corlib_file, default_path, status, FALSE);
2618         g_free (corlib_file);
2619
2620         return corlib;
2621 }
2622
2623 MonoAssembly*
2624 mono_assembly_load_full_nosearch (MonoAssemblyName *aname, 
2625                                                                   const char       *basedir, 
2626                                                                   MonoImageOpenStatus *status,
2627                                                                   gboolean refonly)
2628 {
2629         MonoAssembly *result;
2630         char *fullpath, *filename;
2631 #ifndef DISABLE_ASSEMBLY_REMAPPING
2632         MonoAssemblyName maped_aname;
2633 #endif
2634         MonoAssemblyName maped_name_pp;
2635         int ext_index;
2636         const char *ext;
2637         int len;
2638
2639 #ifndef DISABLE_ASSEMBLY_REMAPPING
2640         aname = mono_assembly_remap_version (aname, &maped_aname);
2641 #endif
2642         
2643         /* Reflection only assemblies don't get assembly binding */
2644         if (!refonly)
2645                 aname = mono_assembly_apply_binding (aname, &maped_name_pp);
2646         
2647         result = mono_assembly_loaded_full (aname, refonly);
2648         if (result)
2649                 return result;
2650
2651         result = refonly ? invoke_assembly_refonly_preload_hook (aname, assemblies_path) : invoke_assembly_preload_hook (aname, assemblies_path);
2652         if (result) {
2653                 result->in_gac = FALSE;
2654                 return result;
2655         }
2656
2657         /* Currently we retrieve the loaded corlib for reflection 
2658          * only requests, like a common reflection only assembly 
2659          */
2660         if (strcmp (aname->name, "mscorlib") == 0 || strcmp (aname->name, "mscorlib.dll") == 0) {
2661                 return mono_assembly_load_corlib (mono_get_runtime_info (), status);
2662         }
2663
2664         len = strlen (aname->name);
2665         for (ext_index = 0; ext_index < 2; ext_index ++) {
2666                 ext = ext_index == 0 ? ".dll" : ".exe";
2667                 if (len > 4 && (!strcmp (aname->name + len - 4, ".dll") || !strcmp (aname->name + len - 4, ".exe"))) {
2668                         filename = g_strdup (aname->name);
2669                         /* Don't try appending .dll/.exe if it already has one of those extensions */
2670                         ext_index++;
2671                 } else {
2672                         filename = g_strconcat (aname->name, ext, NULL);
2673                 }
2674
2675                 result = mono_assembly_load_from_gac (aname, filename, status, refonly);
2676                 if (result) {
2677                         g_free (filename);
2678                         return result;
2679                 }
2680
2681                 if (basedir) {
2682                         fullpath = g_build_filename (basedir, filename, NULL);
2683                         result = mono_assembly_open_full (fullpath, status, refonly);
2684                         g_free (fullpath);
2685                         if (result) {
2686                                 result->in_gac = FALSE;
2687                                 g_free (filename);
2688                                 return result;
2689                         }
2690                 }
2691
2692                 result = load_in_path (filename, default_path, status, refonly);
2693                 if (result)
2694                         result->in_gac = FALSE;
2695                 g_free (filename);
2696                 if (result)
2697                         return result;
2698         }
2699
2700         return result;
2701 }
2702
2703 /**
2704  * mono_assembly_load_full:
2705  * @aname: A MonoAssemblyName with the assembly name to load.
2706  * @basedir: A directory to look up the assembly at.
2707  * @status: a pointer to a MonoImageOpenStatus to return the status of the load operation
2708  * @refonly: Whether this assembly is being opened in "reflection-only" mode.
2709  *
2710  * Loads the assembly referenced by @aname, if the value of @basedir is not NULL, it
2711  * attempts to load the assembly from that directory before probing the standard locations.
2712  *
2713  * If the assembly is being opened in reflection-only mode (@refonly set to TRUE) then no 
2714  * assembly binding takes place.
2715  *
2716  * Returns: the assembly referenced by @aname loaded or NULL on error.   On error the
2717  * value pointed by status is updated with an error code.
2718  */
2719 MonoAssembly*
2720 mono_assembly_load_full (MonoAssemblyName *aname, const char *basedir, MonoImageOpenStatus *status, gboolean refonly)
2721 {
2722         MonoAssembly *result = mono_assembly_load_full_nosearch (aname, basedir, status, refonly);
2723         
2724         if (!result)
2725                 /* Try a postload search hook */
2726                 result = mono_assembly_invoke_search_hook_internal (aname, refonly, TRUE);
2727         return result;
2728 }
2729
2730 /**
2731  * mono_assembly_load:
2732  * @aname: A MonoAssemblyName with the assembly name to load.
2733  * @basedir: A directory to look up the assembly at.
2734  * @status: a pointer to a MonoImageOpenStatus to return the status of the load operation
2735  *
2736  * Loads the assembly referenced by @aname, if the value of @basedir is not NULL, it
2737  * attempts to load the assembly from that directory before probing the standard locations.
2738  *
2739  * Returns: the assembly referenced by @aname loaded or NULL on error.   On error the
2740  * value pointed by status is updated with an error code.
2741  */
2742 MonoAssembly*
2743 mono_assembly_load (MonoAssemblyName *aname, const char *basedir, MonoImageOpenStatus *status)
2744 {
2745         return mono_assembly_load_full (aname, basedir, status, FALSE);
2746 }
2747         
2748 MonoAssembly*
2749 mono_assembly_loaded_full (MonoAssemblyName *aname, gboolean refonly)
2750 {
2751         MonoAssembly *res;
2752 #ifndef DISABLE_ASSEMBLY_REMAPPING
2753         MonoAssemblyName maped_aname;
2754
2755         aname = mono_assembly_remap_version (aname, &maped_aname);
2756 #endif
2757
2758         res = mono_assembly_invoke_search_hook_internal (aname, refonly, FALSE);
2759
2760         return res;
2761 }
2762
2763 /**
2764  * mono_assembly_loaded:
2765  * @aname: an assembly to look for.
2766  *
2767  * Returns: NULL If the given @aname assembly has not been loaded, or a pointer to
2768  * a MonoAssembly that matches the MonoAssemblyName specified.
2769  */
2770 MonoAssembly*
2771 mono_assembly_loaded (MonoAssemblyName *aname)
2772 {
2773         return mono_assembly_loaded_full (aname, FALSE);
2774 }
2775
2776 /*
2777  * Returns whether mono_assembly_close_finish() must be called as
2778  * well.  See comment for mono_image_close_except_pools() for why we
2779  * unload in two steps.
2780  */
2781 gboolean
2782 mono_assembly_close_except_image_pools (MonoAssembly *assembly)
2783 {
2784         GSList *tmp;
2785         g_return_val_if_fail (assembly != NULL, FALSE);
2786
2787         if (assembly == REFERENCE_MISSING)
2788                 return FALSE;
2789
2790         /* Might be 0 already */
2791         if (InterlockedDecrement (&assembly->ref_count) > 0)
2792                 return FALSE;
2793
2794         mono_profiler_assembly_event (assembly, MONO_PROFILE_START_UNLOAD);
2795
2796         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_ASSEMBLY, "Unloading assembly %s [%p].", assembly->aname.name, assembly);
2797
2798         mono_debug_close_image (assembly->image);
2799
2800         mono_assemblies_lock ();
2801         loaded_assemblies = g_list_remove (loaded_assemblies, assembly);
2802         mono_assemblies_unlock ();
2803
2804         assembly->image->assembly = NULL;
2805
2806         if (!mono_image_close_except_pools (assembly->image))
2807                 assembly->image = NULL;
2808
2809         for (tmp = assembly->friend_assembly_names; tmp; tmp = tmp->next) {
2810                 MonoAssemblyName *fname = tmp->data;
2811                 mono_assembly_name_free (fname);
2812                 g_free (fname);
2813         }
2814         g_slist_free (assembly->friend_assembly_names);
2815         g_free (assembly->basedir);
2816
2817         mono_profiler_assembly_event (assembly, MONO_PROFILE_END_UNLOAD);
2818
2819         return TRUE;
2820 }
2821
2822 void
2823 mono_assembly_close_finish (MonoAssembly *assembly)
2824 {
2825         g_assert (assembly && assembly != REFERENCE_MISSING);
2826
2827         if (assembly->image)
2828                 mono_image_close_finish (assembly->image);
2829
2830         if (assembly->dynamic) {
2831                 g_free ((char*)assembly->aname.culture);
2832         } else {
2833                 g_free (assembly);
2834         }
2835 }
2836
2837 /**
2838  * mono_assembly_close:
2839  * @assembly: the assembly to release.
2840  *
2841  * This method releases a reference to the @assembly.  The assembly is
2842  * only released when all the outstanding references to it are released.
2843  */
2844 void
2845 mono_assembly_close (MonoAssembly *assembly)
2846 {
2847         if (mono_assembly_close_except_image_pools (assembly))
2848                 mono_assembly_close_finish (assembly);
2849 }
2850
2851 MonoImage*
2852 mono_assembly_load_module (MonoAssembly *assembly, guint32 idx)
2853 {
2854         return mono_image_load_file_for_image (assembly->image, idx);
2855 }
2856
2857 void
2858 mono_assembly_foreach (GFunc func, gpointer user_data)
2859 {
2860         GList *copy;
2861
2862         /*
2863          * We make a copy of the list to avoid calling the callback inside the 
2864          * lock, which could lead to deadlocks.
2865          */
2866         mono_assemblies_lock ();
2867         copy = g_list_copy (loaded_assemblies);
2868         mono_assemblies_unlock ();
2869
2870         g_list_foreach (loaded_assemblies, func, user_data);
2871
2872         g_list_free (copy);
2873 }
2874
2875 /**
2876  * mono_assemblies_cleanup:
2877  *
2878  * Free all resources used by this module.
2879  */
2880 void
2881 mono_assemblies_cleanup (void)
2882 {
2883         GSList *l;
2884
2885         DeleteCriticalSection (&assemblies_mutex);
2886
2887         for (l = loaded_assembly_bindings; l; l = l->next) {
2888                 MonoAssemblyBindingInfo *info = l->data;
2889
2890                 mono_assembly_binding_info_free (info);
2891                 g_free (info);
2892         }
2893         g_slist_free (loaded_assembly_bindings);
2894
2895         free_assembly_load_hooks ();
2896         free_assembly_search_hooks ();
2897         free_assembly_preload_hooks ();
2898 }
2899
2900 /*
2901  * Holds the assembly of the application, for
2902  * System.Diagnostics.Process::MainModule
2903  */
2904 static MonoAssembly *main_assembly=NULL;
2905
2906 void
2907 mono_assembly_set_main (MonoAssembly *assembly)
2908 {
2909         main_assembly = assembly;
2910 }
2911
2912 /**
2913  * mono_assembly_get_main:
2914  *
2915  * Returns: the assembly for the application, the first assembly that is loaded by the VM
2916  */
2917 MonoAssembly *
2918 mono_assembly_get_main (void)
2919 {
2920         return (main_assembly);
2921 }
2922
2923 /**
2924  * mono_assembly_get_image:
2925  * @assembly: The assembly to retrieve the image from
2926  *
2927  * Returns: the MonoImage associated with this assembly.
2928  */
2929 MonoImage*
2930 mono_assembly_get_image (MonoAssembly *assembly)
2931 {
2932         return assembly->image;
2933 }
2934
2935 void
2936 mono_register_bundled_assemblies (const MonoBundledAssembly **assemblies)
2937 {
2938         bundles = assemblies;
2939 }
2940
2941 #define MONO_DECLSEC_FORMAT_10          0x3C
2942 #define MONO_DECLSEC_FORMAT_20          0x2E
2943 #define MONO_DECLSEC_FIELD              0x53
2944 #define MONO_DECLSEC_PROPERTY           0x54
2945
2946 #define SKIP_VISIBILITY_XML_ATTRIBUTE ("\"SkipVerification\"")
2947 #define SKIP_VISIBILITY_ATTRIBUTE_NAME ("System.Security.Permissions.SecurityPermissionAttribute")
2948 #define SKIP_VISIBILITY_ATTRIBUTE_SIZE (sizeof (SKIP_VISIBILITY_ATTRIBUTE_NAME) - 1)
2949 #define SKIP_VISIBILITY_PROPERTY_NAME ("SkipVerification")
2950 #define SKIP_VISIBILITY_PROPERTY_SIZE (sizeof (SKIP_VISIBILITY_PROPERTY_NAME) - 1)
2951
2952 static gboolean
2953 mono_assembly_try_decode_skip_verification_param (const char *p, const char **resp, gboolean *abort_decoding)
2954 {
2955         int len;
2956         switch (*p++) {
2957         case MONO_DECLSEC_PROPERTY:
2958                 break;
2959         case MONO_DECLSEC_FIELD:
2960         default:
2961                 *abort_decoding = TRUE;
2962                 return FALSE;
2963                 break;
2964         }
2965
2966         if (*p++ != MONO_TYPE_BOOLEAN) {
2967                 *abort_decoding = TRUE;
2968                 return FALSE;
2969         }
2970                 
2971         /* property name length */
2972         len = mono_metadata_decode_value (p, &p);
2973
2974         if (len >= SKIP_VISIBILITY_PROPERTY_SIZE && !memcmp (p, SKIP_VISIBILITY_PROPERTY_NAME, SKIP_VISIBILITY_PROPERTY_SIZE)) {
2975                 p += len;
2976                 return *p;
2977         }
2978         p += len + 1;
2979
2980         *resp = p;
2981         return FALSE;
2982 }
2983
2984 static gboolean
2985 mono_assembly_try_decode_skip_verification (const char *p, const char *endn)
2986 {
2987         int i, j, num, len, params_len;
2988
2989         if (*p == MONO_DECLSEC_FORMAT_10) {
2990                 gsize read, written;
2991                 char *res = g_convert (p, endn - p, "UTF-8", "UTF-16LE", &read, &written, NULL);
2992                 if (res) {
2993                         gboolean found = strstr (res, SKIP_VISIBILITY_XML_ATTRIBUTE) != NULL;
2994                         g_free (res);
2995                         return found;
2996                 }
2997                 return FALSE;
2998         }
2999         if (*p++ != MONO_DECLSEC_FORMAT_20)
3000                 return FALSE;
3001
3002         /* number of encoded permission attributes */
3003         num = mono_metadata_decode_value (p, &p);
3004         for (i = 0; i < num; ++i) {
3005                 gboolean is_valid = FALSE;
3006                 gboolean abort_decoding = FALSE;
3007
3008                 /* attribute name length */
3009                 len =  mono_metadata_decode_value (p, &p);
3010
3011                 /* We don't really need to fully decode the type. Comparing the name is enough */
3012                 is_valid = len >= SKIP_VISIBILITY_ATTRIBUTE_SIZE && !memcmp (p, SKIP_VISIBILITY_ATTRIBUTE_NAME, SKIP_VISIBILITY_ATTRIBUTE_SIZE);
3013
3014                 p += len;
3015
3016                 /*size of the params table*/
3017                 params_len =  mono_metadata_decode_value (p, &p);
3018                 if (is_valid) {
3019                         const char *params_end = p + params_len;
3020                         
3021                         /* number of parameters */
3022                         len = mono_metadata_decode_value (p, &p);
3023         
3024                         for (j = 0; j < len; ++j) {
3025                                 if (mono_assembly_try_decode_skip_verification_param (p, &p, &abort_decoding))
3026                                         return TRUE;
3027                                 if (abort_decoding)
3028                                         break;
3029                         }
3030                         p = params_end;
3031                 } else {
3032                         p += params_len;
3033                 }
3034         }
3035         
3036         return FALSE;
3037 }
3038
3039
3040 gboolean
3041 mono_assembly_has_skip_verification (MonoAssembly *assembly)
3042 {
3043         MonoTableInfo *t;       
3044         guint32 cols [MONO_DECL_SECURITY_SIZE];
3045         const char *blob;
3046         int i, len;
3047
3048         if (MONO_SECMAN_FLAG_INIT (assembly->skipverification))
3049                 return MONO_SECMAN_FLAG_GET_VALUE (assembly->skipverification);
3050
3051         t = &assembly->image->tables [MONO_TABLE_DECLSECURITY];
3052
3053         for (i = 0; i < t->rows; ++i) {
3054                 mono_metadata_decode_row (t, i, cols, MONO_DECL_SECURITY_SIZE);
3055                 if ((cols [MONO_DECL_SECURITY_PARENT] & MONO_HAS_DECL_SECURITY_MASK) != MONO_HAS_DECL_SECURITY_ASSEMBLY)
3056                         continue;
3057                 if (cols [MONO_DECL_SECURITY_ACTION] != SECURITY_ACTION_REQMIN)
3058                         continue;
3059
3060                 blob = mono_metadata_blob_heap (assembly->image, cols [MONO_DECL_SECURITY_PERMISSIONSET]);
3061                 len = mono_metadata_decode_blob_size (blob, &blob);
3062                 if (!len)
3063                         continue;
3064
3065                 if (mono_assembly_try_decode_skip_verification (blob, blob + len)) {
3066                         MONO_SECMAN_FLAG_SET_VALUE (assembly->skipverification, TRUE);
3067                         return TRUE;
3068                 }
3069         }
3070
3071         MONO_SECMAN_FLAG_SET_VALUE (assembly->skipverification, FALSE);
3072         return FALSE;
3073 }