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