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