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