Merge branch 'master' of github.com:mono/mono
[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         return g_strdup_printf (
761                 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
762                 aname->name,
763                 aname->major, aname->minor, aname->build, aname->revision,
764                 aname->culture && *aname->culture? aname->culture: "neutral",
765                 aname->public_key_token [0] ? (char *)aname->public_key_token : "null",
766                 (aname->flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
767 }
768
769 static gchar*
770 assemblyref_public_tok (MonoImage *image, guint32 key_index, guint32 flags)
771 {
772         const gchar *public_tok;
773         int len;
774
775         public_tok = mono_metadata_blob_heap (image, key_index);
776         len = mono_metadata_decode_blob_size (public_tok, &public_tok);
777
778         if (flags & ASSEMBLYREF_FULL_PUBLIC_KEY_FLAG) {
779                 guchar token [8];
780                 mono_digest_get_public_token (token, (guchar*)public_tok, len);
781                 return encode_public_tok (token, 8);
782         }
783
784         return encode_public_tok ((guchar*)public_tok, len);
785 }
786
787 /**
788  * mono_assembly_addref:
789  * @assemnly: the assembly to reference
790  *
791  * This routine increments the reference count on a MonoAssembly.
792  * The reference count is reduced every time the method mono_assembly_close() is
793  * invoked.
794  */
795 void
796 mono_assembly_addref (MonoAssembly *assembly)
797 {
798         InterlockedIncrement (&assembly->ref_count);
799 }
800
801 #ifndef DISABLE_ASSEMBLY_REMAPPING
802 static MonoAssemblyName *
803 mono_assembly_remap_version (MonoAssemblyName *aname, MonoAssemblyName *dest_aname)
804 {
805         const MonoRuntimeInfo *current_runtime;
806         int pos, first, last;
807
808         if (aname->name == NULL) return aname;
809         current_runtime = mono_get_runtime_info ();
810
811         first = 0;
812         last = G_N_ELEMENTS (framework_assemblies) - 1;
813         
814         while (first <= last) {
815                 int res;
816                 pos = first + (last - first) / 2;
817                 res = strcmp (aname->name, framework_assemblies[pos].assembly_name);
818                 if (res == 0) {
819                         const AssemblyVersionSet* vset;
820                         int index = framework_assemblies[pos].version_set_index;
821                         g_assert (index < G_N_ELEMENTS (current_runtime->version_sets));
822                         vset = &current_runtime->version_sets [index];
823
824                         if (aname->major == vset->major && aname->minor == vset->minor &&
825                                 aname->build == vset->build && aname->revision == vset->revision)
826                                 return aname;
827                 
828                         if ((aname->major | aname->minor | aname->build | aname->revision) != 0)
829                                 mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_ASSEMBLY,
830                                         "The request to load the assembly %s v%d.%d.%d.%d was remapped to v%d.%d.%d.%d",
831                                                         aname->name,
832                                                         aname->major, aname->minor, aname->build, aname->revision,
833                                                         vset->major, vset->minor, vset->build, vset->revision
834                                                         );
835                         
836                         memcpy (dest_aname, aname, sizeof(MonoAssemblyName));
837                         dest_aname->major = vset->major;
838                         dest_aname->minor = vset->minor;
839                         dest_aname->build = vset->build;
840                         dest_aname->revision = vset->revision;
841                         return dest_aname;
842                 } else if (res < 0) {
843                         last = pos - 1;
844                 } else {
845                         first = pos + 1;
846                 }
847         }
848         return aname;
849 }
850 #endif
851
852 /*
853  * mono_assembly_get_assemblyref:
854  *
855  *   Fill out ANAME with the assembly name of the INDEXth assembly reference in IMAGE.
856  */
857 void
858 mono_assembly_get_assemblyref (MonoImage *image, int index, MonoAssemblyName *aname)
859 {
860         MonoTableInfo *t;
861         guint32 cols [MONO_ASSEMBLYREF_SIZE];
862         const char *hash;
863
864         t = &image->tables [MONO_TABLE_ASSEMBLYREF];
865
866         mono_metadata_decode_row (t, index, cols, MONO_ASSEMBLYREF_SIZE);
867                 
868         hash = mono_metadata_blob_heap (image, cols [MONO_ASSEMBLYREF_HASH_VALUE]);
869         aname->hash_len = mono_metadata_decode_blob_size (hash, &hash);
870         aname->hash_value = hash;
871         aname->name = mono_metadata_string_heap (image, cols [MONO_ASSEMBLYREF_NAME]);
872         aname->culture = mono_metadata_string_heap (image, cols [MONO_ASSEMBLYREF_CULTURE]);
873         aname->flags = cols [MONO_ASSEMBLYREF_FLAGS];
874         aname->major = cols [MONO_ASSEMBLYREF_MAJOR_VERSION];
875         aname->minor = cols [MONO_ASSEMBLYREF_MINOR_VERSION];
876         aname->build = cols [MONO_ASSEMBLYREF_BUILD_NUMBER];
877         aname->revision = cols [MONO_ASSEMBLYREF_REV_NUMBER];
878
879         if (cols [MONO_ASSEMBLYREF_PUBLIC_KEY]) {
880                 gchar *token = assemblyref_public_tok (image, cols [MONO_ASSEMBLYREF_PUBLIC_KEY], aname->flags);
881                 g_strlcpy ((char*)aname->public_key_token, token, MONO_PUBLIC_KEY_TOKEN_LENGTH);
882                 g_free (token);
883         } else {
884                 memset (aname->public_key_token, 0, MONO_PUBLIC_KEY_TOKEN_LENGTH);
885         }
886 }
887
888 void
889 mono_assembly_load_reference (MonoImage *image, int index)
890 {
891         MonoAssembly *reference;
892         MonoAssemblyName aname;
893         MonoImageOpenStatus status;
894
895         /*
896          * image->references is shared between threads, so we need to access
897          * it inside a critical section.
898          */
899         mono_assemblies_lock ();
900         if (!image->references) {
901                 MonoTableInfo *t = &image->tables [MONO_TABLE_ASSEMBLYREF];
902         
903                 image->references = g_new0 (MonoAssembly *, t->rows + 1);
904         }
905         reference = image->references [index];
906         mono_assemblies_unlock ();
907         if (reference)
908                 return;
909
910         mono_assembly_get_assemblyref (image, index, &aname);
911
912         if (image->assembly && image->assembly->ref_only) {
913                 /* We use the loaded corlib */
914                 if (!strcmp (aname.name, "mscorlib"))
915                         reference = mono_assembly_load_full (&aname, image->assembly->basedir, &status, FALSE);
916                 else {
917                         reference = mono_assembly_loaded_full (&aname, TRUE);
918                         if (!reference)
919                                 /* Try a postload search hook */
920                                 reference = mono_assembly_invoke_search_hook_internal (&aname, TRUE, TRUE);
921                 }
922
923                 /*
924                  * Here we must advice that the error was due to
925                  * a non loaded reference using the ReflectionOnly api
926                 */
927                 if (!reference)
928                         reference = REFERENCE_MISSING;
929         } else
930                 reference = mono_assembly_load (&aname, image->assembly? image->assembly->basedir: NULL, &status);
931
932         if (reference == NULL){
933                 char *extra_msg;
934
935                 if (status == MONO_IMAGE_ERROR_ERRNO && errno == ENOENT) {
936                         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 : "" );
937                 } else if (status == MONO_IMAGE_ERROR_ERRNO) {
938                         extra_msg = g_strdup_printf ("System error: %s\n", strerror (errno));
939                 } else if (status == MONO_IMAGE_MISSING_ASSEMBLYREF) {
940                         extra_msg = g_strdup ("Cannot find an assembly referenced from this one.\n");
941                 } else if (status == MONO_IMAGE_IMAGE_INVALID) {
942                         extra_msg = g_strdup ("The file exists but is not a valid assembly.\n");
943                 } else {
944                         extra_msg = g_strdup ("");
945                 }
946                 
947                 mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_ASSEMBLY, "The following assembly referenced from %s could not be loaded:\n"
948                                    "     Assembly:   %s    (assemblyref_index=%d)\n"
949                                    "     Version:    %d.%d.%d.%d\n"
950                                    "     Public Key: %s\n%s",
951                                    image->name, aname.name, index,
952                                    aname.major, aname.minor, aname.build, aname.revision,
953                                    strlen ((char*)aname.public_key_token) == 0 ? "(none)" : (char*)aname.public_key_token, extra_msg);
954                 g_free (extra_msg);
955         }
956
957         mono_assemblies_lock ();
958         if (reference == NULL) {
959                 /* Flag as not found */
960                 reference = REFERENCE_MISSING;
961         }       
962
963         if (!image->references [index]) {
964                 if (reference != REFERENCE_MISSING){
965                         mono_assembly_addref (reference);
966                         if (image->assembly)
967                                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_ASSEMBLY, "Assembly Ref addref %s %p -> %s %p: %d",
968                                     image->assembly->aname.name, image->assembly, reference->aname.name, reference, reference->ref_count);
969                 } else {
970                         if (image->assembly)
971                                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_ASSEMBLY, "Failed to load assembly %s %p\n",
972                                     image->assembly->aname.name, image->assembly);
973                 }
974                 
975                 image->references [index] = reference;
976         }
977         mono_assemblies_unlock ();
978
979         if (image->references [index] != reference) {
980                 /* Somebody loaded it before us */
981                 mono_assembly_close (reference);
982         }
983 }
984
985 void
986 mono_assembly_load_references (MonoImage *image, MonoImageOpenStatus *status)
987 {
988         /* This is a no-op now but it is part of the embedding API so we can't remove it */
989         *status = MONO_IMAGE_OK;
990 }
991
992 typedef struct AssemblyLoadHook AssemblyLoadHook;
993 struct AssemblyLoadHook {
994         AssemblyLoadHook *next;
995         MonoAssemblyLoadFunc func;
996         gpointer user_data;
997 };
998
999 AssemblyLoadHook *assembly_load_hook = NULL;
1000
1001 void
1002 mono_assembly_invoke_load_hook (MonoAssembly *ass)
1003 {
1004         AssemblyLoadHook *hook;
1005
1006         for (hook = assembly_load_hook; hook; hook = hook->next) {
1007                 hook->func (ass, hook->user_data);
1008         }
1009 }
1010
1011 void
1012 mono_install_assembly_load_hook (MonoAssemblyLoadFunc func, gpointer user_data)
1013 {
1014         AssemblyLoadHook *hook;
1015         
1016         g_return_if_fail (func != NULL);
1017
1018         hook = g_new0 (AssemblyLoadHook, 1);
1019         hook->func = func;
1020         hook->user_data = user_data;
1021         hook->next = assembly_load_hook;
1022         assembly_load_hook = hook;
1023 }
1024
1025 static void
1026 free_assembly_load_hooks (void)
1027 {
1028         AssemblyLoadHook *hook, *next;
1029
1030         for (hook = assembly_load_hook; hook; hook = next) {
1031                 next = hook->next;
1032                 g_free (hook);
1033         }
1034 }
1035
1036 typedef struct AssemblySearchHook AssemblySearchHook;
1037 struct AssemblySearchHook {
1038         AssemblySearchHook *next;
1039         MonoAssemblySearchFunc func;
1040         gboolean refonly;
1041         gboolean postload;
1042         gpointer user_data;
1043 };
1044
1045 AssemblySearchHook *assembly_search_hook = NULL;
1046
1047 static MonoAssembly*
1048 mono_assembly_invoke_search_hook_internal (MonoAssemblyName *aname, gboolean refonly, gboolean postload)
1049 {
1050         AssemblySearchHook *hook;
1051
1052         for (hook = assembly_search_hook; hook; hook = hook->next) {
1053                 if ((hook->refonly == refonly) && (hook->postload == postload)) {
1054                         MonoAssembly *ass = hook->func (aname, hook->user_data);
1055                         if (ass)
1056                                 return ass;
1057                 }
1058         }
1059
1060         return NULL;
1061 }
1062
1063 MonoAssembly*
1064 mono_assembly_invoke_search_hook (MonoAssemblyName *aname)
1065 {
1066         return mono_assembly_invoke_search_hook_internal (aname, FALSE, FALSE);
1067 }
1068
1069 static void
1070 mono_install_assembly_search_hook_internal (MonoAssemblySearchFunc func, gpointer user_data, gboolean refonly, gboolean postload)
1071 {
1072         AssemblySearchHook *hook;
1073         
1074         g_return_if_fail (func != NULL);
1075
1076         hook = g_new0 (AssemblySearchHook, 1);
1077         hook->func = func;
1078         hook->user_data = user_data;
1079         hook->refonly = refonly;
1080         hook->postload = postload;
1081         hook->next = assembly_search_hook;
1082         assembly_search_hook = hook;
1083 }
1084
1085 void          
1086 mono_install_assembly_search_hook (MonoAssemblySearchFunc func, gpointer user_data)
1087 {
1088         mono_install_assembly_search_hook_internal (func, user_data, FALSE, FALSE);
1089 }       
1090
1091 static void
1092 free_assembly_search_hooks (void)
1093 {
1094         AssemblySearchHook *hook, *next;
1095
1096         for (hook = assembly_search_hook; hook; hook = next) {
1097                 next = hook->next;
1098                 g_free (hook);
1099         }
1100 }
1101
1102 void
1103 mono_install_assembly_refonly_search_hook (MonoAssemblySearchFunc func, gpointer user_data)
1104 {
1105         mono_install_assembly_search_hook_internal (func, user_data, TRUE, FALSE);
1106 }
1107
1108 void          
1109 mono_install_assembly_postload_search_hook (MonoAssemblySearchFunc func, gpointer user_data)
1110 {
1111         mono_install_assembly_search_hook_internal (func, user_data, FALSE, TRUE);
1112 }       
1113
1114 void
1115 mono_install_assembly_postload_refonly_search_hook (MonoAssemblySearchFunc func, gpointer user_data)
1116 {
1117         mono_install_assembly_search_hook_internal (func, user_data, TRUE, TRUE);
1118 }
1119
1120 typedef struct AssemblyPreLoadHook AssemblyPreLoadHook;
1121 struct AssemblyPreLoadHook {
1122         AssemblyPreLoadHook *next;
1123         MonoAssemblyPreLoadFunc func;
1124         gpointer user_data;
1125 };
1126
1127 static AssemblyPreLoadHook *assembly_preload_hook = NULL;
1128 static AssemblyPreLoadHook *assembly_refonly_preload_hook = NULL;
1129
1130 static MonoAssembly *
1131 invoke_assembly_preload_hook (MonoAssemblyName *aname, gchar **assemblies_path)
1132 {
1133         AssemblyPreLoadHook *hook;
1134         MonoAssembly *assembly;
1135
1136         for (hook = assembly_preload_hook; hook; hook = hook->next) {
1137                 assembly = hook->func (aname, assemblies_path, hook->user_data);
1138                 if (assembly != NULL)
1139                         return assembly;
1140         }
1141
1142         return NULL;
1143 }
1144
1145 static MonoAssembly *
1146 invoke_assembly_refonly_preload_hook (MonoAssemblyName *aname, gchar **assemblies_path)
1147 {
1148         AssemblyPreLoadHook *hook;
1149         MonoAssembly *assembly;
1150
1151         for (hook = assembly_refonly_preload_hook; hook; hook = hook->next) {
1152                 assembly = hook->func (aname, assemblies_path, hook->user_data);
1153                 if (assembly != NULL)
1154                         return assembly;
1155         }
1156
1157         return NULL;
1158 }
1159
1160 void
1161 mono_install_assembly_preload_hook (MonoAssemblyPreLoadFunc func, gpointer user_data)
1162 {
1163         AssemblyPreLoadHook *hook;
1164         
1165         g_return_if_fail (func != NULL);
1166
1167         hook = g_new0 (AssemblyPreLoadHook, 1);
1168         hook->func = func;
1169         hook->user_data = user_data;
1170         hook->next = assembly_preload_hook;
1171         assembly_preload_hook = hook;
1172 }
1173
1174 void
1175 mono_install_assembly_refonly_preload_hook (MonoAssemblyPreLoadFunc func, gpointer user_data)
1176 {
1177         AssemblyPreLoadHook *hook;
1178         
1179         g_return_if_fail (func != NULL);
1180
1181         hook = g_new0 (AssemblyPreLoadHook, 1);
1182         hook->func = func;
1183         hook->user_data = user_data;
1184         hook->next = assembly_refonly_preload_hook;
1185         assembly_refonly_preload_hook = hook;
1186 }
1187
1188 static void
1189 free_assembly_preload_hooks (void)
1190 {
1191         AssemblyPreLoadHook *hook, *next;
1192
1193         for (hook = assembly_preload_hook; hook; hook = next) {
1194                 next = hook->next;
1195                 g_free (hook);
1196         }
1197
1198         for (hook = assembly_refonly_preload_hook; hook; hook = next) {
1199                 next = hook->next;
1200                 g_free (hook);
1201         }
1202 }
1203
1204 static gchar *
1205 absolute_dir (const gchar *filename)
1206 {
1207         gchar *cwd;
1208         gchar *mixed;
1209         gchar **parts;
1210         gchar *part;
1211         GList *list, *tmp;
1212         GString *result;
1213         gchar *res;
1214         gint i;
1215
1216         if (g_path_is_absolute (filename)) {
1217                 part = g_path_get_dirname (filename);
1218                 res = g_strconcat (part, G_DIR_SEPARATOR_S, NULL);
1219                 g_free (part);
1220                 return res;
1221         }
1222
1223         cwd = g_get_current_dir ();
1224         mixed = g_build_filename (cwd, filename, NULL);
1225         parts = g_strsplit (mixed, G_DIR_SEPARATOR_S, 0);
1226         g_free (mixed);
1227         g_free (cwd);
1228
1229         list = NULL;
1230         for (i = 0; (part = parts [i]) != NULL; i++) {
1231                 if (!strcmp (part, "."))
1232                         continue;
1233
1234                 if (!strcmp (part, "..")) {
1235                         if (list && list->next) /* Don't remove root */
1236                                 list = g_list_delete_link (list, list);
1237                 } else {
1238                         list = g_list_prepend (list, part);
1239                 }
1240         }
1241
1242         result = g_string_new ("");
1243         list = g_list_reverse (list);
1244
1245         /* Ignores last data pointer, which should be the filename */
1246         for (tmp = list; tmp && tmp->next != NULL; tmp = tmp->next){
1247                 if (tmp->data)
1248                         g_string_append_printf (result, "%s%c", (char *) tmp->data,
1249                                                                 G_DIR_SEPARATOR);
1250         }
1251
1252         res = result->str;
1253         g_string_free (result, FALSE);
1254         g_list_free (list);
1255         g_strfreev (parts);
1256         if (*res == '\0') {
1257                 g_free (res);
1258                 return g_strdup (".");
1259         }
1260
1261         return res;
1262 }
1263
1264 /** 
1265  * mono_assembly_open_from_bundle:
1266  * @filename: Filename requested
1267  * @status: return value
1268  *
1269  * This routine tries to open the assembly specified by `filename' from the
1270  * defined bundles, if found, returns the MonoImage for it, if not found
1271  * returns NULL
1272  */
1273 MonoImage *
1274 mono_assembly_open_from_bundle (const char *filename, MonoImageOpenStatus *status, gboolean refonly)
1275 {
1276         int i;
1277         char *name;
1278         MonoImage *image = NULL;
1279
1280         /*
1281          * we do a very simple search for bundled assemblies: it's not a general 
1282          * purpose assembly loading mechanism.
1283          */
1284
1285         if (!bundles)
1286                 return NULL;
1287
1288         name = g_path_get_basename (filename);
1289
1290         mono_assemblies_lock ();
1291         for (i = 0; !image && bundles [i]; ++i) {
1292                 if (strcmp (bundles [i]->name, name) == 0) {
1293                         image = mono_image_open_from_data_with_name ((char*)bundles [i]->data, bundles [i]->size, FALSE, status, refonly, name);
1294                         break;
1295                 }
1296         }
1297         mono_assemblies_unlock ();
1298         g_free (name);
1299         if (image) {
1300                 mono_image_addref (image);
1301                 return image;
1302         }
1303         return NULL;
1304 }
1305
1306 MonoAssembly *
1307 mono_assembly_open_full (const char *filename, MonoImageOpenStatus *status, gboolean refonly)
1308 {
1309         MonoImage *image;
1310         MonoAssembly *ass;
1311         MonoImageOpenStatus def_status;
1312         gchar *fname;
1313         gchar *new_fname;
1314         
1315         g_return_val_if_fail (filename != NULL, NULL);
1316
1317         if (!status)
1318                 status = &def_status;
1319         *status = MONO_IMAGE_OK;
1320
1321         if (strncmp (filename, "file://", 7) == 0) {
1322                 GError *error = NULL;
1323                 gchar *uri = (gchar *) filename;
1324                 gchar *tmpuri;
1325
1326                 /*
1327                  * MS allows file://c:/... and fails on file://localhost/c:/... 
1328                  * They also throw an IndexOutOfRangeException if "file://"
1329                  */
1330                 if (uri [7] != '/')
1331                         uri = g_strdup_printf ("file:///%s", uri + 7);
1332         
1333                 tmpuri = uri;
1334                 uri = mono_escape_uri_string (tmpuri);
1335                 fname = g_filename_from_uri (uri, NULL, &error);
1336                 g_free (uri);
1337
1338                 if (tmpuri != filename)
1339                         g_free (tmpuri);
1340
1341                 if (error != NULL) {
1342                         g_warning ("%s\n", error->message);
1343                         g_error_free (error);
1344                         fname = g_strdup (filename);
1345                 }
1346         } else {
1347                 fname = g_strdup (filename);
1348         }
1349
1350         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_ASSEMBLY,
1351                         "Assembly Loader probing location: '%s'.", fname);
1352
1353         new_fname = NULL;
1354         if (!mono_assembly_is_in_gac (fname))
1355                 new_fname = mono_make_shadow_copy (fname);
1356         if (new_fname && new_fname != fname) {
1357                 g_free (fname);
1358                 fname = new_fname;
1359                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_ASSEMBLY,
1360                             "Assembly Loader shadow-copied assembly to: '%s'.", fname);
1361         }
1362         
1363         image = NULL;
1364
1365         if (bundles != NULL)
1366                 image = mono_assembly_open_from_bundle (fname, status, refonly);
1367
1368         if (!image)
1369                 image = mono_image_open_full (fname, status, refonly);
1370
1371         if (!image){
1372                 if (*status == MONO_IMAGE_OK)
1373                         *status = MONO_IMAGE_ERROR_ERRNO;
1374                 g_free (fname);
1375                 return NULL;
1376         }
1377
1378         if (image->assembly) {
1379                 /* Already loaded by another appdomain */
1380                 mono_assembly_invoke_load_hook (image->assembly);
1381                 mono_image_close (image);
1382                 g_free (fname);
1383                 return image->assembly;
1384         }
1385
1386         ass = mono_assembly_load_from_full (image, fname, status, refonly);
1387
1388         if (ass) {
1389                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_ASSEMBLY,
1390                                 "Assembly Loader loaded assembly from location: '%s'.", filename);
1391                 if (!refonly)
1392                         mono_config_for_assembly (ass->image);
1393         }
1394
1395         /* Clear the reference added by mono_image_open */
1396         mono_image_close (image);
1397         
1398         g_free (fname);
1399
1400         return ass;
1401 }
1402
1403 static void
1404 free_item (gpointer val, gpointer user_data)
1405 {
1406         g_free (val);
1407 }
1408
1409 /*
1410  * mono_assembly_load_friends:
1411  * @ass: an assembly
1412  *
1413  * Load the list of friend assemblies that are allowed to access
1414  * the assembly's internal types and members. They are stored as assembly
1415  * names in custom attributes.
1416  *
1417  * This is an internal method, we need this because when we load mscorlib
1418  * we do not have the mono_defaults.internals_visible_class loaded yet,
1419  * so we need to load these after we initialize the runtime. 
1420  *
1421  * LOCKING: Acquires the assemblies lock plus the loader lock.
1422  */
1423 void
1424 mono_assembly_load_friends (MonoAssembly* ass)
1425 {
1426         int i;
1427         MonoCustomAttrInfo* attrs;
1428         GSList *list;
1429
1430         if (ass->friend_assembly_names_inited)
1431                 return;
1432
1433         attrs = mono_custom_attrs_from_assembly (ass);
1434         if (!attrs) {
1435                 mono_assemblies_lock ();
1436                 ass->friend_assembly_names_inited = TRUE;
1437                 mono_assemblies_unlock ();
1438                 return;
1439         }
1440
1441         mono_assemblies_lock ();
1442         if (ass->friend_assembly_names_inited) {
1443                 mono_assemblies_unlock ();
1444                 return;
1445         }
1446         mono_assemblies_unlock ();
1447
1448         list = NULL;
1449         /* 
1450          * We build the list outside the assemblies lock, the worse that can happen
1451          * is that we'll need to free the allocated list.
1452          */
1453         for (i = 0; i < attrs->num_attrs; ++i) {
1454                 MonoCustomAttrEntry *attr = &attrs->attrs [i];
1455                 MonoAssemblyName *aname;
1456                 const gchar *data;
1457                 guint slen;
1458                 /* Do some sanity checking */
1459                 if (!attr->ctor || attr->ctor->klass != mono_defaults.internals_visible_class)
1460                         continue;
1461                 if (attr->data_size < 4)
1462                         continue;
1463                 data = (const char*)attr->data;
1464                 /* 0xFF means null string, see custom attr format */
1465                 if (data [0] != 1 || data [1] != 0 || (data [2] & 0xFF) == 0xFF)
1466                         continue;
1467                 slen = mono_metadata_decode_value (data + 2, &data);
1468                 aname = g_new0 (MonoAssemblyName, 1);
1469                 /*g_print ("friend ass: %s\n", data);*/
1470                 if (mono_assembly_name_parse_full (data, aname, TRUE, NULL, NULL)) {
1471                         list = g_slist_prepend (list, aname);
1472                 } else {
1473                         g_free (aname);
1474                 }
1475         }
1476         mono_custom_attrs_free (attrs);
1477
1478         mono_assemblies_lock ();
1479         if (ass->friend_assembly_names_inited) {
1480                 mono_assemblies_unlock ();
1481                 g_slist_foreach (list, free_item, NULL);
1482                 g_slist_free (list);
1483                 return;
1484         }
1485         ass->friend_assembly_names = list;
1486
1487         /* Because of the double checked locking pattern above */
1488         mono_memory_barrier ();
1489         ass->friend_assembly_names_inited = TRUE;
1490         mono_assemblies_unlock ();
1491 }
1492
1493 /**
1494  * mono_assembly_open:
1495  * @filename: Opens the assembly pointed out by this name
1496  * @status: where a status code can be returned
1497  *
1498  * mono_assembly_open opens the PE-image pointed by @filename, and
1499  * loads any external assemblies referenced by it.
1500  *
1501  * Return: a pointer to the MonoAssembly if @filename contains a valid
1502  * assembly or NULL on error.  Details about the error are stored in the
1503  * @status variable.
1504  */
1505 MonoAssembly *
1506 mono_assembly_open (const char *filename, MonoImageOpenStatus *status)
1507 {
1508         return mono_assembly_open_full (filename, status, FALSE);
1509 }
1510
1511 MonoAssembly *
1512 mono_assembly_load_from_full (MonoImage *image, const char*fname, 
1513                               MonoImageOpenStatus *status, gboolean refonly)
1514 {
1515         MonoAssembly *ass, *ass2;
1516         char *base_dir;
1517
1518         if (!image->tables [MONO_TABLE_ASSEMBLY].rows) {
1519                 /* 'image' doesn't have a manifest -- maybe someone is trying to Assembly.Load a .netmodule */
1520                 *status = MONO_IMAGE_IMAGE_INVALID;
1521                 return NULL;
1522         }
1523
1524 #if defined (HOST_WIN32)
1525         {
1526                 gchar *tmp_fn;
1527                 int i;
1528
1529                 tmp_fn = g_strdup (fname);
1530                 for (i = strlen (tmp_fn) - 1; i >= 0; i--) {
1531                         if (tmp_fn [i] == '/')
1532                                 tmp_fn [i] = '\\';
1533                 }
1534
1535                 base_dir = absolute_dir (tmp_fn);
1536                 g_free (tmp_fn);
1537         }
1538 #else
1539         base_dir = absolute_dir (fname);
1540 #endif
1541
1542         /*
1543          * Create assembly struct, and enter it into the assembly cache
1544          */
1545         ass = g_new0 (MonoAssembly, 1);
1546         ass->basedir = base_dir;
1547         ass->ref_only = refonly;
1548         ass->image = image;
1549
1550         mono_profiler_assembly_event (ass, MONO_PROFILE_START_LOAD);
1551
1552         mono_assembly_fill_assembly_name (image, &ass->aname);
1553
1554         if (mono_defaults.corlib && strcmp (ass->aname.name, "mscorlib") == 0) {
1555                 // MS.NET doesn't support loading other mscorlibs
1556                 g_free (ass);
1557                 g_free (base_dir);
1558                 mono_image_addref (mono_defaults.corlib);
1559                 *status = MONO_IMAGE_OK;
1560                 return mono_defaults.corlib->assembly;
1561         }
1562
1563         /* Add a non-temporary reference because of ass->image */
1564         mono_image_addref (image);
1565
1566         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);
1567
1568         /* 
1569          * The load hooks might take locks so we can't call them while holding the
1570          * assemblies lock.
1571          */
1572         if (ass->aname.name) {
1573                 ass2 = mono_assembly_invoke_search_hook_internal (&ass->aname, refonly, FALSE);
1574                 if (ass2) {
1575                         g_free (ass);
1576                         g_free (base_dir);
1577                         mono_image_close (image);
1578                         *status = MONO_IMAGE_OK;
1579                         return ass2;
1580                 }
1581         }
1582
1583         mono_assemblies_lock ();
1584
1585         if (image->assembly) {
1586                 /* 
1587                  * This means another thread has already loaded the assembly, but not yet
1588                  * called the load hooks so the search hook can't find the assembly.
1589                  */
1590                 mono_assemblies_unlock ();
1591                 ass2 = image->assembly;
1592                 g_free (ass);
1593                 g_free (base_dir);
1594                 mono_image_close (image);
1595                 *status = MONO_IMAGE_OK;
1596                 return ass2;
1597         }
1598
1599         image->assembly = ass;
1600
1601         loaded_assemblies = g_list_prepend (loaded_assemblies, ass);
1602         mono_assemblies_unlock ();
1603
1604 #ifdef HOST_WIN32
1605         if (image->is_module_handle)
1606                 mono_image_fixup_vtable (image);
1607 #endif
1608
1609         mono_assembly_invoke_load_hook (ass);
1610
1611         mono_profiler_assembly_loaded (ass, MONO_PROFILE_OK);
1612         
1613         return ass;
1614 }
1615
1616 MonoAssembly *
1617 mono_assembly_load_from (MonoImage *image, const char *fname,
1618                          MonoImageOpenStatus *status)
1619 {
1620         return mono_assembly_load_from_full (image, fname, status, FALSE);
1621 }
1622
1623 /**
1624  * mono_assembly_name_free:
1625  * @aname: assembly name to free
1626  * 
1627  * Frees the provided assembly name object.
1628  * (it does not frees the object itself, only the name members).
1629  */
1630 void
1631 mono_assembly_name_free (MonoAssemblyName *aname)
1632 {
1633         if (aname == NULL)
1634                 return;
1635
1636         g_free ((void *) aname->name);
1637         g_free ((void *) aname->culture);
1638         g_free ((void *) aname->hash_value);
1639 }
1640
1641 static gboolean
1642 parse_public_key (const gchar *key, gchar** pubkey)
1643 {
1644         const gchar *pkey;
1645         gchar header [16], val, *arr;
1646         gint i, j, offset, bitlen, keylen, pkeylen;
1647         
1648         keylen = strlen (key) >> 1;
1649         if (keylen < 1)
1650                 return FALSE;
1651         
1652         val = g_ascii_xdigit_value (key [0]) << 4;
1653         val |= g_ascii_xdigit_value (key [1]);
1654         switch (val) {
1655                 case 0x00:
1656                         if (keylen < 13)
1657                                 return FALSE;
1658                         val = g_ascii_xdigit_value (key [24]);
1659                         val |= g_ascii_xdigit_value (key [25]);
1660                         if (val != 0x06)
1661                                 return FALSE;
1662                         pkey = key + 24;
1663                         break;
1664                 case 0x06:
1665                         pkey = key;
1666                         break;
1667                 default:
1668                         return FALSE;
1669         }
1670                 
1671         /* We need the first 16 bytes
1672         * to check whether this key is valid or not */
1673         pkeylen = strlen (pkey) >> 1;
1674         if (pkeylen < 16)
1675                 return FALSE;
1676                 
1677         for (i = 0, j = 0; i < 16; i++) {
1678                 header [i] = g_ascii_xdigit_value (pkey [j++]) << 4;
1679                 header [i] |= g_ascii_xdigit_value (pkey [j++]);
1680         }
1681
1682         if (header [0] != 0x06 || /* PUBLICKEYBLOB (0x06) */
1683                         header [1] != 0x02 || /* Version (0x02) */
1684                         header [2] != 0x00 || /* Reserved (word) */
1685                         header [3] != 0x00 ||
1686                         (guint)(read32 (header + 8)) != 0x31415352) /* DWORD magic = RSA1 */
1687                 return FALSE;
1688
1689         /* Based on this length, we _should_ be able to know if the length is right */
1690         bitlen = read32 (header + 12) >> 3;
1691         if ((bitlen + 16 + 4) != pkeylen)
1692                 return FALSE;
1693
1694         /* parsing is OK and the public key itself is not requested back */
1695         if (!pubkey)
1696                 return TRUE;
1697                 
1698         /* Encode the size of the blob */
1699         offset = 0;
1700         if (keylen <= 127) {
1701                 arr = g_malloc (keylen + 1);
1702                 arr [offset++] = keylen;
1703         } else {
1704                 arr = g_malloc (keylen + 2);
1705                 arr [offset++] = 0x80; /* 10bs */
1706                 arr [offset++] = keylen;
1707         }
1708                 
1709         for (i = offset, j = 0; i < keylen + offset; i++) {
1710                 arr [i] = g_ascii_xdigit_value (key [j++]) << 4;
1711                 arr [i] |= g_ascii_xdigit_value (key [j++]);
1712         }
1713
1714         *pubkey = arr;
1715
1716         return TRUE;
1717 }
1718
1719 static gboolean
1720 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)
1721 {
1722         gint major, minor, build, revision;
1723         gint len;
1724         gint version_parts;
1725         gchar *pkey, *pkeyptr, *encoded, tok [8];
1726
1727         memset (aname, 0, sizeof (MonoAssemblyName));
1728
1729         if (version) {
1730                 version_parts = sscanf (version, "%u.%u.%u.%u", &major, &minor, &build, &revision);
1731                 if (version_parts < 2 || version_parts > 4)
1732                         return FALSE;
1733
1734                 /* FIXME: we should set build & revision to -1 (instead of 0)
1735                 if these are not set in the version string. That way, later on,
1736                 we can still determine if these were specified. */
1737                 aname->major = major;
1738                 aname->minor = minor;
1739                 if (version_parts >= 3)
1740                         aname->build = build;
1741                 else
1742                         aname->build = 0;
1743                 if (version_parts == 4)
1744                         aname->revision = revision;
1745                 else
1746                         aname->revision = 0;
1747         }
1748         
1749         aname->flags = flags;
1750         aname->name = g_strdup (name);
1751         
1752         if (culture) {
1753                 if (g_ascii_strcasecmp (culture, "neutral") == 0)
1754                         aname->culture = g_strdup ("");
1755                 else
1756                         aname->culture = g_strdup (culture);
1757         }
1758         
1759         if (token && strncmp (token, "null", 4) != 0) {
1760                 char *lower;
1761
1762                 /* the constant includes the ending NULL, hence the -1 */
1763                 if (strlen (token) != (MONO_PUBLIC_KEY_TOKEN_LENGTH - 1)) {
1764                         mono_assembly_name_free (aname);
1765                         return FALSE;
1766                 }
1767                 lower = g_ascii_strdown (token, MONO_PUBLIC_KEY_TOKEN_LENGTH);
1768                 g_strlcpy ((char*)aname->public_key_token, lower, MONO_PUBLIC_KEY_TOKEN_LENGTH);
1769                 g_free (lower);
1770         }
1771
1772         if (key) {
1773                 if (strcmp (key, "null") == 0 || !parse_public_key (key, &pkey)) {
1774                         mono_assembly_name_free (aname);
1775                         return FALSE;
1776                 }
1777                 
1778                 len = mono_metadata_decode_blob_size ((const gchar *) pkey, (const gchar **) &pkeyptr);
1779                 // We also need to generate the key token
1780                 mono_digest_get_public_token ((guchar*) tok, (guint8*) pkeyptr, len);
1781                 encoded = encode_public_tok ((guchar*) tok, 8);
1782                 g_strlcpy ((gchar*)aname->public_key_token, encoded, MONO_PUBLIC_KEY_TOKEN_LENGTH);
1783                 g_free (encoded);
1784
1785                 if (save_public_key)
1786                         aname->public_key = (guint8*) pkey;
1787                 else
1788                         g_free (pkey);
1789         }
1790
1791         return TRUE;
1792 }
1793
1794 static gboolean
1795 parse_assembly_directory_name (const char *name, const char *dirname, MonoAssemblyName *aname)
1796 {
1797         gchar **parts;
1798         gboolean res;
1799         
1800         parts = g_strsplit (dirname, "_", 3);
1801         if (!parts || !parts[0] || !parts[1] || !parts[2]) {
1802                 g_strfreev (parts);
1803                 return FALSE;
1804         }
1805         
1806         res = build_assembly_name (name, parts[0], parts[1], parts[2], NULL, 0, aname, FALSE);
1807         g_strfreev (parts);
1808         return res;
1809 }
1810
1811 gboolean
1812 mono_assembly_name_parse_full (const char *name, MonoAssemblyName *aname, gboolean save_public_key, gboolean *is_version_defined, gboolean *is_token_defined)
1813 {
1814         gchar *dllname;
1815         gchar *version = NULL;
1816         gchar *culture = NULL;
1817         gchar *token = NULL;
1818         gchar *key = NULL;
1819         gchar *retargetable = NULL;
1820         gboolean res;
1821         gchar *value;
1822         gchar **parts;
1823         gchar **tmp;
1824         gboolean version_defined;
1825         gboolean token_defined;
1826         guint32 flags = 0;
1827
1828         if (!is_version_defined)
1829                 is_version_defined = &version_defined;
1830         *is_version_defined = FALSE;
1831         if (!is_token_defined)
1832                 is_token_defined = &token_defined;
1833         *is_token_defined = FALSE;
1834         
1835         parts = tmp = g_strsplit (name, ",", 6);
1836         if (!tmp || !*tmp) {
1837                 g_strfreev (tmp);
1838                 return FALSE;
1839         }
1840
1841         dllname = g_strstrip (*tmp);
1842         
1843         tmp++;
1844
1845         while (*tmp) {
1846                 value = g_strstrip (*tmp);
1847                 if (!g_ascii_strncasecmp (value, "Version=", 8)) {
1848                         *is_version_defined = TRUE;
1849                         version = g_strstrip (value + 8);
1850                         if (strlen (version) == 0) {
1851                                 goto cleanup_and_fail;
1852                         }
1853                         tmp++;
1854                         continue;
1855                 }
1856
1857                 if (!g_ascii_strncasecmp (value, "Culture=", 8)) {
1858                         culture = g_strstrip (value + 8);
1859                         if (strlen (culture) == 0) {
1860                                 goto cleanup_and_fail;
1861                         }
1862                         tmp++;
1863                         continue;
1864                 }
1865
1866                 if (!g_ascii_strncasecmp (value, "PublicKeyToken=", 15)) {
1867                         *is_token_defined = TRUE;
1868                         token = g_strstrip (value + 15);
1869                         if (strlen (token) == 0) {
1870                                 goto cleanup_and_fail;
1871                         }
1872                         tmp++;
1873                         continue;
1874                 }
1875
1876                 if (!g_ascii_strncasecmp (value, "PublicKey=", 10)) {
1877                         key = g_strstrip (value + 10);
1878                         if (strlen (key) == 0) {
1879                                 goto cleanup_and_fail;
1880                         }
1881                         tmp++;
1882                         continue;
1883                 }
1884
1885                 if (!g_ascii_strncasecmp (value, "Retargetable=", 13)) {
1886                         retargetable = g_strstrip (value + 13);
1887                         if (strlen (retargetable) == 0) {
1888                                 goto cleanup_and_fail;
1889                         }
1890                         if (!g_ascii_strcasecmp (retargetable, "yes")) {
1891                                 flags |= ASSEMBLYREF_RETARGETABLE_FLAG;
1892                         } else if (g_ascii_strcasecmp (retargetable, "no")) {
1893                                 goto cleanup_and_fail;
1894                         }
1895                         tmp++;
1896                         continue;
1897                 }
1898
1899                 if (!g_ascii_strncasecmp (value, "ProcessorArchitecture=", 22)) {
1900                         /* this is ignored for now, until we can change MonoAssemblyName */
1901                         tmp++;
1902                         continue;
1903                 }
1904
1905                 g_strfreev (parts);
1906                 return FALSE;
1907         }
1908
1909         /* if retargetable flag is set, then we must have a fully qualified name */
1910         if (retargetable != NULL && (version == NULL || culture == NULL || (key == NULL && token == NULL))) {
1911                 goto cleanup_and_fail;
1912         }
1913
1914         res = build_assembly_name (dllname, version, culture, token, key, flags,
1915                 aname, save_public_key);
1916         g_strfreev (parts);
1917         return res;
1918
1919 cleanup_and_fail:
1920         g_strfreev (parts);
1921         return FALSE;
1922 }
1923
1924 /**
1925  * mono_assembly_name_parse:
1926  * @name: name to parse
1927  * @aname: the destination assembly name
1928  * 
1929  * Parses an assembly qualified type name and assigns the name,
1930  * version, culture and token to the provided assembly name object.
1931  *
1932  * Returns: true if the name could be parsed.
1933  */
1934 gboolean
1935 mono_assembly_name_parse (const char *name, MonoAssemblyName *aname)
1936 {
1937         return mono_assembly_name_parse_full (name, aname, FALSE, NULL, NULL);
1938 }
1939
1940 /**
1941  * mono_assembly_name_new:
1942  * @name: name to parse
1943  *
1944  * Allocate a new MonoAssemblyName and fill its values from the
1945  * passed @name.
1946  *
1947  * Returns: a newly allocated structure or NULL if there was any failure.
1948  */
1949 MonoAssemblyName*
1950 mono_assembly_name_new (const char *name)
1951 {
1952         MonoAssemblyName *aname = g_new0 (MonoAssemblyName, 1);
1953         if (mono_assembly_name_parse (name, aname))
1954                 return aname;
1955         g_free (aname);
1956         return NULL;
1957 }
1958
1959 const char*
1960 mono_assembly_name_get_name (MonoAssemblyName *aname)
1961 {
1962         return aname->name;
1963 }
1964
1965 const char*
1966 mono_assembly_name_get_culture (MonoAssemblyName *aname)
1967 {
1968         return aname->culture;
1969 }
1970
1971 mono_byte*
1972 mono_assembly_name_get_pubkeytoken (MonoAssemblyName *aname)
1973 {
1974         if (aname->public_key_token [0])
1975                 return aname->public_key_token;
1976         return NULL;
1977 }
1978
1979 uint16_t
1980 mono_assembly_name_get_version (MonoAssemblyName *aname, uint16_t *minor, uint16_t *build, uint16_t *revision)
1981 {
1982         if (minor)
1983                 *minor = aname->minor;
1984         if (build)
1985                 *build = aname->build;
1986         if (revision)
1987                 *revision = aname->revision;
1988         return aname->major;
1989 }
1990
1991 static MonoAssembly*
1992 probe_for_partial_name (const char *basepath, const char *fullname, MonoAssemblyName *aname, MonoImageOpenStatus *status)
1993 {
1994         gchar *fullpath = NULL;
1995         GDir *dirhandle;
1996         const char* direntry;
1997         MonoAssemblyName gac_aname;
1998         gint major=-1, minor=0, build=0, revision=0;
1999         gboolean exact_version;
2000         
2001         dirhandle = g_dir_open (basepath, 0, NULL);
2002         if (!dirhandle)
2003                 return NULL;
2004                 
2005         exact_version = (aname->major | aname->minor | aname->build | aname->revision) != 0;
2006
2007         while ((direntry = g_dir_read_name (dirhandle))) {
2008                 gboolean match = TRUE;
2009                 
2010                 if(!parse_assembly_directory_name (aname->name, direntry, &gac_aname))
2011                         continue;
2012                 
2013                 if (aname->culture != NULL && strcmp (aname->culture, gac_aname.culture) != 0)
2014                         match = FALSE;
2015                         
2016                 if (match && strlen ((char*)aname->public_key_token) > 0 && 
2017                                 !mono_public_tokens_are_equal (aname->public_key_token, gac_aname.public_key_token))
2018                         match = FALSE;
2019                 
2020                 if (match) {
2021                         if (exact_version) {
2022                                 match = (aname->major == gac_aname.major && aname->minor == gac_aname.minor &&
2023                                                  aname->build == gac_aname.build && aname->revision == gac_aname.revision); 
2024                         }
2025                         else if (gac_aname.major < major)
2026                                 match = FALSE;
2027                         else if (gac_aname.major == major) {
2028                                 if (gac_aname.minor < minor)
2029                                         match = FALSE;
2030                                 else if (gac_aname.minor == minor) {
2031                                         if (gac_aname.build < build)
2032                                                 match = FALSE;
2033                                         else if (gac_aname.build == build && gac_aname.revision <= revision)
2034                                                 match = FALSE; 
2035                                 }
2036                         }
2037                 }
2038                 
2039                 if (match) {
2040                         major = gac_aname.major;
2041                         minor = gac_aname.minor;
2042                         build = gac_aname.build;
2043                         revision = gac_aname.revision;
2044                         g_free (fullpath);
2045                         fullpath = g_build_path (G_DIR_SEPARATOR_S, basepath, direntry, fullname, NULL);
2046                 }
2047
2048                 mono_assembly_name_free (&gac_aname);
2049         }
2050         
2051         g_dir_close (dirhandle);
2052         
2053         if (fullpath == NULL)
2054                 return NULL;
2055         else {
2056                 MonoAssembly *res = mono_assembly_open (fullpath, status);
2057                 g_free (fullpath);
2058                 return res;
2059         }
2060 }
2061
2062 MonoAssembly*
2063 mono_assembly_load_with_partial_name (const char *name, MonoImageOpenStatus *status)
2064 {
2065         MonoAssembly *res;
2066         MonoAssemblyName *aname, base_name;
2067 #ifndef DISABLE_ASSEMBLY_REMAPPING
2068         MonoAssemblyName maped_aname;
2069 #endif
2070         gchar *fullname, *gacpath;
2071         gchar **paths;
2072
2073         memset (&base_name, 0, sizeof (MonoAssemblyName));
2074         aname = &base_name;
2075
2076         if (!mono_assembly_name_parse (name, aname))
2077                 return NULL;
2078
2079 #ifndef DISABLE_ASSEMBLY_REMAPPING
2080         /* 
2081          * If no specific version has been requested, make sure we load the
2082          * correct version for system assemblies.
2083          */ 
2084         if ((aname->major | aname->minor | aname->build | aname->revision) == 0)
2085                 aname = mono_assembly_remap_version (aname, &maped_aname);
2086 #endif
2087         
2088         res = mono_assembly_loaded (aname);
2089         if (res) {
2090                 mono_assembly_name_free (aname);
2091                 return res;
2092         }
2093
2094         res = invoke_assembly_preload_hook (aname, assemblies_path);
2095         if (res) {
2096                 res->in_gac = FALSE;
2097                 mono_assembly_name_free (aname);
2098                 return res;
2099         }
2100
2101         fullname = g_strdup_printf ("%s.dll", aname->name);
2102
2103         if (extra_gac_paths) {
2104                 paths = extra_gac_paths;
2105                 while (!res && *paths) {
2106                         gacpath = g_build_path (G_DIR_SEPARATOR_S, *paths, "lib", "mono", "gac", aname->name, NULL);
2107                         res = probe_for_partial_name (gacpath, fullname, aname, status);
2108                         g_free (gacpath);
2109                         paths++;
2110                 }
2111         }
2112
2113         if (res) {
2114                 res->in_gac = TRUE;
2115                 g_free (fullname);
2116                 mono_assembly_name_free (aname);
2117                 return res;
2118         }
2119
2120         gacpath = g_build_path (G_DIR_SEPARATOR_S, mono_assembly_getrootdir (), "mono", "gac", aname->name, NULL);
2121         res = probe_for_partial_name (gacpath, fullname, aname, status);
2122         g_free (gacpath);
2123
2124         if (res)
2125                 res->in_gac = TRUE;
2126         else {
2127                 MonoDomain *domain = mono_domain_get ();
2128                 MonoReflectionAssembly *refasm = mono_try_assembly_resolve (domain, mono_string_new (domain, name), FALSE);
2129                 if (refasm)
2130                         res = refasm->assembly;
2131         }
2132         
2133         g_free (fullname);
2134         mono_assembly_name_free (aname);
2135
2136         return res;
2137 }
2138
2139 static MonoBoolean
2140 mono_assembly_is_in_gac (const gchar *filename)
2141 {
2142         const gchar *rootdir;
2143         gchar *gp;
2144         gchar **paths;
2145
2146         if (filename == NULL)
2147                 return FALSE;
2148
2149         for (paths = extra_gac_paths; paths && *paths; paths++) {
2150                 if (strstr (*paths, filename) != *paths)
2151                         continue;
2152
2153                 gp = (gchar *) (filename + strlen (*paths));
2154                 if (*gp != G_DIR_SEPARATOR)
2155                         continue;
2156                 gp++;
2157                 if (strncmp (gp, "lib", 3))
2158                         continue;
2159                 gp += 3;
2160                 if (*gp != G_DIR_SEPARATOR)
2161                         continue;
2162                 gp++;
2163                 if (strncmp (gp, "mono", 4))
2164                         continue;
2165                 gp += 4;
2166                 if (*gp != G_DIR_SEPARATOR)
2167                         continue;
2168                 gp++;
2169                 if (strncmp (gp, "gac", 3))
2170                         continue;
2171                 gp += 3;
2172                 if (*gp != G_DIR_SEPARATOR)
2173                         continue;
2174
2175                 return TRUE;
2176         }
2177
2178         rootdir = mono_assembly_getrootdir ();
2179         if (strstr (filename, rootdir) != filename)
2180                 return FALSE;
2181
2182         gp = (gchar *) (filename + strlen (rootdir));
2183         if (*gp != G_DIR_SEPARATOR)
2184                 return FALSE;
2185         gp++;
2186         if (strncmp (gp, "mono", 4))
2187                 return FALSE;
2188         gp += 4;
2189         if (*gp != G_DIR_SEPARATOR)
2190                 return FALSE;
2191         gp++;
2192         if (strncmp (gp, "gac", 3))
2193                 return FALSE;
2194         gp += 3;
2195         if (*gp != G_DIR_SEPARATOR)
2196                 return FALSE;
2197         return TRUE;
2198 }
2199
2200 static MonoImage*
2201 mono_assembly_load_publisher_policy (MonoAssemblyName *aname)
2202 {
2203         MonoImage *image;
2204         gchar *filename, *pname, *name, *culture, *version, *fullpath, *subpath;
2205         gchar **paths;
2206         gint32 len;
2207
2208         if (strstr (aname->name, ".dll")) {
2209                 len = strlen (aname->name) - 4;
2210                 name = g_malloc (len);
2211                 strncpy (name, aname->name, len);
2212         } else
2213                 name = g_strdup (aname->name);
2214         
2215         if (aname->culture)
2216                 culture = g_utf8_strdown (aname->culture, -1);
2217         else
2218                 culture = g_strdup ("");
2219         
2220         pname = g_strdup_printf ("policy.%d.%d.%s", aname->major, aname->minor, name);
2221         version = g_strdup_printf ("0.0.0.0_%s_%s", culture, aname->public_key_token);
2222         g_free (name);
2223         g_free (culture);
2224         
2225         filename = g_strconcat (pname, ".dll", NULL);
2226         subpath = g_build_path (G_DIR_SEPARATOR_S, pname, version, filename, NULL);
2227         g_free (pname);
2228         g_free (version);
2229         g_free (filename);
2230
2231         image = NULL;
2232         if (extra_gac_paths) {
2233                 paths = extra_gac_paths;
2234                 while (!image && *paths) {
2235                         fullpath = g_build_path (G_DIR_SEPARATOR_S, *paths,
2236                                         "lib", "mono", "gac", subpath, NULL);
2237                         image = mono_image_open (fullpath, NULL);
2238                         g_free (fullpath);
2239                         paths++;
2240                 }
2241         }
2242
2243         if (image) {
2244                 g_free (subpath);
2245                 return image;
2246         }
2247
2248         fullpath = g_build_path (G_DIR_SEPARATOR_S, mono_assembly_getrootdir (), 
2249                         "mono", "gac", subpath, NULL);
2250         image = mono_image_open (fullpath, NULL);
2251         g_free (subpath);
2252         g_free (fullpath);
2253         
2254         return image;
2255 }
2256
2257 static MonoAssemblyName*
2258 mono_assembly_bind_version (MonoAssemblyBindingInfo *info, MonoAssemblyName *aname, MonoAssemblyName *dest_name)
2259 {
2260         memcpy (dest_name, aname, sizeof (MonoAssemblyName));
2261         dest_name->major = info->new_version.major;
2262         dest_name->minor = info->new_version.minor;
2263         dest_name->build = info->new_version.build;
2264         dest_name->revision = info->new_version.revision;
2265         
2266         return dest_name;
2267 }
2268
2269 /* LOCKING: Assumes that we are already locked */
2270 static MonoAssemblyBindingInfo*
2271 search_binding_loaded (MonoAssemblyName *aname)
2272 {
2273         GSList *tmp;
2274
2275         for (tmp = loaded_assembly_bindings; tmp; tmp = tmp->next) {
2276                 MonoAssemblyBindingInfo *info = tmp->data;
2277                 if (assembly_binding_maps_name (info, aname))
2278                         return info;
2279         }
2280
2281         return NULL;
2282 }
2283
2284 static inline gboolean
2285 info_compare_versions (AssemblyVersionSet *left, AssemblyVersionSet *right)
2286 {
2287         if (left->major != right->major || left->minor != right->minor ||
2288             left->build != right->build || left->revision != right->revision)
2289                 return FALSE;
2290
2291         return TRUE;
2292 }
2293
2294 static inline gboolean
2295 info_versions_equal (MonoAssemblyBindingInfo *left, MonoAssemblyBindingInfo *right)
2296 {
2297         if (left->has_old_version_bottom != right->has_old_version_bottom)
2298                 return FALSE;
2299
2300         if (left->has_old_version_top != right->has_old_version_top)
2301                 return FALSE;
2302
2303         if (left->has_new_version != right->has_new_version)
2304                 return FALSE;
2305
2306         if (left->has_old_version_bottom && !info_compare_versions (&left->old_version_bottom, &right->old_version_bottom))
2307                 return FALSE;
2308
2309         if (left->has_old_version_top && !info_compare_versions (&left->old_version_top, &right->old_version_top))
2310                 return FALSE;
2311
2312         if (left->has_new_version && !info_compare_versions (&left->new_version, &right->new_version))
2313                 return FALSE;
2314
2315         return TRUE;
2316 }
2317
2318 /* LOCKING: assumes all the necessary locks are held */
2319 static void
2320 assembly_binding_info_parsed (MonoAssemblyBindingInfo *info, void *user_data)
2321 {
2322         MonoAssemblyBindingInfo *info_copy;
2323         GSList *tmp;
2324         MonoAssemblyBindingInfo *info_tmp;
2325         MonoDomain *domain = (MonoDomain*)user_data;
2326
2327         if (!domain)
2328                 return;
2329
2330         for (tmp = domain->assembly_bindings; tmp; tmp = tmp->next) {
2331                 info_tmp = tmp->data;
2332                 if (strcmp (info->name, info_tmp->name) == 0 && info_versions_equal (info, info_tmp))
2333                         return;
2334         }
2335
2336         info_copy = mono_mempool_alloc0 (domain->mp, sizeof (MonoAssemblyBindingInfo));
2337         memcpy (info_copy, info, sizeof (MonoAssemblyBindingInfo));
2338         if (info->name)
2339                 info_copy->name = mono_mempool_strdup (domain->mp, info->name);
2340         if (info->culture)
2341                 info_copy->culture = mono_mempool_strdup (domain->mp, info->culture);
2342
2343         domain->assembly_bindings = g_slist_append_mempool (domain->mp, domain->assembly_bindings, info_copy);
2344 }
2345
2346 static inline gboolean
2347 info_major_minor_in_range (MonoAssemblyBindingInfo *info, MonoAssemblyName *aname)
2348 {
2349         if (!info->has_old_version_bottom)
2350                 return FALSE;
2351
2352         if (info->old_version_bottom.major > aname->major || info->old_version_bottom.minor > aname->minor)
2353                 return FALSE;
2354
2355         if (info->has_old_version_top && (info->old_version_top.major < aname->major || info->old_version_top.minor < aname->minor))
2356                 return FALSE;
2357
2358         /* This is not the nicest way to do it, but it's a by-product of the way parsing is done */
2359         info->major = aname->major;
2360         info->minor = aname->minor;
2361
2362         return TRUE;
2363 }
2364
2365 /* LOCKING: Assumes that we are already locked - both loader and domain locks */
2366 static MonoAssemblyBindingInfo*
2367 get_per_domain_assembly_binding_info (MonoDomain *domain, MonoAssemblyName *aname)
2368 {
2369         MonoAssemblyBindingInfo *info;
2370         GSList *list;
2371
2372         if (!domain->assembly_bindings)
2373                 return NULL;
2374
2375         info = NULL;
2376         for (list = domain->assembly_bindings; list; list = list->next) {
2377                 info = list->data;
2378                 if (info && !strcmp (aname->name, info->name) && info_major_minor_in_range (info, aname))
2379                         break;
2380                 info = NULL;
2381         }
2382
2383         if (info) {
2384                 if (info->name && info->public_key_token [0] && info->has_old_version_bottom &&
2385                     info->has_new_version && assembly_binding_maps_name (info, aname))
2386                         info->is_valid = TRUE;
2387                 else
2388                         info->is_valid = FALSE;
2389         }
2390
2391         return info;
2392 }
2393
2394 static MonoAssemblyName*
2395 mono_assembly_apply_binding (MonoAssemblyName *aname, MonoAssemblyName *dest_name)
2396 {
2397         MonoAssemblyBindingInfo *info, *info2;
2398         MonoImage *ppimage;
2399         MonoDomain *domain;
2400
2401         if (aname->public_key_token [0] == 0)
2402                 return aname;
2403
2404         domain = mono_domain_get ();
2405         mono_loader_lock ();
2406         info = search_binding_loaded (aname);
2407         if (!info) {
2408                 mono_domain_lock (domain);
2409                 info = get_per_domain_assembly_binding_info (domain, aname);
2410                 mono_domain_unlock (domain);
2411         }
2412
2413         mono_loader_unlock ();
2414         if (info) {
2415                 if (!check_policy_versions (info, aname))
2416                         return aname;
2417                 
2418                 mono_assembly_bind_version (info, aname, dest_name);
2419                 return dest_name;
2420         }
2421
2422         if (domain && domain->setup && domain->setup->configuration_file) {
2423                 mono_domain_lock (domain);
2424                 if (!domain->assembly_bindings_parsed) {
2425                         gchar *domain_config_file = mono_string_to_utf8 (domain->setup->configuration_file);
2426
2427                         mono_config_parse_assembly_bindings (domain_config_file, aname->major, aname->minor, domain, assembly_binding_info_parsed);
2428                         domain->assembly_bindings_parsed = TRUE;
2429                         g_free (domain_config_file);
2430                 }
2431                 mono_domain_unlock (domain);
2432
2433                 mono_loader_lock ();
2434                 mono_domain_lock (domain);
2435                 info = get_per_domain_assembly_binding_info (domain, aname);
2436                 mono_domain_unlock (domain);
2437                 mono_loader_unlock ();
2438         }
2439
2440         if (!info) {
2441                 info = g_new0 (MonoAssemblyBindingInfo, 1);
2442                 info->major = aname->major;
2443                 info->minor = aname->minor;
2444         }
2445
2446         if (!info->is_valid) {
2447                 ppimage = mono_assembly_load_publisher_policy (aname);
2448                 if (ppimage) {
2449                         get_publisher_policy_info (ppimage, aname, info);
2450                         mono_image_close (ppimage);
2451                 }
2452         }
2453
2454         /* Define default error value if needed */
2455         if (!info->is_valid) {
2456                 info->name = g_strdup (aname->name);
2457                 info->culture = g_strdup (aname->culture);
2458                 g_strlcpy ((char *)info->public_key_token, (const char *)aname->public_key_token, MONO_PUBLIC_KEY_TOKEN_LENGTH);
2459         }
2460         
2461         mono_loader_lock ();
2462         info2 = search_binding_loaded (aname);
2463         if (info2) {
2464                 /* This binding was added by another thread 
2465                  * before us */
2466                 mono_assembly_binding_info_free (info);
2467                 g_free (info);
2468                 
2469                 info = info2;
2470         } else
2471                 loaded_assembly_bindings = g_slist_prepend (loaded_assembly_bindings, info);
2472                 
2473         mono_loader_unlock ();
2474         
2475         if (!info->is_valid || !check_policy_versions (info, aname))
2476                 return aname;
2477
2478         mono_assembly_bind_version (info, aname, dest_name);
2479         return dest_name;
2480 }
2481
2482 /**
2483  * mono_assembly_load_from_gac
2484  *
2485  * @aname: The assembly name object
2486  */
2487 static MonoAssembly*
2488 mono_assembly_load_from_gac (MonoAssemblyName *aname,  gchar *filename, MonoImageOpenStatus *status, MonoBoolean refonly)
2489 {
2490         MonoAssembly *result = NULL;
2491         gchar *name, *version, *culture, *fullpath, *subpath;
2492         gint32 len;
2493         gchar **paths;
2494         char *pubtok;
2495
2496         if (aname->public_key_token [0] == 0) {
2497                 return NULL;
2498         }
2499
2500         if (strstr (aname->name, ".dll")) {
2501                 len = strlen (filename) - 4;
2502                 name = g_malloc (len);
2503                 strncpy (name, aname->name, len);
2504         } else {
2505                 name = g_strdup (aname->name);
2506         }
2507
2508         if (aname->culture) {
2509                 culture = g_utf8_strdown (aname->culture, -1);
2510         } else {
2511                 culture = g_strdup ("");
2512         }
2513
2514         pubtok = g_ascii_strdown ((char*)aname->public_key_token, MONO_PUBLIC_KEY_TOKEN_LENGTH);
2515         version = g_strdup_printf ("%d.%d.%d.%d_%s_%s", aname->major,
2516                         aname->minor, aname->build, aname->revision,
2517                         culture, pubtok);
2518         g_free (pubtok);
2519         
2520         subpath = g_build_path (G_DIR_SEPARATOR_S, name, version, filename, NULL);
2521         g_free (name);
2522         g_free (version);
2523         g_free (culture);
2524
2525         if (extra_gac_paths) {
2526                 paths = extra_gac_paths;
2527                 while (!result && *paths) {
2528                         fullpath = g_build_path (G_DIR_SEPARATOR_S, *paths, "lib", "mono", "gac", subpath, NULL);
2529                         result = mono_assembly_open_full (fullpath, status, refonly);
2530                         g_free (fullpath);
2531                         paths++;
2532                 }
2533         }
2534
2535         if (result) {
2536                 result->in_gac = TRUE;
2537                 g_free (subpath);
2538                 return result;
2539         }
2540
2541         fullpath = g_build_path (G_DIR_SEPARATOR_S, mono_assembly_getrootdir (),
2542                         "mono", "gac", subpath, NULL);
2543         result = mono_assembly_open_full (fullpath, status, refonly);
2544         g_free (fullpath);
2545
2546         if (result)
2547                 result->in_gac = TRUE;
2548         
2549         g_free (subpath);
2550
2551         return result;
2552 }
2553
2554 MonoAssembly*
2555 mono_assembly_load_corlib (const MonoRuntimeInfo *runtime, MonoImageOpenStatus *status)
2556 {
2557         char *corlib_file;
2558
2559         if (corlib) {
2560                 /* g_print ("corlib already loaded\n"); */
2561                 return corlib;
2562         }
2563
2564 #if defined(__native_client__)
2565         if (corlibData != NULL && corlibSize != 0) {
2566                 int status = 0;
2567                 /* First "FALSE" instructs mono not to make a copy. */
2568                 /* Second "FALSE" says this is not just a ref.      */
2569                 MonoImage* image = mono_image_open_from_data_full (corlibData, corlibSize, FALSE, &status, FALSE);
2570                 if (image == NULL || status != 0)
2571                         g_print("mono_image_open_from_data_full failed: %d\n", status);
2572                 corlib = mono_assembly_load_from_full (image, "mscorlib", &status, FALSE);
2573                 if (corlib == NULL || status != 0)
2574                         g_print ("mono_assembly_load_from_full failed: %d\n", status);
2575                 if (corlib)
2576                         return corlib;
2577         }
2578 #endif
2579         
2580         if (assemblies_path) {
2581                 corlib = load_in_path ("mscorlib.dll", (const char**)assemblies_path, status, FALSE);
2582                 if (corlib)
2583                         return corlib;
2584         }
2585
2586         /* Load corlib from mono/<version> */
2587         
2588         corlib_file = g_build_filename ("mono", runtime->framework_version, "mscorlib.dll", NULL);
2589         if (assemblies_path) {
2590                 corlib = load_in_path (corlib_file, (const char**)assemblies_path, status, FALSE);
2591                 if (corlib) {
2592                         g_free (corlib_file);
2593                         return corlib;
2594                 }
2595         }
2596         corlib = load_in_path (corlib_file, default_path, status, FALSE);
2597         g_free (corlib_file);
2598
2599         return corlib;
2600 }
2601
2602 MonoAssembly*
2603 mono_assembly_load_full_nosearch (MonoAssemblyName *aname, 
2604                                                                   const char       *basedir, 
2605                                                                   MonoImageOpenStatus *status,
2606                                                                   gboolean refonly)
2607 {
2608         MonoAssembly *result;
2609         char *fullpath, *filename;
2610 #ifndef DISABLE_ASSEMBLY_REMAPPING
2611         MonoAssemblyName maped_aname;
2612 #endif
2613         MonoAssemblyName maped_name_pp;
2614         int ext_index;
2615         const char *ext;
2616         int len;
2617
2618 #ifndef DISABLE_ASSEMBLY_REMAPPING
2619         aname = mono_assembly_remap_version (aname, &maped_aname);
2620 #endif
2621         
2622         /* Reflection only assemblies don't get assembly binding */
2623         if (!refonly)
2624                 aname = mono_assembly_apply_binding (aname, &maped_name_pp);
2625         
2626         result = mono_assembly_loaded_full (aname, refonly);
2627         if (result)
2628                 return result;
2629
2630         result = refonly ? invoke_assembly_refonly_preload_hook (aname, assemblies_path) : invoke_assembly_preload_hook (aname, assemblies_path);
2631         if (result) {
2632                 result->in_gac = FALSE;
2633                 return result;
2634         }
2635
2636         /* Currently we retrieve the loaded corlib for reflection 
2637          * only requests, like a common reflection only assembly 
2638          */
2639         if (strcmp (aname->name, "mscorlib") == 0 || strcmp (aname->name, "mscorlib.dll") == 0) {
2640                 return mono_assembly_load_corlib (mono_get_runtime_info (), status);
2641         }
2642
2643         len = strlen (aname->name);
2644         for (ext_index = 0; ext_index < 2; ext_index ++) {
2645                 ext = ext_index == 0 ? ".dll" : ".exe";
2646                 if (len > 4 && (!strcmp (aname->name + len - 4, ".dll") || !strcmp (aname->name + len - 4, ".exe"))) {
2647                         filename = g_strdup (aname->name);
2648                         /* Don't try appending .dll/.exe if it already has one of those extensions */
2649                         ext_index++;
2650                 } else {
2651                         filename = g_strconcat (aname->name, ext, NULL);
2652                 }
2653
2654                 result = mono_assembly_load_from_gac (aname, filename, status, refonly);
2655                 if (result) {
2656                         g_free (filename);
2657                         return result;
2658                 }
2659
2660                 if (basedir) {
2661                         fullpath = g_build_filename (basedir, filename, NULL);
2662                         result = mono_assembly_open_full (fullpath, status, refonly);
2663                         g_free (fullpath);
2664                         if (result) {
2665                                 result->in_gac = FALSE;
2666                                 g_free (filename);
2667                                 return result;
2668                         }
2669                 }
2670
2671                 result = load_in_path (filename, default_path, status, refonly);
2672                 if (result)
2673                         result->in_gac = FALSE;
2674                 g_free (filename);
2675                 if (result)
2676                         return result;
2677         }
2678
2679         return result;
2680 }
2681
2682 /**
2683  * mono_assembly_load_full:
2684  * @aname: A MonoAssemblyName with the assembly name to load.
2685  * @basedir: A directory to look up the assembly at.
2686  * @status: a pointer to a MonoImageOpenStatus to return the status of the load operation
2687  * @refonly: Whether this assembly is being opened in "reflection-only" mode.
2688  *
2689  * Loads the assembly referenced by @aname, if the value of @basedir is not NULL, it
2690  * attempts to load the assembly from that directory before probing the standard locations.
2691  *
2692  * If the assembly is being opened in reflection-only mode (@refonly set to TRUE) then no 
2693  * assembly binding takes place.
2694  *
2695  * Returns: the assembly referenced by @aname loaded or NULL on error.   On error the
2696  * value pointed by status is updated with an error code.
2697  */
2698 MonoAssembly*
2699 mono_assembly_load_full (MonoAssemblyName *aname, const char *basedir, MonoImageOpenStatus *status, gboolean refonly)
2700 {
2701         MonoAssembly *result = mono_assembly_load_full_nosearch (aname, basedir, status, refonly);
2702         
2703         if (!result)
2704                 /* Try a postload search hook */
2705                 result = mono_assembly_invoke_search_hook_internal (aname, refonly, TRUE);
2706         return result;
2707 }
2708
2709 /**
2710  * mono_assembly_load:
2711  * @aname: A MonoAssemblyName with the assembly name to load.
2712  * @basedir: A directory to look up the assembly at.
2713  * @status: a pointer to a MonoImageOpenStatus to return the status of the load operation
2714  *
2715  * Loads the assembly referenced by @aname, if the value of @basedir is not NULL, it
2716  * attempts to load the assembly from that directory before probing the standard locations.
2717  *
2718  * Returns: the assembly referenced by @aname loaded or NULL on error.   On error the
2719  * value pointed by status is updated with an error code.
2720  */
2721 MonoAssembly*
2722 mono_assembly_load (MonoAssemblyName *aname, const char *basedir, MonoImageOpenStatus *status)
2723 {
2724         return mono_assembly_load_full (aname, basedir, status, FALSE);
2725 }
2726         
2727 MonoAssembly*
2728 mono_assembly_loaded_full (MonoAssemblyName *aname, gboolean refonly)
2729 {
2730         MonoAssembly *res;
2731 #ifndef DISABLE_ASSEMBLY_REMAPPING
2732         MonoAssemblyName maped_aname;
2733
2734         aname = mono_assembly_remap_version (aname, &maped_aname);
2735 #endif
2736
2737         res = mono_assembly_invoke_search_hook_internal (aname, refonly, FALSE);
2738
2739         return res;
2740 }
2741
2742 /**
2743  * mono_assembly_loaded:
2744  * @aname: an assembly to look for.
2745  *
2746  * Returns: NULL If the given @aname assembly has not been loaded, or a pointer to
2747  * a MonoAssembly that matches the MonoAssemblyName specified.
2748  */
2749 MonoAssembly*
2750 mono_assembly_loaded (MonoAssemblyName *aname)
2751 {
2752         return mono_assembly_loaded_full (aname, FALSE);
2753 }
2754
2755 /*
2756  * Returns whether mono_assembly_close_finish() must be called as
2757  * well.  See comment for mono_image_close_except_pools() for why we
2758  * unload in two steps.
2759  */
2760 gboolean
2761 mono_assembly_close_except_image_pools (MonoAssembly *assembly)
2762 {
2763         GSList *tmp;
2764         g_return_val_if_fail (assembly != NULL, FALSE);
2765
2766         if (assembly == REFERENCE_MISSING)
2767                 return FALSE;
2768
2769         /* Might be 0 already */
2770         if (InterlockedDecrement (&assembly->ref_count) > 0)
2771                 return FALSE;
2772
2773         mono_profiler_assembly_event (assembly, MONO_PROFILE_START_UNLOAD);
2774
2775         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_ASSEMBLY, "Unloading assembly %s [%p].", assembly->aname.name, assembly);
2776
2777         mono_debug_close_image (assembly->image);
2778
2779         mono_assemblies_lock ();
2780         loaded_assemblies = g_list_remove (loaded_assemblies, assembly);
2781         mono_assemblies_unlock ();
2782
2783         assembly->image->assembly = NULL;
2784
2785         if (!mono_image_close_except_pools (assembly->image))
2786                 assembly->image = NULL;
2787
2788         for (tmp = assembly->friend_assembly_names; tmp; tmp = tmp->next) {
2789                 MonoAssemblyName *fname = tmp->data;
2790                 mono_assembly_name_free (fname);
2791                 g_free (fname);
2792         }
2793         g_slist_free (assembly->friend_assembly_names);
2794         g_free (assembly->basedir);
2795
2796         mono_profiler_assembly_event (assembly, MONO_PROFILE_END_UNLOAD);
2797
2798         return TRUE;
2799 }
2800
2801 void
2802 mono_assembly_close_finish (MonoAssembly *assembly)
2803 {
2804         g_assert (assembly && assembly != REFERENCE_MISSING);
2805
2806         if (assembly->image)
2807                 mono_image_close_finish (assembly->image);
2808
2809         if (assembly->dynamic) {
2810                 g_free ((char*)assembly->aname.culture);
2811         } else {
2812                 g_free (assembly);
2813         }
2814 }
2815
2816 /**
2817  * mono_assembly_close:
2818  * @assembly: the assembly to release.
2819  *
2820  * This method releases a reference to the @assembly.  The assembly is
2821  * only released when all the outstanding references to it are released.
2822  */
2823 void
2824 mono_assembly_close (MonoAssembly *assembly)
2825 {
2826         if (mono_assembly_close_except_image_pools (assembly))
2827                 mono_assembly_close_finish (assembly);
2828 }
2829
2830 MonoImage*
2831 mono_assembly_load_module (MonoAssembly *assembly, guint32 idx)
2832 {
2833         return mono_image_load_file_for_image (assembly->image, idx);
2834 }
2835
2836 void
2837 mono_assembly_foreach (GFunc func, gpointer user_data)
2838 {
2839         GList *copy;
2840
2841         /*
2842          * We make a copy of the list to avoid calling the callback inside the 
2843          * lock, which could lead to deadlocks.
2844          */
2845         mono_assemblies_lock ();
2846         copy = g_list_copy (loaded_assemblies);
2847         mono_assemblies_unlock ();
2848
2849         g_list_foreach (loaded_assemblies, func, user_data);
2850
2851         g_list_free (copy);
2852 }
2853
2854 /**
2855  * mono_assemblies_cleanup:
2856  *
2857  * Free all resources used by this module.
2858  */
2859 void
2860 mono_assemblies_cleanup (void)
2861 {
2862         GSList *l;
2863
2864         DeleteCriticalSection (&assemblies_mutex);
2865
2866         for (l = loaded_assembly_bindings; l; l = l->next) {
2867                 MonoAssemblyBindingInfo *info = l->data;
2868
2869                 mono_assembly_binding_info_free (info);
2870                 g_free (info);
2871         }
2872         g_slist_free (loaded_assembly_bindings);
2873
2874         free_assembly_load_hooks ();
2875         free_assembly_search_hooks ();
2876         free_assembly_preload_hooks ();
2877 }
2878
2879 /*
2880  * Holds the assembly of the application, for
2881  * System.Diagnostics.Process::MainModule
2882  */
2883 static MonoAssembly *main_assembly=NULL;
2884
2885 void
2886 mono_assembly_set_main (MonoAssembly *assembly)
2887 {
2888         main_assembly = assembly;
2889 }
2890
2891 /**
2892  * mono_assembly_get_main:
2893  *
2894  * Returns: the assembly for the application, the first assembly that is loaded by the VM
2895  */
2896 MonoAssembly *
2897 mono_assembly_get_main (void)
2898 {
2899         return (main_assembly);
2900 }
2901
2902 /**
2903  * mono_assembly_get_image:
2904  * @assembly: The assembly to retrieve the image from
2905  *
2906  * Returns: the MonoImage associated with this assembly.
2907  */
2908 MonoImage*
2909 mono_assembly_get_image (MonoAssembly *assembly)
2910 {
2911         return assembly->image;
2912 }
2913
2914 void
2915 mono_register_bundled_assemblies (const MonoBundledAssembly **assemblies)
2916 {
2917         bundles = assemblies;
2918 }
2919
2920 #define MONO_DECLSEC_FORMAT_10          0x3C
2921 #define MONO_DECLSEC_FORMAT_20          0x2E
2922 #define MONO_DECLSEC_FIELD              0x53
2923 #define MONO_DECLSEC_PROPERTY           0x54
2924
2925 #define SKIP_VISIBILITY_XML_ATTRIBUTE ("\"SkipVerification\"")
2926 #define SKIP_VISIBILITY_ATTRIBUTE_NAME ("System.Security.Permissions.SecurityPermissionAttribute")
2927 #define SKIP_VISIBILITY_ATTRIBUTE_SIZE (sizeof (SKIP_VISIBILITY_ATTRIBUTE_NAME) - 1)
2928 #define SKIP_VISIBILITY_PROPERTY_NAME ("SkipVerification")
2929 #define SKIP_VISIBILITY_PROPERTY_SIZE (sizeof (SKIP_VISIBILITY_PROPERTY_NAME) - 1)
2930
2931 static gboolean
2932 mono_assembly_try_decode_skip_verification_param (const char *p, const char **resp, gboolean *abort_decoding)
2933 {
2934         int len;
2935         switch (*p++) {
2936         case MONO_DECLSEC_PROPERTY:
2937                 break;
2938         case MONO_DECLSEC_FIELD:
2939         default:
2940                 *abort_decoding = TRUE;
2941                 return FALSE;
2942                 break;
2943         }
2944
2945         if (*p++ != MONO_TYPE_BOOLEAN) {
2946                 *abort_decoding = TRUE;
2947                 return FALSE;
2948         }
2949                 
2950         /* property name length */
2951         len = mono_metadata_decode_value (p, &p);
2952
2953         if (len >= SKIP_VISIBILITY_PROPERTY_SIZE && !memcmp (p, SKIP_VISIBILITY_PROPERTY_NAME, SKIP_VISIBILITY_PROPERTY_SIZE)) {
2954                 p += len;
2955                 return *p;
2956         }
2957         p += len + 1;
2958
2959         *resp = p;
2960         return FALSE;
2961 }
2962
2963 static gboolean
2964 mono_assembly_try_decode_skip_verification (const char *p, const char *endn)
2965 {
2966         int i, j, num, len, params_len;
2967
2968         if (*p == MONO_DECLSEC_FORMAT_10) {
2969                 gsize read, written;
2970                 char *res = g_convert (p, endn - p, "UTF-8", "UTF-16LE", &read, &written, NULL);
2971                 if (res) {
2972                         gboolean found = strstr (res, SKIP_VISIBILITY_XML_ATTRIBUTE) != NULL;
2973                         g_free (res);
2974                         return found;
2975                 }
2976                 return FALSE;
2977         }
2978         if (*p++ != MONO_DECLSEC_FORMAT_20)
2979                 return FALSE;
2980
2981         /* number of encoded permission attributes */
2982         num = mono_metadata_decode_value (p, &p);
2983         for (i = 0; i < num; ++i) {
2984                 gboolean is_valid = FALSE;
2985                 gboolean abort_decoding = FALSE;
2986
2987                 /* attribute name length */
2988                 len =  mono_metadata_decode_value (p, &p);
2989
2990                 /* We don't really need to fully decode the type. Comparing the name is enough */
2991                 is_valid = len >= SKIP_VISIBILITY_ATTRIBUTE_SIZE && !memcmp (p, SKIP_VISIBILITY_ATTRIBUTE_NAME, SKIP_VISIBILITY_ATTRIBUTE_SIZE);
2992
2993                 p += len;
2994
2995                 /*size of the params table*/
2996                 params_len =  mono_metadata_decode_value (p, &p);
2997                 if (is_valid) {
2998                         const char *params_end = p + params_len;
2999                         
3000                         /* number of parameters */
3001                         len = mono_metadata_decode_value (p, &p);
3002         
3003                         for (j = 0; j < len; ++j) {
3004                                 if (mono_assembly_try_decode_skip_verification_param (p, &p, &abort_decoding))
3005                                         return TRUE;
3006                                 if (abort_decoding)
3007                                         break;
3008                         }
3009                         p = params_end;
3010                 } else {
3011                         p += params_len;
3012                 }
3013         }
3014         
3015         return FALSE;
3016 }
3017
3018
3019 gboolean
3020 mono_assembly_has_skip_verification (MonoAssembly *assembly)
3021 {
3022         MonoTableInfo *t;       
3023         guint32 cols [MONO_DECL_SECURITY_SIZE];
3024         const char *blob;
3025         int i, len;
3026
3027         if (MONO_SECMAN_FLAG_INIT (assembly->skipverification))
3028                 return MONO_SECMAN_FLAG_GET_VALUE (assembly->skipverification);
3029
3030         t = &assembly->image->tables [MONO_TABLE_DECLSECURITY];
3031
3032         for (i = 0; i < t->rows; ++i) {
3033                 mono_metadata_decode_row (t, i, cols, MONO_DECL_SECURITY_SIZE);
3034                 if ((cols [MONO_DECL_SECURITY_PARENT] & MONO_HAS_DECL_SECURITY_MASK) != MONO_HAS_DECL_SECURITY_ASSEMBLY)
3035                         continue;
3036                 if (cols [MONO_DECL_SECURITY_ACTION] != SECURITY_ACTION_REQMIN)
3037                         continue;
3038
3039                 blob = mono_metadata_blob_heap (assembly->image, cols [MONO_DECL_SECURITY_PERMISSIONSET]);
3040                 len = mono_metadata_decode_blob_size (blob, &blob);
3041                 if (!len)
3042                         continue;
3043
3044                 if (mono_assembly_try_decode_skip_verification (blob, blob + len)) {
3045                         MONO_SECMAN_FLAG_SET_VALUE (assembly->skipverification, TRUE);
3046                         return TRUE;
3047                 }
3048         }
3049
3050         MONO_SECMAN_FLAG_SET_VALUE (assembly->skipverification, FALSE);
3051         return FALSE;
3052 }