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