2 * appdomain.c: AppDomain functions
5 * Dietmar Maurer (dietmar@ximian.com)
7 * Gonzalo Paniagua Javier (gonzalo@ximian.com)
9 * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
10 * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
12 #undef ASSEMBLY_LOAD_DEBUG
21 #include <sys/types.h>
22 #ifdef HAVE_SYS_TIME_H
28 #ifdef HAVE_SYS_UTIME_H
29 #include <sys/utime.h>
33 #include <mono/metadata/gc-internal.h>
34 #include <mono/metadata/object.h>
35 #include <mono/metadata/domain-internals.h>
36 #include "mono/metadata/metadata-internals.h"
37 #include <mono/metadata/assembly.h>
38 #include <mono/metadata/exception.h>
39 #include <mono/metadata/threads.h>
40 #include <mono/metadata/socket-io.h>
41 #include <mono/metadata/tabledefs.h>
42 #include <mono/metadata/gc-internal.h>
43 #include <mono/metadata/mono-gc.h>
44 #include <mono/metadata/marshal.h>
45 #include <mono/metadata/monitor.h>
46 #include <mono/metadata/threadpool.h>
47 #include <mono/metadata/mono-debug.h>
48 #include <mono/metadata/attach.h>
49 #include <mono/metadata/file-io.h>
50 #include <mono/utils/mono-uri.h>
51 #include <mono/utils/mono-logger.h>
52 #include <mono/utils/mono-path.h>
53 #include <mono/utils/mono-stdlib.h>
54 #include <mono/utils/mono-io-portability.h>
60 * This is the version number of the corlib-runtime interface. When
61 * making changes to this interface (by changing the layout
62 * of classes the runtime knows about, changing icall signature or
63 * semantics etc), increment this variable. Also increment the
64 * pair of this variable in mscorlib in:
65 * mcs/class/mscorlib/System/Environment.cs
67 * Changes which are already detected at runtime, like the addition
68 * of icalls, do not require an increment.
70 #define MONO_CORLIB_VERSION 69
75 int assemblybinding_count;
79 CRITICAL_SECTION mono_delegate_section;
82 /* Need to lock here because EGLIB has locking defined as no-ops, we can not depend on mono_strtod do the right locking */
83 /* Ideally this will be fixed in eglib */
84 CRITICAL_SECTION mono_strtod_mutex;
88 static gunichar2 process_guid [36];
89 static gboolean process_guid_set = FALSE;
91 static gboolean shutting_down = FALSE;
93 static gboolean no_exec = FALSE;
96 mono_domain_assembly_preload (MonoAssemblyName *aname,
97 gchar **assemblies_path,
100 static MonoAssembly *
101 mono_domain_assembly_search (MonoAssemblyName *aname,
104 static MonoAssembly *
105 mono_domain_assembly_postload_search (MonoAssemblyName *aname,
109 mono_domain_fire_assembly_load (MonoAssembly *assembly, gpointer user_data);
112 add_assemblies_to_domain (MonoDomain *domain, MonoAssembly *ass, GHashTable *hash);
114 static MonoAppDomain *
115 mono_domain_create_appdomain_internal (char *friendly_name, MonoAppDomainSetup *setup);
117 static MonoLoadFunc load_function = NULL;
120 mono_install_runtime_load (MonoLoadFunc func)
122 load_function = func;
126 mono_runtime_load (const char *filename, const char *runtime_version)
128 g_assert (load_function);
129 return load_function (filename, runtime_version);
133 * mono_runtime_set_no_exec:
135 * Instructs the runtime to operate in static mode, i.e. avoid/do not allow managed
136 * code execution. This is useful for running the AOT compiler on platforms which
137 * allow full-aot execution only.
138 * This should be called before mono_runtime_init ().
141 mono_runtime_set_no_exec (gboolean val)
147 mono_runtime_get_no_exec (void)
154 * @domain: domain returned by mono_init ()
156 * Initialize the core AppDomain: this function will run also some
157 * IL initialization code, so it needs the execution engine to be fully
160 * AppDomain.SetupInformation is set up in mono_runtime_exec_main, where
161 * we know the entry_assembly.
165 mono_runtime_init (MonoDomain *domain, MonoThreadStartCB start_cb,
166 MonoThreadAttachCB attach_cb)
168 MonoAppDomainSetup *setup;
173 mono_portability_helpers_init ();
175 mono_gc_base_init ();
176 mono_monitor_init ();
177 mono_thread_pool_init ();
178 mono_marshal_init ();
180 mono_install_assembly_preload_hook (mono_domain_assembly_preload, GUINT_TO_POINTER (FALSE));
181 mono_install_assembly_refonly_preload_hook (mono_domain_assembly_preload, GUINT_TO_POINTER (TRUE));
182 mono_install_assembly_search_hook (mono_domain_assembly_search, GUINT_TO_POINTER (FALSE));
183 mono_install_assembly_refonly_search_hook (mono_domain_assembly_search, GUINT_TO_POINTER (TRUE));
184 mono_install_assembly_postload_search_hook (mono_domain_assembly_postload_search, GUINT_TO_POINTER (FALSE));
185 mono_install_assembly_postload_refonly_search_hook (mono_domain_assembly_postload_search, GUINT_TO_POINTER (TRUE));
186 mono_install_assembly_load_hook (mono_domain_fire_assembly_load, NULL);
187 mono_install_lookup_dynamic_token (mono_reflection_lookup_dynamic_token);
189 mono_thread_init (start_cb, attach_cb);
191 class = mono_class_from_name (mono_defaults.corlib, "System", "AppDomainSetup");
192 setup = (MonoAppDomainSetup *) mono_object_new (domain, class);
194 class = mono_class_from_name (mono_defaults.corlib, "System", "AppDomain");
195 ad = (MonoAppDomain *) mono_object_new (domain, class);
198 domain->setup = setup;
200 InitializeCriticalSection (&mono_delegate_section);
203 /* Needed until EGLIB is fixed #464316 */
204 InitializeCriticalSection (&mono_strtod_mutex);
207 mono_thread_attach (domain);
208 mono_context_init (domain);
209 mono_context_set (domain->default_context);
211 mono_type_initialization_init ();
213 if (!mono_runtime_get_no_exec ()) {
215 * Create an instance early since we can't do it when there is no memory.
217 arg = mono_string_new (domain, "Out of memory");
218 domain->out_of_memory_ex = mono_exception_from_name_two_strings (mono_defaults.corlib, "System", "OutOfMemoryException", arg, NULL);
221 * These two are needed because the signal handlers might be executing on
222 * an alternate stack, and Boehm GC can't handle that.
224 arg = mono_string_new (domain, "A null value was found where an object instance was required");
225 domain->null_reference_ex = mono_exception_from_name_two_strings (mono_defaults.corlib, "System", "NullReferenceException", arg, NULL);
226 arg = mono_string_new (domain, "The requested operation caused a stack overflow.");
227 domain->stack_overflow_ex = mono_exception_from_name_two_strings (mono_defaults.corlib, "System", "StackOverflowException", arg, NULL);
230 /* GC init has to happen after thread init */
233 #ifndef DISABLE_SOCKETS
234 mono_network_init ();
239 /* mscorlib is loaded before we install the load hook */
240 mono_domain_fire_assembly_load (mono_defaults.corlib->assembly, NULL);
246 mono_get_corlib_version (void)
249 MonoClassField *field;
252 klass = mono_class_from_name (mono_defaults.corlib, "System", "Environment");
253 mono_class_init (klass);
254 field = mono_class_get_field_from_name (klass, "mono_corlib_version");
257 if (! (field->type->attrs & FIELD_ATTRIBUTE_STATIC))
259 value = mono_field_get_value_object (mono_domain_get (), field, NULL);
260 return *(gint32*)((gchar*)value + sizeof (MonoObject));
264 mono_check_corlib_version (void)
266 int version = mono_get_corlib_version ();
267 if (version != MONO_CORLIB_VERSION)
268 return g_strdup_printf ("expected corlib version %d, found %d.", MONO_CORLIB_VERSION, version);
274 mono_context_init (MonoDomain *domain)
277 MonoAppContext *context;
279 class = mono_class_from_name (mono_defaults.corlib, "System.Runtime.Remoting.Contexts", "Context");
280 context = (MonoAppContext *) mono_object_new (domain, class);
281 context->domain_id = domain->domain_id;
282 context->context_id = 0;
283 domain->default_context = context;
287 * mono_runtime_cleanup:
292 * This must not be called while there are still running threads executing
296 mono_runtime_cleanup (MonoDomain *domain)
298 shutting_down = TRUE;
300 mono_attach_cleanup ();
302 /* This ends up calling any pending pending (for at most 2 seconds) */
305 mono_thread_cleanup ();
307 #ifndef DISABLE_SOCKETS
308 mono_network_cleanup ();
310 mono_marshal_cleanup ();
312 mono_type_initialization_cleanup ();
314 mono_monitor_cleanup ();
316 #ifndef PLATFORM_WIN32
321 static MonoDomainFunc quit_function = NULL;
324 mono_install_runtime_cleanup (MonoDomainFunc func)
326 quit_function = func;
332 if (quit_function != NULL)
333 quit_function (mono_get_root_domain (), NULL);
337 * mono_runtime_set_shutting_down:
339 * Invoked by System.Environment.Exit to flag that the runtime
343 mono_runtime_set_shutting_down (void)
345 shutting_down = TRUE;
349 * mono_runtime_is_shutting_down:
351 * Returns whether the runtime has been flagged for shutdown.
353 * This is consumed by the P:System.Environment.HasShutdownStarted
358 mono_runtime_is_shutting_down (void)
360 return shutting_down;
364 * mono_domain_create_appdomain:
365 * @friendly_name: The friendly name of the appdomain to create
366 * @configuration_file: The configuration file to initialize the appdomain with
368 * Returns a MonoDomain initialized with the appdomain
371 mono_domain_create_appdomain (char *friendly_name, char *configuration_file)
374 MonoAppDomainSetup *setup;
377 class = mono_class_from_name (mono_defaults.corlib, "System", "AppDomainSetup");
378 setup = (MonoAppDomainSetup *) mono_object_new (mono_domain_get (), class);
379 setup->configuration_file = configuration_file != NULL ? mono_string_new (mono_domain_get (), configuration_file) : NULL;
381 ad = mono_domain_create_appdomain_internal (friendly_name, setup);
383 return mono_domain_from_appdomain (ad);
386 static MonoAppDomain *
387 mono_domain_create_appdomain_internal (char *friendly_name, MonoAppDomainSetup *setup)
395 adclass = mono_class_from_name (mono_defaults.corlib, "System", "AppDomain");
397 /* FIXME: pin all those objects */
398 data = mono_domain_create();
400 ad = (MonoAppDomain *) mono_object_new (data, adclass);
404 data->friendly_name = g_strdup (friendly_name);
405 // FIXME: The ctor runs in the current domain
406 // FIXME: Initialize null_reference_ex and stack_overflow_ex
407 data->out_of_memory_ex = mono_exception_from_name_domain (data, mono_defaults.corlib, "System", "OutOfMemoryException");
409 if (!setup->application_base) {
410 /* Inherit from the root domain since MS.NET does this */
411 MonoDomain *root = mono_get_root_domain ();
412 if (root->setup->application_base)
413 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)));
416 mono_context_init (data);
418 mono_set_private_bin_path_from_config (data);
420 add_assemblies_to_domain (data, mono_defaults.corlib->assembly, NULL);
426 * mono_domain_has_type_resolve:
427 * @domain: application domains being looked up
429 * Returns true if the AppDomain.TypeResolve field has been
433 mono_domain_has_type_resolve (MonoDomain *domain)
435 static MonoClassField *field = NULL;
439 field = mono_class_get_field_from_name (mono_defaults.appdomain_class, "TypeResolve");
443 mono_field_get_value ((MonoObject*)(domain->domain), field, &o);
448 * mono_domain_try_type_resolve:
449 * @domain: application domainwhere the name where the type is going to be resolved
450 * @name: the name of the type to resolve or NULL.
451 * @tb: A System.Reflection.Emit.TypeBuilder, used if name is NULL.
453 * This routine invokes the internal System.AppDomain.DoTypeResolve and returns
454 * the assembly that matches name.
456 * If @name is null, the value of ((TypeBuilder)tb).FullName is used instead
458 * Returns: A MonoReflectionAssembly or NULL if not found
460 MonoReflectionAssembly *
461 mono_domain_try_type_resolve (MonoDomain *domain, char *name, MonoObject *tb)
465 static MonoMethod *method = NULL;
467 g_assert (domain != NULL && ((name != NULL) || (tb != NULL)));
469 if (method == NULL) {
470 klass = domain->domain->mbr.obj.vtable->klass;
473 method = mono_class_get_method_from_name (klass, "DoTypeResolve", -1);
474 if (method == NULL) {
475 g_warning ("Method AppDomain.DoTypeResolve not found.\n");
481 *params = (MonoObject*)mono_string_new (mono_domain_get (), name);
484 return (MonoReflectionAssembly *) mono_runtime_invoke (method, domain->domain, params, NULL);
488 * mono_domain_owns_vtable_slot:
490 * Returns whenever VTABLE_SLOT is inside a vtable which belongs to DOMAIN.
493 mono_domain_owns_vtable_slot (MonoDomain *domain, gpointer vtable_slot)
497 mono_domain_lock (domain);
498 res = mono_mempool_contains_addr (domain->mp, vtable_slot);
499 mono_domain_unlock (domain);
506 * @force: force setting.
508 * Set the current appdomain to @domain. If @force is set, set it even
509 * if it is being unloaded.
513 * FALSE if the domain is unloaded
516 mono_domain_set (MonoDomain *domain, gboolean force)
518 if (!force && domain->state == MONO_APPDOMAIN_UNLOADED)
521 mono_domain_set_internal (domain);
527 ves_icall_System_AppDomain_GetData (MonoAppDomain *ad, MonoString *name)
535 g_assert (ad != NULL);
537 g_assert (add != NULL);
540 mono_raise_exception (mono_get_exception_argument_null ("name"));
542 str = mono_string_to_utf8 (name);
544 mono_domain_lock (add);
546 if (!strcmp (str, "APPBASE"))
547 o = (MonoObject *)add->setup->application_base;
548 else if (!strcmp (str, "APP_CONFIG_FILE"))
549 o = (MonoObject *)add->setup->configuration_file;
550 else if (!strcmp (str, "DYNAMIC_BASE"))
551 o = (MonoObject *)add->setup->dynamic_base;
552 else if (!strcmp (str, "APP_NAME"))
553 o = (MonoObject *)add->setup->application_name;
554 else if (!strcmp (str, "CACHE_BASE"))
555 o = (MonoObject *)add->setup->cache_path;
556 else if (!strcmp (str, "PRIVATE_BINPATH"))
557 o = (MonoObject *)add->setup->private_bin_path;
558 else if (!strcmp (str, "BINPATH_PROBE_ONLY"))
559 o = (MonoObject *)add->setup->private_bin_path_probe;
560 else if (!strcmp (str, "SHADOW_COPY_DIRS"))
561 o = (MonoObject *)add->setup->shadow_copy_directories;
562 else if (!strcmp (str, "FORCE_CACHE_INSTALL"))
563 o = (MonoObject *)add->setup->shadow_copy_files;
565 o = mono_g_hash_table_lookup (add->env, name);
567 mono_domain_unlock (add);
577 ves_icall_System_AppDomain_SetData (MonoAppDomain *ad, MonoString *name, MonoObject *data)
583 g_assert (ad != NULL);
585 g_assert (add != NULL);
588 mono_raise_exception (mono_get_exception_argument_null ("name"));
590 mono_domain_lock (add);
592 mono_g_hash_table_insert (add->env, name, data);
594 mono_domain_unlock (add);
598 ves_icall_System_AppDomain_getSetup (MonoAppDomain *ad)
602 g_assert (ad != NULL);
603 g_assert (ad->data != NULL);
605 return ad->data->setup;
609 ves_icall_System_AppDomain_getFriendlyName (MonoAppDomain *ad)
613 g_assert (ad != NULL);
614 g_assert (ad->data != NULL);
616 return mono_string_new (ad->data, ad->data->friendly_name);
620 ves_icall_System_AppDomain_getCurDomain ()
622 MonoDomain *add = mono_domain_get ();
630 ves_icall_System_AppDomain_getRootDomain ()
632 MonoDomain *root = mono_get_root_domain ();
640 get_attribute_value (const gchar **attribute_names,
641 const gchar **attribute_values,
642 const char *att_name)
645 for (n = 0; attribute_names [n] != NULL; n++) {
646 if (strcmp (attribute_names [n], att_name) == 0)
647 return g_strdup (attribute_values [n]);
653 start_element (GMarkupParseContext *context,
654 const gchar *element_name,
655 const gchar **attribute_names,
656 const gchar **attribute_values,
660 RuntimeConfig *runtime_config = user_data;
662 if (strcmp (element_name, "runtime") == 0) {
663 runtime_config->runtime_count++;
667 if (strcmp (element_name, "assemblyBinding") == 0) {
668 runtime_config->assemblybinding_count++;
672 if (runtime_config->runtime_count != 1 || runtime_config->assemblybinding_count != 1)
675 if (strcmp (element_name, "probing") != 0)
678 g_free (runtime_config->domain->private_bin_path);
679 runtime_config->domain->private_bin_path = get_attribute_value (attribute_names, attribute_values, "privatePath");
680 if (runtime_config->domain->private_bin_path && !runtime_config->domain->private_bin_path [0]) {
681 g_free (runtime_config->domain->private_bin_path);
682 runtime_config->domain->private_bin_path = NULL;
688 end_element (GMarkupParseContext *context,
689 const gchar *element_name,
693 RuntimeConfig *runtime_config = user_data;
694 if (strcmp (element_name, "runtime") == 0)
695 runtime_config->runtime_count--;
696 else if (strcmp (element_name, "assemblyBinding") == 0)
697 runtime_config->assemblybinding_count--;
700 static const GMarkupParser
710 mono_set_private_bin_path_from_config (MonoDomain *domain)
712 gchar *config_file, *text;
715 GMarkupParseContext *context;
716 RuntimeConfig runtime_config;
718 if (!domain || !domain->setup || !domain->setup->configuration_file)
721 config_file = mono_string_to_utf8 (domain->setup->configuration_file);
722 if (stat (config_file, &sbuf) != 0) {
723 g_free (config_file);
727 if (!g_file_get_contents (config_file, &text, &len, NULL)) {
728 g_free (config_file);
731 g_free (config_file);
733 runtime_config.runtime_count = 0;
734 runtime_config.assemblybinding_count = 0;
735 runtime_config.domain = domain;
737 context = g_markup_parse_context_new (&mono_parser, 0, &runtime_config, NULL);
738 if (g_markup_parse_context_parse (context, text, len, NULL))
739 g_markup_parse_context_end_parse (context, NULL);
740 g_markup_parse_context_free (context);
745 ves_icall_System_AppDomain_createDomain (MonoString *friendly_name, MonoAppDomainSetup *setup)
747 char *fname = mono_string_to_utf8 (friendly_name);
748 MonoAppDomain *ad = mono_domain_create_appdomain_internal (fname, setup);
756 ves_icall_System_AppDomain_GetAssemblies (MonoAppDomain *ad, MonoBoolean refonly)
758 MonoDomain *domain = ad->data;
760 static MonoClass *System_Reflection_Assembly;
764 GPtrArray *assemblies;
768 if (!System_Reflection_Assembly)
769 System_Reflection_Assembly = mono_class_from_name (
770 mono_defaults.corlib, "System.Reflection", "Assembly");
773 * Make a copy of the list of assemblies because we can't hold the assemblies
774 * lock while creating objects etc.
776 assemblies = g_ptr_array_new ();
777 /* Need to skip internal assembly builders created by remoting */
778 mono_domain_assemblies_lock (domain);
779 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
781 if (refonly && !ass->ref_only)
783 if (ass->corlib_internal)
785 g_ptr_array_add (assemblies, ass);
787 mono_domain_assemblies_unlock (domain);
789 res = mono_array_new (domain, System_Reflection_Assembly, assemblies->len);
790 for (i = 0; i < assemblies->len; ++i) {
791 ass = g_ptr_array_index (assemblies, i);
792 mono_array_setref (res, i, mono_assembly_get_object (domain, ass));
795 g_ptr_array_free (assemblies, TRUE);
800 MonoReflectionAssembly *
801 mono_try_assembly_resolve (MonoDomain *domain, MonoString *fname, gboolean refonly)
805 MonoBoolean isrefonly;
808 g_assert (domain != NULL && fname != NULL);
810 klass = domain->domain->mbr.obj.vtable->klass;
813 method = mono_class_get_method_from_name (klass, "DoAssemblyResolve", -1);
814 if (method == NULL) {
815 g_warning ("Method AppDomain.DoAssemblyResolve not found.\n");
819 isrefonly = refonly ? 1 : 0;
821 params [1] = &isrefonly;
822 return (MonoReflectionAssembly *) mono_runtime_invoke (method, domain->domain, params, NULL);
825 static MonoAssembly *
826 mono_domain_assembly_postload_search (MonoAssemblyName *aname,
829 gboolean refonly = GPOINTER_TO_UINT (user_data);
830 MonoReflectionAssembly *assembly;
831 MonoDomain *domain = mono_domain_get ();
834 aname_str = mono_stringify_assembly_name (aname);
836 /* FIXME: We invoke managed code here, so there is a potential for deadlocks */
837 assembly = mono_try_assembly_resolve (domain, mono_string_new (domain, aname_str), refonly);
842 return assembly->assembly;
848 * LOCKING: assumes assemblies_lock in the domain is already locked.
851 add_assemblies_to_domain (MonoDomain *domain, MonoAssembly *ass, GHashTable *ht)
855 gboolean destroy_ht = FALSE;
857 if (!ass->aname.name)
861 ht = g_hash_table_new (mono_aligned_addr_hash, NULL);
865 /* FIXME: handle lazy loaded assemblies */
866 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
867 g_hash_table_insert (ht, tmp->data, tmp->data);
869 if (!g_hash_table_lookup (ht, ass)) {
870 mono_assembly_addref (ass);
871 g_hash_table_insert (ht, ass, ass);
872 domain->domain_assemblies = g_slist_prepend (domain->domain_assemblies, ass);
873 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);
876 if (ass->image->references) {
877 for (i = 0; ass->image->references [i] != NULL; i++) {
878 if (ass->image->references [i] != REFERENCE_MISSING)
879 if (!g_hash_table_lookup (ht, ass->image->references [i])) {
880 add_assemblies_to_domain (domain, ass->image->references [i], ht);
885 g_hash_table_destroy (ht);
889 mono_domain_fire_assembly_load (MonoAssembly *assembly, gpointer user_data)
891 static MonoClassField *assembly_load_field;
892 static MonoMethod *assembly_load_method;
893 MonoDomain *domain = mono_domain_get ();
894 MonoReflectionAssembly *ref_assembly;
900 /* This can happen during startup */
902 #ifdef ASSEMBLY_LOAD_DEBUG
903 fprintf (stderr, "Loading %s into domain %s\n", assembly->aname.name, domain->friendly_name);
905 klass = domain->domain->mbr.obj.vtable->klass;
907 mono_domain_assemblies_lock (domain);
908 add_assemblies_to_domain (domain, assembly, NULL);
909 mono_domain_assemblies_unlock (domain);
911 if (assembly_load_field == NULL) {
912 assembly_load_field = mono_class_get_field_from_name (klass, "AssemblyLoad");
913 g_assert (assembly_load_field);
916 mono_field_get_value ((MonoObject*) domain->domain, assembly_load_field, &load_value);
917 if (load_value == NULL) {
918 /* No events waiting to be triggered */
922 ref_assembly = mono_assembly_get_object (domain, assembly);
923 g_assert (ref_assembly);
925 if (assembly_load_method == NULL) {
926 assembly_load_method = mono_class_get_method_from_name (klass, "DoAssemblyLoad", -1);
927 g_assert (assembly_load_method);
930 *params = ref_assembly;
931 mono_runtime_invoke (assembly_load_method, domain->domain, params, NULL);
935 * LOCKING: Acquires the domain assemblies lock.
938 set_domain_search_path (MonoDomain *domain)
940 MonoAppDomainSetup *setup;
942 gchar *search_path = NULL;
945 gchar **pvt_split = NULL;
946 GError *error = NULL;
947 gint appbaselen = -1;
950 * We use the low-level domain assemblies lock, since this is called from
951 * assembly loads hooks, which means this thread might hold the loader lock.
953 mono_domain_assemblies_lock (domain);
955 if (!domain->setup) {
956 mono_domain_assemblies_unlock (domain);
960 if ((domain->search_path != NULL) && !domain->setup->path_changed) {
961 mono_domain_assemblies_unlock (domain);
964 setup = domain->setup;
965 if (!setup->application_base) {
966 mono_domain_assemblies_unlock (domain);
967 return; /* Must set application base to get private path working */
972 if (setup->private_bin_path)
973 search_path = mono_string_to_utf8 (setup->private_bin_path);
975 if (domain->private_bin_path) {
976 if (search_path == NULL)
977 search_path = domain->private_bin_path;
979 gchar *tmp2 = search_path;
980 search_path = g_strjoin (";", search_path, domain->private_bin_path, NULL);
987 * As per MSDN documentation, AppDomainSetup.PrivateBinPath contains a list of
988 * directories relative to ApplicationBase separated by semicolons (see
989 * http://msdn2.microsoft.com/en-us/library/system.appdomainsetup.privatebinpath.aspx)
990 * The loop below copes with the fact that some Unix applications may use ':' (or
991 * System.IO.Path.PathSeparator) as the path search separator. We replace it with
992 * ';' for the subsequent split.
994 * The issue was reported in bug #81446
997 #ifndef PLATFORM_WIN32
1000 slen = strlen (search_path);
1001 for (i = 0; i < slen; i++)
1002 if (search_path [i] == ':')
1003 search_path [i] = ';';
1006 pvt_split = g_strsplit (search_path, ";", 1000);
1007 g_free (search_path);
1008 for (tmp = pvt_split; *tmp; tmp++, npaths++);
1013 g_strfreev (pvt_split);
1015 * Don't do this because the first time is called, the domain
1016 * setup is not finished.
1018 * domain->search_path = g_malloc (sizeof (char *));
1019 * domain->search_path [0] = NULL;
1021 mono_domain_assemblies_unlock (domain);
1025 if (domain->search_path)
1026 g_strfreev (domain->search_path);
1028 domain->search_path = tmp = g_malloc ((npaths + 1) * sizeof (gchar *));
1029 tmp [npaths] = NULL;
1031 *tmp = mono_string_to_utf8 (setup->application_base);
1033 /* FIXME: is this needed? */
1034 if (strncmp (*tmp, "file://", 7) == 0) {
1040 uri = g_strdup_printf ("file:///%s", uri + 7);
1043 uri = mono_escape_uri_string (tmpuri);
1044 *tmp = g_filename_from_uri (uri, NULL, &error);
1050 if (error != NULL) {
1051 g_warning ("%s\n", error->message);
1052 g_error_free (error);
1059 for (i = 1; pvt_split && i < npaths; i++) {
1060 if (g_path_is_absolute (pvt_split [i - 1])) {
1061 tmp [i] = g_strdup (pvt_split [i - 1]);
1063 tmp [i] = g_build_filename (tmp [0], pvt_split [i - 1], NULL);
1066 if (strchr (tmp [i], '.')) {
1070 reduced = mono_path_canonicalize (tmp [i]);
1071 if (appbaselen == -1)
1072 appbaselen = strlen (tmp [0]);
1074 if (strncmp (tmp [0], reduced, appbaselen)) {
1077 tmp [i] = g_strdup ("");
1087 if (setup->private_bin_path_probe != NULL) {
1089 tmp [0] = g_strdup ("");
1092 domain->setup->path_changed = FALSE;
1094 g_strfreev (pvt_split);
1096 mono_domain_assemblies_unlock (domain);
1099 #ifdef DISABLE_SHADOW_COPY
1101 mono_is_shadow_copy_enabled (MonoDomain *domain, const gchar *dir_name)
1107 mono_make_shadow_copy (const char *filename)
1109 return (char *) filename;
1113 shadow_copy_sibling (gchar *src, gint srclen, const char *extension, gchar *target, gint targetlen, gint tail_len)
1115 guint16 *orig, *dest;
1116 gboolean copy_result;
1118 strcpy (src + srclen - tail_len, extension);
1119 if (!g_file_test (src, G_FILE_TEST_IS_REGULAR))
1121 orig = g_utf8_to_utf16 (src, strlen (src), NULL, NULL, NULL);
1123 strcpy (target + targetlen - tail_len, extension);
1124 dest = g_utf8_to_utf16 (target, strlen (target), NULL, NULL, NULL);
1127 copy_result = CopyFile (orig, dest, FALSE);
1135 get_cstring_hash (const char *str)
1141 if (!str || !str [0])
1146 for (i = 0; i < len; i++) {
1147 h = (h << 5) - h + *p;
1155 get_shadow_assembly_location_base (MonoDomain *domain)
1157 MonoAppDomainSetup *setup;
1158 char *cache_path, *appname;
1162 setup = domain->setup;
1163 if (setup->cache_path != NULL && setup->application_name != NULL) {
1164 cache_path = mono_string_to_utf8 (setup->cache_path);
1165 #ifndef PLATFORM_WIN32
1168 for (i = strlen (cache_path) - 1; i >= 0; i--)
1169 if (cache_path [i] == '\\')
1170 cache_path [i] = '/';
1174 appname = mono_string_to_utf8 (setup->application_name);
1175 location = g_build_filename (cache_path, appname, "assembly", "shadow", NULL);
1177 g_free (cache_path);
1179 userdir = g_strdup_printf ("%s-mono-cachepath", g_get_user_name ());
1180 location = g_build_filename (g_get_tmp_dir (), userdir, "assembly", "shadow", NULL);
1187 get_shadow_assembly_location (const char *filename)
1189 gint32 hash = 0, hash2 = 0;
1191 char path_hash [30];
1192 char *bname = g_path_get_basename (filename);
1193 char *dirname = g_path_get_dirname (filename);
1194 char *location, *tmploc;
1195 MonoDomain *domain = mono_domain_get ();
1197 hash = get_cstring_hash (bname);
1198 hash2 = get_cstring_hash (dirname);
1199 g_snprintf (name_hash, sizeof (name_hash), "%08x", hash);
1200 g_snprintf (path_hash, sizeof (path_hash), "%08x_%08x_%08x", hash ^ hash2, hash2, domain->shadow_serial);
1201 tmploc = get_shadow_assembly_location_base (domain);
1202 location = g_build_filename (tmploc, name_hash, path_hash, bname, NULL);
1208 ensure_directory_exists (const char *filename)
1210 #ifdef PLATFORM_WIN32
1211 gchar *dir_utf8 = g_path_get_dirname (filename);
1213 gunichar2 *dir_utf16 = NULL;
1216 if (!dir_utf8 || !dir_utf8 [0])
1219 dir_utf16 = g_utf8_to_utf16 (dir_utf8, strlen (dir_utf8), NULL, NULL, NULL);
1227 /* make life easy and only use one directory seperator */
1238 while (*p++ != '\\')
1244 p = wcschr (p, '\\');
1247 retval = _wmkdir (dir_utf16);
1248 if (retval != 0 && errno != EEXIST) {
1261 gchar *dir = g_path_get_dirname (filename);
1265 if (!dir || !dir [0]) {
1270 if (stat (dir, &sbuf) == 0 && S_ISDIR (sbuf.st_mode)) {
1280 p = strchr (p, '/');
1283 retval = mkdir (dir, 0777);
1284 if (retval != 0 && errno != EEXIST) {
1299 private_file_needs_copying (const char *src, struct stat *sbuf_src, char *dest)
1301 struct stat sbuf_dest;
1303 if (stat (src, sbuf_src) == -1 || stat (dest, &sbuf_dest) == -1)
1306 if (sbuf_src->st_mode == sbuf_dest.st_mode &&
1307 sbuf_src->st_size == sbuf_dest.st_size &&
1308 sbuf_src->st_mtime == sbuf_dest.st_mtime)
1315 shadow_copy_create_ini (const char *shadow, const char *filename)
1325 dir_name = g_path_get_dirname (shadow);
1326 ini_file = g_build_filename (dir_name, "__AssemblyInfo__.ini", NULL);
1328 if (g_file_test (ini_file, G_FILE_TEST_IS_REGULAR)) {
1333 u16_ini = g_utf8_to_utf16 (ini_file, strlen (ini_file), NULL, NULL, NULL);
1338 handle = CreateFile (u16_ini, GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE,
1339 NULL, CREATE_NEW, FileAttributes_Normal, NULL);
1341 if (handle == INVALID_HANDLE_VALUE) {
1345 full_path = mono_path_resolve_symlinks (filename);
1346 result = WriteFile (handle, full_path, strlen (full_path), &n, NULL);
1348 CloseHandle (handle);
1353 mono_is_shadow_copy_enabled (MonoDomain *domain, const gchar *dir_name)
1355 const char *version;
1356 MonoAppDomainSetup *setup;
1359 gchar **directories;
1360 gchar *shadow_status_string;
1362 gboolean shadow_enabled;
1363 gboolean found = FALSE;
1368 setup = domain->setup;
1369 if (setup == NULL || setup->shadow_copy_files == NULL)
1372 version = mono_get_runtime_info ()->framework_version;
1373 shadow_status_string = mono_string_to_utf8 (setup->shadow_copy_files);
1374 /* For 1.x, not NULL is enough. In 2.0 it has to be "true" */
1375 shadow_enabled = (*version <= '1' || !g_ascii_strncasecmp (shadow_status_string, "true", 4));
1376 g_free (shadow_status_string);
1377 if (!shadow_enabled)
1380 if (setup->shadow_copy_directories == NULL)
1383 /* Is dir_name a shadow_copy destination already? */
1384 base_dir = get_shadow_assembly_location_base (domain);
1385 if (strstr (dir_name, base_dir) == dir_name) {
1391 all_dirs = mono_string_to_utf8 (setup->shadow_copy_directories);
1392 directories = g_strsplit (all_dirs, G_SEARCHPATH_SEPARATOR_S, 1000);
1393 dir_ptr = directories;
1395 if (**dir_ptr != '\0' && !strcmp (*dir_ptr, dir_name)) {
1401 g_strfreev (directories);
1407 mono_make_shadow_copy (const char *filename)
1409 gchar *sibling_source, *sibling_target;
1410 gint sibling_source_len, sibling_target_len;
1411 guint16 *orig, *dest;
1413 gboolean copy_result;
1415 struct stat src_sbuf;
1416 struct utimbuf utbuf;
1417 char *dir_name = g_path_get_dirname (filename);
1418 MonoDomain *domain = mono_domain_get ();
1419 set_domain_search_path (domain);
1421 if (!mono_is_shadow_copy_enabled (domain, dir_name)) {
1423 return (char *) filename;
1427 shadow = get_shadow_assembly_location (filename);
1428 if (ensure_directory_exists (shadow) == FALSE) {
1430 exc = mono_get_exception_execution_engine ("Failed to create shadow copy (ensure directory exists).");
1431 mono_raise_exception (exc);
1434 if (!private_file_needs_copying (filename, &src_sbuf, shadow))
1435 return (char*) shadow;
1437 orig = g_utf8_to_utf16 (filename, strlen (filename), NULL, NULL, NULL);
1438 dest = g_utf8_to_utf16 (shadow, strlen (shadow), NULL, NULL, NULL);
1440 copy_result = CopyFile (orig, dest, FALSE);
1444 if (copy_result == FALSE) {
1446 exc = mono_get_exception_execution_engine ("Failed to create shadow copy (CopyFile).");
1447 mono_raise_exception (exc);
1450 /* attempt to copy .mdb, .config if they exist */
1451 sibling_source = g_strconcat (filename, ".config", NULL);
1452 sibling_source_len = strlen (sibling_source);
1453 sibling_target = g_strconcat (shadow, ".config", NULL);
1454 sibling_target_len = strlen (sibling_target);
1456 copy_result = shadow_copy_sibling (sibling_source, sibling_source_len, ".mdb", sibling_target, sibling_target_len, 7);
1457 if (copy_result == TRUE)
1458 copy_result = shadow_copy_sibling (sibling_source, sibling_source_len, ".config", sibling_target, sibling_target_len, 7);
1460 g_free (sibling_source);
1461 g_free (sibling_target);
1463 if (copy_result == FALSE) {
1465 exc = mono_get_exception_execution_engine ("Failed to create shadow copy of sibling data (CopyFile).");
1466 mono_raise_exception (exc);
1469 /* Create a .ini file containing the original assembly location */
1470 if (!shadow_copy_create_ini (shadow, filename)) {
1472 exc = mono_get_exception_execution_engine ("Failed to create shadow copy .ini file.");
1473 mono_raise_exception (exc);
1476 utbuf.actime = src_sbuf.st_atime;
1477 utbuf.modtime = src_sbuf.st_mtime;
1478 utime (shadow, &utbuf);
1482 #endif /* DISABLE_SHADOW_COPY */
1485 mono_domain_from_appdomain (MonoAppDomain *appdomain)
1487 if (appdomain == NULL)
1490 return appdomain->data;
1494 try_load_from (MonoAssembly **assembly, const gchar *path1, const gchar *path2,
1495 const gchar *path3, const gchar *path4,
1496 gboolean refonly, gboolean is_private)
1499 gboolean found = FALSE;
1502 fullpath = g_build_filename (path1, path2, path3, path4, NULL);
1504 if (IS_PORTABILITY_SET) {
1505 gchar *new_fullpath = mono_portability_find_file (fullpath, TRUE);
1508 fullpath = new_fullpath;
1512 found = g_file_test (fullpath, G_FILE_TEST_IS_REGULAR);
1515 *assembly = mono_assembly_open_full (fullpath, NULL, refonly);
1518 return (*assembly != NULL);
1521 static MonoAssembly *
1522 real_load (gchar **search_path, const gchar *culture, const gchar *name, gboolean refonly)
1524 MonoAssembly *result = NULL;
1527 const gchar *local_culture;
1529 gboolean is_private = FALSE;
1531 if (!culture || *culture == '\0') {
1534 local_culture = culture;
1537 filename = g_strconcat (name, ".dll", NULL);
1538 len = strlen (filename);
1540 for (path = search_path; *path; path++) {
1541 if (**path == '\0') {
1543 continue; /* Ignore empty ApplicationBase */
1546 /* See test cases in bug #58992 and bug #57710 */
1547 /* 1st try: [culture]/[name].dll (culture may be empty) */
1548 strcpy (filename + len - 4, ".dll");
1549 if (try_load_from (&result, *path, local_culture, "", filename, refonly, is_private))
1552 /* 2nd try: [culture]/[name].exe (culture may be empty) */
1553 strcpy (filename + len - 4, ".exe");
1554 if (try_load_from (&result, *path, local_culture, "", filename, refonly, is_private))
1557 /* 3rd try: [culture]/[name]/[name].dll (culture may be empty) */
1558 strcpy (filename + len - 4, ".dll");
1559 if (try_load_from (&result, *path, local_culture, name, filename, refonly, is_private))
1562 /* 4th try: [culture]/[name]/[name].exe (culture may be empty) */
1563 strcpy (filename + len - 4, ".exe");
1564 if (try_load_from (&result, *path, local_culture, name, filename, refonly, is_private))
1573 * Try loading the assembly from ApplicationBase and PrivateBinPath
1574 * and then from assemblies_path if any.
1575 * LOCKING: This is called from the assembly loading code, which means the caller
1576 * might hold the loader lock. Thus, this function must not acquire the domain lock.
1578 static MonoAssembly *
1579 mono_domain_assembly_preload (MonoAssemblyName *aname,
1580 gchar **assemblies_path,
1583 MonoDomain *domain = mono_domain_get ();
1584 MonoAssembly *result = NULL;
1585 gboolean refonly = GPOINTER_TO_UINT (user_data);
1587 set_domain_search_path (domain);
1589 if (domain->search_path && domain->search_path [0] != NULL) {
1590 result = real_load (domain->search_path, aname->culture, aname->name, refonly);
1593 if (result == NULL && assemblies_path && assemblies_path [0] != NULL) {
1594 result = real_load (assemblies_path, aname->culture, aname->name, refonly);
1601 * Check whenever a given assembly was already loaded in the current appdomain.
1603 static MonoAssembly *
1604 mono_domain_assembly_search (MonoAssemblyName *aname,
1607 MonoDomain *domain = mono_domain_get ();
1610 gboolean refonly = GPOINTER_TO_UINT (user_data);
1612 mono_domain_assemblies_lock (domain);
1613 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
1615 /* Dynamic assemblies can't match here in MS.NET */
1616 if (ass->dynamic || refonly != ass->ref_only || !mono_assembly_names_equal (aname, &ass->aname))
1619 mono_domain_assemblies_unlock (domain);
1622 mono_domain_assemblies_unlock (domain);
1627 MonoReflectionAssembly *
1628 ves_icall_System_Reflection_Assembly_LoadFrom (MonoString *fname, MonoBoolean refOnly)
1630 MonoDomain *domain = mono_domain_get ();
1631 char *name, *filename;
1632 MonoImageOpenStatus status = MONO_IMAGE_OK;
1635 MONO_ARCH_SAVE_REGS;
1637 if (fname == NULL) {
1638 MonoException *exc = mono_get_exception_argument_null ("assemblyFile");
1639 mono_raise_exception (exc);
1642 name = filename = mono_string_to_utf8 (fname);
1644 ass = mono_assembly_open_full (filename, &status, refOnly);
1649 if (status == MONO_IMAGE_IMAGE_INVALID)
1650 exc = mono_get_exception_bad_image_format2 (NULL, fname);
1652 exc = mono_get_exception_file_not_found2 (NULL, fname);
1654 mono_raise_exception (exc);
1659 return mono_assembly_get_object (domain, ass);
1662 MonoReflectionAssembly *
1663 ves_icall_System_AppDomain_LoadAssemblyRaw (MonoAppDomain *ad,
1664 MonoArray *raw_assembly,
1665 MonoArray *raw_symbol_store, MonoObject *evidence,
1666 MonoBoolean refonly)
1669 MonoReflectionAssembly *refass = NULL;
1670 MonoDomain *domain = ad->data;
1671 MonoImageOpenStatus status;
1672 guint32 raw_assembly_len = mono_array_length (raw_assembly);
1673 MonoImage *image = mono_image_open_from_data_full (mono_array_addr (raw_assembly, gchar, 0), raw_assembly_len, TRUE, NULL, refonly);
1676 mono_raise_exception (mono_get_exception_bad_image_format (""));
1680 if (raw_symbol_store != NULL)
1681 mono_debug_open_image_from_memory (image, mono_array_addr (raw_symbol_store, guint8, 0), mono_array_length (raw_symbol_store));
1683 ass = mono_assembly_load_from_full (image, "", &status, refonly);
1687 mono_image_close (image);
1688 mono_raise_exception (mono_get_exception_bad_image_format (""));
1692 refass = mono_assembly_get_object (domain, ass);
1693 MONO_OBJECT_SETREF (refass, evidence, evidence);
1697 MonoReflectionAssembly *
1698 ves_icall_System_AppDomain_LoadAssembly (MonoAppDomain *ad, MonoString *assRef, MonoObject *evidence, MonoBoolean refOnly)
1700 MonoDomain *domain = ad->data;
1701 MonoImageOpenStatus status = MONO_IMAGE_OK;
1703 MonoAssemblyName aname;
1704 MonoReflectionAssembly *refass = NULL;
1708 MONO_ARCH_SAVE_REGS;
1710 g_assert (assRef != NULL);
1712 name = mono_string_to_utf8 (assRef);
1713 parsed = mono_assembly_name_parse (name, &aname);
1717 /* This is a parse error... */
1721 ass = mono_assembly_load_full_nosearch (&aname, NULL, &status, refOnly);
1722 mono_assembly_name_free (&aname);
1725 /* MS.NET doesn't seem to call the assembly resolve handler for refonly assemblies */
1727 refass = mono_try_assembly_resolve (domain, assRef, refOnly);
1736 refass = mono_assembly_get_object (domain, ass);
1738 MONO_OBJECT_SETREF (refass, evidence, evidence);
1743 ves_icall_System_AppDomain_InternalUnload (gint32 domain_id)
1745 MonoDomain * domain = mono_domain_get_by_id (domain_id);
1747 MONO_ARCH_SAVE_REGS;
1749 if (NULL == domain) {
1750 MonoException *exc = mono_get_exception_execution_engine ("Failed to unload domain, domain id not found");
1751 mono_raise_exception (exc);
1754 if (domain == mono_get_root_domain ()) {
1755 mono_raise_exception (mono_get_exception_cannot_unload_appdomain ("The default appdomain can not be unloaded."));
1760 * Unloading seems to cause problems when running NUnit/NAnt, hence
1763 if (g_getenv ("MONO_NO_UNLOAD"))
1766 mono_domain_unload (domain);
1770 ves_icall_System_AppDomain_InternalIsFinalizingForUnload (gint32 domain_id)
1772 MonoDomain *domain = mono_domain_get_by_id (domain_id);
1777 return mono_domain_is_unloading (domain);
1781 ves_icall_System_AppDomain_ExecuteAssembly (MonoAppDomain *ad,
1782 MonoReflectionAssembly *refass, MonoArray *args)
1787 MONO_ARCH_SAVE_REGS;
1790 image = refass->assembly->image;
1793 method = mono_get_method (image, mono_image_get_entry_point (image), NULL);
1796 g_error ("No entry point method found in %s", image->name);
1799 args = (MonoArray *) mono_array_new (ad->data, mono_defaults.string_class, 0);
1801 return mono_runtime_exec_main (method, (MonoArray *)args, NULL);
1805 ves_icall_System_AppDomain_GetIDFromDomain (MonoAppDomain * ad)
1807 MONO_ARCH_SAVE_REGS;
1809 return ad->data->domain_id;
1813 ves_icall_System_AppDomain_InternalSetDomain (MonoAppDomain *ad)
1815 MonoDomain *old_domain = mono_domain_get();
1817 MONO_ARCH_SAVE_REGS;
1819 if (!mono_domain_set (ad->data, FALSE))
1820 mono_raise_exception (mono_get_exception_appdomain_unloaded ());
1822 return old_domain->domain;
1826 ves_icall_System_AppDomain_InternalSetDomainByID (gint32 domainid)
1828 MonoDomain *current_domain = mono_domain_get ();
1829 MonoDomain *domain = mono_domain_get_by_id (domainid);
1831 MONO_ARCH_SAVE_REGS;
1833 if (!domain || !mono_domain_set (domain, FALSE))
1834 mono_raise_exception (mono_get_exception_appdomain_unloaded ());
1836 return current_domain->domain;
1840 ves_icall_System_AppDomain_InternalPushDomainRef (MonoAppDomain *ad)
1842 MONO_ARCH_SAVE_REGS;
1844 mono_thread_push_appdomain_ref (ad->data);
1848 ves_icall_System_AppDomain_InternalPushDomainRefByID (gint32 domain_id)
1850 MonoDomain *domain = mono_domain_get_by_id (domain_id);
1852 MONO_ARCH_SAVE_REGS;
1856 * Raise an exception to prevent the managed code from executing a pop
1859 mono_raise_exception (mono_get_exception_appdomain_unloaded ());
1861 mono_thread_push_appdomain_ref (domain);
1865 ves_icall_System_AppDomain_InternalPopDomainRef (void)
1867 MONO_ARCH_SAVE_REGS;
1869 mono_thread_pop_appdomain_ref ();
1873 ves_icall_System_AppDomain_InternalGetContext ()
1875 MONO_ARCH_SAVE_REGS;
1877 return mono_context_get ();
1881 ves_icall_System_AppDomain_InternalGetDefaultContext ()
1883 MONO_ARCH_SAVE_REGS;
1885 return mono_domain_get ()->default_context;
1889 ves_icall_System_AppDomain_InternalSetContext (MonoAppContext *mc)
1891 MonoAppContext *old_context = mono_context_get ();
1893 MONO_ARCH_SAVE_REGS;
1895 mono_context_set (mc);
1901 ves_icall_System_AppDomain_InternalGetProcessGuid (MonoString* newguid)
1903 MonoDomain* mono_root_domain = mono_get_root_domain ();
1904 mono_domain_lock (mono_root_domain);
1905 if (process_guid_set) {
1906 mono_domain_unlock (mono_root_domain);
1907 return mono_string_new_utf16 (mono_domain_get (), process_guid, sizeof(process_guid)/2);
1909 memcpy (process_guid, mono_string_chars(newguid), sizeof(process_guid));
1910 process_guid_set = TRUE;
1911 mono_domain_unlock (mono_root_domain);
1916 mono_domain_is_unloading (MonoDomain *domain)
1918 if (domain->state == MONO_APPDOMAIN_UNLOADING || domain->state == MONO_APPDOMAIN_UNLOADED)
1925 clear_cached_vtable (gpointer key, gpointer value, gpointer user_data)
1927 MonoClass *klass = (MonoClass*)key;
1928 MonoDomain *domain = (MonoDomain*)user_data;
1929 MonoClassRuntimeInfo *runtime_info;
1931 runtime_info = klass->runtime_info;
1932 if (runtime_info && runtime_info->max_domain >= domain->domain_id)
1933 runtime_info->domain_vtables [domain->domain_id] = NULL;
1936 typedef struct unload_data {
1938 char *failure_reason;
1942 static guint32 WINAPI
1943 unload_thread_main (void *arg)
1945 unload_data *data = (unload_data*)arg;
1946 MonoDomain *domain = data->domain;
1948 /* Have to attach to the runtime so shutdown can wait for this thread */
1949 mono_thread_attach (mono_get_root_domain ());
1952 * FIXME: Abort our parent thread last, so we can return a failure
1953 * indication if aborting times out.
1955 if (!mono_threads_abort_appdomain_threads (domain, -1)) {
1956 data->failure_reason = g_strdup_printf ("Aborting of threads in domain %s timed out.", domain->friendly_name);
1960 if (!mono_thread_pool_remove_domain_jobs (domain, -1)) {
1961 data->failure_reason = g_strdup_printf ("Cleanup of threadpool jobs of domain %s timed out.", domain->friendly_name);
1965 /* Finalize all finalizable objects in the doomed appdomain */
1966 if (!mono_domain_finalize (domain, -1)) {
1967 data->failure_reason = g_strdup_printf ("Finalization of domain %s timed out.", domain->friendly_name);
1971 /* Clear references to our vtables in class->runtime_info.
1972 * We also hold the loader lock because we're going to change
1973 * class->runtime_info.
1975 mono_domain_lock (domain);
1976 mono_loader_lock ();
1977 g_hash_table_foreach (domain->class_vtable_hash, clear_cached_vtable, domain);
1978 mono_loader_unlock ();
1979 mono_domain_unlock (domain);
1981 mono_threads_clear_cached_culture (domain);
1983 domain->state = MONO_APPDOMAIN_UNLOADED;
1985 /* printf ("UNLOADED %s.\n", domain->friendly_name); */
1987 /* remove from the handle table the items related to this domain */
1988 mono_gchandle_free_domain (domain);
1990 mono_domain_free (domain, FALSE);
1992 mono_gc_collect (mono_gc_max_generation ());
1998 * mono_domain_unload:
1999 * @domain: The domain to unload
2001 * Unloads an appdomain. Follows the process outlined in:
2002 * http://blogs.gotdotnet.com/cbrumme
2004 * If doing things the 'right' way is too hard or complex, we do it the
2005 * 'simple' way, which means do everything needed to avoid crashes and
2006 * memory leaks, but not much else.
2009 mono_domain_unload (MonoDomain *domain)
2011 HANDLE thread_handle;
2014 MonoAppDomainState prev_state;
2017 unload_data thread_data;
2018 MonoDomain *caller_domain = mono_domain_get ();
2020 /* printf ("UNLOAD STARTING FOR %s (%p) IN THREAD 0x%x.\n", domain->friendly_name, domain, GetCurrentThreadId ()); */
2022 /* Atomically change our state to UNLOADING */
2023 prev_state = InterlockedCompareExchange ((gint32*)&domain->state,
2024 MONO_APPDOMAIN_UNLOADING_START,
2025 MONO_APPDOMAIN_CREATED);
2026 if (prev_state != MONO_APPDOMAIN_CREATED) {
2027 switch (prev_state) {
2028 case MONO_APPDOMAIN_UNLOADING_START:
2029 case MONO_APPDOMAIN_UNLOADING:
2030 mono_raise_exception (mono_get_exception_cannot_unload_appdomain ("Appdomain is already being unloaded."));
2032 case MONO_APPDOMAIN_UNLOADED:
2033 mono_raise_exception (mono_get_exception_cannot_unload_appdomain ("Appdomain is already unloaded."));
2036 g_warning ("Incalid appdomain state %d", prev_state);
2037 g_assert_not_reached ();
2041 mono_domain_set (domain, FALSE);
2042 /* Notify OnDomainUnload listeners */
2043 method = mono_class_get_method_from_name (domain->domain->mbr.obj.vtable->klass, "DoDomainUnload", -1);
2047 mono_runtime_invoke (method, domain->domain, NULL, &exc);
2049 /* Roll back the state change */
2050 domain->state = MONO_APPDOMAIN_CREATED;
2051 mono_domain_set (caller_domain, FALSE);
2052 mono_raise_exception ((MonoException*)exc);
2055 thread_data.domain = domain;
2056 thread_data.failure_reason = NULL;
2058 /*The managed callback finished successfully, now we start tearing down the appdomain*/
2059 domain->state = MONO_APPDOMAIN_UNLOADING;
2061 * First we create a separate thread for unloading, since
2062 * we might have to abort some threads, including the current one.
2065 * If we create a non-suspended thread, the runtime will hang.
2067 * http://bugzilla.ximian.com/show_bug.cgi?id=27663
2070 thread_handle = CreateThread (NULL, 0, unload_thread_main, &thread_data, 0, &tid);
2072 thread_handle = CreateThread (NULL, 0, (LPTHREAD_START_ROUTINE)unload_thread_main, &thread_data, CREATE_SUSPENDED, &tid);
2073 if (thread_handle == NULL) {
2076 ResumeThread (thread_handle);
2079 /* Wait for the thread */
2080 while ((res = WaitForSingleObjectEx (thread_handle, INFINITE, TRUE) == WAIT_IO_COMPLETION)) {
2081 if (mono_thread_has_appdomain_ref (mono_thread_current (), domain) && (mono_thread_interruption_requested ()))
2082 /* The unload thread tries to abort us */
2083 /* The icall wrapper will execute the abort */
2084 CloseHandle (thread_handle);
2087 CloseHandle (thread_handle);
2089 mono_domain_set (caller_domain, FALSE);
2091 if (thread_data.failure_reason) {
2094 /* Roll back the state change */
2095 domain->state = MONO_APPDOMAIN_CREATED;
2097 g_warning (thread_data.failure_reason);
2099 ex = mono_get_exception_cannot_unload_appdomain (thread_data.failure_reason);
2101 g_free (thread_data.failure_reason);
2102 thread_data.failure_reason = NULL;
2104 mono_raise_exception (ex);