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