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