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