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