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