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