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