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