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