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