2 * appdomain.c: AppDomain functions
5 * Dietmar Maurer (dietmar@ximian.com)
7 * Gonzalo Paniagua Javier (gonzalo@ximian.com)
9 * (c) 2001-2003 Ximian, Inc. (http://www.ximian.com)
11 #undef ASSEMBLY_LOAD_DEBUG
20 #include <sys/types.h>
22 #include <mono/metadata/gc-internal.h>
23 #include <mono/metadata/object.h>
24 #include <mono/metadata/domain-internals.h>
25 #include "mono/metadata/metadata-internals.h"
26 #include <mono/metadata/assembly.h>
27 #include <mono/metadata/exception.h>
28 #include <mono/metadata/threads.h>
29 #include <mono/metadata/socket-io.h>
30 #include <mono/metadata/tabledefs.h>
31 #include <mono/metadata/gc-internal.h>
32 #include <mono/metadata/mono-gc.h>
33 #include <mono/metadata/marshal.h>
34 #include <mono/metadata/monitor.h>
35 #include <mono/metadata/threadpool.h>
36 #include <mono/metadata/mono-debug.h>
37 #include <mono/utils/mono-uri.h>
38 #include <mono/utils/mono-logger.h>
39 #include <mono/utils/mono-path.h>
40 #include <mono/utils/mono-stdlib.h>
41 #include <mono/utils/mono-io-portability.h>
47 * This is the version number of the corlib-runtime interface. When
48 * making changes to this interface (by changing the layout
49 * of classes the runtime knows about, changing icall signature or
50 * semantics etc), increment this variable. Also increment the
51 * pair of this variable in mscorlib in:
52 * mcs/class/mscorlib/System/Environment.cs
54 * Changes which are already detected at runtime, like the addition
55 * of icalls, do not require an increment.
57 #define MONO_CORLIB_VERSION 66
62 int assemblybinding_count;
66 CRITICAL_SECTION mono_delegate_section;
68 static gunichar2 process_guid [36];
69 static gboolean process_guid_set = FALSE;
71 static gboolean shutting_down = FALSE;
74 mono_domain_assembly_preload (MonoAssemblyName *aname,
75 gchar **assemblies_path,
79 mono_domain_assembly_search (MonoAssemblyName *aname,
83 mono_domain_assembly_postload_search (MonoAssemblyName *aname,
87 mono_domain_fire_assembly_load (MonoAssembly *assembly, gpointer user_data);
90 add_assemblies_to_domain (MonoDomain *domain, MonoAssembly *ass, GHashTable *hash);
93 mono_domain_unload (MonoDomain *domain);
97 * @domain: domain returned by mono_init ()
99 * Initialize the core AppDomain: this function will run also some
100 * IL initialization code, so it needs the execution engine to be fully
103 * AppDomain.SetupInformation is set up in mono_runtime_exec_main, where
104 * we know the entry_assembly.
108 mono_runtime_init (MonoDomain *domain, MonoThreadStartCB start_cb,
109 MonoThreadAttachCB attach_cb)
111 MonoAppDomainSetup *setup;
116 mono_portability_helpers_init ();
118 mono_gc_base_init ();
119 mono_monitor_init ();
120 mono_thread_pool_init ();
121 mono_marshal_init ();
123 mono_install_assembly_preload_hook (mono_domain_assembly_preload, GUINT_TO_POINTER (FALSE));
124 mono_install_assembly_refonly_preload_hook (mono_domain_assembly_preload, GUINT_TO_POINTER (TRUE));
125 mono_install_assembly_search_hook (mono_domain_assembly_search, GUINT_TO_POINTER (FALSE));
126 mono_install_assembly_refonly_search_hook (mono_domain_assembly_search, GUINT_TO_POINTER (TRUE));
127 mono_install_assembly_postload_search_hook (mono_domain_assembly_postload_search, GUINT_TO_POINTER (FALSE));
128 mono_install_assembly_postload_refonly_search_hook (mono_domain_assembly_postload_search, GUINT_TO_POINTER (TRUE));
129 mono_install_assembly_load_hook (mono_domain_fire_assembly_load, NULL);
130 mono_install_lookup_dynamic_token (mono_reflection_lookup_dynamic_token);
132 mono_thread_init (start_cb, attach_cb);
134 class = mono_class_from_name (mono_defaults.corlib, "System", "AppDomainSetup");
135 setup = (MonoAppDomainSetup *) mono_object_new (domain, class);
137 class = mono_class_from_name (mono_defaults.corlib, "System", "AppDomain");
138 ad = (MonoAppDomain *) mono_object_new (domain, class);
141 domain->setup = setup;
143 InitializeCriticalSection (&mono_delegate_section);
145 mono_thread_attach (domain);
146 mono_context_init (domain);
147 mono_context_set (domain->default_context);
149 mono_type_initialization_init ();
153 * Create an instance early since we can't do it when there is no memory.
155 arg = mono_string_new (domain, "Out of memory");
156 domain->out_of_memory_ex = mono_exception_from_name_two_strings (mono_defaults.corlib, "System", "OutOfMemoryException", arg, NULL);
159 * These two are needed because the signal handlers might be executing on
160 * an alternate stack, and Boehm GC can't handle that.
162 arg = mono_string_new (domain, "A null value was found where an object instance was required");
163 domain->null_reference_ex = mono_exception_from_name_two_strings (mono_defaults.corlib, "System", "NullReferenceException", arg, NULL);
164 arg = mono_string_new (domain, "The requested operation caused a stack overflow.");
165 domain->stack_overflow_ex = mono_exception_from_name_two_strings (mono_defaults.corlib, "System", "StackOverflowException", arg, NULL);
167 /* GC init has to happen after thread init */
170 mono_network_init ();
172 /* mscorlib is loaded before we install the load hook */
173 mono_domain_fire_assembly_load (mono_defaults.corlib->assembly, NULL);
179 mono_get_corlib_version (void)
182 MonoClassField *field;
185 klass = mono_class_from_name (mono_defaults.corlib, "System", "Environment");
186 mono_class_init (klass);
187 field = mono_class_get_field_from_name (klass, "mono_corlib_version");
190 if (! (field->type->attrs & FIELD_ATTRIBUTE_STATIC))
192 value = mono_field_get_value_object (mono_domain_get (), field, NULL);
193 return *(gint32*)((gchar*)value + sizeof (MonoObject));
197 mono_check_corlib_version (void)
199 int version = mono_get_corlib_version ();
200 if (version != MONO_CORLIB_VERSION)
201 return g_strdup_printf ("expected corlib version %d, found %d.", MONO_CORLIB_VERSION, version);
207 mono_context_init (MonoDomain *domain)
210 MonoAppContext *context;
212 class = mono_class_from_name (mono_defaults.corlib, "System.Runtime.Remoting.Contexts", "Context");
213 context = (MonoAppContext *) mono_object_new (domain, class);
214 context->domain_id = domain->domain_id;
215 context->context_id = 0;
216 domain->default_context = context;
220 * mono_runtime_cleanup:
225 * This must not be called while there are still running threads executing
229 mono_runtime_cleanup (MonoDomain *domain)
231 shutting_down = TRUE;
233 /* This ends up calling any pending pending (for at most 2 seconds) */
236 mono_thread_cleanup ();
238 mono_network_cleanup ();
240 mono_marshal_cleanup ();
242 mono_type_initialization_cleanup ();
244 mono_monitor_cleanup ();
246 #ifndef PLATFORM_WIN32
251 static MonoDomainFunc quit_function = NULL;
254 mono_install_runtime_cleanup (MonoDomainFunc func)
256 quit_function = func;
262 if (quit_function != NULL)
263 quit_function (mono_get_root_domain (), NULL);
267 * mono_runtime_set_shutting_down:
269 * Invoked by System.Environment.Exit to flag that the runtime
273 mono_runtime_set_shutting_down (void)
275 shutting_down = TRUE;
279 * mono_runtime_is_shutting_down:
281 * Returns whether the runtime has been flagged for shutdown.
283 * This is consumed by the P:System.Environment.HasShutdownStarted
288 mono_runtime_is_shutting_down (void)
290 return shutting_down;
294 * mono_domain_has_type_resolve:
295 * @domain: application domains being looked up
297 * Returns true if the AppDomain.TypeResolve field has been
301 mono_domain_has_type_resolve (MonoDomain *domain)
303 static MonoClassField *field = NULL;
307 field = mono_class_get_field_from_name (mono_defaults.appdomain_class, "TypeResolve");
311 mono_field_get_value ((MonoObject*)(domain->domain), field, &o);
316 * mono_domain_try_type_resolve:
317 * @domain: application domainwhere the name where the type is going to be resolved
318 * @name: the name of the type to resolve or NULL.
319 * @tb: A System.Reflection.Emit.TypeBuilder, used if name is NULL.
321 * This routine invokes the internal System.AppDomain.DoTypeResolve and returns
322 * the assembly that matches name.
324 * If @name is null, the value of ((TypeBuilder)tb).FullName is used instead
326 * Returns: A MonoReflectionAssembly or NULL if not found
328 MonoReflectionAssembly *
329 mono_domain_try_type_resolve (MonoDomain *domain, char *name, MonoObject *tb)
333 static MonoMethod *method = NULL;
335 g_assert (domain != NULL && ((name != NULL) || (tb != NULL)));
337 if (method == NULL) {
338 klass = domain->domain->mbr.obj.vtable->klass;
341 method = mono_class_get_method_from_name (klass, "DoTypeResolve", -1);
342 if (method == NULL) {
343 g_warning ("Method AppDomain.DoTypeResolve not found.\n");
349 *params = (MonoObject*)mono_string_new (mono_domain_get (), name);
352 return (MonoReflectionAssembly *) mono_runtime_invoke (method, domain->domain, params, NULL);
356 * mono_domain_owns_vtable_slot:
358 * Returns whenever VTABLE_SLOT is inside a vtable which belongs to DOMAIN.
361 mono_domain_owns_vtable_slot (MonoDomain *domain, gpointer vtable_slot)
365 mono_domain_lock (domain);
366 res = mono_mempool_contains_addr (domain->mp, vtable_slot);
367 mono_domain_unlock (domain);
374 * @force: force setting.
376 * Set the current appdomain to @domain. If @force is set, set it even
377 * if it is being unloaded.
381 * FALSE if the domain is unloaded
384 mono_domain_set (MonoDomain *domain, gboolean force)
386 if (!force && domain->state == MONO_APPDOMAIN_UNLOADED)
389 mono_domain_set_internal (domain);
395 ves_icall_System_AppDomain_GetData (MonoAppDomain *ad, MonoString *name)
403 g_assert (ad != NULL);
405 g_assert (add != NULL);
408 mono_raise_exception (mono_get_exception_argument_null ("name"));
410 str = mono_string_to_utf8 (name);
412 mono_domain_lock (add);
414 if (!strcmp (str, "APPBASE"))
415 o = (MonoObject *)add->setup->application_base;
416 else if (!strcmp (str, "APP_CONFIG_FILE"))
417 o = (MonoObject *)add->setup->configuration_file;
418 else if (!strcmp (str, "DYNAMIC_BASE"))
419 o = (MonoObject *)add->setup->dynamic_base;
420 else if (!strcmp (str, "APP_NAME"))
421 o = (MonoObject *)add->setup->application_name;
422 else if (!strcmp (str, "CACHE_BASE"))
423 o = (MonoObject *)add->setup->cache_path;
424 else if (!strcmp (str, "PRIVATE_BINPATH"))
425 o = (MonoObject *)add->setup->private_bin_path;
426 else if (!strcmp (str, "BINPATH_PROBE_ONLY"))
427 o = (MonoObject *)add->setup->private_bin_path_probe;
428 else if (!strcmp (str, "SHADOW_COPY_DIRS"))
429 o = (MonoObject *)add->setup->shadow_copy_directories;
430 else if (!strcmp (str, "FORCE_CACHE_INSTALL"))
431 o = (MonoObject *)add->setup->shadow_copy_files;
433 o = mono_g_hash_table_lookup (add->env, name);
435 mono_domain_unlock (add);
445 ves_icall_System_AppDomain_SetData (MonoAppDomain *ad, MonoString *name, MonoObject *data)
451 g_assert (ad != NULL);
453 g_assert (add != NULL);
456 mono_raise_exception (mono_get_exception_argument_null ("name"));
458 mono_domain_lock (add);
460 mono_g_hash_table_insert (add->env, name, data);
462 mono_domain_unlock (add);
466 ves_icall_System_AppDomain_getSetup (MonoAppDomain *ad)
470 g_assert (ad != NULL);
471 g_assert (ad->data != NULL);
473 return ad->data->setup;
477 ves_icall_System_AppDomain_getFriendlyName (MonoAppDomain *ad)
481 g_assert (ad != NULL);
482 g_assert (ad->data != NULL);
484 return mono_string_new (ad->data, ad->data->friendly_name);
488 ves_icall_System_AppDomain_getCurDomain ()
490 MonoDomain *add = mono_domain_get ();
498 ves_icall_System_AppDomain_getRootDomain ()
500 MonoDomain *root = mono_get_root_domain ();
508 get_attribute_value (const gchar **attribute_names,
509 const gchar **attribute_values,
510 const char *att_name)
513 for (n = 0; attribute_names [n] != NULL; n++) {
514 if (strcmp (attribute_names [n], att_name) == 0)
515 return g_strdup (attribute_values [n]);
521 start_element (GMarkupParseContext *context,
522 const gchar *element_name,
523 const gchar **attribute_names,
524 const gchar **attribute_values,
528 RuntimeConfig *runtime_config = user_data;
530 if (strcmp (element_name, "runtime") == 0) {
531 runtime_config->runtime_count++;
535 if (strcmp (element_name, "assemblyBinding") == 0) {
536 runtime_config->assemblybinding_count++;
540 if (runtime_config->runtime_count != 1 || runtime_config->assemblybinding_count != 1)
543 if (strcmp (element_name, "probing") != 0)
546 g_free (runtime_config->domain->private_bin_path);
547 runtime_config->domain->private_bin_path = get_attribute_value (attribute_names, attribute_values, "privatePath");
548 if (runtime_config->domain->private_bin_path && !runtime_config->domain->private_bin_path [0]) {
549 g_free (runtime_config->domain->private_bin_path);
550 runtime_config->domain->private_bin_path = NULL;
556 end_element (GMarkupParseContext *context,
557 const gchar *element_name,
561 RuntimeConfig *runtime_config = user_data;
562 if (strcmp (element_name, "runtime") == 0)
563 runtime_config->runtime_count--;
564 else if (strcmp (element_name, "assemblyBinding") == 0)
565 runtime_config->assemblybinding_count--;
568 static const GMarkupParser
578 mono_set_private_bin_path_from_config (MonoDomain *domain)
580 gchar *config_file, *text;
583 GMarkupParseContext *context;
584 RuntimeConfig runtime_config;
586 if (!domain || !domain->setup || !domain->setup->configuration_file)
589 config_file = mono_string_to_utf8 (domain->setup->configuration_file);
590 if (stat (config_file, &sbuf) != 0) {
591 g_free (config_file);
595 if (!g_file_get_contents (config_file, &text, &len, NULL)) {
596 g_free (config_file);
599 g_free (config_file);
601 runtime_config.runtime_count = 0;
602 runtime_config.assemblybinding_count = 0;
603 runtime_config.domain = domain;
605 context = g_markup_parse_context_new (&mono_parser, 0, &runtime_config, NULL);
606 if (g_markup_parse_context_parse (context, text, len, NULL))
607 g_markup_parse_context_end_parse (context, NULL);
608 g_markup_parse_context_free (context);
613 ves_icall_System_AppDomain_createDomain (MonoString *friendly_name, MonoAppDomainSetup *setup)
621 adclass = mono_class_from_name (mono_defaults.corlib, "System", "AppDomain");
623 /* FIXME: pin all those objects */
624 data = mono_domain_create();
626 ad = (MonoAppDomain *) mono_object_new (data, adclass);
630 data->friendly_name = mono_string_to_utf8 (friendly_name);
631 // FIXME: The ctor runs in the current domain
632 // FIXME: Initialize null_reference_ex and stack_overflow_ex
633 data->out_of_memory_ex = mono_exception_from_name_domain (data, mono_defaults.corlib, "System", "OutOfMemoryException");
635 if (!setup->application_base) {
636 /* Inherit from the root domain since MS.NET does this */
637 MonoDomain *root = mono_get_root_domain ();
638 if (root->setup->application_base)
639 MONO_OBJECT_SETREF (setup, application_base, mono_string_new_utf16 (data, mono_string_chars (root->setup->application_base), mono_string_length (root->setup->application_base)));
642 mono_set_private_bin_path_from_config (data);
644 mono_context_init (data);
646 add_assemblies_to_domain (data, mono_defaults.corlib->assembly, NULL);
652 ves_icall_System_AppDomain_GetAssemblies (MonoAppDomain *ad, MonoBoolean refonly)
654 MonoDomain *domain = ad->data;
656 static MonoClass *System_Reflection_Assembly;
663 if (!System_Reflection_Assembly)
664 System_Reflection_Assembly = mono_class_from_name (
665 mono_defaults.corlib, "System.Reflection", "Assembly");
668 /* Need to skip internal assembly builders created by remoting */
669 mono_domain_assemblies_lock (domain);
670 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
672 if (refonly && !ass->ref_only)
674 if (!ass->corlib_internal)
677 res = mono_array_new (domain, System_Reflection_Assembly, count);
679 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
681 if (refonly && !ass->ref_only)
683 if (ass->corlib_internal)
685 mono_array_setref (res, i, mono_assembly_get_object (domain, ass));
688 mono_domain_assemblies_unlock (domain);
693 MonoReflectionAssembly *
694 mono_try_assembly_resolve (MonoDomain *domain, MonoString *fname, gboolean refonly)
698 MonoBoolean isrefonly;
701 g_assert (domain != NULL && fname != NULL);
703 klass = domain->domain->mbr.obj.vtable->klass;
706 method = mono_class_get_method_from_name (klass, "DoAssemblyResolve", -1);
707 if (method == NULL) {
708 g_warning ("Method AppDomain.DoAssemblyResolve not found.\n");
712 isrefonly = refonly ? 1 : 0;
714 params [1] = &isrefonly;
715 return (MonoReflectionAssembly *) mono_runtime_invoke (method, domain->domain, params, NULL);
718 static MonoAssembly *
719 mono_domain_assembly_postload_search (MonoAssemblyName *aname,
722 gboolean refonly = GPOINTER_TO_UINT (user_data);
723 MonoReflectionAssembly *assembly;
724 MonoDomain *domain = mono_domain_get ();
727 aname_str = mono_stringify_assembly_name (aname);
729 /* FIXME: We invoke managed code here, so there is a potential for deadlocks */
730 assembly = mono_try_assembly_resolve (domain, mono_string_new (domain, aname_str), refonly);
735 return assembly->assembly;
741 * LOCKING: assumes assemblies_lock in the domain is already locked.
744 add_assemblies_to_domain (MonoDomain *domain, MonoAssembly *ass, GHashTable *ht)
748 gboolean destroy_ht = FALSE;
750 if (!ass->aname.name)
754 ht = g_hash_table_new (mono_aligned_addr_hash, NULL);
758 /* FIXME: handle lazy loaded assemblies */
759 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
760 g_hash_table_insert (ht, tmp->data, tmp->data);
762 if (!g_hash_table_lookup (ht, ass)) {
763 mono_assembly_addref (ass);
764 g_hash_table_insert (ht, ass, ass);
765 domain->domain_assemblies = g_slist_prepend (domain->domain_assemblies, ass);
766 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_ASSEMBLY, "Assembly %s %p added to domain %s, ref_count=%d\n", ass->aname.name, ass, domain->friendly_name, ass->ref_count);
769 if (ass->image->references) {
770 for (i = 0; ass->image->references [i] != NULL; i++) {
771 if (ass->image->references [i] != REFERENCE_MISSING)
772 if (!g_hash_table_lookup (ht, ass->image->references [i])) {
773 add_assemblies_to_domain (domain, ass->image->references [i], ht);
778 g_hash_table_destroy (ht);
782 mono_domain_fire_assembly_load (MonoAssembly *assembly, gpointer user_data)
784 static MonoClassField *assembly_load_field;
785 static MonoMethod *assembly_load_method;
786 MonoDomain *domain = mono_domain_get ();
787 MonoReflectionAssembly *ref_assembly;
793 /* This can happen during startup */
795 #ifdef ASSEMBLY_LOAD_DEBUG
796 fprintf (stderr, "Loading %s into domain %s\n", assembly->aname.name, domain->friendly_name);
798 klass = domain->domain->mbr.obj.vtable->klass;
800 mono_domain_assemblies_lock (domain);
801 add_assemblies_to_domain (domain, assembly, NULL);
802 mono_domain_assemblies_unlock (domain);
804 if (assembly_load_field == NULL) {
805 assembly_load_field = mono_class_get_field_from_name (klass, "AssemblyLoad");
806 g_assert (assembly_load_field);
809 mono_field_get_value ((MonoObject*) domain->domain, assembly_load_field, &load_value);
810 if (load_value == NULL) {
811 /* No events waiting to be triggered */
815 ref_assembly = mono_assembly_get_object (domain, assembly);
816 g_assert (ref_assembly);
818 if (assembly_load_method == NULL) {
819 assembly_load_method = mono_class_get_method_from_name (klass, "DoAssemblyLoad", -1);
820 g_assert (assembly_load_method);
823 *params = ref_assembly;
824 mono_runtime_invoke (assembly_load_method, domain->domain, params, NULL);
828 set_domain_search_path (MonoDomain *domain)
830 MonoAppDomainSetup *setup;
832 gchar *search_path = NULL;
835 gchar **pvt_split = NULL;
836 GError *error = NULL;
837 gint appbaselen = -1;
839 if ((domain->search_path != NULL) && !domain->setup->path_changed)
844 setup = domain->setup;
845 if (!setup->application_base)
846 return; /* Must set application base to get private path working */
850 if (setup->private_bin_path)
851 search_path = mono_string_to_utf8 (setup->private_bin_path);
853 if (domain->private_bin_path) {
854 if (search_path == NULL)
855 search_path = domain->private_bin_path;
857 gchar *tmp2 = search_path;
858 search_path = g_strjoin (";", search_path, domain->private_bin_path, NULL);
865 * As per MSDN documentation, AppDomainSetup.PrivateBinPath contains a list of
866 * directories relative to ApplicationBase separated by semicolons (see
867 * http://msdn2.microsoft.com/en-us/library/system.appdomainsetup.privatebinpath.aspx)
868 * The loop below copes with the fact that some Unix applications may use ':' (or
869 * System.IO.Path.PathSeparator) as the path search separator. We replace it with
870 * ';' for the subsequent split.
872 * The issue was reported in bug #81446
875 #ifndef PLATFORM_WIN32
878 slen = strlen (search_path);
879 for (i = 0; i < slen; i++)
880 if (search_path [i] == ':')
881 search_path [i] = ';';
884 pvt_split = g_strsplit (search_path, ";", 1000);
885 g_free (search_path);
886 for (tmp = pvt_split; *tmp; tmp++, npaths++);
891 g_strfreev (pvt_split);
893 * Don't do this because the first time is called, the domain
894 * setup is not finished.
896 * domain->search_path = g_malloc (sizeof (char *));
897 * domain->search_path [0] = NULL;
902 if (domain->search_path)
903 g_strfreev (domain->search_path);
905 domain->search_path = tmp = g_malloc ((npaths + 1) * sizeof (gchar *));
908 *tmp = mono_string_to_utf8 (setup->application_base);
910 /* FIXME: is this needed? */
911 if (strncmp (*tmp, "file://", 7) == 0) {
917 uri = g_strdup_printf ("file:///%s", uri + 7);
920 uri = mono_escape_uri_string (tmpuri);
921 *tmp = g_filename_from_uri (uri, NULL, &error);
928 g_warning ("%s\n", error->message);
929 g_error_free (error);
936 for (i = 1; pvt_split && i < npaths; i++) {
937 if (g_path_is_absolute (pvt_split [i - 1])) {
938 tmp [i] = g_strdup (pvt_split [i - 1]);
940 tmp [i] = g_build_filename (tmp [0], pvt_split [i - 1], NULL);
943 if (strchr (tmp [i], '.')) {
947 reduced = mono_path_canonicalize (tmp [i]);
948 if (appbaselen == -1)
949 appbaselen = strlen (tmp [0]);
951 if (strncmp (tmp [0], reduced, appbaselen)) {
954 tmp [i] = g_strdup ("");
964 if (setup->private_bin_path_probe != NULL) {
966 tmp [0] = g_strdup ("");
969 domain->setup->path_changed = FALSE;
971 g_strfreev (pvt_split);
975 shadow_copy_sibling (gchar *src, gint srclen, const char *extension, gchar *target, gint targetlen, gint tail_len)
977 guint16 *orig, *dest;
978 gboolean copy_result;
980 strcpy (src + srclen - tail_len, extension);
981 if (!g_file_test (src, G_FILE_TEST_IS_REGULAR))
983 orig = g_utf8_to_utf16 (src, strlen (src), NULL, NULL, NULL);
985 strcpy (target + targetlen - tail_len, extension);
986 dest = g_utf8_to_utf16 (target, strlen (target), NULL, NULL, NULL);
989 copy_result = CopyFile (orig, dest, FALSE);
997 get_cstring_hash (const char *str)
1003 if (!str || !str [0])
1008 for (i = 0; i < len; i++) {
1009 h = (h << 5) - h + *p;
1017 get_shadow_assembly_location (const char *filename)
1019 gint32 hash = 0, hash2 = 0;
1021 char path_hash [30];
1022 char *bname = g_path_get_basename (filename);
1023 char *dirname = g_path_get_dirname (filename);
1024 char *location, *dyn_base;
1025 MonoDomain *domain = mono_domain_get ();
1027 hash = get_cstring_hash (bname);
1028 hash2 = get_cstring_hash (dirname);
1029 g_snprintf (name_hash, sizeof (name_hash), "%08x", hash);
1030 g_snprintf (path_hash, sizeof (path_hash), "%08x_%08x_%08x", hash ^ hash2, hash2, domain->shadow_serial);
1031 dyn_base = mono_string_to_utf8 (domain->setup->dynamic_base);
1032 location = g_build_filename (dyn_base, "assembly", "shadow", name_hash, path_hash, bname, NULL);
1040 ensure_directory_exists (const char *filename)
1042 #ifdef PLATFORM_WIN32
1043 gchar *dir_utf8 = g_path_get_dirname (filename);
1045 gunichar2 *dir_utf16 = NULL;
1048 if (!dir_utf8 || !dir_utf8 [0])
1051 dir_utf16 = g_utf8_to_utf16 (dir_utf8, strlen (dir_utf8), NULL, NULL, NULL);
1059 /* make life easy and only use one directory seperator */
1070 while (*p++ != '\\')
1076 p = wcschr (p, '\\');
1079 retval = _wmkdir (dir_utf16);
1080 if (retval != 0 && errno != EEXIST) {
1093 gchar *dir = g_path_get_dirname (filename);
1096 if (!dir || !dir [0])
1104 p = strchr (p, '/');
1107 retval = mkdir (dir, 0777);
1108 if (retval != 0 && errno != EEXIST) {
1123 make_shadow_copy (const char *filename)
1125 gchar *sibling_source, *sibling_target;
1126 gint sibling_source_len, sibling_target_len;
1127 guint16 *orig, *dest;
1129 gboolean copy_result;
1132 shadow = get_shadow_assembly_location (filename);
1133 if (ensure_directory_exists (shadow) == FALSE) {
1134 exc = mono_get_exception_execution_engine ("Failed to create shadow copy (ensure directory exists).");
1135 mono_raise_exception (exc);
1138 orig = g_utf8_to_utf16 (filename, strlen (filename), NULL, NULL, NULL);
1139 dest = g_utf8_to_utf16 (shadow, strlen (shadow), NULL, NULL, NULL);
1141 copy_result = CopyFile (orig, dest, FALSE);
1145 if (copy_result == FALSE) {
1147 exc = mono_get_exception_execution_engine ("Failed to create shadow copy (CopyFile).");
1148 mono_raise_exception (exc);
1151 /* attempt to copy .mdb, .config if they exist */
1152 sibling_source = g_strconcat (filename, ".config", NULL);
1153 sibling_source_len = strlen (sibling_source);
1154 sibling_target = g_strconcat (shadow, ".config", NULL);
1155 sibling_target_len = strlen (sibling_target);
1157 copy_result = shadow_copy_sibling (sibling_source, sibling_source_len, ".mdb", sibling_target, sibling_target_len, 7);
1158 if (copy_result == TRUE)
1159 copy_result = shadow_copy_sibling (sibling_source, sibling_source_len, ".config", sibling_target, sibling_target_len, 7);
1161 g_free (sibling_source);
1162 g_free (sibling_target);
1164 if (copy_result == FALSE) {
1166 exc = mono_get_exception_execution_engine ("Failed to create shadow copy of sibling data (CopyFile).");
1167 mono_raise_exception (exc);
1174 try_load_from (MonoAssembly **assembly, const gchar *path1, const gchar *path2,
1175 const gchar *path3, const gchar *path4,
1176 gboolean refonly, gboolean is_private)
1182 fullpath = g_build_filename (path1, path2, path3, path4, NULL);
1183 if (g_file_test (fullpath, G_FILE_TEST_IS_REGULAR)) {
1185 char *new_path = make_shadow_copy (fullpath);
1187 fullpath = new_path;
1190 *assembly = mono_assembly_open_full (fullpath, NULL, refonly);
1194 return (*assembly != NULL);
1197 static MonoAssembly *
1198 real_load (gchar **search_path, const gchar *culture, const gchar *name, gboolean refonly)
1200 MonoAssembly *result = NULL;
1203 const gchar *local_culture;
1205 gboolean is_private = FALSE;
1207 if (!culture || *culture == '\0') {
1210 local_culture = culture;
1213 filename = g_strconcat (name, ".dll", NULL);
1214 len = strlen (filename);
1216 for (path = search_path; *path; path++) {
1217 if (**path == '\0') {
1219 continue; /* Ignore empty ApplicationBase */
1222 /* See test cases in bug #58992 and bug #57710 */
1223 /* 1st try: [culture]/[name].dll (culture may be empty) */
1224 strcpy (filename + len - 4, ".dll");
1225 if (try_load_from (&result, *path, local_culture, "", filename, refonly, is_private))
1228 /* 2nd try: [culture]/[name].exe (culture may be empty) */
1229 strcpy (filename + len - 4, ".exe");
1230 if (try_load_from (&result, *path, local_culture, "", filename, refonly, is_private))
1233 /* 3rd try: [culture]/[name]/[name].dll (culture may be empty) */
1234 strcpy (filename + len - 4, ".dll");
1235 if (try_load_from (&result, *path, local_culture, name, filename, refonly, is_private))
1238 /* 4th try: [culture]/[name]/[name].exe (culture may be empty) */
1239 strcpy (filename + len - 4, ".exe");
1240 if (try_load_from (&result, *path, local_culture, name, filename, refonly, is_private))
1249 * Try loading the assembly from ApplicationBase and PrivateBinPath
1250 * and then from assemblies_path if any.
1252 static MonoAssembly *
1253 mono_domain_assembly_preload (MonoAssemblyName *aname,
1254 gchar **assemblies_path,
1257 MonoDomain *domain = mono_domain_get ();
1258 MonoAssembly *result = NULL;
1259 gboolean refonly = GPOINTER_TO_UINT (user_data);
1261 set_domain_search_path (domain);
1263 if (domain->search_path && domain->search_path [0] != NULL) {
1264 result = real_load (domain->search_path, aname->culture, aname->name, refonly);
1267 if (result == NULL && assemblies_path && assemblies_path [0] != NULL) {
1268 result = real_load (assemblies_path, aname->culture, aname->name, refonly);
1275 * Check whenever a given assembly was already loaded in the current appdomain.
1277 static MonoAssembly *
1278 mono_domain_assembly_search (MonoAssemblyName *aname,
1281 MonoDomain *domain = mono_domain_get ();
1284 gboolean refonly = GPOINTER_TO_UINT (user_data);
1286 mono_domain_assemblies_lock (domain);
1287 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
1289 /* Dynamic assemblies can't match here in MS.NET */
1290 if (ass->dynamic || refonly != ass->ref_only || !mono_assembly_names_equal (aname, &ass->aname))
1293 mono_domain_assemblies_unlock (domain);
1296 mono_domain_assemblies_unlock (domain);
1301 MonoReflectionAssembly *
1302 ves_icall_System_Reflection_Assembly_LoadFrom (MonoString *fname, MonoBoolean refOnly)
1304 MonoDomain *domain = mono_domain_get ();
1305 char *name, *filename;
1306 MonoImageOpenStatus status = MONO_IMAGE_OK;
1309 MONO_ARCH_SAVE_REGS;
1311 if (fname == NULL) {
1312 MonoException *exc = mono_get_exception_argument_null ("assemblyFile");
1313 mono_raise_exception (exc);
1316 name = filename = mono_string_to_utf8 (fname);
1318 ass = mono_assembly_open_full (filename, &status, refOnly);
1323 if (status == MONO_IMAGE_IMAGE_INVALID)
1324 exc = mono_get_exception_bad_image_format2 (NULL, fname);
1326 exc = mono_get_exception_file_not_found2 (NULL, fname);
1328 mono_raise_exception (exc);
1333 return mono_assembly_get_object (domain, ass);
1336 MonoReflectionAssembly *
1337 ves_icall_System_AppDomain_LoadAssemblyRaw (MonoAppDomain *ad,
1338 MonoArray *raw_assembly,
1339 MonoArray *raw_symbol_store, MonoObject *evidence,
1340 MonoBoolean refonly)
1343 MonoReflectionAssembly *refass = NULL;
1344 MonoDomain *domain = ad->data;
1345 MonoImageOpenStatus status;
1346 guint32 raw_assembly_len = mono_array_length (raw_assembly);
1347 MonoImage *image = mono_image_open_from_data_full (mono_array_addr (raw_assembly, gchar, 0), raw_assembly_len, TRUE, NULL, refonly);
1350 mono_raise_exception (mono_get_exception_bad_image_format (""));
1354 if (raw_symbol_store != NULL)
1355 mono_debug_open_image_from_memory (image, mono_array_addr (raw_symbol_store, guint8, 0), mono_array_length (raw_symbol_store));
1357 ass = mono_assembly_load_from_full (image, "", &status, refonly);
1361 mono_image_close (image);
1362 mono_raise_exception (mono_get_exception_bad_image_format (""));
1366 refass = mono_assembly_get_object (domain, ass);
1367 MONO_OBJECT_SETREF (refass, evidence, evidence);
1371 MonoReflectionAssembly *
1372 ves_icall_System_AppDomain_LoadAssembly (MonoAppDomain *ad, MonoString *assRef, MonoObject *evidence, MonoBoolean refOnly)
1374 MonoDomain *domain = ad->data;
1375 MonoImageOpenStatus status = MONO_IMAGE_OK;
1377 MonoAssemblyName aname;
1378 MonoReflectionAssembly *refass = NULL;
1382 MONO_ARCH_SAVE_REGS;
1384 g_assert (assRef != NULL);
1386 name = mono_string_to_utf8 (assRef);
1387 parsed = mono_assembly_name_parse (name, &aname);
1393 /* This is a parse error... */
1394 exc = mono_get_exception_file_not_found2 (NULL, assRef);
1395 mono_raise_exception (exc);
1398 ass = mono_assembly_load_full_nosearch (&aname, NULL, &status, refOnly);
1399 mono_assembly_name_free (&aname);
1402 /* MS.NET doesn't seem to call the assembly resolve handler for refonly assemblies */
1404 refass = mono_try_assembly_resolve (domain, assRef, refOnly);
1408 /* FIXME: it doesn't make much sense since we really don't have a filename ... */
1409 MonoException *exc = mono_get_exception_file_not_found2 (NULL, assRef);
1410 mono_raise_exception (exc);
1415 refass = mono_assembly_get_object (domain, ass);
1417 MONO_OBJECT_SETREF (refass, evidence, evidence);
1422 ves_icall_System_AppDomain_InternalUnload (gint32 domain_id)
1424 MonoDomain * domain = mono_domain_get_by_id (domain_id);
1426 MONO_ARCH_SAVE_REGS;
1428 if (NULL == domain) {
1429 MonoException *exc = mono_get_exception_execution_engine ("Failed to unload domain, domain id not found");
1430 mono_raise_exception (exc);
1433 if (domain == mono_get_root_domain ()) {
1434 mono_raise_exception (mono_get_exception_cannot_unload_appdomain ("The default appdomain can not be unloaded."));
1439 * Unloading seems to cause problems when running NUnit/NAnt, hence
1442 if (g_getenv ("MONO_NO_UNLOAD"))
1445 mono_domain_unload (domain);
1449 ves_icall_System_AppDomain_InternalIsFinalizingForUnload (gint32 domain_id)
1451 MonoDomain *domain = mono_domain_get_by_id (domain_id);
1456 return mono_domain_is_unloading (domain);
1460 ves_icall_System_AppDomain_ExecuteAssembly (MonoAppDomain *ad,
1461 MonoReflectionAssembly *refass, MonoArray *args)
1466 MONO_ARCH_SAVE_REGS;
1469 image = refass->assembly->image;
1472 method = mono_get_method (image, mono_image_get_entry_point (image), NULL);
1475 g_error ("No entry point method found in %s", image->name);
1478 args = (MonoArray *) mono_array_new (ad->data, mono_defaults.string_class, 0);
1480 return mono_runtime_exec_main (method, (MonoArray *)args, NULL);
1484 ves_icall_System_AppDomain_GetIDFromDomain (MonoAppDomain * ad)
1486 MONO_ARCH_SAVE_REGS;
1488 return ad->data->domain_id;
1492 ves_icall_System_AppDomain_InternalSetDomain (MonoAppDomain *ad)
1494 MonoDomain *old_domain = mono_domain_get();
1496 MONO_ARCH_SAVE_REGS;
1498 if (!mono_domain_set (ad->data, FALSE))
1499 mono_raise_exception (mono_get_exception_appdomain_unloaded ());
1501 return old_domain->domain;
1505 ves_icall_System_AppDomain_InternalSetDomainByID (gint32 domainid)
1507 MonoDomain *current_domain = mono_domain_get ();
1508 MonoDomain *domain = mono_domain_get_by_id (domainid);
1510 MONO_ARCH_SAVE_REGS;
1512 if (!domain || !mono_domain_set (domain, FALSE))
1513 mono_raise_exception (mono_get_exception_appdomain_unloaded ());
1515 return current_domain->domain;
1519 ves_icall_System_AppDomain_InternalPushDomainRef (MonoAppDomain *ad)
1521 MONO_ARCH_SAVE_REGS;
1523 mono_thread_push_appdomain_ref (ad->data);
1527 ves_icall_System_AppDomain_InternalPushDomainRefByID (gint32 domain_id)
1529 MonoDomain *domain = mono_domain_get_by_id (domain_id);
1531 MONO_ARCH_SAVE_REGS;
1535 * Raise an exception to prevent the managed code from executing a pop
1538 mono_raise_exception (mono_get_exception_appdomain_unloaded ());
1540 mono_thread_push_appdomain_ref (domain);
1544 ves_icall_System_AppDomain_InternalPopDomainRef (void)
1546 MONO_ARCH_SAVE_REGS;
1548 mono_thread_pop_appdomain_ref ();
1552 ves_icall_System_AppDomain_InternalGetContext ()
1554 MONO_ARCH_SAVE_REGS;
1556 return mono_context_get ();
1560 ves_icall_System_AppDomain_InternalGetDefaultContext ()
1562 MONO_ARCH_SAVE_REGS;
1564 return mono_domain_get ()->default_context;
1568 ves_icall_System_AppDomain_InternalSetContext (MonoAppContext *mc)
1570 MonoAppContext *old_context = mono_context_get ();
1572 MONO_ARCH_SAVE_REGS;
1574 mono_context_set (mc);
1580 ves_icall_System_AppDomain_InternalGetProcessGuid (MonoString* newguid)
1582 MonoDomain* mono_root_domain = mono_get_root_domain ();
1583 mono_domain_lock (mono_root_domain);
1584 if (process_guid_set) {
1585 mono_domain_unlock (mono_root_domain);
1586 return mono_string_new_utf16 (mono_domain_get (), process_guid, sizeof(process_guid)/2);
1588 memcpy (process_guid, mono_string_chars(newguid), sizeof(process_guid));
1589 process_guid_set = TRUE;
1590 mono_domain_unlock (mono_root_domain);
1595 mono_domain_is_unloading (MonoDomain *domain)
1597 if (domain->state == MONO_APPDOMAIN_UNLOADING || domain->state == MONO_APPDOMAIN_UNLOADED)
1604 clear_cached_vtable (gpointer key, gpointer value, gpointer user_data)
1606 MonoClass *klass = (MonoClass*)key;
1607 MonoDomain *domain = (MonoDomain*)user_data;
1608 MonoClassRuntimeInfo *runtime_info;
1610 runtime_info = klass->runtime_info;
1611 if (runtime_info && runtime_info->max_domain >= domain->domain_id)
1612 runtime_info->domain_vtables [domain->domain_id] = NULL;
1615 typedef struct unload_data {
1617 char *failure_reason;
1620 static guint32 WINAPI
1621 unload_thread_main (void *arg)
1623 unload_data *data = (unload_data*)arg;
1624 MonoDomain *domain = data->domain;
1627 * FIXME: Abort our parent thread last, so we can return a failure
1628 * indication if aborting times out.
1630 if (!mono_threads_abort_appdomain_threads (domain, 10000)) {
1631 data->failure_reason = g_strdup_printf ("Aborting of threads in domain %s timed out.", domain->friendly_name);
1635 /* Finalize all finalizable objects in the doomed appdomain */
1636 if (!mono_domain_finalize (domain, 10000)) {
1637 data->failure_reason = g_strdup_printf ("Finalization of domain %s timed out.", domain->friendly_name);
1641 /* Clear references to our vtables in class->runtime_info.
1642 * We also hold the loader lock because we're going to change
1643 * class->runtime_info.
1645 mono_domain_lock (domain);
1646 mono_loader_lock ();
1647 g_hash_table_foreach (domain->class_vtable_hash, clear_cached_vtable, domain);
1648 mono_loader_unlock ();
1649 mono_domain_unlock (domain);
1651 mono_threads_clear_cached_culture (domain);
1653 domain->state = MONO_APPDOMAIN_UNLOADED;
1655 /* printf ("UNLOADED %s.\n", domain->friendly_name); */
1657 /* remove from the handle table the items related to this domain */
1658 mono_gchandle_free_domain (domain);
1660 mono_domain_free (domain, FALSE);
1662 mono_gc_collect (mono_gc_max_generation ());
1668 * mono_domain_unload:
1669 * @domain: The domain to unload
1671 * Unloads an appdomain. Follows the process outlined in:
1672 * http://blogs.gotdotnet.com/cbrumme
1674 * If doing things the 'right' way is too hard or complex, we do it the
1675 * 'simple' way, which means do everything needed to avoid crashes and
1676 * memory leaks, but not much else.
1679 mono_domain_unload (MonoDomain *domain)
1681 HANDLE thread_handle;
1684 MonoAppDomainState prev_state;
1687 unload_data thread_data;
1688 MonoDomain *caller_domain = mono_domain_get ();
1690 /* printf ("UNLOAD STARTING FOR %s (%p) IN THREAD 0x%x.\n", domain->friendly_name, domain, GetCurrentThreadId ()); */
1692 /* Atomically change our state to UNLOADING */
1693 prev_state = InterlockedCompareExchange ((gint32*)&domain->state,
1694 MONO_APPDOMAIN_UNLOADING,
1695 MONO_APPDOMAIN_CREATED);
1696 if (prev_state != MONO_APPDOMAIN_CREATED) {
1697 if (prev_state == MONO_APPDOMAIN_UNLOADING)
1698 mono_raise_exception (mono_get_exception_cannot_unload_appdomain ("Appdomain is already being unloaded."));
1700 if (prev_state == MONO_APPDOMAIN_UNLOADED)
1701 mono_raise_exception (mono_get_exception_cannot_unload_appdomain ("Appdomain is already unloaded."));
1703 g_assert_not_reached ();
1706 mono_domain_set (domain, FALSE);
1707 /* Notify OnDomainUnload listeners */
1708 method = mono_class_get_method_from_name (domain->domain->mbr.obj.vtable->klass, "DoDomainUnload", -1);
1712 mono_runtime_invoke (method, domain->domain, NULL, &exc);
1714 /* Roll back the state change */
1715 domain->state = MONO_APPDOMAIN_CREATED;
1716 mono_domain_set (caller_domain, FALSE);
1717 mono_raise_exception ((MonoException*)exc);
1720 thread_data.domain = domain;
1721 thread_data.failure_reason = NULL;
1724 * First we create a separate thread for unloading, since
1725 * we might have to abort some threads, including the current one.
1728 * If we create a non-suspended thread, the runtime will hang.
1730 * http://bugzilla.ximian.com/show_bug.cgi?id=27663
1733 thread_handle = CreateThread (NULL, 0, unload_thread_main, &thread_data, 0, &tid);
1735 thread_handle = CreateThread (NULL, 0, (LPTHREAD_START_ROUTINE)unload_thread_main, &thread_data, CREATE_SUSPENDED, &tid);
1736 if (thread_handle == NULL) {
1739 ResumeThread (thread_handle);
1742 /* Wait for the thread */
1743 while ((res = WaitForSingleObjectEx (thread_handle, INFINITE, TRUE) == WAIT_IO_COMPLETION)) {
1744 if (mono_thread_has_appdomain_ref (mono_thread_current (), domain) && (mono_thread_interruption_requested ()))
1745 /* The unload thread tries to abort us */
1746 /* The icall wrapper will execute the abort */
1747 CloseHandle (thread_handle);
1750 CloseHandle (thread_handle);
1752 mono_domain_set (caller_domain, FALSE);
1754 if (thread_data.failure_reason) {
1757 /* Roll back the state change */
1758 domain->state = MONO_APPDOMAIN_CREATED;
1760 g_warning (thread_data.failure_reason);
1762 ex = mono_get_exception_cannot_unload_appdomain (thread_data.failure_reason);
1764 g_free (thread_data.failure_reason);
1765 thread_data.failure_reason = NULL;
1767 mono_raise_exception (ex);