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