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