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