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