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