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