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