TARGET_J2EE:
[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         /* Add a non-temporary reference because of ass->image */
1430         mono_image_addref (image);
1431
1432         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);
1433
1434         /* 
1435          * Atomically search the loaded list and add ourselves to it if necessary.
1436          */
1437         mono_assemblies_lock ();
1438         if (ass->aname.name) {
1439                 /* avoid loading the same assembly twice for now... */
1440                 ass2 = search_loaded (&ass->aname, refonly);
1441                 if (ass2) {
1442                         mono_assemblies_unlock ();
1443                         g_free (ass);
1444                         g_free (base_dir);
1445                         mono_image_close (image);
1446                         *status = MONO_IMAGE_OK;
1447                         return ass2;
1448                 }
1449         }
1450
1451         g_assert (image->assembly == NULL);
1452         image->assembly = ass;
1453
1454         loaded_assemblies = g_list_prepend (loaded_assemblies, ass);
1455         if (mono_defaults.internals_visible_class)
1456                 mono_assembly_load_friends (ass);
1457         mono_assemblies_unlock ();
1458
1459         mono_assembly_invoke_load_hook (ass);
1460
1461         mono_profiler_assembly_loaded (ass, MONO_PROFILE_OK);
1462         
1463         return ass;
1464 }
1465
1466 MonoAssembly *
1467 mono_assembly_load_from (MonoImage *image, const char *fname,
1468                          MonoImageOpenStatus *status)
1469 {
1470         return mono_assembly_load_from_full (image, fname, status, FALSE);
1471 }
1472
1473 /**
1474  * mono_assembly_name_free:
1475  * @aname: assembly name to free
1476  * 
1477  * Frees the provided assembly name object.
1478  * (it does not frees the object itself, only the name members).
1479  */
1480 void
1481 mono_assembly_name_free (MonoAssemblyName *aname)
1482 {
1483         if (aname == NULL)
1484                 return;
1485
1486         g_free ((void *) aname->name);
1487         g_free ((void *) aname->culture);
1488         g_free ((void *) aname->hash_value);
1489 }
1490
1491 static gboolean
1492 parse_public_key (const gchar *key, gchar** pubkey)
1493 {
1494         const gchar *pkey;
1495         gchar header [16], val, *arr;
1496         gint i, j, offset, bitlen, keylen, pkeylen;
1497         
1498         keylen = strlen (key) >> 1;
1499         if (keylen < 1)
1500                 return FALSE;
1501         
1502         val = g_ascii_xdigit_value (key [0]) << 4;
1503         val |= g_ascii_xdigit_value (key [1]);
1504         switch (val) {
1505                 case 0x00:
1506                         if (keylen < 13)
1507                                 return FALSE;
1508                         val = g_ascii_xdigit_value (key [24]);
1509                         val |= g_ascii_xdigit_value (key [25]);
1510                         if (val != 0x06)
1511                                 return FALSE;
1512                         pkey = key + 24;
1513                         break;
1514                 case 0x06:
1515                         pkey = key;
1516                         break;
1517                 default:
1518                         return FALSE;
1519         }
1520                 
1521         /* We need the first 16 bytes
1522         * to check whether this key is valid or not */
1523         pkeylen = strlen (pkey) >> 1;
1524         if (pkeylen < 16)
1525                 return FALSE;
1526                 
1527         for (i = 0, j = 0; i < 16; i++) {
1528                 header [i] = g_ascii_xdigit_value (pkey [j++]) << 4;
1529                 header [i] |= g_ascii_xdigit_value (pkey [j++]);
1530         }
1531
1532         if (header [0] != 0x06 || /* PUBLICKEYBLOB (0x06) */
1533                         header [1] != 0x02 || /* Version (0x02) */
1534                         header [2] != 0x00 || /* Reserved (word) */
1535                         header [3] != 0x00 ||
1536                         (guint)(read32 (header + 8)) != 0x31415352) /* DWORD magic = RSA1 */
1537                 return FALSE;
1538
1539         /* Based on this length, we _should_ be able to know if the length is right */
1540         bitlen = read32 (header + 12) >> 3;
1541         if ((bitlen + 16 + 4) != pkeylen)
1542                 return FALSE;
1543                 
1544         /* Encode the size of the blob */
1545         offset = 0;
1546         if (keylen <= 127) {
1547                 arr = g_malloc (keylen + 1);
1548                 arr [offset++] = keylen;
1549         } else {
1550                 arr = g_malloc (keylen + 2);
1551                 arr [offset++] = 0x80; /* 10bs */
1552                 arr [offset++] = keylen;
1553         }
1554                 
1555         for (i = offset, j = 0; i < keylen + offset; i++) {
1556                 arr [i] = g_ascii_xdigit_value (key [j++]) << 4;
1557                 arr [i] |= g_ascii_xdigit_value (key [j++]);
1558         }
1559         if (pubkey)
1560                 *pubkey = arr;
1561
1562         return TRUE;
1563 }
1564
1565 static gboolean
1566 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)
1567 {
1568         gint major, minor, build, revision;
1569         gint len;
1570         gint version_parts;
1571         gchar *pkey, *pkeyptr, *encoded, tok [8];
1572
1573         memset (aname, 0, sizeof (MonoAssemblyName));
1574
1575         if (version) {
1576                 version_parts = sscanf (version, "%u.%u.%u.%u", &major, &minor, &build, &revision);
1577                 if (version_parts < 2 || version_parts > 4)
1578                         return FALSE;
1579
1580                 /* FIXME: we should set build & revision to -1 (instead of 0)
1581                 if these are not set in the version string. That way, later on,
1582                 we can still determine if these were specified. */
1583                 aname->major = major;
1584                 aname->minor = minor;
1585                 if (version_parts >= 3)
1586                         aname->build = build;
1587                 else
1588                         aname->build = 0;
1589                 if (version_parts == 4)
1590                         aname->revision = revision;
1591                 else
1592                         aname->revision = 0;
1593         }
1594         
1595         aname->flags = flags;
1596         aname->name = g_strdup (name);
1597         
1598         if (culture) {
1599                 if (g_ascii_strcasecmp (culture, "neutral") == 0)
1600                         aname->culture = g_strdup ("");
1601                 else
1602                         aname->culture = g_strdup (culture);
1603         }
1604         
1605         if (token && strncmp (token, "null", 4) != 0) {
1606                 /* the constant includes the ending NULL, hence the -1 */
1607                 if (strlen (token) != (MONO_PUBLIC_KEY_TOKEN_LENGTH - 1)) {
1608                         return FALSE;
1609                 }
1610                 char *lower = g_ascii_strdown (token, MONO_PUBLIC_KEY_TOKEN_LENGTH);
1611                 g_strlcpy ((char*)aname->public_key_token, lower, MONO_PUBLIC_KEY_TOKEN_LENGTH);
1612                 g_free (lower);
1613         }
1614
1615         if (key) {
1616                 if (strcmp (key, "null") == 0 || !parse_public_key (key, &pkey)) {
1617                         mono_assembly_name_free (aname);
1618                         return FALSE;
1619                 }
1620                 
1621                 len = mono_metadata_decode_blob_size ((const gchar *) pkey, (const gchar **) &pkeyptr);
1622                 // We also need to generate the key token
1623                 mono_digest_get_public_token ((guchar*) tok, (guint8*) pkeyptr, len);
1624                 encoded = encode_public_tok ((guchar*) tok, 8);
1625                 g_strlcpy ((gchar*)aname->public_key_token, encoded, MONO_PUBLIC_KEY_TOKEN_LENGTH);
1626                 g_free (encoded);
1627
1628                 if (save_public_key)
1629                         aname->public_key = (guint8*) pkey;
1630                 else
1631                         g_free (pkey);
1632         }
1633
1634         return TRUE;
1635 }
1636
1637 static gboolean
1638 parse_assembly_directory_name (const char *name, const char *dirname, MonoAssemblyName *aname)
1639 {
1640         gchar **parts;
1641         gboolean res;
1642         
1643         parts = g_strsplit (dirname, "_", 3);
1644         if (!parts || !parts[0] || !parts[1] || !parts[2]) {
1645                 g_strfreev (parts);
1646                 return FALSE;
1647         }
1648         
1649         res = build_assembly_name (name, parts[0], parts[1], parts[2], NULL, 0, aname, FALSE);
1650         g_strfreev (parts);
1651         return res;
1652 }
1653
1654 gboolean
1655 mono_assembly_name_parse_full (const char *name, MonoAssemblyName *aname, gboolean save_public_key, gboolean *is_version_defined, gboolean *is_token_defined)
1656 {
1657         gchar *dllname;
1658         gchar *version = NULL;
1659         gchar *culture = NULL;
1660         gchar *token = NULL;
1661         gchar *key = NULL;
1662         gchar *retargetable = NULL;
1663         gboolean res;
1664         gchar *value;
1665         gchar **parts;
1666         gchar **tmp;
1667         gboolean version_defined;
1668         gboolean token_defined;
1669         guint32 flags = 0;
1670
1671         if (!is_version_defined)
1672                 is_version_defined = &version_defined;
1673         *is_version_defined = FALSE;
1674         if (!is_token_defined)
1675                 is_token_defined = &token_defined;
1676         *is_token_defined = FALSE;
1677         
1678         parts = tmp = g_strsplit (name, ",", 6);
1679         if (!tmp || !*tmp) {
1680                 g_strfreev (tmp);
1681                 return FALSE;
1682         }
1683
1684         dllname = g_strstrip (*tmp);
1685         
1686         tmp++;
1687
1688         while (*tmp) {
1689                 value = g_strstrip (*tmp);
1690                 if (!g_ascii_strncasecmp (value, "Version=", 8)) {
1691                         *is_version_defined = TRUE;
1692                         version = g_strstrip (value + 8);
1693                         if (strlen (version) == 0) {
1694                                 return FALSE;
1695                         }
1696                         tmp++;
1697                         continue;
1698                 }
1699
1700                 if (!g_ascii_strncasecmp (value, "Culture=", 8)) {
1701                         culture = g_strstrip (value + 8);
1702                         if (strlen (culture) == 0) {
1703                                 return FALSE;
1704                         }
1705                         tmp++;
1706                         continue;
1707                 }
1708
1709                 if (!g_ascii_strncasecmp (value, "PublicKeyToken=", 15)) {
1710                         *is_token_defined = TRUE;
1711                         token = g_strstrip (value + 15);
1712                         if (strlen (token) == 0) {
1713                                 return FALSE;
1714                         }
1715                         tmp++;
1716                         continue;
1717                 }
1718
1719                 if (!g_ascii_strncasecmp (value, "PublicKey=", 10)) {
1720                         key = g_strstrip (value + 10);
1721                         if (strlen (key) == 0) {
1722                                 return FALSE;
1723                         }
1724                         tmp++;
1725                         continue;
1726                 }
1727
1728                 if (!g_ascii_strncasecmp (value, "Retargetable=", 13)) {
1729                         retargetable = g_strstrip (value + 13);
1730                         if (strlen (retargetable) == 0) {
1731                                 return FALSE;
1732                         }
1733                         if (!g_ascii_strcasecmp (retargetable, "yes")) {
1734                                 flags |= ASSEMBLYREF_RETARGETABLE_FLAG;
1735                         } else if (g_ascii_strcasecmp (retargetable, "no")) {
1736                                 return FALSE;
1737                         }
1738                         tmp++;
1739                         continue;
1740                 }
1741
1742                 if (!g_ascii_strncasecmp (value, "ProcessorArchitecture=", 22)) {
1743                         /* this is ignored for now, until we can change MonoAssemblyName */
1744                         tmp++;
1745                         continue;
1746                 }
1747
1748                 g_strfreev (parts);
1749                 return FALSE;
1750         }
1751
1752         /* if retargetable flag is set, then we must have a fully qualified name */
1753         if (retargetable != NULL && (version == NULL || culture == NULL || (key == NULL && token == NULL))) {
1754                 return FALSE;
1755         }
1756
1757         res = build_assembly_name (dllname, version, culture, token, key, flags,
1758                 aname, save_public_key);
1759         g_strfreev (parts);
1760         return res;
1761 }
1762
1763 /**
1764  * mono_assembly_name_parse:
1765  * @name: name to parse
1766  * @aname: the destination assembly name
1767  * 
1768  * Parses an assembly qualified type name and assigns the name,
1769  * version, culture and token to the provided assembly name object.
1770  *
1771  * Returns: true if the name could be parsed.
1772  */
1773 gboolean
1774 mono_assembly_name_parse (const char *name, MonoAssemblyName *aname)
1775 {
1776         return mono_assembly_name_parse_full (name, aname, FALSE, NULL, NULL);
1777 }
1778
1779 static MonoAssembly*
1780 probe_for_partial_name (const char *basepath, const char *fullname, MonoAssemblyName *aname, MonoImageOpenStatus *status)
1781 {
1782         gchar *fullpath = NULL;
1783         GDir *dirhandle;
1784         const char* direntry;
1785         MonoAssemblyName gac_aname;
1786         gint major=-1, minor=0, build=0, revision=0;
1787         gboolean exact_version;
1788         
1789         dirhandle = g_dir_open (basepath, 0, NULL);
1790         if (!dirhandle)
1791                 return NULL;
1792                 
1793         exact_version = (aname->major | aname->minor | aname->build | aname->revision) != 0;
1794
1795         while ((direntry = g_dir_read_name (dirhandle))) {
1796                 gboolean match = TRUE;
1797                 
1798                 if(!parse_assembly_directory_name (aname->name, direntry, &gac_aname))
1799                         continue;
1800                 
1801                 if (aname->culture != NULL && strcmp (aname->culture, gac_aname.culture) != 0)
1802                         match = FALSE;
1803                         
1804                 if (match && strlen ((char*)aname->public_key_token) > 0 && 
1805                                 strcmp ((char*)aname->public_key_token, (char*)gac_aname.public_key_token) != 0)
1806                         match = FALSE;
1807                 
1808                 if (match) {
1809                         if (exact_version) {
1810                                 match = (aname->major == gac_aname.major && aname->minor == gac_aname.minor &&
1811                                                  aname->build == gac_aname.build && aname->revision == gac_aname.revision); 
1812                         }
1813                         else if (gac_aname.major < major)
1814                                 match = FALSE;
1815                         else if (gac_aname.major == major) {
1816                                 if (gac_aname.minor < minor)
1817                                         match = FALSE;
1818                                 else if (gac_aname.minor == minor) {
1819                                         if (gac_aname.build < build)
1820                                                 match = FALSE;
1821                                         else if (gac_aname.build == build && gac_aname.revision <= revision)
1822                                                 match = FALSE; 
1823                                 }
1824                         }
1825                 }
1826                 
1827                 if (match) {
1828                         major = gac_aname.major;
1829                         minor = gac_aname.minor;
1830                         build = gac_aname.build;
1831                         revision = gac_aname.revision;
1832                         g_free (fullpath);
1833                         fullpath = g_build_path (G_DIR_SEPARATOR_S, basepath, direntry, fullname, NULL);
1834                 }
1835
1836                 mono_assembly_name_free (&gac_aname);
1837         }
1838         
1839         g_dir_close (dirhandle);
1840         
1841         if (fullpath == NULL)
1842                 return NULL;
1843         else {
1844                 MonoAssembly *res = mono_assembly_open (fullpath, status);
1845                 g_free (fullpath);
1846                 return res;
1847         }
1848 }
1849
1850 MonoAssembly*
1851 mono_assembly_load_with_partial_name (const char *name, MonoImageOpenStatus *status)
1852 {
1853         MonoAssembly *res;
1854         MonoAssemblyName *aname, base_name, maped_aname;
1855         gchar *fullname, *gacpath;
1856         gchar **paths;
1857
1858         memset (&base_name, 0, sizeof (MonoAssemblyName));
1859         aname = &base_name;
1860
1861         if (!mono_assembly_name_parse (name, aname))
1862                 return NULL;
1863
1864         /* 
1865          * If no specific version has been requested, make sure we load the
1866          * correct version for system assemblies.
1867          */ 
1868         if ((aname->major | aname->minor | aname->build | aname->revision) == 0)
1869                 aname = mono_assembly_remap_version (aname, &maped_aname);
1870         
1871         res = mono_assembly_loaded (aname);
1872         if (res) {
1873                 mono_assembly_name_free (aname);
1874                 return res;
1875         }
1876
1877         res = invoke_assembly_preload_hook (aname, assemblies_path);
1878         if (res) {
1879                 res->in_gac = FALSE;
1880                 mono_assembly_name_free (aname);
1881                 return res;
1882         }
1883
1884         fullname = g_strdup_printf ("%s.dll", aname->name);
1885
1886         if (extra_gac_paths) {
1887                 paths = extra_gac_paths;
1888                 while (!res && *paths) {
1889                         gacpath = g_build_path (G_DIR_SEPARATOR_S, *paths, "lib", "mono", "gac", aname->name, NULL);
1890                         res = probe_for_partial_name (gacpath, fullname, aname, status);
1891                         g_free (gacpath);
1892                         paths++;
1893                 }
1894         }
1895
1896         if (res) {
1897                 res->in_gac = TRUE;
1898                 g_free (fullname);
1899                 mono_assembly_name_free (aname);
1900                 return res;
1901         }
1902
1903         gacpath = g_build_path (G_DIR_SEPARATOR_S, mono_assembly_getrootdir (), "mono", "gac", aname->name, NULL);
1904         res = probe_for_partial_name (gacpath, fullname, aname, status);
1905         g_free (gacpath);
1906
1907         if (res)
1908                 res->in_gac = TRUE;
1909         else {
1910                 MonoDomain *domain = mono_domain_get ();
1911                 MonoReflectionAssembly *refasm = mono_try_assembly_resolve (domain, mono_string_new (domain, name), FALSE);
1912                 if (refasm)
1913                         res = refasm->assembly;
1914         }
1915         
1916         g_free (fullname);
1917         mono_assembly_name_free (aname);
1918
1919         return res;
1920 }
1921
1922 static MonoImage*
1923 mono_assembly_load_publisher_policy (MonoAssemblyName *aname)
1924 {
1925         MonoImage *image;
1926         gchar *filename, *pname, *name, *culture, *version, *fullpath, *subpath;
1927         gchar **paths;
1928         gint32 len;
1929
1930         if (strstr (aname->name, ".dll")) {
1931                 len = strlen (aname->name) - 4;
1932                 name = g_malloc (len);
1933                 strncpy (name, aname->name, len);
1934         } else
1935                 name = g_strdup (aname->name);
1936         
1937         if (aname->culture) {
1938                 culture = g_strdup (aname->culture);
1939                 g_strdown (culture);
1940         } else
1941                 culture = g_strdup ("");
1942         
1943         pname = g_strdup_printf ("policy.%d.%d.%s", aname->major, aname->minor, name);
1944         version = g_strdup_printf ("0.0.0.0_%s_%s", culture, aname->public_key_token);
1945         g_free (name);
1946         g_free (culture);
1947         
1948         filename = g_strconcat (pname, ".dll", NULL);
1949         subpath = g_build_path (G_DIR_SEPARATOR_S, pname, version, filename, NULL);
1950         g_free (pname);
1951         g_free (version);
1952         g_free (filename);
1953
1954         image = NULL;
1955         if (extra_gac_paths) {
1956                 paths = extra_gac_paths;
1957                 while (!image && *paths) {
1958                         fullpath = g_build_path (G_DIR_SEPARATOR_S, *paths,
1959                                         "lib", "mono", "gac", subpath, NULL);
1960                         image = mono_image_open (fullpath, NULL);
1961                         g_free (fullpath);
1962                         paths++;
1963                 }
1964         }
1965
1966         if (image) {
1967                 g_free (subpath);
1968                 return image;
1969         }
1970
1971         fullpath = g_build_path (G_DIR_SEPARATOR_S, mono_assembly_getrootdir (), 
1972                         "mono", "gac", subpath, NULL);
1973         image = mono_image_open (fullpath, NULL);
1974         g_free (subpath);
1975         g_free (fullpath);
1976         
1977         return image;
1978 }
1979
1980 static MonoAssemblyName*
1981 mono_assembly_bind_version (MonoAssemblyBindingInfo *info, MonoAssemblyName *aname, MonoAssemblyName *dest_name)
1982 {
1983         memcpy (dest_name, aname, sizeof (MonoAssemblyName));
1984         dest_name->major = info->new_version.major;
1985         dest_name->minor = info->new_version.minor;
1986         dest_name->build = info->new_version.build;
1987         dest_name->revision = info->new_version.revision;
1988         
1989         return dest_name;
1990 }
1991
1992 /* LOCKING: Assumes that we are already locked */
1993 static MonoAssemblyBindingInfo*
1994 search_binding_loaded (MonoAssemblyName *aname)
1995 {
1996         GSList *tmp;
1997
1998         for (tmp = loaded_assembly_bindings; tmp; tmp = tmp->next) {
1999                 MonoAssemblyBindingInfo *info = tmp->data;
2000                 if (assembly_binding_maps_name (info, aname))
2001                         return info;
2002         }
2003
2004         return NULL;
2005 }
2006
2007 static MonoAssemblyName*
2008 mono_assembly_apply_binding (MonoAssemblyName *aname, MonoAssemblyName *dest_name)
2009 {
2010         MonoAssemblyBindingInfo *info, *info2;
2011         MonoImage *ppimage;
2012
2013         if (aname->public_key_token [0] == 0)
2014                 return aname;
2015
2016         mono_loader_lock ();
2017         info = search_binding_loaded (aname);
2018         mono_loader_unlock ();
2019         if (info) {
2020                 if (!check_policy_versions (info, aname))
2021                         return aname;
2022                 
2023                 mono_assembly_bind_version (info, aname, dest_name);
2024                 return dest_name;
2025         }
2026
2027         info = g_new0 (MonoAssemblyBindingInfo, 1);
2028         info->major = aname->major;
2029         info->minor = aname->minor;
2030         
2031         ppimage = mono_assembly_load_publisher_policy (aname);
2032         if (ppimage) {
2033                 get_publisher_policy_info (ppimage, aname, info);
2034                 mono_image_close (ppimage);
2035         }
2036
2037         /* Define default error value if needed */
2038         if (!info->is_valid) {
2039                 info->name = g_strdup (aname->name);
2040                 info->culture = g_strdup (aname->culture);
2041                 g_strlcpy ((char *)info->public_key_token, (const char *)aname->public_key_token, MONO_PUBLIC_KEY_TOKEN_LENGTH);
2042         }
2043         
2044         mono_loader_lock ();
2045         info2 = search_binding_loaded (aname);
2046         if (info2) {
2047                 /* This binding was added by another thread 
2048                  * before us */
2049                 mono_assembly_binding_info_free (info);
2050                 g_free (info);
2051                 
2052                 info = info2;
2053         } else
2054                 loaded_assembly_bindings = g_slist_prepend (loaded_assembly_bindings, info);
2055                 
2056         mono_loader_unlock ();
2057         
2058         if (!info->is_valid || !check_policy_versions (info, aname))
2059                 return aname;
2060
2061         mono_assembly_bind_version (info, aname, dest_name);
2062         return dest_name;
2063 }
2064
2065 /**
2066  * mono_assembly_load_from_gac
2067  *
2068  * @aname: The assembly name object
2069  */
2070 static MonoAssembly*
2071 mono_assembly_load_from_gac (MonoAssemblyName *aname,  gchar *filename, MonoImageOpenStatus *status, MonoBoolean refonly)
2072 {
2073         MonoAssembly *result = NULL;
2074         gchar *name, *version, *culture, *fullpath, *subpath;
2075         gint32 len;
2076         gchar **paths;
2077
2078         if (aname->public_key_token [0] == 0) {
2079                 return NULL;
2080         }
2081
2082         if (strstr (aname->name, ".dll")) {
2083                 len = strlen (filename) - 4;
2084                 name = g_malloc (len);
2085                 strncpy (name, aname->name, len);
2086         } else {
2087                 name = g_strdup (aname->name);
2088         }
2089
2090         if (aname->culture) {
2091                 culture = g_strdup (aname->culture);
2092                 g_strdown (culture);
2093         } else {
2094                 culture = g_strdup ("");
2095         }
2096
2097         version = g_strdup_printf ("%d.%d.%d.%d_%s_%s", aname->major,
2098                         aname->minor, aname->build, aname->revision,
2099                         culture, aname->public_key_token);
2100         
2101         subpath = g_build_path (G_DIR_SEPARATOR_S, name, version, filename, NULL);
2102         g_free (name);
2103         g_free (version);
2104         g_free (culture);
2105
2106         if (extra_gac_paths) {
2107                 paths = extra_gac_paths;
2108                 while (!result && *paths) {
2109                         fullpath = g_build_path (G_DIR_SEPARATOR_S, *paths, "lib", "mono", "gac", subpath, NULL);
2110                         result = mono_assembly_open_full (fullpath, status, refonly);
2111                         g_free (fullpath);
2112                         paths++;
2113                 }
2114         }
2115
2116         if (result) {
2117                 result->in_gac = TRUE;
2118                 g_free (subpath);
2119                 return result;
2120         }
2121
2122         fullpath = g_build_path (G_DIR_SEPARATOR_S, mono_assembly_getrootdir (),
2123                         "mono", "gac", subpath, NULL);
2124         result = mono_assembly_open_full (fullpath, status, refonly);
2125         g_free (fullpath);
2126
2127         if (result)
2128                 result->in_gac = TRUE;
2129         
2130         g_free (subpath);
2131
2132         return result;
2133 }
2134
2135
2136 MonoAssembly*
2137 mono_assembly_load_corlib (const MonoRuntimeInfo *runtime, MonoImageOpenStatus *status)
2138 {
2139         char *corlib_file;
2140
2141         if (corlib) {
2142                 /* g_print ("corlib already loaded\n"); */
2143                 return corlib;
2144         }
2145         
2146         if (assemblies_path) {
2147                 corlib = load_in_path ("mscorlib.dll", (const char**)assemblies_path, status, FALSE);
2148                 if (corlib)
2149                         return corlib;
2150         }
2151
2152         /* Load corlib from mono/<version> */
2153         
2154         corlib_file = g_build_filename ("mono", runtime->framework_version, "mscorlib.dll", NULL);
2155         if (assemblies_path) {
2156                 corlib = load_in_path (corlib_file, (const char**)assemblies_path, status, FALSE);
2157                 if (corlib) {
2158                         g_free (corlib_file);
2159                         return corlib;
2160                 }
2161         }
2162         corlib = load_in_path (corlib_file, default_path, status, FALSE);
2163         g_free (corlib_file);
2164
2165         return corlib;
2166 }
2167
2168 MonoAssembly* mono_assembly_load_full_nosearch (MonoAssemblyName *aname, 
2169                                                 const char       *basedir, 
2170                                                 MonoImageOpenStatus *status,
2171                                                 gboolean refonly)
2172 {
2173         MonoAssembly *result;
2174         char *fullpath, *filename;
2175         MonoAssemblyName maped_aname, maped_name_pp;
2176         int ext_index;
2177         const char *ext;
2178         int len;
2179
2180         aname = mono_assembly_remap_version (aname, &maped_aname);
2181         
2182         /* Reflection only assemblies don't get assembly binding */
2183         if (!refonly)
2184                 aname = mono_assembly_apply_binding (aname, &maped_name_pp);
2185         
2186         result = mono_assembly_loaded_full (aname, refonly);
2187         if (result)
2188                 return result;
2189
2190         result = refonly ? invoke_assembly_refonly_preload_hook (aname, assemblies_path) : invoke_assembly_preload_hook (aname, assemblies_path);
2191         if (result) {
2192                 result->in_gac = FALSE;
2193                 return result;
2194         }
2195
2196         /* Currently we retrieve the loaded corlib for reflection 
2197          * only requests, like a common reflection only assembly 
2198          */
2199         if (strcmp (aname->name, "mscorlib") == 0 || strcmp (aname->name, "mscorlib.dll") == 0) {
2200                 return mono_assembly_load_corlib (mono_get_runtime_info (), status);
2201         }
2202
2203         len = strlen (aname->name);
2204         for (ext_index = 0; ext_index < 2; ext_index ++) {
2205                 ext = ext_index == 0 ? ".dll" : ".exe";
2206                 if (len > 4 && (!strcmp (aname->name + len - 4, ".dll") || !strcmp (aname->name + len - 4, ".exe"))) {
2207                         filename = g_strdup (aname->name);
2208                         /* Don't try appending .dll/.exe if it already has one of those extensions */
2209                         ext_index++;
2210                 } else {
2211                         filename = g_strconcat (aname->name, ext, NULL);
2212                 }
2213
2214                 result = mono_assembly_load_from_gac (aname, filename, status, refonly);
2215                 if (result) {
2216                         g_free (filename);
2217                         return result;
2218                 }
2219
2220                 if (basedir) {
2221                         fullpath = g_build_filename (basedir, filename, NULL);
2222                         result = mono_assembly_open_full (fullpath, status, refonly);
2223                         g_free (fullpath);
2224                         if (result) {
2225                                 result->in_gac = FALSE;
2226                                 g_free (filename);
2227                                 return result;
2228                         }
2229                 }
2230
2231                 result = load_in_path (filename, default_path, status, refonly);
2232                 if (result)
2233                         result->in_gac = FALSE;
2234                 g_free (filename);
2235                 if (result)
2236                         return result;
2237         }
2238
2239         return result;
2240 }
2241
2242 /**
2243  * mono_assembly_load_full:
2244  * @aname: A MonoAssemblyName with the assembly name to load.
2245  * @basedir: A directory to look up the assembly at.
2246  * @status: a pointer to a MonoImageOpenStatus to return the status of the load operation
2247  * @refonly: Whether this assembly is being opened in "reflection-only" mode.
2248  *
2249  * Loads the assembly referenced by @aname, if the value of @basedir is not NULL, it
2250  * attempts to load the assembly from that directory before probing the standard locations.
2251  *
2252  * If the assembly is being opened in reflection-only mode (@refonly set to TRUE) then no 
2253  * assembly binding takes place.
2254  *
2255  * Returns: the assembly referenced by @aname loaded or NULL on error.   On error the
2256  * value pointed by status is updated with an error code.
2257  */
2258 MonoAssembly*
2259 mono_assembly_load_full (MonoAssemblyName *aname, const char *basedir, MonoImageOpenStatus *status, gboolean refonly)
2260 {
2261         MonoAssembly *result = mono_assembly_load_full_nosearch (aname, basedir, status, refonly);
2262         
2263         if (!result)
2264                 /* Try a postload search hook */
2265                 result = mono_assembly_invoke_search_hook_internal (aname, refonly, TRUE);
2266         return result;
2267 }
2268
2269 /**
2270  * mono_assembly_load:
2271  * @aname: A MonoAssemblyName with the assembly name to load.
2272  * @basedir: A directory to look up the assembly at.
2273  * @status: a pointer to a MonoImageOpenStatus to return the status of the load operation
2274  *
2275  * Loads the assembly referenced by @aname, if the value of @basedir is not NULL, it
2276  * attempts to load the assembly from that directory before probing the standard locations.
2277  *
2278  * Returns: the assembly referenced by @aname loaded or NULL on error.   On error the
2279  * value pointed by status is updated with an error code.
2280  */
2281 MonoAssembly*
2282 mono_assembly_load (MonoAssemblyName *aname, const char *basedir, MonoImageOpenStatus *status)
2283 {
2284         return mono_assembly_load_full (aname, basedir, status, FALSE);
2285 }
2286         
2287 MonoAssembly*
2288 mono_assembly_loaded_full (MonoAssemblyName *aname, gboolean refonly)
2289 {
2290         MonoAssembly *res;
2291         MonoAssemblyName maped_aname;
2292
2293         aname = mono_assembly_remap_version (aname, &maped_aname);
2294
2295         mono_assemblies_lock ();
2296         res = search_loaded (aname, refonly);
2297         mono_assemblies_unlock ();
2298
2299         return res;
2300 }
2301
2302 /**
2303  * mono_assembly_loaded:
2304  * @aname: an assembly to look for.
2305  *
2306  * Returns: NULL If the given @aname assembly has not been loaded, or a pointer to
2307  * a MonoAssembly that matches the MonoAssemblyName specified.
2308  */
2309 MonoAssembly*
2310 mono_assembly_loaded (MonoAssemblyName *aname)
2311 {
2312         return mono_assembly_loaded_full (aname, FALSE);
2313 }
2314
2315 /**
2316  * mono_assembly_close:
2317  * @assembly: the assembly to release.
2318  *
2319  * This method releases a reference to the @assembly.  The assembly is
2320  * only released when all the outstanding references to it are released.
2321  */
2322 void
2323 mono_assembly_close (MonoAssembly *assembly)
2324 {
2325         GSList *tmp;
2326         g_return_if_fail (assembly != NULL);
2327
2328         if (assembly == REFERENCE_MISSING)
2329                 return;
2330         
2331         /* Might be 0 already */
2332         if (InterlockedDecrement (&assembly->ref_count) > 0)
2333                 return;
2334
2335         mono_profiler_assembly_event (assembly, MONO_PROFILE_START_UNLOAD);
2336
2337         mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_ASSEMBLY, "Unloading assembly %s [%p].", assembly->aname.name, assembly);
2338
2339         mono_debug_close_image (assembly->image);
2340
2341         mono_assemblies_lock ();
2342         loaded_assemblies = g_list_remove (loaded_assemblies, assembly);
2343         mono_assemblies_unlock ();
2344
2345         assembly->image->assembly = NULL;
2346
2347         mono_image_close (assembly->image);
2348
2349         for (tmp = assembly->friend_assembly_names; tmp; tmp = tmp->next) {
2350                 MonoAssemblyName *fname = tmp->data;
2351                 mono_assembly_name_free (fname);
2352                 g_free (fname);
2353         }
2354         g_slist_free (assembly->friend_assembly_names);
2355         g_free (assembly->basedir);
2356         if (assembly->dynamic) {
2357                 g_free ((char*)assembly->aname.culture);
2358         } else {
2359                 g_free (assembly);
2360         }
2361
2362         mono_profiler_assembly_event (assembly, MONO_PROFILE_END_UNLOAD);
2363 }
2364
2365 MonoImage*
2366 mono_assembly_load_module (MonoAssembly *assembly, guint32 idx)
2367 {
2368         return mono_image_load_file_for_image (assembly->image, idx);
2369 }
2370
2371 void
2372 mono_assembly_foreach (GFunc func, gpointer user_data)
2373 {
2374         GList *copy;
2375
2376         /*
2377          * We make a copy of the list to avoid calling the callback inside the 
2378          * lock, which could lead to deadlocks.
2379          */
2380         mono_assemblies_lock ();
2381         copy = g_list_copy (loaded_assemblies);
2382         mono_assemblies_unlock ();
2383
2384         g_list_foreach (loaded_assemblies, func, user_data);
2385
2386         g_list_free (copy);
2387 }
2388
2389 /**
2390  * mono_assemblies_cleanup:
2391  *
2392  * Free all resources used by this module.
2393  */
2394 void
2395 mono_assemblies_cleanup (void)
2396 {
2397         GSList *l;
2398
2399         DeleteCriticalSection (&assemblies_mutex);
2400
2401         for (l = loaded_assembly_bindings; l; l = l->next) {
2402                 MonoAssemblyBindingInfo *info = l->data;
2403
2404                 mono_assembly_binding_info_free (info);
2405                 g_free (info);
2406         }
2407         g_slist_free (loaded_assembly_bindings);
2408
2409         free_assembly_load_hooks ();
2410         free_assembly_search_hooks ();
2411         free_assembly_preload_hooks ();
2412 }
2413
2414 /*
2415  * Holds the assembly of the application, for
2416  * System.Diagnostics.Process::MainModule
2417  */
2418 static MonoAssembly *main_assembly=NULL;
2419
2420 void
2421 mono_assembly_set_main (MonoAssembly *assembly)
2422 {
2423         main_assembly = assembly;
2424 }
2425
2426 /**
2427  * mono_assembly_get_main:
2428  *
2429  * Returns: the assembly for the application, the first assembly that is loaded by the VM
2430  */
2431 MonoAssembly *
2432 mono_assembly_get_main (void)
2433 {
2434         return (main_assembly);
2435 }
2436
2437 /**
2438  * mono_assembly_get_image:
2439  * @assembly: The assembly to retrieve the image from
2440  *
2441  * Returns: the MonoImage associated with this assembly.
2442  */
2443 MonoImage*
2444 mono_assembly_get_image (MonoAssembly *assembly)
2445 {
2446         return assembly->image;
2447 }
2448
2449 void
2450 mono_register_bundled_assemblies (const MonoBundledAssembly **assemblies)
2451 {
2452         bundles = assemblies;
2453 }