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