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