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