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