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