Merge pull request #754 from blackfusion/master
[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 /*
848  * CAUTION: This table must be kept in sync with
849  *          ivkm/reflect/Fusion.cs
850  */
851
852 #define SILVERLIGHT_KEY "7cec85d7bea7798e"
853 #define WINFX_KEY "31bf3856ad364e35"
854 #define ECMA_KEY "b77a5c561934e089"
855 #define MSFINAL_KEY "b03f5f7f11d50a3a"
856
857 typedef struct {
858         const char *name;
859         const char *from;
860         const char *to;
861 } KeyRemapEntry;
862
863 static KeyRemapEntry key_remap_table[] = {
864         { "Microsoft.CSharp", WINFX_KEY, MSFINAL_KEY },
865         { "System", SILVERLIGHT_KEY, ECMA_KEY },
866         { "System.ComponentModel.Composition", WINFX_KEY, ECMA_KEY },
867         { "System.ComponentModel.DataAnnotations", "ddd0da4d3e678217", WINFX_KEY },
868         { "System.Core", SILVERLIGHT_KEY, ECMA_KEY },
869         // FIXME: MS uses MSFINAL_KEY for .NET 4.5
870         { "System.Net", SILVERLIGHT_KEY, MSFINAL_KEY },
871         { "System.Numerics", WINFX_KEY, ECMA_KEY },
872         { "System.Runtime.Serialization", SILVERLIGHT_KEY, ECMA_KEY },
873         { "System.ServiceModel", WINFX_KEY, ECMA_KEY },
874         { "System.ServiceModel.Web", SILVERLIGHT_KEY, WINFX_KEY },
875         { "System.Windows", SILVERLIGHT_KEY, MSFINAL_KEY },
876         { "System.Xml", SILVERLIGHT_KEY, ECMA_KEY },
877         { "System.Xml.Linq", WINFX_KEY, ECMA_KEY },
878         { "System.Xml.Serialization", WINFX_KEY, ECMA_KEY }
879 };
880
881 static void
882 remap_keys (MonoAssemblyName *aname)
883 {
884         int i;
885         for (i = 0; i < G_N_ELEMENTS (key_remap_table); i++) {
886                 const KeyRemapEntry *entry = &key_remap_table [i];
887
888                 if (strcmp (aname->name, entry->name) ||
889                     !mono_public_tokens_are_equal (aname->public_key_token, (const unsigned char*) entry->from))
890                         continue;
891
892                 memcpy (aname->public_key_token, entry->to, MONO_PUBLIC_KEY_TOKEN_LENGTH);
893                      
894                 mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_ASSEMBLY,
895                             "Remapped public key token of retargetable assembly %s from %s to %s",
896                             aname->name, entry->from, entry->to);
897                 return;
898         }
899 }
900
901 static MonoAssemblyName *
902 mono_assembly_remap_version (MonoAssemblyName *aname, MonoAssemblyName *dest_aname)
903 {
904         const MonoRuntimeInfo *current_runtime;
905         int pos, first, last;
906
907         if (aname->name == NULL) return aname;
908
909         current_runtime = mono_get_runtime_info ();
910
911         if (aname->flags & ASSEMBLYREF_RETARGETABLE_FLAG) {
912                 const AssemblyVersionSet* vset;
913
914                 /* Remap to current runtime */
915                 vset = &current_runtime->version_sets [0];
916
917                 memcpy (dest_aname, aname, sizeof(MonoAssemblyName));
918                 dest_aname->major = vset->major;
919                 dest_aname->minor = vset->minor;
920                 dest_aname->build = vset->build;
921                 dest_aname->revision = vset->revision;
922                 dest_aname->flags &= ~ASSEMBLYREF_RETARGETABLE_FLAG;
923
924                 /* Remap assembly name */
925                 if (!strcmp (aname->name, "System.Net"))
926                         dest_aname->name = g_strdup ("System");
927                 
928                 remap_keys (dest_aname);
929
930                 mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_ASSEMBLY,
931                                         "The request to load the retargetable assembly %s v%d.%d.%d.%d was remapped to %s v%d.%d.%d.%d",
932                                         aname->name,
933                                         aname->major, aname->minor, aname->build, aname->revision,
934                                         dest_aname->name,
935                                         vset->major, vset->minor, vset->build, vset->revision
936                                         );
937
938                 return dest_aname;
939         }
940         
941 #ifndef DISABLE_ASSEMBLY_REMAPPING
942         first = 0;
943         last = G_N_ELEMENTS (framework_assemblies) - 1;
944         
945         while (first <= last) {
946                 int res;
947                 pos = first + (last - first) / 2;
948                 res = strcmp (aname->name, framework_assemblies[pos].assembly_name);
949                 if (res == 0) {
950                         const AssemblyVersionSet* vset;
951                         int index = framework_assemblies[pos].version_set_index;
952                         g_assert (index < G_N_ELEMENTS (current_runtime->version_sets));
953                         vset = &current_runtime->version_sets [index];
954
955                         if (aname->major == vset->major && aname->minor == vset->minor &&
956                                 aname->build == vset->build && aname->revision == vset->revision)
957                                 return aname;
958                 
959                         if ((aname->major | aname->minor | aname->build | aname->revision) != 0)
960                                 mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_ASSEMBLY,
961                                         "The request to load the assembly %s v%d.%d.%d.%d was remapped to v%d.%d.%d.%d",
962                                                         aname->name,
963                                                         aname->major, aname->minor, aname->build, aname->revision,
964                                                         vset->major, vset->minor, vset->build, vset->revision
965                                                         );
966                         
967                         memcpy (dest_aname, aname, sizeof(MonoAssemblyName));
968                         dest_aname->major = vset->major;
969                         dest_aname->minor = vset->minor;
970                         dest_aname->build = vset->build;
971                         dest_aname->revision = vset->revision;
972                         return dest_aname;
973                 } else if (res < 0) {
974                         last = pos - 1;
975                 } else {
976                         first = pos + 1;
977                 }
978         }
979 #endif
980
981         return aname;
982 }
983
984 /*
985  * mono_assembly_get_assemblyref:
986  *
987  *   Fill out ANAME with the assembly name of the INDEXth assembly reference in IMAGE.
988  */
989 void
990 mono_assembly_get_assemblyref (MonoImage *image, int index, MonoAssemblyName *aname)
991 {
992         MonoTableInfo *t;
993         guint32 cols [MONO_ASSEMBLYREF_SIZE];
994         const char *hash;
995
996         t = &image->tables [MONO_TABLE_ASSEMBLYREF];
997
998         mono_metadata_decode_row (t, index, cols, MONO_ASSEMBLYREF_SIZE);
999                 
1000         hash = mono_metadata_blob_heap (image, cols [MONO_ASSEMBLYREF_HASH_VALUE]);
1001         aname->hash_len = mono_metadata_decode_blob_size (hash, &hash);
1002         aname->hash_value = hash;
1003         aname->name = mono_metadata_string_heap (image, cols [MONO_ASSEMBLYREF_NAME]);
1004         aname->culture = mono_metadata_string_heap (image, cols [MONO_ASSEMBLYREF_CULTURE]);
1005         aname->flags = cols [MONO_ASSEMBLYREF_FLAGS];
1006         aname->major = cols [MONO_ASSEMBLYREF_MAJOR_VERSION];
1007         aname->minor = cols [MONO_ASSEMBLYREF_MINOR_VERSION];
1008         aname->build = cols [MONO_ASSEMBLYREF_BUILD_NUMBER];
1009         aname->revision = cols [MONO_ASSEMBLYREF_REV_NUMBER];
1010
1011         if (cols [MONO_ASSEMBLYREF_PUBLIC_KEY]) {
1012                 gchar *token = assemblyref_public_tok (image, cols [MONO_ASSEMBLYREF_PUBLIC_KEY], aname->flags);
1013                 g_strlcpy ((char*)aname->public_key_token, token, MONO_PUBLIC_KEY_TOKEN_LENGTH);
1014                 g_free (token);
1015         } else {
1016                 memset (aname->public_key_token, 0, MONO_PUBLIC_KEY_TOKEN_LENGTH);
1017         }
1018 }
1019
1020 void
1021 mono_assembly_load_reference (MonoImage *image, int index)
1022 {
1023         MonoAssembly *reference;
1024         MonoAssemblyName aname;
1025         MonoImageOpenStatus status;
1026
1027         /*
1028          * image->references is shared between threads, so we need to access
1029          * it inside a critical section.
1030          */
1031         mono_assemblies_lock ();
1032         if (!image->references) {
1033                 MonoTableInfo *t = &image->tables [MONO_TABLE_ASSEMBLYREF];
1034         
1035                 image->references = g_new0 (MonoAssembly *, t->rows + 1);
1036                 image->nreferences = t->rows;
1037         }
1038         reference = image->references [index];
1039         mono_assemblies_unlock ();
1040         if (reference)
1041                 return;
1042
1043         mono_assembly_get_assemblyref (image, index, &aname);
1044
1045         if (image->assembly && image->assembly->ref_only) {
1046                 /* We use the loaded corlib */
1047                 if (!strcmp (aname.name, "mscorlib"))
1048                         reference = mono_assembly_load_full (&aname, image->assembly->basedir, &status, FALSE);
1049                 else {
1050                         reference = mono_assembly_loaded_full (&aname, TRUE);
1051                         if (!reference)
1052                                 /* Try a postload search hook */
1053                                 reference = mono_assembly_invoke_search_hook_internal (&aname, TRUE, TRUE);
1054                 }
1055
1056                 /*
1057                  * Here we must advice that the error was due to
1058                  * a non loaded reference using the ReflectionOnly api
1059                 */
1060                 if (!reference)
1061                         reference = REFERENCE_MISSING;
1062         } else
1063                 reference = mono_assembly_load (&aname, image->assembly? image->assembly->basedir: NULL, &status);
1064
1065         if (reference == NULL){
1066                 char *extra_msg;
1067
1068                 if (status == MONO_IMAGE_ERROR_ERRNO && errno == ENOENT) {
1069                         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 : "" );
1070                 } else if (status == MONO_IMAGE_ERROR_ERRNO) {
1071                         extra_msg = g_strdup_printf ("System error: %s\n", strerror (errno));
1072                 } else if (status == MONO_IMAGE_MISSING_ASSEMBLYREF) {
1073                         extra_msg = g_strdup ("Cannot find an assembly referenced from this one.\n");
1074                 } else if (status == MONO_IMAGE_IMAGE_INVALID) {
1075                         extra_msg = g_strdup ("The file exists but is not a valid assembly.\n");
1076                 } else {
1077                         extra_msg = g_strdup ("");
1078                 }
1079                 
1080                 mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_ASSEMBLY, "The following assembly referenced from %s could not be loaded:\n"
1081                                    "     Assembly:   %s    (assemblyref_index=%d)\n"
1082                                    "     Version:    %d.%d.%d.%d\n"
1083                                    "     Public Key: %s\n%s",
1084                                    image->name, aname.name, index,
1085                                    aname.major, aname.minor, aname.build, aname.revision,
1086                                    strlen ((char*)aname.public_key_token) == 0 ? "(none)" : (char*)aname.public_key_token, extra_msg);
1087                 g_free (extra_msg);
1088         }
1089
1090         mono_assemblies_lock ();
1091         if (reference == NULL) {
1092                 /* Flag as not found */
1093                 reference = REFERENCE_MISSING;
1094         }       
1095
1096         if (!image->references [index]) {
1097                 if (reference != REFERENCE_MISSING){
1098                         mono_assembly_addref (reference);
1099                         if (image->assembly)
1100                                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_ASSEMBLY, "Assembly Ref addref %s[%p] -> %s[%p]: %d",
1101                                     image->assembly->aname.name, image->assembly, reference->aname.name, reference, reference->ref_count);
1102                 } else {
1103                         if (image->assembly)
1104                                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_ASSEMBLY, "Failed to load assembly %s[%p]\n",
1105                                     image->assembly->aname.name, image->assembly);
1106                 }
1107                 
1108                 image->references [index] = reference;
1109         }
1110         mono_assemblies_unlock ();
1111
1112         if (image->references [index] != reference) {
1113                 /* Somebody loaded it before us */
1114                 mono_assembly_close (reference);
1115         }
1116 }
1117
1118 void
1119 mono_assembly_load_references (MonoImage *image, MonoImageOpenStatus *status)
1120 {
1121         /* This is a no-op now but it is part of the embedding API so we can't remove it */
1122         *status = MONO_IMAGE_OK;
1123 }
1124
1125 typedef struct AssemblyLoadHook AssemblyLoadHook;
1126 struct AssemblyLoadHook {
1127         AssemblyLoadHook *next;
1128         MonoAssemblyLoadFunc func;
1129         gpointer user_data;
1130 };
1131
1132 AssemblyLoadHook *assembly_load_hook = NULL;
1133
1134 void
1135 mono_assembly_invoke_load_hook (MonoAssembly *ass)
1136 {
1137         AssemblyLoadHook *hook;
1138
1139         for (hook = assembly_load_hook; hook; hook = hook->next) {
1140                 hook->func (ass, hook->user_data);
1141         }
1142 }
1143
1144 void
1145 mono_install_assembly_load_hook (MonoAssemblyLoadFunc func, gpointer user_data)
1146 {
1147         AssemblyLoadHook *hook;
1148         
1149         g_return_if_fail (func != NULL);
1150
1151         hook = g_new0 (AssemblyLoadHook, 1);
1152         hook->func = func;
1153         hook->user_data = user_data;
1154         hook->next = assembly_load_hook;
1155         assembly_load_hook = hook;
1156 }
1157
1158 static void
1159 free_assembly_load_hooks (void)
1160 {
1161         AssemblyLoadHook *hook, *next;
1162
1163         for (hook = assembly_load_hook; hook; hook = next) {
1164                 next = hook->next;
1165                 g_free (hook);
1166         }
1167 }
1168
1169 typedef struct AssemblySearchHook AssemblySearchHook;
1170 struct AssemblySearchHook {
1171         AssemblySearchHook *next;
1172         MonoAssemblySearchFunc func;
1173         gboolean refonly;
1174         gboolean postload;
1175         gpointer user_data;
1176 };
1177
1178 AssemblySearchHook *assembly_search_hook = NULL;
1179
1180 static MonoAssembly*
1181 mono_assembly_invoke_search_hook_internal (MonoAssemblyName *aname, gboolean refonly, gboolean postload)
1182 {
1183         AssemblySearchHook *hook;
1184
1185         for (hook = assembly_search_hook; hook; hook = hook->next) {
1186                 if ((hook->refonly == refonly) && (hook->postload == postload)) {
1187                         MonoAssembly *ass = hook->func (aname, hook->user_data);
1188                         if (ass)
1189                                 return ass;
1190                 }
1191         }
1192
1193         return NULL;
1194 }
1195
1196 MonoAssembly*
1197 mono_assembly_invoke_search_hook (MonoAssemblyName *aname)
1198 {
1199         return mono_assembly_invoke_search_hook_internal (aname, FALSE, FALSE);
1200 }
1201
1202 static void
1203 mono_install_assembly_search_hook_internal (MonoAssemblySearchFunc func, gpointer user_data, gboolean refonly, gboolean postload)
1204 {
1205         AssemblySearchHook *hook;
1206         
1207         g_return_if_fail (func != NULL);
1208
1209         hook = g_new0 (AssemblySearchHook, 1);
1210         hook->func = func;
1211         hook->user_data = user_data;
1212         hook->refonly = refonly;
1213         hook->postload = postload;
1214         hook->next = assembly_search_hook;
1215         assembly_search_hook = hook;
1216 }
1217
1218 void          
1219 mono_install_assembly_search_hook (MonoAssemblySearchFunc func, gpointer user_data)
1220 {
1221         mono_install_assembly_search_hook_internal (func, user_data, FALSE, FALSE);
1222 }       
1223
1224 static void
1225 free_assembly_search_hooks (void)
1226 {
1227         AssemblySearchHook *hook, *next;
1228
1229         for (hook = assembly_search_hook; hook; hook = next) {
1230                 next = hook->next;
1231                 g_free (hook);
1232         }
1233 }
1234
1235 void
1236 mono_install_assembly_refonly_search_hook (MonoAssemblySearchFunc func, gpointer user_data)
1237 {
1238         mono_install_assembly_search_hook_internal (func, user_data, TRUE, FALSE);
1239 }
1240
1241 void          
1242 mono_install_assembly_postload_search_hook (MonoAssemblySearchFunc func, gpointer user_data)
1243 {
1244         mono_install_assembly_search_hook_internal (func, user_data, FALSE, TRUE);
1245 }       
1246
1247 void
1248 mono_install_assembly_postload_refonly_search_hook (MonoAssemblySearchFunc func, gpointer user_data)
1249 {
1250         mono_install_assembly_search_hook_internal (func, user_data, TRUE, TRUE);
1251 }
1252
1253 typedef struct AssemblyPreLoadHook AssemblyPreLoadHook;
1254 struct AssemblyPreLoadHook {
1255         AssemblyPreLoadHook *next;
1256         MonoAssemblyPreLoadFunc func;
1257         gpointer user_data;
1258 };
1259
1260 static AssemblyPreLoadHook *assembly_preload_hook = NULL;
1261 static AssemblyPreLoadHook *assembly_refonly_preload_hook = NULL;
1262
1263 static MonoAssembly *
1264 invoke_assembly_preload_hook (MonoAssemblyName *aname, gchar **assemblies_path)
1265 {
1266         AssemblyPreLoadHook *hook;
1267         MonoAssembly *assembly;
1268
1269         for (hook = assembly_preload_hook; hook; hook = hook->next) {
1270                 assembly = hook->func (aname, assemblies_path, hook->user_data);
1271                 if (assembly != NULL)
1272                         return assembly;
1273         }
1274
1275         return NULL;
1276 }
1277
1278 static MonoAssembly *
1279 invoke_assembly_refonly_preload_hook (MonoAssemblyName *aname, gchar **assemblies_path)
1280 {
1281         AssemblyPreLoadHook *hook;
1282         MonoAssembly *assembly;
1283
1284         for (hook = assembly_refonly_preload_hook; hook; hook = hook->next) {
1285                 assembly = hook->func (aname, assemblies_path, hook->user_data);
1286                 if (assembly != NULL)
1287                         return assembly;
1288         }
1289
1290         return NULL;
1291 }
1292
1293 void
1294 mono_install_assembly_preload_hook (MonoAssemblyPreLoadFunc func, gpointer user_data)
1295 {
1296         AssemblyPreLoadHook *hook;
1297         
1298         g_return_if_fail (func != NULL);
1299
1300         hook = g_new0 (AssemblyPreLoadHook, 1);
1301         hook->func = func;
1302         hook->user_data = user_data;
1303         hook->next = assembly_preload_hook;
1304         assembly_preload_hook = hook;
1305 }
1306
1307 void
1308 mono_install_assembly_refonly_preload_hook (MonoAssemblyPreLoadFunc func, gpointer user_data)
1309 {
1310         AssemblyPreLoadHook *hook;
1311         
1312         g_return_if_fail (func != NULL);
1313
1314         hook = g_new0 (AssemblyPreLoadHook, 1);
1315         hook->func = func;
1316         hook->user_data = user_data;
1317         hook->next = assembly_refonly_preload_hook;
1318         assembly_refonly_preload_hook = hook;
1319 }
1320
1321 static void
1322 free_assembly_preload_hooks (void)
1323 {
1324         AssemblyPreLoadHook *hook, *next;
1325
1326         for (hook = assembly_preload_hook; hook; hook = next) {
1327                 next = hook->next;
1328                 g_free (hook);
1329         }
1330
1331         for (hook = assembly_refonly_preload_hook; hook; hook = next) {
1332                 next = hook->next;
1333                 g_free (hook);
1334         }
1335 }
1336
1337 static gchar *
1338 absolute_dir (const gchar *filename)
1339 {
1340         gchar *cwd;
1341         gchar *mixed;
1342         gchar **parts;
1343         gchar *part;
1344         GList *list, *tmp;
1345         GString *result;
1346         gchar *res;
1347         gint i;
1348
1349         if (g_path_is_absolute (filename)) {
1350                 part = g_path_get_dirname (filename);
1351                 res = g_strconcat (part, G_DIR_SEPARATOR_S, NULL);
1352                 g_free (part);
1353                 return res;
1354         }
1355
1356         cwd = g_get_current_dir ();
1357         mixed = g_build_filename (cwd, filename, NULL);
1358         parts = g_strsplit (mixed, G_DIR_SEPARATOR_S, 0);
1359         g_free (mixed);
1360         g_free (cwd);
1361
1362         list = NULL;
1363         for (i = 0; (part = parts [i]) != NULL; i++) {
1364                 if (!strcmp (part, "."))
1365                         continue;
1366
1367                 if (!strcmp (part, "..")) {
1368                         if (list && list->next) /* Don't remove root */
1369                                 list = g_list_delete_link (list, list);
1370                 } else {
1371                         list = g_list_prepend (list, part);
1372                 }
1373         }
1374
1375         result = g_string_new ("");
1376         list = g_list_reverse (list);
1377
1378         /* Ignores last data pointer, which should be the filename */
1379         for (tmp = list; tmp && tmp->next != NULL; tmp = tmp->next){
1380                 if (tmp->data)
1381                         g_string_append_printf (result, "%s%c", (char *) tmp->data,
1382                                                                 G_DIR_SEPARATOR);
1383         }
1384
1385         res = result->str;
1386         g_string_free (result, FALSE);
1387         g_list_free (list);
1388         g_strfreev (parts);
1389         if (*res == '\0') {
1390                 g_free (res);
1391                 return g_strdup (".");
1392         }
1393
1394         return res;
1395 }
1396
1397 /** 
1398  * mono_assembly_open_from_bundle:
1399  * @filename: Filename requested
1400  * @status: return value
1401  *
1402  * This routine tries to open the assembly specified by `filename' from the
1403  * defined bundles, if found, returns the MonoImage for it, if not found
1404  * returns NULL
1405  */
1406 MonoImage *
1407 mono_assembly_open_from_bundle (const char *filename, MonoImageOpenStatus *status, gboolean refonly)
1408 {
1409         int i;
1410         char *name;
1411         MonoImage *image = NULL;
1412
1413         /*
1414          * we do a very simple search for bundled assemblies: it's not a general 
1415          * purpose assembly loading mechanism.
1416          */
1417
1418         if (!bundles)
1419                 return NULL;
1420
1421         name = g_path_get_basename (filename);
1422
1423         mono_assemblies_lock ();
1424         for (i = 0; !image && bundles [i]; ++i) {
1425                 if (strcmp (bundles [i]->name, name) == 0) {
1426                         image = mono_image_open_from_data_with_name ((char*)bundles [i]->data, bundles [i]->size, FALSE, status, refonly, name);
1427                         break;
1428                 }
1429         }
1430         mono_assemblies_unlock ();
1431         g_free (name);
1432         if (image) {
1433                 mono_image_addref (image);
1434                 return image;
1435         }
1436         return NULL;
1437 }
1438
1439 MonoAssembly *
1440 mono_assembly_open_full (const char *filename, MonoImageOpenStatus *status, gboolean refonly)
1441 {
1442         MonoImage *image;
1443         MonoAssembly *ass;
1444         MonoImageOpenStatus def_status;
1445         gchar *fname;
1446         gchar *new_fname;
1447         
1448         g_return_val_if_fail (filename != NULL, NULL);
1449
1450         if (!status)
1451                 status = &def_status;
1452         *status = MONO_IMAGE_OK;
1453
1454         if (strncmp (filename, "file://", 7) == 0) {
1455                 GError *error = NULL;
1456                 gchar *uri = (gchar *) filename;
1457                 gchar *tmpuri;
1458
1459                 /*
1460                  * MS allows file://c:/... and fails on file://localhost/c:/... 
1461                  * They also throw an IndexOutOfRangeException if "file://"
1462                  */
1463                 if (uri [7] != '/')
1464                         uri = g_strdup_printf ("file:///%s", uri + 7);
1465         
1466                 tmpuri = uri;
1467                 uri = mono_escape_uri_string (tmpuri);
1468                 fname = g_filename_from_uri (uri, NULL, &error);
1469                 g_free (uri);
1470
1471                 if (tmpuri != filename)
1472                         g_free (tmpuri);
1473
1474                 if (error != NULL) {
1475                         g_warning ("%s\n", error->message);
1476                         g_error_free (error);
1477                         fname = g_strdup (filename);
1478                 }
1479         } else {
1480                 fname = g_strdup (filename);
1481         }
1482
1483         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_ASSEMBLY,
1484                         "Assembly Loader probing location: '%s'.", fname);
1485
1486         new_fname = NULL;
1487         if (!mono_assembly_is_in_gac (fname))
1488                 new_fname = mono_make_shadow_copy (fname);
1489         if (new_fname && new_fname != fname) {
1490                 g_free (fname);
1491                 fname = new_fname;
1492                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_ASSEMBLY,
1493                             "Assembly Loader shadow-copied assembly to: '%s'.", fname);
1494         }
1495         
1496         image = NULL;
1497
1498         if (bundles != NULL)
1499                 image = mono_assembly_open_from_bundle (fname, status, refonly);
1500
1501         if (!image)
1502                 image = mono_image_open_full (fname, status, refonly);
1503
1504         if (!image){
1505                 if (*status == MONO_IMAGE_OK)
1506                         *status = MONO_IMAGE_ERROR_ERRNO;
1507                 g_free (fname);
1508                 return NULL;
1509         }
1510
1511         if (image->assembly) {
1512                 /* Already loaded by another appdomain */
1513                 mono_assembly_invoke_load_hook (image->assembly);
1514                 mono_image_close (image);
1515                 g_free (fname);
1516                 return image->assembly;
1517         }
1518
1519         ass = mono_assembly_load_from_full (image, fname, status, refonly);
1520
1521         if (ass) {
1522                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_ASSEMBLY,
1523                                 "Assembly Loader loaded assembly from location: '%s'.", filename);
1524                 if (!refonly)
1525                         mono_config_for_assembly (ass->image);
1526         }
1527
1528         /* Clear the reference added by mono_image_open */
1529         mono_image_close (image);
1530         
1531         g_free (fname);
1532
1533         return ass;
1534 }
1535
1536 static void
1537 free_item (gpointer val, gpointer user_data)
1538 {
1539         g_free (val);
1540 }
1541
1542 /*
1543  * mono_assembly_load_friends:
1544  * @ass: an assembly
1545  *
1546  * Load the list of friend assemblies that are allowed to access
1547  * the assembly's internal types and members. They are stored as assembly
1548  * names in custom attributes.
1549  *
1550  * This is an internal method, we need this because when we load mscorlib
1551  * we do not have the mono_defaults.internals_visible_class loaded yet,
1552  * so we need to load these after we initialize the runtime. 
1553  *
1554  * LOCKING: Acquires the assemblies lock plus the loader lock.
1555  */
1556 void
1557 mono_assembly_load_friends (MonoAssembly* ass)
1558 {
1559         int i;
1560         MonoCustomAttrInfo* attrs;
1561         GSList *list;
1562
1563         if (ass->friend_assembly_names_inited)
1564                 return;
1565
1566         attrs = mono_custom_attrs_from_assembly (ass);
1567         if (!attrs) {
1568                 mono_assemblies_lock ();
1569                 ass->friend_assembly_names_inited = TRUE;
1570                 mono_assemblies_unlock ();
1571                 return;
1572         }
1573
1574         mono_assemblies_lock ();
1575         if (ass->friend_assembly_names_inited) {
1576                 mono_assemblies_unlock ();
1577                 return;
1578         }
1579         mono_assemblies_unlock ();
1580
1581         list = NULL;
1582         /* 
1583          * We build the list outside the assemblies lock, the worse that can happen
1584          * is that we'll need to free the allocated list.
1585          */
1586         for (i = 0; i < attrs->num_attrs; ++i) {
1587                 MonoCustomAttrEntry *attr = &attrs->attrs [i];
1588                 MonoAssemblyName *aname;
1589                 const gchar *data;
1590                 guint slen;
1591                 /* Do some sanity checking */
1592                 if (!attr->ctor || attr->ctor->klass != mono_defaults.internals_visible_class)
1593                         continue;
1594                 if (attr->data_size < 4)
1595                         continue;
1596                 data = (const char*)attr->data;
1597                 /* 0xFF means null string, see custom attr format */
1598                 if (data [0] != 1 || data [1] != 0 || (data [2] & 0xFF) == 0xFF)
1599                         continue;
1600                 slen = mono_metadata_decode_value (data + 2, &data);
1601                 aname = g_new0 (MonoAssemblyName, 1);
1602                 /*g_print ("friend ass: %s\n", data);*/
1603                 if (mono_assembly_name_parse_full (data, aname, TRUE, NULL, NULL)) {
1604                         list = g_slist_prepend (list, aname);
1605                 } else {
1606                         g_free (aname);
1607                 }
1608         }
1609         mono_custom_attrs_free (attrs);
1610
1611         mono_assemblies_lock ();
1612         if (ass->friend_assembly_names_inited) {
1613                 mono_assemblies_unlock ();
1614                 g_slist_foreach (list, free_item, NULL);
1615                 g_slist_free (list);
1616                 return;
1617         }
1618         ass->friend_assembly_names = list;
1619
1620         /* Because of the double checked locking pattern above */
1621         mono_memory_barrier ();
1622         ass->friend_assembly_names_inited = TRUE;
1623         mono_assemblies_unlock ();
1624 }
1625
1626 /**
1627  * mono_assembly_open:
1628  * @filename: Opens the assembly pointed out by this name
1629  * @status: where a status code can be returned
1630  *
1631  * mono_assembly_open opens the PE-image pointed by @filename, and
1632  * loads any external assemblies referenced by it.
1633  *
1634  * Return: a pointer to the MonoAssembly if @filename contains a valid
1635  * assembly or NULL on error.  Details about the error are stored in the
1636  * @status variable.
1637  */
1638 MonoAssembly *
1639 mono_assembly_open (const char *filename, MonoImageOpenStatus *status)
1640 {
1641         return mono_assembly_open_full (filename, status, FALSE);
1642 }
1643
1644 MonoAssembly *
1645 mono_assembly_load_from_full (MonoImage *image, const char*fname, 
1646                               MonoImageOpenStatus *status, gboolean refonly)
1647 {
1648         MonoAssembly *ass, *ass2;
1649         char *base_dir;
1650
1651         if (!image->tables [MONO_TABLE_ASSEMBLY].rows) {
1652                 /* 'image' doesn't have a manifest -- maybe someone is trying to Assembly.Load a .netmodule */
1653                 *status = MONO_IMAGE_IMAGE_INVALID;
1654                 return NULL;
1655         }
1656
1657 #if defined (HOST_WIN32)
1658         {
1659                 gchar *tmp_fn;
1660                 int i;
1661
1662                 tmp_fn = g_strdup (fname);
1663                 for (i = strlen (tmp_fn) - 1; i >= 0; i--) {
1664                         if (tmp_fn [i] == '/')
1665                                 tmp_fn [i] = '\\';
1666                 }
1667
1668                 base_dir = absolute_dir (tmp_fn);
1669                 g_free (tmp_fn);
1670         }
1671 #else
1672         base_dir = absolute_dir (fname);
1673 #endif
1674
1675         /*
1676          * Create assembly struct, and enter it into the assembly cache
1677          */
1678         ass = g_new0 (MonoAssembly, 1);
1679         ass->basedir = base_dir;
1680         ass->ref_only = refonly;
1681         ass->image = image;
1682
1683         mono_profiler_assembly_event (ass, MONO_PROFILE_START_LOAD);
1684
1685         mono_assembly_fill_assembly_name (image, &ass->aname);
1686
1687         if (mono_defaults.corlib && strcmp (ass->aname.name, "mscorlib") == 0) {
1688                 // MS.NET doesn't support loading other mscorlibs
1689                 g_free (ass);
1690                 g_free (base_dir);
1691                 mono_image_addref (mono_defaults.corlib);
1692                 *status = MONO_IMAGE_OK;
1693                 return mono_defaults.corlib->assembly;
1694         }
1695
1696         /* Add a non-temporary reference because of ass->image */
1697         mono_image_addref (image);
1698
1699         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);
1700
1701         /* 
1702          * The load hooks might take locks so we can't call them while holding the
1703          * assemblies lock.
1704          */
1705         if (ass->aname.name) {
1706                 ass2 = mono_assembly_invoke_search_hook_internal (&ass->aname, refonly, FALSE);
1707                 if (ass2) {
1708                         g_free (ass);
1709                         g_free (base_dir);
1710                         mono_image_close (image);
1711                         *status = MONO_IMAGE_OK;
1712                         return ass2;
1713                 }
1714         }
1715
1716         mono_assemblies_lock ();
1717
1718         if (image->assembly) {
1719                 /* 
1720                  * This means another thread has already loaded the assembly, but not yet
1721                  * called the load hooks so the search hook can't find the assembly.
1722                  */
1723                 mono_assemblies_unlock ();
1724                 ass2 = image->assembly;
1725                 g_free (ass);
1726                 g_free (base_dir);
1727                 mono_image_close (image);
1728                 *status = MONO_IMAGE_OK;
1729                 return ass2;
1730         }
1731
1732         image->assembly = ass;
1733
1734         loaded_assemblies = g_list_prepend (loaded_assemblies, ass);
1735         mono_assemblies_unlock ();
1736
1737 #ifdef HOST_WIN32
1738         if (image->is_module_handle)
1739                 mono_image_fixup_vtable (image);
1740 #endif
1741
1742         mono_assembly_invoke_load_hook (ass);
1743
1744         mono_profiler_assembly_loaded (ass, MONO_PROFILE_OK);
1745         
1746         return ass;
1747 }
1748
1749 MonoAssembly *
1750 mono_assembly_load_from (MonoImage *image, const char *fname,
1751                          MonoImageOpenStatus *status)
1752 {
1753         return mono_assembly_load_from_full (image, fname, status, FALSE);
1754 }
1755
1756 /**
1757  * mono_assembly_name_free:
1758  * @aname: assembly name to free
1759  * 
1760  * Frees the provided assembly name object.
1761  * (it does not frees the object itself, only the name members).
1762  */
1763 void
1764 mono_assembly_name_free (MonoAssemblyName *aname)
1765 {
1766         if (aname == NULL)
1767                 return;
1768
1769         g_free ((void *) aname->name);
1770         g_free ((void *) aname->culture);
1771         g_free ((void *) aname->hash_value);
1772 }
1773
1774 static gboolean
1775 parse_public_key (const gchar *key, gchar** pubkey, gboolean *is_ecma)
1776 {
1777         const gchar *pkey;
1778         gchar header [16], val, *arr;
1779         gint i, j, offset, bitlen, keylen, pkeylen;
1780         
1781         keylen = strlen (key) >> 1;
1782         if (keylen < 1)
1783                 return FALSE;
1784
1785         /* allow the ECMA standard key */
1786         if (strcmp (key, "00000000000000000400000000000000") == 0) {
1787                 if (pubkey) {
1788                         *pubkey = g_strdup (key);
1789                         *is_ecma = TRUE;
1790                 }
1791                 return TRUE;
1792         }
1793         *is_ecma = FALSE;
1794         val = g_ascii_xdigit_value (key [0]) << 4;
1795         val |= g_ascii_xdigit_value (key [1]);
1796         switch (val) {
1797                 case 0x00:
1798                         if (keylen < 13)
1799                                 return FALSE;
1800                         val = g_ascii_xdigit_value (key [24]);
1801                         val |= g_ascii_xdigit_value (key [25]);
1802                         if (val != 0x06)
1803                                 return FALSE;
1804                         pkey = key + 24;
1805                         break;
1806                 case 0x06:
1807                         pkey = key;
1808                         break;
1809                 default:
1810                         return FALSE;
1811         }
1812                 
1813         /* We need the first 16 bytes
1814         * to check whether this key is valid or not */
1815         pkeylen = strlen (pkey) >> 1;
1816         if (pkeylen < 16)
1817                 return FALSE;
1818                 
1819         for (i = 0, j = 0; i < 16; i++) {
1820                 header [i] = g_ascii_xdigit_value (pkey [j++]) << 4;
1821                 header [i] |= g_ascii_xdigit_value (pkey [j++]);
1822         }
1823
1824         if (header [0] != 0x06 || /* PUBLICKEYBLOB (0x06) */
1825                         header [1] != 0x02 || /* Version (0x02) */
1826                         header [2] != 0x00 || /* Reserved (word) */
1827                         header [3] != 0x00 ||
1828                         (guint)(read32 (header + 8)) != 0x31415352) /* DWORD magic = RSA1 */
1829                 return FALSE;
1830
1831         /* Based on this length, we _should_ be able to know if the length is right */
1832         bitlen = read32 (header + 12) >> 3;
1833         if ((bitlen + 16 + 4) != pkeylen)
1834                 return FALSE;
1835
1836         /* parsing is OK and the public key itself is not requested back */
1837         if (!pubkey)
1838                 return TRUE;
1839                 
1840         /* Encode the size of the blob */
1841         offset = 0;
1842         if (keylen <= 127) {
1843                 arr = g_malloc (keylen + 1);
1844                 arr [offset++] = keylen;
1845         } else {
1846                 arr = g_malloc (keylen + 2);
1847                 arr [offset++] = 0x80; /* 10bs */
1848                 arr [offset++] = keylen;
1849         }
1850                 
1851         for (i = offset, j = 0; i < keylen + offset; i++) {
1852                 arr [i] = g_ascii_xdigit_value (key [j++]) << 4;
1853                 arr [i] |= g_ascii_xdigit_value (key [j++]);
1854         }
1855
1856         *pubkey = arr;
1857
1858         return TRUE;
1859 }
1860
1861 static gboolean
1862 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)
1863 {
1864         gint major, minor, build, revision;
1865         gint len;
1866         gint version_parts;
1867         gchar *pkey, *pkeyptr, *encoded, tok [8];
1868
1869         memset (aname, 0, sizeof (MonoAssemblyName));
1870
1871         if (version) {
1872                 version_parts = sscanf (version, "%u.%u.%u.%u", &major, &minor, &build, &revision);
1873                 if (version_parts < 2 || version_parts > 4)
1874                         return FALSE;
1875
1876                 /* FIXME: we should set build & revision to -1 (instead of 0)
1877                 if these are not set in the version string. That way, later on,
1878                 we can still determine if these were specified. */
1879                 aname->major = major;
1880                 aname->minor = minor;
1881                 if (version_parts >= 3)
1882                         aname->build = build;
1883                 else
1884                         aname->build = 0;
1885                 if (version_parts == 4)
1886                         aname->revision = revision;
1887                 else
1888                         aname->revision = 0;
1889         }
1890         
1891         aname->flags = flags;
1892         aname->arch = arch;
1893         aname->name = g_strdup (name);
1894         
1895         if (culture) {
1896                 if (g_ascii_strcasecmp (culture, "neutral") == 0)
1897                         aname->culture = g_strdup ("");
1898                 else
1899                         aname->culture = g_strdup (culture);
1900         }
1901         
1902         if (token && strncmp (token, "null", 4) != 0) {
1903                 char *lower;
1904
1905                 /* the constant includes the ending NULL, hence the -1 */
1906                 if (strlen (token) != (MONO_PUBLIC_KEY_TOKEN_LENGTH - 1)) {
1907                         mono_assembly_name_free (aname);
1908                         return FALSE;
1909                 }
1910                 lower = g_ascii_strdown (token, MONO_PUBLIC_KEY_TOKEN_LENGTH);
1911                 g_strlcpy ((char*)aname->public_key_token, lower, MONO_PUBLIC_KEY_TOKEN_LENGTH);
1912                 g_free (lower);
1913         }
1914
1915         if (key) {
1916                 gboolean is_ecma;
1917                 if (strcmp (key, "null") == 0 || !parse_public_key (key, &pkey, &is_ecma)) {
1918                         mono_assembly_name_free (aname);
1919                         return FALSE;
1920                 }
1921
1922                 if (is_ecma) {
1923                         if (save_public_key)
1924                                 aname->public_key = (guint8*)pkey;
1925                         else
1926                                 g_free (pkey);
1927                         g_strlcpy ((gchar*)aname->public_key_token, "b77a5c561934e089", MONO_PUBLIC_KEY_TOKEN_LENGTH);
1928                         return TRUE;
1929                 }
1930                 
1931                 len = mono_metadata_decode_blob_size ((const gchar *) pkey, (const gchar **) &pkeyptr);
1932                 // We also need to generate the key token
1933                 mono_digest_get_public_token ((guchar*) tok, (guint8*) pkeyptr, len);
1934                 encoded = encode_public_tok ((guchar*) tok, 8);
1935                 g_strlcpy ((gchar*)aname->public_key_token, encoded, MONO_PUBLIC_KEY_TOKEN_LENGTH);
1936                 g_free (encoded);
1937
1938                 if (save_public_key)
1939                         aname->public_key = (guint8*) pkey;
1940                 else
1941                         g_free (pkey);
1942         }
1943
1944         return TRUE;
1945 }
1946
1947 static gboolean
1948 parse_assembly_directory_name (const char *name, const char *dirname, MonoAssemblyName *aname)
1949 {
1950         gchar **parts;
1951         gboolean res;
1952         
1953         parts = g_strsplit (dirname, "_", 3);
1954         if (!parts || !parts[0] || !parts[1] || !parts[2]) {
1955                 g_strfreev (parts);
1956                 return FALSE;
1957         }
1958         
1959         res = build_assembly_name (name, parts[0], parts[1], parts[2], NULL, 0, 0, aname, FALSE);
1960         g_strfreev (parts);
1961         return res;
1962 }
1963
1964 static gboolean
1965 split_key_value (const gchar *pair, gchar **key, guint32 *keylen, gchar **value)
1966 {
1967         char *eqsign = strchr (pair, '=');
1968         if (!eqsign) {
1969                 *key = NULL;
1970                 *keylen = 0;
1971                 *value = NULL;
1972                 return FALSE;
1973         }
1974
1975         *key = (gchar*)pair;
1976         *keylen = eqsign - *key;
1977         while (*keylen > 0 && g_ascii_isspace ((*key) [*keylen - 1]))
1978                 (*keylen)--;
1979         *value = g_strstrip (eqsign + 1);
1980         return TRUE;
1981 }
1982
1983 gboolean
1984 mono_assembly_name_parse_full (const char *name, MonoAssemblyName *aname, gboolean save_public_key, gboolean *is_version_defined, gboolean *is_token_defined)
1985 {
1986         gchar *dllname;
1987         gchar *version = NULL;
1988         gchar *culture = NULL;
1989         gchar *token = NULL;
1990         gchar *key = NULL;
1991         gchar *retargetable = NULL;
1992         gboolean res;
1993         gchar *value, *part_name;
1994         guint32 part_name_len;
1995         gchar **parts;
1996         gchar **tmp;
1997         gboolean version_defined;
1998         gboolean token_defined;
1999         guint32 flags = 0;
2000         guint32 arch = MONO_PROCESSOR_ARCHITECTURE_NONE;
2001
2002         if (!is_version_defined)
2003                 is_version_defined = &version_defined;
2004         *is_version_defined = FALSE;
2005         if (!is_token_defined)
2006                 is_token_defined = &token_defined;
2007         *is_token_defined = FALSE;
2008         
2009         parts = tmp = g_strsplit (name, ",", 6);
2010         if (!tmp || !*tmp) {
2011                 g_strfreev (tmp);
2012                 return FALSE;
2013         }
2014
2015         dllname = g_strstrip (*tmp);
2016         
2017         tmp++;
2018
2019         while (*tmp) {
2020                 if (!split_key_value (g_strstrip (*tmp), &part_name, &part_name_len, &value))
2021                         goto cleanup_and_fail;
2022
2023                 if (part_name_len == 7 && !g_ascii_strncasecmp (part_name, "Version", part_name_len)) {
2024                         *is_version_defined = TRUE;
2025                         version = value;
2026                         if (strlen (version) == 0) {
2027                                 goto cleanup_and_fail;
2028                         }
2029                         tmp++;
2030                         continue;
2031                 }
2032
2033                 if (part_name_len == 7 && !g_ascii_strncasecmp (part_name, "Culture", part_name_len)) {
2034                         culture = value;
2035                         if (strlen (culture) == 0) {
2036                                 goto cleanup_and_fail;
2037                         }
2038                         tmp++;
2039                         continue;
2040                 }
2041
2042                 if (part_name_len == 14 && !g_ascii_strncasecmp (part_name, "PublicKeyToken", part_name_len)) {
2043                         *is_token_defined = TRUE;
2044                         token = value;
2045                         if (strlen (token) == 0) {
2046                                 goto cleanup_and_fail;
2047                         }
2048                         tmp++;
2049                         continue;
2050                 }
2051
2052                 if (part_name_len == 9 && !g_ascii_strncasecmp (part_name, "PublicKey", part_name_len)) {
2053                         key = value;
2054                         if (strlen (key) == 0) {
2055                                 goto cleanup_and_fail;
2056                         }
2057                         tmp++;
2058                         continue;
2059                 }
2060
2061                 if (part_name_len == 12 && !g_ascii_strncasecmp (part_name, "Retargetable", part_name_len)) {
2062                         retargetable = value;
2063                         if (strlen (retargetable) == 0) {
2064                                 goto cleanup_and_fail;
2065                         }
2066                         if (!g_ascii_strcasecmp (retargetable, "yes")) {
2067                                 flags |= ASSEMBLYREF_RETARGETABLE_FLAG;
2068                         } else if (g_ascii_strcasecmp (retargetable, "no")) {
2069                                 goto cleanup_and_fail;
2070                         }
2071                         tmp++;
2072                         continue;
2073                 }
2074
2075                 if (part_name_len == 21 && !g_ascii_strncasecmp (part_name, "ProcessorArchitecture", part_name_len)) {
2076                         if (!g_ascii_strcasecmp (value, "None"))
2077                                 arch = MONO_PROCESSOR_ARCHITECTURE_NONE;
2078                         else if (!g_ascii_strcasecmp (value, "MSIL"))
2079                                 arch = MONO_PROCESSOR_ARCHITECTURE_MSIL;
2080                         else if (!g_ascii_strcasecmp (value, "X86"))
2081                                 arch = MONO_PROCESSOR_ARCHITECTURE_X86;
2082                         else if (!g_ascii_strcasecmp (value, "IA64"))
2083                                 arch = MONO_PROCESSOR_ARCHITECTURE_IA64;
2084                         else if (!g_ascii_strcasecmp (value, "AMD64"))
2085                                 arch = MONO_PROCESSOR_ARCHITECTURE_AMD64;
2086                         else
2087                                 goto cleanup_and_fail;
2088                         tmp++;
2089                         continue;
2090                 }
2091
2092                 g_strfreev (parts);
2093                 return FALSE;
2094         }
2095
2096         /* if retargetable flag is set, then we must have a fully qualified name */
2097         if (retargetable != NULL && (version == NULL || culture == NULL || (key == NULL && token == NULL))) {
2098                 goto cleanup_and_fail;
2099         }
2100
2101         res = build_assembly_name (dllname, version, culture, token, key, flags, arch,
2102                 aname, save_public_key);
2103         g_strfreev (parts);
2104         return res;
2105
2106 cleanup_and_fail:
2107         g_strfreev (parts);
2108         return FALSE;
2109 }
2110
2111 /**
2112  * mono_assembly_name_parse:
2113  * @name: name to parse
2114  * @aname: the destination assembly name
2115  * 
2116  * Parses an assembly qualified type name and assigns the name,
2117  * version, culture and token to the provided assembly name object.
2118  *
2119  * Returns: true if the name could be parsed.
2120  */
2121 gboolean
2122 mono_assembly_name_parse (const char *name, MonoAssemblyName *aname)
2123 {
2124         return mono_assembly_name_parse_full (name, aname, FALSE, NULL, NULL);
2125 }
2126
2127 /**
2128  * mono_assembly_name_new:
2129  * @name: name to parse
2130  *
2131  * Allocate a new MonoAssemblyName and fill its values from the
2132  * passed @name.
2133  *
2134  * Returns: a newly allocated structure or NULL if there was any failure.
2135  */
2136 MonoAssemblyName*
2137 mono_assembly_name_new (const char *name)
2138 {
2139         MonoAssemblyName *aname = g_new0 (MonoAssemblyName, 1);
2140         if (mono_assembly_name_parse (name, aname))
2141                 return aname;
2142         g_free (aname);
2143         return NULL;
2144 }
2145
2146 const char*
2147 mono_assembly_name_get_name (MonoAssemblyName *aname)
2148 {
2149         return aname->name;
2150 }
2151
2152 const char*
2153 mono_assembly_name_get_culture (MonoAssemblyName *aname)
2154 {
2155         return aname->culture;
2156 }
2157
2158 mono_byte*
2159 mono_assembly_name_get_pubkeytoken (MonoAssemblyName *aname)
2160 {
2161         if (aname->public_key_token [0])
2162                 return aname->public_key_token;
2163         return NULL;
2164 }
2165
2166 uint16_t
2167 mono_assembly_name_get_version (MonoAssemblyName *aname, uint16_t *minor, uint16_t *build, uint16_t *revision)
2168 {
2169         if (minor)
2170                 *minor = aname->minor;
2171         if (build)
2172                 *build = aname->build;
2173         if (revision)
2174                 *revision = aname->revision;
2175         return aname->major;
2176 }
2177
2178 static MonoAssembly*
2179 probe_for_partial_name (const char *basepath, const char *fullname, MonoAssemblyName *aname, MonoImageOpenStatus *status)
2180 {
2181         gchar *fullpath = NULL;
2182         GDir *dirhandle;
2183         const char* direntry;
2184         MonoAssemblyName gac_aname;
2185         gint major=-1, minor=0, build=0, revision=0;
2186         gboolean exact_version;
2187         
2188         dirhandle = g_dir_open (basepath, 0, NULL);
2189         if (!dirhandle)
2190                 return NULL;
2191                 
2192         exact_version = (aname->major | aname->minor | aname->build | aname->revision) != 0;
2193
2194         while ((direntry = g_dir_read_name (dirhandle))) {
2195                 gboolean match = TRUE;
2196                 
2197                 if(!parse_assembly_directory_name (aname->name, direntry, &gac_aname))
2198                         continue;
2199                 
2200                 if (aname->culture != NULL && strcmp (aname->culture, gac_aname.culture) != 0)
2201                         match = FALSE;
2202                         
2203                 if (match && strlen ((char*)aname->public_key_token) > 0 && 
2204                                 !mono_public_tokens_are_equal (aname->public_key_token, gac_aname.public_key_token))
2205                         match = FALSE;
2206                 
2207                 if (match) {
2208                         if (exact_version) {
2209                                 match = (aname->major == gac_aname.major && aname->minor == gac_aname.minor &&
2210                                                  aname->build == gac_aname.build && aname->revision == gac_aname.revision); 
2211                         }
2212                         else if (gac_aname.major < major)
2213                                 match = FALSE;
2214                         else if (gac_aname.major == major) {
2215                                 if (gac_aname.minor < minor)
2216                                         match = FALSE;
2217                                 else if (gac_aname.minor == minor) {
2218                                         if (gac_aname.build < build)
2219                                                 match = FALSE;
2220                                         else if (gac_aname.build == build && gac_aname.revision <= revision)
2221                                                 match = FALSE; 
2222                                 }
2223                         }
2224                 }
2225                 
2226                 if (match) {
2227                         major = gac_aname.major;
2228                         minor = gac_aname.minor;
2229                         build = gac_aname.build;
2230                         revision = gac_aname.revision;
2231                         g_free (fullpath);
2232                         fullpath = g_build_path (G_DIR_SEPARATOR_S, basepath, direntry, fullname, NULL);
2233                 }
2234
2235                 mono_assembly_name_free (&gac_aname);
2236         }
2237         
2238         g_dir_close (dirhandle);
2239         
2240         if (fullpath == NULL)
2241                 return NULL;
2242         else {
2243                 MonoAssembly *res = mono_assembly_open (fullpath, status);
2244                 g_free (fullpath);
2245                 return res;
2246         }
2247 }
2248
2249 MonoAssembly*
2250 mono_assembly_load_with_partial_name (const char *name, MonoImageOpenStatus *status)
2251 {
2252         MonoAssembly *res;
2253         MonoAssemblyName *aname, base_name;
2254         MonoAssemblyName mapped_aname;
2255         gchar *fullname, *gacpath;
2256         gchar **paths;
2257
2258         memset (&base_name, 0, sizeof (MonoAssemblyName));
2259         aname = &base_name;
2260
2261         if (!mono_assembly_name_parse (name, aname))
2262                 return NULL;
2263
2264         /* 
2265          * If no specific version has been requested, make sure we load the
2266          * correct version for system assemblies.
2267          */ 
2268         if ((aname->major | aname->minor | aname->build | aname->revision) == 0)
2269                 aname = mono_assembly_remap_version (aname, &mapped_aname);
2270         
2271         res = mono_assembly_loaded (aname);
2272         if (res) {
2273                 mono_assembly_name_free (aname);
2274                 return res;
2275         }
2276
2277         res = invoke_assembly_preload_hook (aname, assemblies_path);
2278         if (res) {
2279                 res->in_gac = FALSE;
2280                 mono_assembly_name_free (aname);
2281                 return res;
2282         }
2283
2284         fullname = g_strdup_printf ("%s.dll", aname->name);
2285
2286         if (extra_gac_paths) {
2287                 paths = extra_gac_paths;
2288                 while (!res && *paths) {
2289                         gacpath = g_build_path (G_DIR_SEPARATOR_S, *paths, "lib", "mono", "gac", aname->name, NULL);
2290                         res = probe_for_partial_name (gacpath, fullname, aname, status);
2291                         g_free (gacpath);
2292                         paths++;
2293                 }
2294         }
2295
2296         if (res) {
2297                 res->in_gac = TRUE;
2298                 g_free (fullname);
2299                 mono_assembly_name_free (aname);
2300                 return res;
2301         }
2302
2303         gacpath = g_build_path (G_DIR_SEPARATOR_S, mono_assembly_getrootdir (), "mono", "gac", aname->name, NULL);
2304         res = probe_for_partial_name (gacpath, fullname, aname, status);
2305         g_free (gacpath);
2306
2307         if (res)
2308                 res->in_gac = TRUE;
2309         else {
2310                 MonoDomain *domain = mono_domain_get ();
2311                 MonoReflectionAssembly *refasm = mono_try_assembly_resolve (domain, mono_string_new (domain, name), FALSE);
2312                 if (refasm)
2313                         res = refasm->assembly;
2314         }
2315         
2316         g_free (fullname);
2317         mono_assembly_name_free (aname);
2318
2319         return res;
2320 }
2321
2322 static MonoBoolean
2323 mono_assembly_is_in_gac (const gchar *filename)
2324 {
2325         const gchar *rootdir;
2326         gchar *gp;
2327         gchar **paths;
2328
2329         if (filename == NULL)
2330                 return FALSE;
2331
2332         for (paths = extra_gac_paths; paths && *paths; paths++) {
2333                 if (strstr (*paths, filename) != *paths)
2334                         continue;
2335
2336                 gp = (gchar *) (filename + strlen (*paths));
2337                 if (*gp != G_DIR_SEPARATOR)
2338                         continue;
2339                 gp++;
2340                 if (strncmp (gp, "lib", 3))
2341                         continue;
2342                 gp += 3;
2343                 if (*gp != G_DIR_SEPARATOR)
2344                         continue;
2345                 gp++;
2346                 if (strncmp (gp, "mono", 4))
2347                         continue;
2348                 gp += 4;
2349                 if (*gp != G_DIR_SEPARATOR)
2350                         continue;
2351                 gp++;
2352                 if (strncmp (gp, "gac", 3))
2353                         continue;
2354                 gp += 3;
2355                 if (*gp != G_DIR_SEPARATOR)
2356                         continue;
2357
2358                 return TRUE;
2359         }
2360
2361         rootdir = mono_assembly_getrootdir ();
2362         if (strstr (filename, rootdir) != filename)
2363                 return FALSE;
2364
2365         gp = (gchar *) (filename + strlen (rootdir));
2366         if (*gp != G_DIR_SEPARATOR)
2367                 return FALSE;
2368         gp++;
2369         if (strncmp (gp, "mono", 4))
2370                 return FALSE;
2371         gp += 4;
2372         if (*gp != G_DIR_SEPARATOR)
2373                 return FALSE;
2374         gp++;
2375         if (strncmp (gp, "gac", 3))
2376                 return FALSE;
2377         gp += 3;
2378         if (*gp != G_DIR_SEPARATOR)
2379                 return FALSE;
2380         return TRUE;
2381 }
2382
2383 static MonoImage*
2384 mono_assembly_load_publisher_policy (MonoAssemblyName *aname)
2385 {
2386         MonoImage *image;
2387         gchar *filename, *pname, *name, *culture, *version, *fullpath, *subpath;
2388         gchar **paths;
2389         gint32 len;
2390
2391         if (strstr (aname->name, ".dll")) {
2392                 len = strlen (aname->name) - 4;
2393                 name = g_malloc (len);
2394                 strncpy (name, aname->name, len);
2395         } else
2396                 name = g_strdup (aname->name);
2397         
2398         if (aname->culture)
2399                 culture = g_utf8_strdown (aname->culture, -1);
2400         else
2401                 culture = g_strdup ("");
2402         
2403         pname = g_strdup_printf ("policy.%d.%d.%s", aname->major, aname->minor, name);
2404         version = g_strdup_printf ("0.0.0.0_%s_%s", culture, aname->public_key_token);
2405         g_free (name);
2406         g_free (culture);
2407         
2408         filename = g_strconcat (pname, ".dll", NULL);
2409         subpath = g_build_path (G_DIR_SEPARATOR_S, pname, version, filename, NULL);
2410         g_free (pname);
2411         g_free (version);
2412         g_free (filename);
2413
2414         image = NULL;
2415         if (extra_gac_paths) {
2416                 paths = extra_gac_paths;
2417                 while (!image && *paths) {
2418                         fullpath = g_build_path (G_DIR_SEPARATOR_S, *paths,
2419                                         "lib", "mono", "gac", subpath, NULL);
2420                         image = mono_image_open (fullpath, NULL);
2421                         g_free (fullpath);
2422                         paths++;
2423                 }
2424         }
2425
2426         if (image) {
2427                 g_free (subpath);
2428                 return image;
2429         }
2430
2431         fullpath = g_build_path (G_DIR_SEPARATOR_S, mono_assembly_getrootdir (), 
2432                         "mono", "gac", subpath, NULL);
2433         image = mono_image_open (fullpath, NULL);
2434         g_free (subpath);
2435         g_free (fullpath);
2436         
2437         return image;
2438 }
2439
2440 static MonoAssemblyName*
2441 mono_assembly_bind_version (MonoAssemblyBindingInfo *info, MonoAssemblyName *aname, MonoAssemblyName *dest_name)
2442 {
2443         memcpy (dest_name, aname, sizeof (MonoAssemblyName));
2444         dest_name->major = info->new_version.major;
2445         dest_name->minor = info->new_version.minor;
2446         dest_name->build = info->new_version.build;
2447         dest_name->revision = info->new_version.revision;
2448         
2449         return dest_name;
2450 }
2451
2452 /* LOCKING: Assumes that we are already locked */
2453 static MonoAssemblyBindingInfo*
2454 search_binding_loaded (MonoAssemblyName *aname)
2455 {
2456         GSList *tmp;
2457
2458         for (tmp = loaded_assembly_bindings; tmp; tmp = tmp->next) {
2459                 MonoAssemblyBindingInfo *info = tmp->data;
2460                 if (assembly_binding_maps_name (info, aname))
2461                         return info;
2462         }
2463
2464         return NULL;
2465 }
2466
2467 static inline gboolean
2468 info_compare_versions (AssemblyVersionSet *left, AssemblyVersionSet *right)
2469 {
2470         if (left->major != right->major || left->minor != right->minor ||
2471             left->build != right->build || left->revision != right->revision)
2472                 return FALSE;
2473
2474         return TRUE;
2475 }
2476
2477 static inline gboolean
2478 info_versions_equal (MonoAssemblyBindingInfo *left, MonoAssemblyBindingInfo *right)
2479 {
2480         if (left->has_old_version_bottom != right->has_old_version_bottom)
2481                 return FALSE;
2482
2483         if (left->has_old_version_top != right->has_old_version_top)
2484                 return FALSE;
2485
2486         if (left->has_new_version != right->has_new_version)
2487                 return FALSE;
2488
2489         if (left->has_old_version_bottom && !info_compare_versions (&left->old_version_bottom, &right->old_version_bottom))
2490                 return FALSE;
2491
2492         if (left->has_old_version_top && !info_compare_versions (&left->old_version_top, &right->old_version_top))
2493                 return FALSE;
2494
2495         if (left->has_new_version && !info_compare_versions (&left->new_version, &right->new_version))
2496                 return FALSE;
2497
2498         return TRUE;
2499 }
2500
2501 /* LOCKING: assumes all the necessary locks are held */
2502 static void
2503 assembly_binding_info_parsed (MonoAssemblyBindingInfo *info, void *user_data)
2504 {
2505         MonoAssemblyBindingInfo *info_copy;
2506         GSList *tmp;
2507         MonoAssemblyBindingInfo *info_tmp;
2508         MonoDomain *domain = (MonoDomain*)user_data;
2509
2510         if (!domain)
2511                 return;
2512
2513         for (tmp = domain->assembly_bindings; tmp; tmp = tmp->next) {
2514                 info_tmp = tmp->data;
2515                 if (strcmp (info->name, info_tmp->name) == 0 && info_versions_equal (info, info_tmp))
2516                         return;
2517         }
2518
2519         info_copy = mono_mempool_alloc0 (domain->mp, sizeof (MonoAssemblyBindingInfo));
2520         memcpy (info_copy, info, sizeof (MonoAssemblyBindingInfo));
2521         if (info->name)
2522                 info_copy->name = mono_mempool_strdup (domain->mp, info->name);
2523         if (info->culture)
2524                 info_copy->culture = mono_mempool_strdup (domain->mp, info->culture);
2525
2526         domain->assembly_bindings = g_slist_append_mempool (domain->mp, domain->assembly_bindings, info_copy);
2527 }
2528
2529 static inline gboolean
2530 info_major_minor_in_range (MonoAssemblyBindingInfo *info, MonoAssemblyName *aname)
2531 {
2532         if (!info->has_old_version_bottom)
2533                 return FALSE;
2534
2535         if (info->old_version_bottom.major > aname->major || info->old_version_bottom.minor > aname->minor)
2536                 return FALSE;
2537
2538         if (info->has_old_version_top && (info->old_version_top.major < aname->major || info->old_version_top.minor < aname->minor))
2539                 return FALSE;
2540
2541         /* This is not the nicest way to do it, but it's a by-product of the way parsing is done */
2542         info->major = aname->major;
2543         info->minor = aname->minor;
2544
2545         return TRUE;
2546 }
2547
2548 /* LOCKING: Assumes that we are already locked - both loader and domain locks */
2549 static MonoAssemblyBindingInfo*
2550 get_per_domain_assembly_binding_info (MonoDomain *domain, MonoAssemblyName *aname)
2551 {
2552         MonoAssemblyBindingInfo *info;
2553         GSList *list;
2554
2555         if (!domain->assembly_bindings)
2556                 return NULL;
2557
2558         info = NULL;
2559         for (list = domain->assembly_bindings; list; list = list->next) {
2560                 info = list->data;
2561                 if (info && !strcmp (aname->name, info->name) && info_major_minor_in_range (info, aname))
2562                         break;
2563                 info = NULL;
2564         }
2565
2566         if (info) {
2567                 if (info->name && info->public_key_token [0] && info->has_old_version_bottom &&
2568                     info->has_new_version && assembly_binding_maps_name (info, aname))
2569                         info->is_valid = TRUE;
2570                 else
2571                         info->is_valid = FALSE;
2572         }
2573
2574         return info;
2575 }
2576
2577 static MonoAssemblyName*
2578 mono_assembly_apply_binding (MonoAssemblyName *aname, MonoAssemblyName *dest_name)
2579 {
2580         MonoAssemblyBindingInfo *info, *info2;
2581         MonoImage *ppimage;
2582         MonoDomain *domain;
2583
2584         if (aname->public_key_token [0] == 0)
2585                 return aname;
2586
2587         domain = mono_domain_get ();
2588         mono_loader_lock ();
2589         info = search_binding_loaded (aname);
2590         if (!info) {
2591                 mono_domain_lock (domain);
2592                 info = get_per_domain_assembly_binding_info (domain, aname);
2593                 mono_domain_unlock (domain);
2594         }
2595
2596         mono_loader_unlock ();
2597         if (info) {
2598                 if (!check_policy_versions (info, aname))
2599                         return aname;
2600                 
2601                 mono_assembly_bind_version (info, aname, dest_name);
2602                 return dest_name;
2603         }
2604
2605         if (domain && domain->setup && domain->setup->configuration_file) {
2606                 mono_domain_lock (domain);
2607                 if (!domain->assembly_bindings_parsed) {
2608                         gchar *domain_config_file_name = mono_string_to_utf8 (domain->setup->configuration_file);
2609                         gchar *domain_config_file_path = mono_portability_find_file (domain_config_file_name, TRUE);
2610
2611                         if (!domain_config_file_path)
2612                                 domain_config_file_path = domain_config_file_name;
2613                         
2614                         mono_config_parse_assembly_bindings (domain_config_file_path, aname->major, aname->minor, domain, assembly_binding_info_parsed);
2615                         domain->assembly_bindings_parsed = TRUE;
2616                         if (domain_config_file_name != domain_config_file_path)
2617                                 g_free (domain_config_file_name);
2618                         g_free (domain_config_file_path);
2619                 }
2620                 mono_domain_unlock (domain);
2621
2622                 mono_loader_lock ();
2623                 mono_domain_lock (domain);
2624                 info2 = get_per_domain_assembly_binding_info (domain, aname);
2625
2626                 if (info2) {
2627                         info = g_memdup (info2, sizeof (MonoAssemblyBindingInfo));
2628                         info->name = g_strdup (info2->name);
2629                         info->culture = g_strdup (info2->culture);
2630                         info->domain_id = domain->domain_id;
2631                 }
2632
2633                 mono_domain_unlock (domain);
2634                 mono_loader_unlock ();
2635         }
2636
2637         if (!info) {
2638                 info = g_new0 (MonoAssemblyBindingInfo, 1);
2639                 info->major = aname->major;
2640                 info->minor = aname->minor;
2641         }
2642
2643         if (!info->is_valid) {
2644                 ppimage = mono_assembly_load_publisher_policy (aname);
2645                 if (ppimage) {
2646                         get_publisher_policy_info (ppimage, aname, info);
2647                         mono_image_close (ppimage);
2648                 }
2649         }
2650
2651         /* Define default error value if needed */
2652         if (!info->is_valid) {
2653                 info->name = g_strdup (aname->name);
2654                 info->culture = g_strdup (aname->culture);
2655                 g_strlcpy ((char *)info->public_key_token, (const char *)aname->public_key_token, MONO_PUBLIC_KEY_TOKEN_LENGTH);
2656         }
2657         
2658         mono_loader_lock ();
2659         info2 = search_binding_loaded (aname);
2660         if (info2) {
2661                 /* This binding was added by another thread 
2662                  * before us */
2663                 mono_assembly_binding_info_free (info);
2664                 g_free (info);
2665                 
2666                 info = info2;
2667         } else
2668                 loaded_assembly_bindings = g_slist_prepend (loaded_assembly_bindings, info);
2669                 
2670         mono_loader_unlock ();
2671         
2672         if (!info->is_valid || !check_policy_versions (info, aname))
2673                 return aname;
2674
2675         mono_assembly_bind_version (info, aname, dest_name);
2676         return dest_name;
2677 }
2678
2679 /**
2680  * mono_assembly_load_from_gac
2681  *
2682  * @aname: The assembly name object
2683  */
2684 static MonoAssembly*
2685 mono_assembly_load_from_gac (MonoAssemblyName *aname,  gchar *filename, MonoImageOpenStatus *status, MonoBoolean refonly)
2686 {
2687         MonoAssembly *result = NULL;
2688         gchar *name, *version, *culture, *fullpath, *subpath;
2689         gint32 len;
2690         gchar **paths;
2691         char *pubtok;
2692
2693         if (aname->public_key_token [0] == 0) {
2694                 return NULL;
2695         }
2696
2697         if (strstr (aname->name, ".dll")) {
2698                 len = strlen (filename) - 4;
2699                 name = g_malloc (len);
2700                 strncpy (name, aname->name, len);
2701         } else {
2702                 name = g_strdup (aname->name);
2703         }
2704
2705         if (aname->culture) {
2706                 culture = g_utf8_strdown (aname->culture, -1);
2707         } else {
2708                 culture = g_strdup ("");
2709         }
2710
2711         pubtok = g_ascii_strdown ((char*)aname->public_key_token, MONO_PUBLIC_KEY_TOKEN_LENGTH);
2712         version = g_strdup_printf ("%d.%d.%d.%d_%s_%s", aname->major,
2713                         aname->minor, aname->build, aname->revision,
2714                         culture, pubtok);
2715         g_free (pubtok);
2716         
2717         subpath = g_build_path (G_DIR_SEPARATOR_S, name, version, filename, NULL);
2718         g_free (name);
2719         g_free (version);
2720         g_free (culture);
2721
2722         if (extra_gac_paths) {
2723                 paths = extra_gac_paths;
2724                 while (!result && *paths) {
2725                         fullpath = g_build_path (G_DIR_SEPARATOR_S, *paths, "lib", "mono", "gac", subpath, NULL);
2726                         result = mono_assembly_open_full (fullpath, status, refonly);
2727                         g_free (fullpath);
2728                         paths++;
2729                 }
2730         }
2731
2732         if (result) {
2733                 result->in_gac = TRUE;
2734                 g_free (subpath);
2735                 return result;
2736         }
2737
2738         fullpath = g_build_path (G_DIR_SEPARATOR_S, mono_assembly_getrootdir (),
2739                         "mono", "gac", subpath, NULL);
2740         result = mono_assembly_open_full (fullpath, status, refonly);
2741         g_free (fullpath);
2742
2743         if (result)
2744                 result->in_gac = TRUE;
2745         
2746         g_free (subpath);
2747
2748         return result;
2749 }
2750
2751 MonoAssembly*
2752 mono_assembly_load_corlib (const MonoRuntimeInfo *runtime, MonoImageOpenStatus *status)
2753 {
2754         char *corlib_file;
2755         MonoAssemblyName *aname;
2756
2757         if (corlib) {
2758                 /* g_print ("corlib already loaded\n"); */
2759                 return corlib;
2760         }
2761
2762 #if defined(__native_client__)
2763         if (corlibData != NULL && corlibSize != 0) {
2764                 int status = 0;
2765                 /* First "FALSE" instructs mono not to make a copy. */
2766                 /* Second "FALSE" says this is not just a ref.      */
2767                 MonoImage* image = mono_image_open_from_data_full (corlibData, corlibSize, FALSE, &status, FALSE);
2768                 if (image == NULL || status != 0)
2769                         g_print("mono_image_open_from_data_full failed: %d\n", status);
2770                 corlib = mono_assembly_load_from_full (image, "mscorlib", &status, FALSE);
2771                 if (corlib == NULL || status != 0)
2772                         g_print ("mono_assembly_load_from_full failed: %d\n", status);
2773                 if (corlib)
2774                         return corlib;
2775         }
2776 #endif
2777
2778         aname = mono_assembly_name_new ("mscorlib.dll");
2779         corlib = invoke_assembly_preload_hook (aname, assemblies_path);
2780         mono_assembly_name_free (aname);
2781         g_free (aname);
2782         if (corlib != NULL)
2783                 return corlib;
2784
2785         if (assemblies_path) {
2786                 corlib = load_in_path ("mscorlib.dll", (const char**)assemblies_path, status, FALSE);
2787                 if (corlib)
2788                         return corlib;
2789         }
2790
2791         /* Load corlib from mono/<version> */
2792         
2793         corlib_file = g_build_filename ("mono", runtime->framework_version, "mscorlib.dll", NULL);
2794         if (assemblies_path) {
2795                 corlib = load_in_path (corlib_file, (const char**)assemblies_path, status, FALSE);
2796                 if (corlib) {
2797                         g_free (corlib_file);
2798                         return corlib;
2799                 }
2800         }
2801         corlib = load_in_path (corlib_file, default_path, status, FALSE);
2802         g_free (corlib_file);
2803         
2804         if (corlib && !strcmp (runtime->framework_version, "4.5"))
2805                 default_path [1] = g_strdup_printf ("%s/mono/4.5/Facades", default_path [0]);
2806                 
2807         return corlib;
2808 }
2809
2810 MonoAssembly*
2811 mono_assembly_load_full_nosearch (MonoAssemblyName *aname, 
2812                                                                   const char       *basedir, 
2813                                                                   MonoImageOpenStatus *status,
2814                                                                   gboolean refonly)
2815 {
2816         MonoAssembly *result;
2817         char *fullpath, *filename;
2818         MonoAssemblyName maped_aname;
2819         MonoAssemblyName maped_name_pp;
2820         int ext_index;
2821         const char *ext;
2822         int len;
2823
2824         aname = mono_assembly_remap_version (aname, &maped_aname);
2825         
2826         /* Reflection only assemblies don't get assembly binding */
2827         if (!refonly)
2828                 aname = mono_assembly_apply_binding (aname, &maped_name_pp);
2829         
2830         result = mono_assembly_loaded_full (aname, refonly);
2831         if (result)
2832                 return result;
2833
2834         result = refonly ? invoke_assembly_refonly_preload_hook (aname, assemblies_path) : invoke_assembly_preload_hook (aname, assemblies_path);
2835         if (result) {
2836                 result->in_gac = FALSE;
2837                 return result;
2838         }
2839
2840         /* Currently we retrieve the loaded corlib for reflection 
2841          * only requests, like a common reflection only assembly 
2842          */
2843         if (strcmp (aname->name, "mscorlib") == 0 || strcmp (aname->name, "mscorlib.dll") == 0) {
2844                 return mono_assembly_load_corlib (mono_get_runtime_info (), status);
2845         }
2846
2847         len = strlen (aname->name);
2848         for (ext_index = 0; ext_index < 2; ext_index ++) {
2849                 ext = ext_index == 0 ? ".dll" : ".exe";
2850                 if (len > 4 && (!strcmp (aname->name + len - 4, ".dll") || !strcmp (aname->name + len - 4, ".exe"))) {
2851                         filename = g_strdup (aname->name);
2852                         /* Don't try appending .dll/.exe if it already has one of those extensions */
2853                         ext_index++;
2854                 } else {
2855                         filename = g_strconcat (aname->name, ext, NULL);
2856                 }
2857
2858                 result = mono_assembly_load_from_gac (aname, filename, status, refonly);
2859                 if (result) {
2860                         g_free (filename);
2861                         return result;
2862                 }
2863
2864                 if (basedir) {
2865                         fullpath = g_build_filename (basedir, filename, NULL);
2866                         result = mono_assembly_open_full (fullpath, status, refonly);
2867                         g_free (fullpath);
2868                         if (result) {
2869                                 result->in_gac = FALSE;
2870                                 g_free (filename);
2871                                 return result;
2872                         }
2873                 }
2874
2875                 result = load_in_path (filename, default_path, status, refonly);
2876                 if (result)
2877                         result->in_gac = FALSE;
2878                 g_free (filename);
2879                 if (result)
2880                         return result;
2881         }
2882
2883         return result;
2884 }
2885
2886 /**
2887  * mono_assembly_load_full:
2888  * @aname: A MonoAssemblyName with the assembly name to load.
2889  * @basedir: A directory to look up the assembly at.
2890  * @status: a pointer to a MonoImageOpenStatus to return the status of the load operation
2891  * @refonly: Whether this assembly is being opened in "reflection-only" mode.
2892  *
2893  * Loads the assembly referenced by @aname, if the value of @basedir is not NULL, it
2894  * attempts to load the assembly from that directory before probing the standard locations.
2895  *
2896  * If the assembly is being opened in reflection-only mode (@refonly set to TRUE) then no 
2897  * assembly binding takes place.
2898  *
2899  * Returns: the assembly referenced by @aname loaded or NULL on error.   On error the
2900  * value pointed by status is updated with an error code.
2901  */
2902 MonoAssembly*
2903 mono_assembly_load_full (MonoAssemblyName *aname, const char *basedir, MonoImageOpenStatus *status, gboolean refonly)
2904 {
2905         MonoAssembly *result = mono_assembly_load_full_nosearch (aname, basedir, status, refonly);
2906         
2907         if (!result)
2908                 /* Try a postload search hook */
2909                 result = mono_assembly_invoke_search_hook_internal (aname, refonly, TRUE);
2910         return result;
2911 }
2912
2913 /**
2914  * mono_assembly_load:
2915  * @aname: A MonoAssemblyName with the assembly name to load.
2916  * @basedir: A directory to look up the assembly at.
2917  * @status: a pointer to a MonoImageOpenStatus to return the status of the load operation
2918  *
2919  * Loads the assembly referenced by @aname, if the value of @basedir is not NULL, it
2920  * attempts to load the assembly from that directory before probing the standard locations.
2921  *
2922  * Returns: the assembly referenced by @aname loaded or NULL on error.   On error the
2923  * value pointed by status is updated with an error code.
2924  */
2925 MonoAssembly*
2926 mono_assembly_load (MonoAssemblyName *aname, const char *basedir, MonoImageOpenStatus *status)
2927 {
2928         return mono_assembly_load_full (aname, basedir, status, FALSE);
2929 }
2930         
2931 MonoAssembly*
2932 mono_assembly_loaded_full (MonoAssemblyName *aname, gboolean refonly)
2933 {
2934         MonoAssembly *res;
2935         MonoAssemblyName maped_aname;
2936
2937         aname = mono_assembly_remap_version (aname, &maped_aname);
2938
2939         res = mono_assembly_invoke_search_hook_internal (aname, refonly, FALSE);
2940
2941         return res;
2942 }
2943
2944 /**
2945  * mono_assembly_loaded:
2946  * @aname: an assembly to look for.
2947  *
2948  * Returns: NULL If the given @aname assembly has not been loaded, or a pointer to
2949  * a MonoAssembly that matches the MonoAssemblyName specified.
2950  */
2951 MonoAssembly*
2952 mono_assembly_loaded (MonoAssemblyName *aname)
2953 {
2954         return mono_assembly_loaded_full (aname, FALSE);
2955 }
2956
2957 void
2958 mono_assembly_release_gc_roots (MonoAssembly *assembly)
2959 {
2960         if (assembly == NULL || assembly == REFERENCE_MISSING)
2961                 return;
2962
2963         if (assembly->dynamic) {
2964                 int i;
2965                 MonoDynamicImage *dynimg = (MonoDynamicImage *)assembly->image;
2966                 for (i = 0; i < dynimg->image.module_count; ++i)
2967                         mono_dynamic_image_release_gc_roots ((MonoDynamicImage *)dynimg->image.modules [i]);
2968                 mono_dynamic_image_release_gc_roots (dynimg);
2969         }
2970 }
2971
2972 /*
2973  * Returns whether mono_assembly_close_finish() must be called as
2974  * well.  See comment for mono_image_close_except_pools() for why we
2975  * unload in two steps.
2976  */
2977 gboolean
2978 mono_assembly_close_except_image_pools (MonoAssembly *assembly)
2979 {
2980         GSList *tmp;
2981         g_return_val_if_fail (assembly != NULL, FALSE);
2982
2983         if (assembly == REFERENCE_MISSING)
2984                 return FALSE;
2985
2986         /* Might be 0 already */
2987         if (InterlockedDecrement (&assembly->ref_count) > 0)
2988                 return FALSE;
2989
2990         mono_profiler_assembly_event (assembly, MONO_PROFILE_START_UNLOAD);
2991
2992         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_ASSEMBLY, "Unloading assembly %s [%p].", assembly->aname.name, assembly);
2993
2994         mono_debug_close_image (assembly->image);
2995
2996         mono_assemblies_lock ();
2997         loaded_assemblies = g_list_remove (loaded_assemblies, assembly);
2998         mono_assemblies_unlock ();
2999
3000         assembly->image->assembly = NULL;
3001
3002         if (!mono_image_close_except_pools (assembly->image))
3003                 assembly->image = NULL;
3004
3005         for (tmp = assembly->friend_assembly_names; tmp; tmp = tmp->next) {
3006                 MonoAssemblyName *fname = tmp->data;
3007                 mono_assembly_name_free (fname);
3008                 g_free (fname);
3009         }
3010         g_slist_free (assembly->friend_assembly_names);
3011         g_free (assembly->basedir);
3012
3013         mono_profiler_assembly_event (assembly, MONO_PROFILE_END_UNLOAD);
3014
3015         return TRUE;
3016 }
3017
3018 void
3019 mono_assembly_close_finish (MonoAssembly *assembly)
3020 {
3021         g_assert (assembly && assembly != REFERENCE_MISSING);
3022
3023         if (assembly->image)
3024                 mono_image_close_finish (assembly->image);
3025
3026         if (assembly->dynamic) {
3027                 g_free ((char*)assembly->aname.culture);
3028         } else {
3029                 g_free (assembly);
3030         }
3031 }
3032
3033 /**
3034  * mono_assembly_close:
3035  * @assembly: the assembly to release.
3036  *
3037  * This method releases a reference to the @assembly.  The assembly is
3038  * only released when all the outstanding references to it are released.
3039  */
3040 void
3041 mono_assembly_close (MonoAssembly *assembly)
3042 {
3043         if (mono_assembly_close_except_image_pools (assembly))
3044                 mono_assembly_close_finish (assembly);
3045 }
3046
3047 MonoImage*
3048 mono_assembly_load_module (MonoAssembly *assembly, guint32 idx)
3049 {
3050         return mono_image_load_file_for_image (assembly->image, idx);
3051 }
3052
3053 void
3054 mono_assembly_foreach (GFunc func, gpointer user_data)
3055 {
3056         GList *copy;
3057
3058         /*
3059          * We make a copy of the list to avoid calling the callback inside the 
3060          * lock, which could lead to deadlocks.
3061          */
3062         mono_assemblies_lock ();
3063         copy = g_list_copy (loaded_assemblies);
3064         mono_assemblies_unlock ();
3065
3066         g_list_foreach (loaded_assemblies, func, user_data);
3067
3068         g_list_free (copy);
3069 }
3070
3071 /**
3072  * mono_assemblies_cleanup:
3073  *
3074  * Free all resources used by this module.
3075  */
3076 void
3077 mono_assemblies_cleanup (void)
3078 {
3079         GSList *l;
3080
3081         DeleteCriticalSection (&assemblies_mutex);
3082
3083         for (l = loaded_assembly_bindings; l; l = l->next) {
3084                 MonoAssemblyBindingInfo *info = l->data;
3085
3086                 mono_assembly_binding_info_free (info);
3087                 g_free (info);
3088         }
3089         g_slist_free (loaded_assembly_bindings);
3090
3091         free_assembly_load_hooks ();
3092         free_assembly_search_hooks ();
3093         free_assembly_preload_hooks ();
3094 }
3095
3096 /*LOCKING assumes loader lock is held*/
3097 void
3098 mono_assembly_cleanup_domain_bindings (guint32 domain_id)
3099 {
3100         GSList **iter = &loaded_assembly_bindings;
3101
3102         while (*iter) {
3103                 GSList *l = *iter;
3104                 MonoAssemblyBindingInfo *info = l->data;
3105
3106                 if (info->domain_id == domain_id) {
3107                         *iter = l->next;
3108                         mono_assembly_binding_info_free (info);
3109                         g_free (info);
3110                         g_slist_free_1 (l);
3111                 } else {
3112                         iter = &l->next;
3113                 }
3114         }
3115 }
3116
3117 /*
3118  * Holds the assembly of the application, for
3119  * System.Diagnostics.Process::MainModule
3120  */
3121 static MonoAssembly *main_assembly=NULL;
3122
3123 void
3124 mono_assembly_set_main (MonoAssembly *assembly)
3125 {
3126         main_assembly = assembly;
3127 }
3128
3129 /**
3130  * mono_assembly_get_main:
3131  *
3132  * Returns: the assembly for the application, the first assembly that is loaded by the VM
3133  */
3134 MonoAssembly *
3135 mono_assembly_get_main (void)
3136 {
3137         return (main_assembly);
3138 }
3139
3140 /**
3141  * mono_assembly_get_image:
3142  * @assembly: The assembly to retrieve the image from
3143  *
3144  * Returns: the MonoImage associated with this assembly.
3145  */
3146 MonoImage*
3147 mono_assembly_get_image (MonoAssembly *assembly)
3148 {
3149         return assembly->image;
3150 }
3151
3152 void
3153 mono_register_bundled_assemblies (const MonoBundledAssembly **assemblies)
3154 {
3155         bundles = assemblies;
3156 }
3157
3158 #define MONO_DECLSEC_FORMAT_10          0x3C
3159 #define MONO_DECLSEC_FORMAT_20          0x2E
3160 #define MONO_DECLSEC_FIELD              0x53
3161 #define MONO_DECLSEC_PROPERTY           0x54
3162
3163 #define SKIP_VISIBILITY_XML_ATTRIBUTE ("\"SkipVerification\"")
3164 #define SKIP_VISIBILITY_ATTRIBUTE_NAME ("System.Security.Permissions.SecurityPermissionAttribute")
3165 #define SKIP_VISIBILITY_ATTRIBUTE_SIZE (sizeof (SKIP_VISIBILITY_ATTRIBUTE_NAME) - 1)
3166 #define SKIP_VISIBILITY_PROPERTY_NAME ("SkipVerification")
3167 #define SKIP_VISIBILITY_PROPERTY_SIZE (sizeof (SKIP_VISIBILITY_PROPERTY_NAME) - 1)
3168
3169 static gboolean
3170 mono_assembly_try_decode_skip_verification_param (const char *p, const char **resp, gboolean *abort_decoding)
3171 {
3172         int len;
3173         switch (*p++) {
3174         case MONO_DECLSEC_PROPERTY:
3175                 break;
3176         case MONO_DECLSEC_FIELD:
3177         default:
3178                 *abort_decoding = TRUE;
3179                 return FALSE;
3180                 break;
3181         }
3182
3183         if (*p++ != MONO_TYPE_BOOLEAN) {
3184                 *abort_decoding = TRUE;
3185                 return FALSE;
3186         }
3187                 
3188         /* property name length */
3189         len = mono_metadata_decode_value (p, &p);
3190
3191         if (len >= SKIP_VISIBILITY_PROPERTY_SIZE && !memcmp (p, SKIP_VISIBILITY_PROPERTY_NAME, SKIP_VISIBILITY_PROPERTY_SIZE)) {
3192                 p += len;
3193                 return *p;
3194         }
3195         p += len + 1;
3196
3197         *resp = p;
3198         return FALSE;
3199 }
3200
3201 static gboolean
3202 mono_assembly_try_decode_skip_verification (const char *p, const char *endn)
3203 {
3204         int i, j, num, len, params_len;
3205
3206         if (*p == MONO_DECLSEC_FORMAT_10) {
3207                 gsize read, written;
3208                 char *res = g_convert (p, endn - p, "UTF-8", "UTF-16LE", &read, &written, NULL);
3209                 if (res) {
3210                         gboolean found = strstr (res, SKIP_VISIBILITY_XML_ATTRIBUTE) != NULL;
3211                         g_free (res);
3212                         return found;
3213                 }
3214                 return FALSE;
3215         }
3216         if (*p++ != MONO_DECLSEC_FORMAT_20)
3217                 return FALSE;
3218
3219         /* number of encoded permission attributes */
3220         num = mono_metadata_decode_value (p, &p);
3221         for (i = 0; i < num; ++i) {
3222                 gboolean is_valid = FALSE;
3223                 gboolean abort_decoding = FALSE;
3224
3225                 /* attribute name length */
3226                 len =  mono_metadata_decode_value (p, &p);
3227
3228                 /* We don't really need to fully decode the type. Comparing the name is enough */
3229                 is_valid = len >= SKIP_VISIBILITY_ATTRIBUTE_SIZE && !memcmp (p, SKIP_VISIBILITY_ATTRIBUTE_NAME, SKIP_VISIBILITY_ATTRIBUTE_SIZE);
3230
3231                 p += len;
3232
3233                 /*size of the params table*/
3234                 params_len =  mono_metadata_decode_value (p, &p);
3235                 if (is_valid) {
3236                         const char *params_end = p + params_len;
3237                         
3238                         /* number of parameters */
3239                         len = mono_metadata_decode_value (p, &p);
3240         
3241                         for (j = 0; j < len; ++j) {
3242                                 if (mono_assembly_try_decode_skip_verification_param (p, &p, &abort_decoding))
3243                                         return TRUE;
3244                                 if (abort_decoding)
3245                                         break;
3246                         }
3247                         p = params_end;
3248                 } else {
3249                         p += params_len;
3250                 }
3251         }
3252         
3253         return FALSE;
3254 }
3255
3256
3257 gboolean
3258 mono_assembly_has_skip_verification (MonoAssembly *assembly)
3259 {
3260         MonoTableInfo *t;       
3261         guint32 cols [MONO_DECL_SECURITY_SIZE];
3262         const char *blob;
3263         int i, len;
3264
3265         if (MONO_SECMAN_FLAG_INIT (assembly->skipverification))
3266                 return MONO_SECMAN_FLAG_GET_VALUE (assembly->skipverification);
3267
3268         t = &assembly->image->tables [MONO_TABLE_DECLSECURITY];
3269
3270         for (i = 0; i < t->rows; ++i) {
3271                 mono_metadata_decode_row (t, i, cols, MONO_DECL_SECURITY_SIZE);
3272                 if ((cols [MONO_DECL_SECURITY_PARENT] & MONO_HAS_DECL_SECURITY_MASK) != MONO_HAS_DECL_SECURITY_ASSEMBLY)
3273                         continue;
3274                 if (cols [MONO_DECL_SECURITY_ACTION] != SECURITY_ACTION_REQMIN)
3275                         continue;
3276
3277                 blob = mono_metadata_blob_heap (assembly->image, cols [MONO_DECL_SECURITY_PERMISSIONSET]);
3278                 len = mono_metadata_decode_blob_size (blob, &blob);
3279                 if (!len)
3280                         continue;
3281
3282                 if (mono_assembly_try_decode_skip_verification (blob, blob + len)) {
3283                         MONO_SECMAN_FLAG_SET_VALUE (assembly->skipverification, TRUE);
3284                         return TRUE;
3285                 }
3286         }
3287
3288         MONO_SECMAN_FLAG_SET_VALUE (assembly->skipverification, FALSE);
3289         return FALSE;
3290 }