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