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