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/metadata/lock-tracer.h>
51 #include <mono/utils/mono-uri.h>
52 #include <mono/utils/mono-logger.h>
53 #include <mono/utils/mono-path.h>
54 #include <mono/utils/mono-stdlib.h>
55 #include <mono/utils/mono-io-portability.h>
61 * This is the version number of the corlib-runtime interface. When
62 * making changes to this interface (by changing the layout
63 * of classes the runtime knows about, changing icall signature or
64 * semantics etc), increment this variable. Also increment the
65 * pair of this variable in mscorlib in:
66 * mcs/class/mscorlib/System/Environment.cs
68 * Changes which are already detected at runtime, like the addition
69 * of icalls, do not require an increment.
71 #define MONO_CORLIB_VERSION 70
76 int assemblybinding_count;
80 CRITICAL_SECTION mono_delegate_section;
83 /* Need to lock here because EGLIB has locking defined as no-ops, we can not depend on mono_strtod do the right locking */
84 /* Ideally this will be fixed in eglib */
85 CRITICAL_SECTION mono_strtod_mutex;
89 static gunichar2 process_guid [36];
90 static gboolean process_guid_set = FALSE;
92 static gboolean shutting_down = FALSE;
94 static gboolean no_exec = FALSE;
97 mono_domain_assembly_preload (MonoAssemblyName *aname,
98 gchar **assemblies_path,
101 static MonoAssembly *
102 mono_domain_assembly_search (MonoAssemblyName *aname,
105 static MonoAssembly *
106 mono_domain_assembly_postload_search (MonoAssemblyName *aname,
110 mono_domain_fire_assembly_load (MonoAssembly *assembly, gpointer user_data);
113 add_assemblies_to_domain (MonoDomain *domain, MonoAssembly *ass, GHashTable *hash);
115 static MonoAppDomain *
116 mono_domain_create_appdomain_internal (char *friendly_name, MonoAppDomainSetup *setup);
118 static MonoLoadFunc load_function = NULL;
121 mono_install_runtime_load (MonoLoadFunc func)
123 load_function = func;
127 mono_runtime_load (const char *filename, const char *runtime_version)
129 g_assert (load_function);
130 return load_function (filename, runtime_version);
134 * mono_runtime_set_no_exec:
136 * Instructs the runtime to operate in static mode, i.e. avoid/do not allow managed
137 * code execution. This is useful for running the AOT compiler on platforms which
138 * allow full-aot execution only.
139 * This should be called before mono_runtime_init ().
142 mono_runtime_set_no_exec (gboolean val)
148 mono_runtime_get_no_exec (void)
155 * @domain: domain returned by mono_init ()
157 * Initialize the core AppDomain: this function will run also some
158 * IL initialization code, so it needs the execution engine to be fully
161 * AppDomain.SetupInformation is set up in mono_runtime_exec_main, where
162 * we know the entry_assembly.
166 mono_runtime_init (MonoDomain *domain, MonoThreadStartCB start_cb,
167 MonoThreadAttachCB attach_cb)
169 MonoAppDomainSetup *setup;
174 mono_portability_helpers_init ();
176 mono_gc_base_init ();
177 mono_monitor_init ();
178 mono_thread_pool_init ();
179 mono_marshal_init ();
181 mono_install_assembly_preload_hook (mono_domain_assembly_preload, GUINT_TO_POINTER (FALSE));
182 mono_install_assembly_refonly_preload_hook (mono_domain_assembly_preload, GUINT_TO_POINTER (TRUE));
183 mono_install_assembly_search_hook (mono_domain_assembly_search, GUINT_TO_POINTER (FALSE));
184 mono_install_assembly_refonly_search_hook (mono_domain_assembly_search, GUINT_TO_POINTER (TRUE));
185 mono_install_assembly_postload_search_hook (mono_domain_assembly_postload_search, GUINT_TO_POINTER (FALSE));
186 mono_install_assembly_postload_refonly_search_hook (mono_domain_assembly_postload_search, GUINT_TO_POINTER (TRUE));
187 mono_install_assembly_load_hook (mono_domain_fire_assembly_load, NULL);
188 mono_install_lookup_dynamic_token (mono_reflection_lookup_dynamic_token);
190 mono_thread_init (start_cb, attach_cb);
192 class = mono_class_from_name (mono_defaults.corlib, "System", "AppDomainSetup");
193 setup = (MonoAppDomainSetup *) mono_object_new (domain, class);
195 class = mono_class_from_name (mono_defaults.corlib, "System", "AppDomain");
196 ad = (MonoAppDomain *) mono_object_new (domain, class);
199 domain->setup = setup;
201 InitializeCriticalSection (&mono_delegate_section);
204 /* Needed until EGLIB is fixed #464316 */
205 InitializeCriticalSection (&mono_strtod_mutex);
208 mono_thread_attach (domain);
209 mono_context_init (domain);
210 mono_context_set (domain->default_context);
212 mono_type_initialization_init ();
214 if (!mono_runtime_get_no_exec ()) {
216 * Create an instance early since we can't do it when there is no memory.
218 arg = mono_string_new (domain, "Out of memory");
219 domain->out_of_memory_ex = mono_exception_from_name_two_strings (mono_defaults.corlib, "System", "OutOfMemoryException", arg, NULL);
222 * These two are needed because the signal handlers might be executing on
223 * an alternate stack, and Boehm GC can't handle that.
225 arg = mono_string_new (domain, "A null value was found where an object instance was required");
226 domain->null_reference_ex = mono_exception_from_name_two_strings (mono_defaults.corlib, "System", "NullReferenceException", arg, NULL);
227 arg = mono_string_new (domain, "The requested operation caused a stack overflow.");
228 domain->stack_overflow_ex = mono_exception_from_name_two_strings (mono_defaults.corlib, "System", "StackOverflowException", arg, NULL);
231 /* GC init has to happen after thread init */
234 #ifndef DISABLE_SOCKETS
235 mono_network_init ();
240 mono_locks_tracer_init ();
242 /* mscorlib is loaded before we install the load hook */
243 mono_domain_fire_assembly_load (mono_defaults.corlib->assembly, NULL);
249 mono_get_corlib_version (void)
252 MonoClassField *field;
255 klass = mono_class_from_name (mono_defaults.corlib, "System", "Environment");
256 mono_class_init (klass);
257 field = mono_class_get_field_from_name (klass, "mono_corlib_version");
260 if (! (field->type->attrs & FIELD_ATTRIBUTE_STATIC))
262 value = mono_field_get_value_object (mono_domain_get (), field, NULL);
263 return *(gint32*)((gchar*)value + sizeof (MonoObject));
267 mono_check_corlib_version (void)
269 int version = mono_get_corlib_version ();
270 if (version != MONO_CORLIB_VERSION)
271 return g_strdup_printf ("expected corlib version %d, found %d.", MONO_CORLIB_VERSION, version);
277 mono_context_init (MonoDomain *domain)
280 MonoAppContext *context;
282 class = mono_class_from_name (mono_defaults.corlib, "System.Runtime.Remoting.Contexts", "Context");
283 context = (MonoAppContext *) mono_object_new (domain, class);
284 context->domain_id = domain->domain_id;
285 context->context_id = 0;
286 domain->default_context = context;
290 * mono_runtime_cleanup:
295 * This must not be called while there are still running threads executing
299 mono_runtime_cleanup (MonoDomain *domain)
301 shutting_down = TRUE;
303 mono_attach_cleanup ();
305 /* This ends up calling any pending pending (for at most 2 seconds) */
308 mono_thread_cleanup ();
310 #ifndef DISABLE_SOCKETS
311 mono_network_cleanup ();
313 mono_marshal_cleanup ();
315 mono_type_initialization_cleanup ();
317 mono_monitor_cleanup ();
319 #ifndef PLATFORM_WIN32
324 static MonoDomainFunc quit_function = NULL;
327 mono_install_runtime_cleanup (MonoDomainFunc func)
329 quit_function = func;
335 if (quit_function != NULL)
336 quit_function (mono_get_root_domain (), NULL);
340 * mono_runtime_set_shutting_down:
342 * Invoked by System.Environment.Exit to flag that the runtime
346 mono_runtime_set_shutting_down (void)
348 shutting_down = TRUE;
352 * mono_runtime_is_shutting_down:
354 * Returns whether the runtime has been flagged for shutdown.
356 * This is consumed by the P:System.Environment.HasShutdownStarted
361 mono_runtime_is_shutting_down (void)
363 return shutting_down;
367 * mono_domain_create_appdomain:
368 * @friendly_name: The friendly name of the appdomain to create
369 * @configuration_file: The configuration file to initialize the appdomain with
371 * Returns a MonoDomain initialized with the appdomain
374 mono_domain_create_appdomain (char *friendly_name, char *configuration_file)
377 MonoAppDomainSetup *setup;
380 class = mono_class_from_name (mono_defaults.corlib, "System", "AppDomainSetup");
381 setup = (MonoAppDomainSetup *) mono_object_new (mono_domain_get (), class);
382 setup->configuration_file = configuration_file != NULL ? mono_string_new (mono_domain_get (), configuration_file) : NULL;
384 ad = mono_domain_create_appdomain_internal (friendly_name, setup);
386 return mono_domain_from_appdomain (ad);
389 static MonoAppDomain *
390 mono_domain_create_appdomain_internal (char *friendly_name, MonoAppDomainSetup *setup)
398 adclass = mono_class_from_name (mono_defaults.corlib, "System", "AppDomain");
400 /* FIXME: pin all those objects */
401 data = mono_domain_create();
403 ad = (MonoAppDomain *) mono_object_new (data, adclass);
407 data->friendly_name = g_strdup (friendly_name);
408 // FIXME: The ctor runs in the current domain
409 // FIXME: Initialize null_reference_ex and stack_overflow_ex
410 data->out_of_memory_ex = mono_exception_from_name_domain (data, mono_defaults.corlib, "System", "OutOfMemoryException");
412 if (!setup->application_base) {
413 /* Inherit from the root domain since MS.NET does this */
414 MonoDomain *root = mono_get_root_domain ();
415 if (root->setup->application_base)
416 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)));
419 mono_context_init (data);
421 mono_set_private_bin_path_from_config (data);
423 add_assemblies_to_domain (data, mono_defaults.corlib->assembly, NULL);
429 * mono_domain_has_type_resolve:
430 * @domain: application domains being looked up
432 * Returns true if the AppDomain.TypeResolve field has been
436 mono_domain_has_type_resolve (MonoDomain *domain)
438 static MonoClassField *field = NULL;
442 field = mono_class_get_field_from_name (mono_defaults.appdomain_class, "TypeResolve");
446 mono_field_get_value ((MonoObject*)(domain->domain), field, &o);
451 * mono_domain_try_type_resolve:
452 * @domain: application domainwhere the name where the type is going to be resolved
453 * @name: the name of the type to resolve or NULL.
454 * @tb: A System.Reflection.Emit.TypeBuilder, used if name is NULL.
456 * This routine invokes the internal System.AppDomain.DoTypeResolve and returns
457 * the assembly that matches name.
459 * If @name is null, the value of ((TypeBuilder)tb).FullName is used instead
461 * Returns: A MonoReflectionAssembly or NULL if not found
463 MonoReflectionAssembly *
464 mono_domain_try_type_resolve (MonoDomain *domain, char *name, MonoObject *tb)
468 static MonoMethod *method = NULL;
470 g_assert (domain != NULL && ((name != NULL) || (tb != NULL)));
472 if (method == NULL) {
473 klass = domain->domain->mbr.obj.vtable->klass;
476 method = mono_class_get_method_from_name (klass, "DoTypeResolve", -1);
477 if (method == NULL) {
478 g_warning ("Method AppDomain.DoTypeResolve not found.\n");
484 *params = (MonoObject*)mono_string_new (mono_domain_get (), name);
487 return (MonoReflectionAssembly *) mono_runtime_invoke (method, domain->domain, params, NULL);
491 * mono_domain_owns_vtable_slot:
493 * Returns whenever VTABLE_SLOT is inside a vtable which belongs to DOMAIN.
496 mono_domain_owns_vtable_slot (MonoDomain *domain, gpointer vtable_slot)
500 mono_domain_lock (domain);
501 res = mono_mempool_contains_addr (domain->mp, vtable_slot);
502 mono_domain_unlock (domain);
509 * @force: force setting.
511 * Set the current appdomain to @domain. If @force is set, set it even
512 * if it is being unloaded.
516 * FALSE if the domain is unloaded
519 mono_domain_set (MonoDomain *domain, gboolean force)
521 if (!force && domain->state == MONO_APPDOMAIN_UNLOADED)
524 mono_domain_set_internal (domain);
530 ves_icall_System_AppDomain_GetData (MonoAppDomain *ad, MonoString *name)
538 g_assert (ad != NULL);
540 g_assert (add != NULL);
543 mono_raise_exception (mono_get_exception_argument_null ("name"));
545 str = mono_string_to_utf8 (name);
547 mono_domain_lock (add);
549 if (!strcmp (str, "APPBASE"))
550 o = (MonoObject *)add->setup->application_base;
551 else if (!strcmp (str, "APP_CONFIG_FILE"))
552 o = (MonoObject *)add->setup->configuration_file;
553 else if (!strcmp (str, "DYNAMIC_BASE"))
554 o = (MonoObject *)add->setup->dynamic_base;
555 else if (!strcmp (str, "APP_NAME"))
556 o = (MonoObject *)add->setup->application_name;
557 else if (!strcmp (str, "CACHE_BASE"))
558 o = (MonoObject *)add->setup->cache_path;
559 else if (!strcmp (str, "PRIVATE_BINPATH"))
560 o = (MonoObject *)add->setup->private_bin_path;
561 else if (!strcmp (str, "BINPATH_PROBE_ONLY"))
562 o = (MonoObject *)add->setup->private_bin_path_probe;
563 else if (!strcmp (str, "SHADOW_COPY_DIRS"))
564 o = (MonoObject *)add->setup->shadow_copy_directories;
565 else if (!strcmp (str, "FORCE_CACHE_INSTALL"))
566 o = (MonoObject *)add->setup->shadow_copy_files;
568 o = mono_g_hash_table_lookup (add->env, name);
570 mono_domain_unlock (add);
580 ves_icall_System_AppDomain_SetData (MonoAppDomain *ad, MonoString *name, MonoObject *data)
586 g_assert (ad != NULL);
588 g_assert (add != NULL);
591 mono_raise_exception (mono_get_exception_argument_null ("name"));
593 mono_domain_lock (add);
595 mono_g_hash_table_insert (add->env, name, data);
597 mono_domain_unlock (add);
601 ves_icall_System_AppDomain_getSetup (MonoAppDomain *ad)
605 g_assert (ad != NULL);
606 g_assert (ad->data != NULL);
608 return ad->data->setup;
612 ves_icall_System_AppDomain_getFriendlyName (MonoAppDomain *ad)
616 g_assert (ad != NULL);
617 g_assert (ad->data != NULL);
619 return mono_string_new (ad->data, ad->data->friendly_name);
623 ves_icall_System_AppDomain_getCurDomain ()
625 MonoDomain *add = mono_domain_get ();
633 ves_icall_System_AppDomain_getRootDomain ()
635 MonoDomain *root = mono_get_root_domain ();
643 get_attribute_value (const gchar **attribute_names,
644 const gchar **attribute_values,
645 const char *att_name)
648 for (n = 0; attribute_names [n] != NULL; n++) {
649 if (strcmp (attribute_names [n], att_name) == 0)
650 return g_strdup (attribute_values [n]);
656 start_element (GMarkupParseContext *context,
657 const gchar *element_name,
658 const gchar **attribute_names,
659 const gchar **attribute_values,
663 RuntimeConfig *runtime_config = user_data;
665 if (strcmp (element_name, "runtime") == 0) {
666 runtime_config->runtime_count++;
670 if (strcmp (element_name, "assemblyBinding") == 0) {
671 runtime_config->assemblybinding_count++;
675 if (runtime_config->runtime_count != 1 || runtime_config->assemblybinding_count != 1)
678 if (strcmp (element_name, "probing") != 0)
681 g_free (runtime_config->domain->private_bin_path);
682 runtime_config->domain->private_bin_path = get_attribute_value (attribute_names, attribute_values, "privatePath");
683 if (runtime_config->domain->private_bin_path && !runtime_config->domain->private_bin_path [0]) {
684 g_free (runtime_config->domain->private_bin_path);
685 runtime_config->domain->private_bin_path = NULL;
691 end_element (GMarkupParseContext *context,
692 const gchar *element_name,
696 RuntimeConfig *runtime_config = user_data;
697 if (strcmp (element_name, "runtime") == 0)
698 runtime_config->runtime_count--;
699 else if (strcmp (element_name, "assemblyBinding") == 0)
700 runtime_config->assemblybinding_count--;
703 static const GMarkupParser
713 mono_set_private_bin_path_from_config (MonoDomain *domain)
715 gchar *config_file, *text;
717 GMarkupParseContext *context;
718 RuntimeConfig runtime_config;
720 if (!domain || !domain->setup || !domain->setup->configuration_file)
723 config_file = mono_string_to_utf8 (domain->setup->configuration_file);
725 if (!g_file_get_contents (config_file, &text, &len, NULL)) {
726 g_free (config_file);
729 g_free (config_file);
731 runtime_config.runtime_count = 0;
732 runtime_config.assemblybinding_count = 0;
733 runtime_config.domain = domain;
735 context = g_markup_parse_context_new (&mono_parser, 0, &runtime_config, NULL);
736 if (g_markup_parse_context_parse (context, text, len, NULL))
737 g_markup_parse_context_end_parse (context, NULL);
738 g_markup_parse_context_free (context);
743 ves_icall_System_AppDomain_createDomain (MonoString *friendly_name, MonoAppDomainSetup *setup)
745 char *fname = mono_string_to_utf8 (friendly_name);
746 MonoAppDomain *ad = mono_domain_create_appdomain_internal (fname, setup);
754 ves_icall_System_AppDomain_GetAssemblies (MonoAppDomain *ad, MonoBoolean refonly)
756 MonoDomain *domain = ad->data;
758 static MonoClass *System_Reflection_Assembly;
762 GPtrArray *assemblies;
766 if (!System_Reflection_Assembly)
767 System_Reflection_Assembly = mono_class_from_name (
768 mono_defaults.corlib, "System.Reflection", "Assembly");
771 * Make a copy of the list of assemblies because we can't hold the assemblies
772 * lock while creating objects etc.
774 assemblies = g_ptr_array_new ();
775 /* Need to skip internal assembly builders created by remoting */
776 mono_domain_assemblies_lock (domain);
777 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
779 if (refonly && !ass->ref_only)
781 if (ass->corlib_internal)
783 g_ptr_array_add (assemblies, ass);
785 mono_domain_assemblies_unlock (domain);
787 res = mono_array_new (domain, System_Reflection_Assembly, assemblies->len);
788 for (i = 0; i < assemblies->len; ++i) {
789 ass = g_ptr_array_index (assemblies, i);
790 mono_array_setref (res, i, mono_assembly_get_object (domain, ass));
793 g_ptr_array_free (assemblies, TRUE);
798 MonoReflectionAssembly *
799 mono_try_assembly_resolve (MonoDomain *domain, MonoString *fname, gboolean refonly)
803 MonoBoolean isrefonly;
806 g_assert (domain != NULL && fname != NULL);
808 klass = domain->domain->mbr.obj.vtable->klass;
811 method = mono_class_get_method_from_name (klass, "DoAssemblyResolve", -1);
812 if (method == NULL) {
813 g_warning ("Method AppDomain.DoAssemblyResolve not found.\n");
817 isrefonly = refonly ? 1 : 0;
819 params [1] = &isrefonly;
820 return (MonoReflectionAssembly *) mono_runtime_invoke (method, domain->domain, params, NULL);
823 static MonoAssembly *
824 mono_domain_assembly_postload_search (MonoAssemblyName *aname,
827 gboolean refonly = GPOINTER_TO_UINT (user_data);
828 MonoReflectionAssembly *assembly;
829 MonoDomain *domain = mono_domain_get ();
832 aname_str = mono_stringify_assembly_name (aname);
834 /* FIXME: We invoke managed code here, so there is a potential for deadlocks */
835 assembly = mono_try_assembly_resolve (domain, mono_string_new (domain, aname_str), refonly);
840 return assembly->assembly;
846 * LOCKING: assumes assemblies_lock in the domain is already locked.
849 add_assemblies_to_domain (MonoDomain *domain, MonoAssembly *ass, GHashTable *ht)
853 gboolean destroy_ht = FALSE;
855 if (!ass->aname.name)
859 ht = g_hash_table_new (mono_aligned_addr_hash, NULL);
863 /* FIXME: handle lazy loaded assemblies */
864 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
865 g_hash_table_insert (ht, tmp->data, tmp->data);
867 if (!g_hash_table_lookup (ht, ass)) {
868 mono_assembly_addref (ass);
869 g_hash_table_insert (ht, ass, ass);
870 domain->domain_assemblies = g_slist_prepend (domain->domain_assemblies, ass);
871 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);
874 if (ass->image->references) {
875 for (i = 0; ass->image->references [i] != NULL; i++) {
876 if (ass->image->references [i] != REFERENCE_MISSING)
877 if (!g_hash_table_lookup (ht, ass->image->references [i])) {
878 add_assemblies_to_domain (domain, ass->image->references [i], ht);
883 g_hash_table_destroy (ht);
887 mono_domain_fire_assembly_load (MonoAssembly *assembly, gpointer user_data)
889 static MonoClassField *assembly_load_field;
890 static MonoMethod *assembly_load_method;
891 MonoDomain *domain = mono_domain_get ();
892 MonoReflectionAssembly *ref_assembly;
898 /* This can happen during startup */
900 #ifdef ASSEMBLY_LOAD_DEBUG
901 fprintf (stderr, "Loading %s into domain %s\n", assembly->aname.name, domain->friendly_name);
903 klass = domain->domain->mbr.obj.vtable->klass;
905 mono_domain_assemblies_lock (domain);
906 add_assemblies_to_domain (domain, assembly, NULL);
907 mono_domain_assemblies_unlock (domain);
909 if (assembly_load_field == NULL) {
910 assembly_load_field = mono_class_get_field_from_name (klass, "AssemblyLoad");
911 g_assert (assembly_load_field);
914 mono_field_get_value ((MonoObject*) domain->domain, assembly_load_field, &load_value);
915 if (load_value == NULL) {
916 /* No events waiting to be triggered */
920 ref_assembly = mono_assembly_get_object (domain, assembly);
921 g_assert (ref_assembly);
923 if (assembly_load_method == NULL) {
924 assembly_load_method = mono_class_get_method_from_name (klass, "DoAssemblyLoad", -1);
925 g_assert (assembly_load_method);
928 *params = ref_assembly;
929 mono_runtime_invoke (assembly_load_method, domain->domain, params, NULL);
933 * LOCKING: Acquires the domain assemblies lock.
936 set_domain_search_path (MonoDomain *domain)
938 MonoAppDomainSetup *setup;
940 gchar *search_path = NULL;
943 gchar **pvt_split = NULL;
944 GError *error = NULL;
945 gint appbaselen = -1;
948 * We use the low-level domain assemblies lock, since this is called from
949 * assembly loads hooks, which means this thread might hold the loader lock.
951 mono_domain_assemblies_lock (domain);
953 if (!domain->setup) {
954 mono_domain_assemblies_unlock (domain);
958 if ((domain->search_path != NULL) && !domain->setup->path_changed) {
959 mono_domain_assemblies_unlock (domain);
962 setup = domain->setup;
963 if (!setup->application_base) {
964 mono_domain_assemblies_unlock (domain);
965 return; /* Must set application base to get private path working */
970 if (setup->private_bin_path)
971 search_path = mono_string_to_utf8 (setup->private_bin_path);
973 if (domain->private_bin_path) {
974 if (search_path == NULL)
975 search_path = domain->private_bin_path;
977 gchar *tmp2 = search_path;
978 search_path = g_strjoin (";", search_path, domain->private_bin_path, NULL);
985 * As per MSDN documentation, AppDomainSetup.PrivateBinPath contains a list of
986 * directories relative to ApplicationBase separated by semicolons (see
987 * http://msdn2.microsoft.com/en-us/library/system.appdomainsetup.privatebinpath.aspx)
988 * The loop below copes with the fact that some Unix applications may use ':' (or
989 * System.IO.Path.PathSeparator) as the path search separator. We replace it with
990 * ';' for the subsequent split.
992 * The issue was reported in bug #81446
995 #ifndef PLATFORM_WIN32
998 slen = strlen (search_path);
999 for (i = 0; i < slen; i++)
1000 if (search_path [i] == ':')
1001 search_path [i] = ';';
1004 pvt_split = g_strsplit (search_path, ";", 1000);
1005 g_free (search_path);
1006 for (tmp = pvt_split; *tmp; tmp++, npaths++);
1011 g_strfreev (pvt_split);
1013 * Don't do this because the first time is called, the domain
1014 * setup is not finished.
1016 * domain->search_path = g_malloc (sizeof (char *));
1017 * domain->search_path [0] = NULL;
1019 mono_domain_assemblies_unlock (domain);
1023 if (domain->search_path)
1024 g_strfreev (domain->search_path);
1026 domain->search_path = tmp = g_malloc ((npaths + 1) * sizeof (gchar *));
1027 tmp [npaths] = NULL;
1029 *tmp = mono_string_to_utf8 (setup->application_base);
1031 /* FIXME: is this needed? */
1032 if (strncmp (*tmp, "file://", 7) == 0) {
1038 uri = g_strdup_printf ("file:///%s", uri + 7);
1041 uri = mono_escape_uri_string (tmpuri);
1042 *tmp = g_filename_from_uri (uri, NULL, &error);
1048 if (error != NULL) {
1049 g_warning ("%s\n", error->message);
1050 g_error_free (error);
1057 for (i = 1; pvt_split && i < npaths; i++) {
1058 if (g_path_is_absolute (pvt_split [i - 1])) {
1059 tmp [i] = g_strdup (pvt_split [i - 1]);
1061 tmp [i] = g_build_filename (tmp [0], pvt_split [i - 1], NULL);
1064 if (strchr (tmp [i], '.')) {
1068 reduced = mono_path_canonicalize (tmp [i]);
1069 if (appbaselen == -1)
1070 appbaselen = strlen (tmp [0]);
1072 if (strncmp (tmp [0], reduced, appbaselen)) {
1075 tmp [i] = g_strdup ("");
1085 if (setup->private_bin_path_probe != NULL) {
1087 tmp [0] = g_strdup ("");
1090 domain->setup->path_changed = FALSE;
1092 g_strfreev (pvt_split);
1094 mono_domain_assemblies_unlock (domain);
1097 #ifdef DISABLE_SHADOW_COPY
1099 mono_is_shadow_copy_enabled (MonoDomain *domain, const gchar *dir_name)
1105 mono_make_shadow_copy (const char *filename)
1107 return (char *) filename;
1111 shadow_copy_sibling (gchar *src, gint srclen, const char *extension, gchar *target, gint targetlen, gint tail_len)
1113 guint16 *orig, *dest;
1114 gboolean copy_result;
1116 strcpy (src + srclen - tail_len, extension);
1117 if (!g_file_test (src, G_FILE_TEST_IS_REGULAR))
1119 orig = g_utf8_to_utf16 (src, strlen (src), NULL, NULL, NULL);
1121 strcpy (target + targetlen - tail_len, extension);
1122 dest = g_utf8_to_utf16 (target, strlen (target), NULL, NULL, NULL);
1125 copy_result = CopyFile (orig, dest, FALSE);
1133 get_cstring_hash (const char *str)
1139 if (!str || !str [0])
1144 for (i = 0; i < len; i++) {
1145 h = (h << 5) - h + *p;
1153 get_shadow_assembly_location_base (MonoDomain *domain)
1155 MonoAppDomainSetup *setup;
1156 char *cache_path, *appname;
1160 setup = domain->setup;
1161 if (setup->cache_path != NULL && setup->application_name != NULL) {
1162 cache_path = mono_string_to_utf8 (setup->cache_path);
1163 #ifndef PLATFORM_WIN32
1166 for (i = strlen (cache_path) - 1; i >= 0; i--)
1167 if (cache_path [i] == '\\')
1168 cache_path [i] = '/';
1172 appname = mono_string_to_utf8 (setup->application_name);
1173 location = g_build_filename (cache_path, appname, "assembly", "shadow", NULL);
1175 g_free (cache_path);
1177 userdir = g_strdup_printf ("%s-mono-cachepath", g_get_user_name ());
1178 location = g_build_filename (g_get_tmp_dir (), userdir, "assembly", "shadow", NULL);
1185 get_shadow_assembly_location (const char *filename)
1187 gint32 hash = 0, hash2 = 0;
1189 char path_hash [30];
1190 char *bname = g_path_get_basename (filename);
1191 char *dirname = g_path_get_dirname (filename);
1192 char *location, *tmploc;
1193 MonoDomain *domain = mono_domain_get ();
1195 hash = get_cstring_hash (bname);
1196 hash2 = get_cstring_hash (dirname);
1197 g_snprintf (name_hash, sizeof (name_hash), "%08x", hash);
1198 g_snprintf (path_hash, sizeof (path_hash), "%08x_%08x_%08x", hash ^ hash2, hash2, domain->shadow_serial);
1199 tmploc = get_shadow_assembly_location_base (domain);
1200 location = g_build_filename (tmploc, name_hash, path_hash, bname, NULL);
1206 ensure_directory_exists (const char *filename)
1208 #ifdef PLATFORM_WIN32
1209 gchar *dir_utf8 = g_path_get_dirname (filename);
1211 gunichar2 *dir_utf16 = NULL;
1214 if (!dir_utf8 || !dir_utf8 [0])
1217 dir_utf16 = g_utf8_to_utf16 (dir_utf8, strlen (dir_utf8), NULL, NULL, NULL);
1225 /* make life easy and only use one directory seperator */
1236 while (*p++ != '\\')
1242 p = wcschr (p, '\\');
1245 retval = _wmkdir (dir_utf16);
1246 if (retval != 0 && errno != EEXIST) {
1259 gchar *dir = g_path_get_dirname (filename);
1263 if (!dir || !dir [0]) {
1268 if (stat (dir, &sbuf) == 0 && S_ISDIR (sbuf.st_mode)) {
1278 p = strchr (p, '/');
1281 retval = mkdir (dir, 0777);
1282 if (retval != 0 && errno != EEXIST) {
1297 private_file_needs_copying (const char *src, struct stat *sbuf_src, char *dest)
1299 struct stat sbuf_dest;
1301 if (stat (src, sbuf_src) == -1 || stat (dest, &sbuf_dest) == -1)
1304 if (sbuf_src->st_mode == sbuf_dest.st_mode &&
1305 sbuf_src->st_size == sbuf_dest.st_size &&
1306 sbuf_src->st_mtime == sbuf_dest.st_mtime)
1313 shadow_copy_create_ini (const char *shadow, const char *filename)
1323 dir_name = g_path_get_dirname (shadow);
1324 ini_file = g_build_filename (dir_name, "__AssemblyInfo__.ini", NULL);
1326 if (g_file_test (ini_file, G_FILE_TEST_IS_REGULAR)) {
1331 u16_ini = g_utf8_to_utf16 (ini_file, strlen (ini_file), NULL, NULL, NULL);
1336 handle = CreateFile (u16_ini, GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE,
1337 NULL, CREATE_NEW, FileAttributes_Normal, NULL);
1339 if (handle == INVALID_HANDLE_VALUE) {
1343 full_path = mono_path_resolve_symlinks (filename);
1344 result = WriteFile (handle, full_path, strlen (full_path), &n, NULL);
1346 CloseHandle (handle);
1351 mono_is_shadow_copy_enabled (MonoDomain *domain, const gchar *dir_name)
1353 const char *version;
1354 MonoAppDomainSetup *setup;
1357 gchar **directories;
1358 gchar *shadow_status_string;
1360 gboolean shadow_enabled;
1361 gboolean found = FALSE;
1366 setup = domain->setup;
1367 if (setup == NULL || setup->shadow_copy_files == NULL)
1370 version = mono_get_runtime_info ()->framework_version;
1371 shadow_status_string = mono_string_to_utf8 (setup->shadow_copy_files);
1372 /* For 1.x, not NULL is enough. In 2.0 it has to be "true" */
1373 shadow_enabled = (*version <= '1' || !g_ascii_strncasecmp (shadow_status_string, "true", 4));
1374 g_free (shadow_status_string);
1375 if (!shadow_enabled)
1378 if (setup->shadow_copy_directories == NULL)
1381 /* Is dir_name a shadow_copy destination already? */
1382 base_dir = get_shadow_assembly_location_base (domain);
1383 if (strstr (dir_name, base_dir) == dir_name) {
1389 all_dirs = mono_string_to_utf8 (setup->shadow_copy_directories);
1390 directories = g_strsplit (all_dirs, G_SEARCHPATH_SEPARATOR_S, 1000);
1391 dir_ptr = directories;
1393 if (**dir_ptr != '\0' && !strcmp (*dir_ptr, dir_name)) {
1399 g_strfreev (directories);
1405 mono_make_shadow_copy (const char *filename)
1407 gchar *sibling_source, *sibling_target;
1408 gint sibling_source_len, sibling_target_len;
1409 guint16 *orig, *dest;
1411 gboolean copy_result;
1413 struct stat src_sbuf;
1414 struct utimbuf utbuf;
1415 char *dir_name = g_path_get_dirname (filename);
1416 MonoDomain *domain = mono_domain_get ();
1417 set_domain_search_path (domain);
1419 if (!mono_is_shadow_copy_enabled (domain, dir_name)) {
1421 return (char *) filename;
1425 shadow = get_shadow_assembly_location (filename);
1426 if (ensure_directory_exists (shadow) == FALSE) {
1428 exc = mono_get_exception_execution_engine ("Failed to create shadow copy (ensure directory exists).");
1429 mono_raise_exception (exc);
1432 if (!private_file_needs_copying (filename, &src_sbuf, shadow))
1433 return (char*) shadow;
1435 orig = g_utf8_to_utf16 (filename, strlen (filename), NULL, NULL, NULL);
1436 dest = g_utf8_to_utf16 (shadow, strlen (shadow), NULL, NULL, NULL);
1438 copy_result = CopyFile (orig, dest, FALSE);
1442 if (copy_result == FALSE) {
1444 exc = mono_get_exception_execution_engine ("Failed to create shadow copy (CopyFile).");
1445 mono_raise_exception (exc);
1448 /* attempt to copy .mdb, .config if they exist */
1449 sibling_source = g_strconcat (filename, ".config", NULL);
1450 sibling_source_len = strlen (sibling_source);
1451 sibling_target = g_strconcat (shadow, ".config", NULL);
1452 sibling_target_len = strlen (sibling_target);
1454 copy_result = shadow_copy_sibling (sibling_source, sibling_source_len, ".mdb", sibling_target, sibling_target_len, 7);
1455 if (copy_result == TRUE)
1456 copy_result = shadow_copy_sibling (sibling_source, sibling_source_len, ".config", sibling_target, sibling_target_len, 7);
1458 g_free (sibling_source);
1459 g_free (sibling_target);
1461 if (copy_result == FALSE) {
1463 exc = mono_get_exception_execution_engine ("Failed to create shadow copy of sibling data (CopyFile).");
1464 mono_raise_exception (exc);
1467 /* Create a .ini file containing the original assembly location */
1468 if (!shadow_copy_create_ini (shadow, filename)) {
1470 exc = mono_get_exception_execution_engine ("Failed to create shadow copy .ini file.");
1471 mono_raise_exception (exc);
1474 utbuf.actime = src_sbuf.st_atime;
1475 utbuf.modtime = src_sbuf.st_mtime;
1476 utime (shadow, &utbuf);
1480 #endif /* DISABLE_SHADOW_COPY */
1483 mono_domain_from_appdomain (MonoAppDomain *appdomain)
1485 if (appdomain == NULL)
1488 return appdomain->data;
1492 try_load_from (MonoAssembly **assembly, const gchar *path1, const gchar *path2,
1493 const gchar *path3, const gchar *path4,
1494 gboolean refonly, gboolean is_private)
1497 gboolean found = FALSE;
1500 fullpath = g_build_filename (path1, path2, path3, path4, NULL);
1502 if (IS_PORTABILITY_SET) {
1503 gchar *new_fullpath = mono_portability_find_file (fullpath, TRUE);
1506 fullpath = new_fullpath;
1510 found = g_file_test (fullpath, G_FILE_TEST_IS_REGULAR);
1513 *assembly = mono_assembly_open_full (fullpath, NULL, refonly);
1516 return (*assembly != NULL);
1519 static MonoAssembly *
1520 real_load (gchar **search_path, const gchar *culture, const gchar *name, gboolean refonly)
1522 MonoAssembly *result = NULL;
1525 const gchar *local_culture;
1527 gboolean is_private = FALSE;
1529 if (!culture || *culture == '\0') {
1532 local_culture = culture;
1535 filename = g_strconcat (name, ".dll", NULL);
1536 len = strlen (filename);
1538 for (path = search_path; *path; path++) {
1539 if (**path == '\0') {
1541 continue; /* Ignore empty ApplicationBase */
1544 /* See test cases in bug #58992 and bug #57710 */
1545 /* 1st try: [culture]/[name].dll (culture may be empty) */
1546 strcpy (filename + len - 4, ".dll");
1547 if (try_load_from (&result, *path, local_culture, "", filename, refonly, is_private))
1550 /* 2nd try: [culture]/[name].exe (culture may be empty) */
1551 strcpy (filename + len - 4, ".exe");
1552 if (try_load_from (&result, *path, local_culture, "", filename, refonly, is_private))
1555 /* 3rd try: [culture]/[name]/[name].dll (culture may be empty) */
1556 strcpy (filename + len - 4, ".dll");
1557 if (try_load_from (&result, *path, local_culture, name, filename, refonly, is_private))
1560 /* 4th try: [culture]/[name]/[name].exe (culture may be empty) */
1561 strcpy (filename + len - 4, ".exe");
1562 if (try_load_from (&result, *path, local_culture, name, filename, refonly, is_private))
1571 * Try loading the assembly from ApplicationBase and PrivateBinPath
1572 * and then from assemblies_path if any.
1573 * LOCKING: This is called from the assembly loading code, which means the caller
1574 * might hold the loader lock. Thus, this function must not acquire the domain lock.
1576 static MonoAssembly *
1577 mono_domain_assembly_preload (MonoAssemblyName *aname,
1578 gchar **assemblies_path,
1581 MonoDomain *domain = mono_domain_get ();
1582 MonoAssembly *result = NULL;
1583 gboolean refonly = GPOINTER_TO_UINT (user_data);
1585 set_domain_search_path (domain);
1587 if (domain->search_path && domain->search_path [0] != NULL) {
1588 result = real_load (domain->search_path, aname->culture, aname->name, refonly);
1591 if (result == NULL && assemblies_path && assemblies_path [0] != NULL) {
1592 result = real_load (assemblies_path, aname->culture, aname->name, refonly);
1599 * Check whenever a given assembly was already loaded in the current appdomain.
1601 static MonoAssembly *
1602 mono_domain_assembly_search (MonoAssemblyName *aname,
1605 MonoDomain *domain = mono_domain_get ();
1608 gboolean refonly = GPOINTER_TO_UINT (user_data);
1610 mono_domain_assemblies_lock (domain);
1611 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
1613 /* Dynamic assemblies can't match here in MS.NET */
1614 if (ass->dynamic || refonly != ass->ref_only || !mono_assembly_names_equal (aname, &ass->aname))
1617 mono_domain_assemblies_unlock (domain);
1620 mono_domain_assemblies_unlock (domain);
1625 MonoReflectionAssembly *
1626 ves_icall_System_Reflection_Assembly_LoadFrom (MonoString *fname, MonoBoolean refOnly)
1628 MonoDomain *domain = mono_domain_get ();
1629 char *name, *filename;
1630 MonoImageOpenStatus status = MONO_IMAGE_OK;
1633 MONO_ARCH_SAVE_REGS;
1635 if (fname == NULL) {
1636 MonoException *exc = mono_get_exception_argument_null ("assemblyFile");
1637 mono_raise_exception (exc);
1640 name = filename = mono_string_to_utf8 (fname);
1642 ass = mono_assembly_open_full (filename, &status, refOnly);
1647 if (status == MONO_IMAGE_IMAGE_INVALID)
1648 exc = mono_get_exception_bad_image_format2 (NULL, fname);
1650 exc = mono_get_exception_file_not_found2 (NULL, fname);
1652 mono_raise_exception (exc);
1657 return mono_assembly_get_object (domain, ass);
1660 MonoReflectionAssembly *
1661 ves_icall_System_AppDomain_LoadAssemblyRaw (MonoAppDomain *ad,
1662 MonoArray *raw_assembly,
1663 MonoArray *raw_symbol_store, MonoObject *evidence,
1664 MonoBoolean refonly)
1667 MonoReflectionAssembly *refass = NULL;
1668 MonoDomain *domain = ad->data;
1669 MonoImageOpenStatus status;
1670 guint32 raw_assembly_len = mono_array_length (raw_assembly);
1671 MonoImage *image = mono_image_open_from_data_full (mono_array_addr (raw_assembly, gchar, 0), raw_assembly_len, TRUE, NULL, refonly);
1674 mono_raise_exception (mono_get_exception_bad_image_format (""));
1678 if (raw_symbol_store != NULL)
1679 mono_debug_open_image_from_memory (image, mono_array_addr (raw_symbol_store, guint8, 0), mono_array_length (raw_symbol_store));
1681 ass = mono_assembly_load_from_full (image, "", &status, refonly);
1685 mono_image_close (image);
1686 mono_raise_exception (mono_get_exception_bad_image_format (""));
1690 refass = mono_assembly_get_object (domain, ass);
1691 MONO_OBJECT_SETREF (refass, evidence, evidence);
1695 MonoReflectionAssembly *
1696 ves_icall_System_AppDomain_LoadAssembly (MonoAppDomain *ad, MonoString *assRef, MonoObject *evidence, MonoBoolean refOnly)
1698 MonoDomain *domain = ad->data;
1699 MonoImageOpenStatus status = MONO_IMAGE_OK;
1701 MonoAssemblyName aname;
1702 MonoReflectionAssembly *refass = NULL;
1706 MONO_ARCH_SAVE_REGS;
1708 g_assert (assRef != NULL);
1710 name = mono_string_to_utf8 (assRef);
1711 parsed = mono_assembly_name_parse (name, &aname);
1715 /* This is a parse error... */
1719 ass = mono_assembly_load_full_nosearch (&aname, NULL, &status, refOnly);
1720 mono_assembly_name_free (&aname);
1723 /* MS.NET doesn't seem to call the assembly resolve handler for refonly assemblies */
1725 refass = mono_try_assembly_resolve (domain, assRef, refOnly);
1734 refass = mono_assembly_get_object (domain, ass);
1736 MONO_OBJECT_SETREF (refass, evidence, evidence);
1741 ves_icall_System_AppDomain_InternalUnload (gint32 domain_id)
1743 MonoDomain * domain = mono_domain_get_by_id (domain_id);
1745 MONO_ARCH_SAVE_REGS;
1747 if (NULL == domain) {
1748 MonoException *exc = mono_get_exception_execution_engine ("Failed to unload domain, domain id not found");
1749 mono_raise_exception (exc);
1752 if (domain == mono_get_root_domain ()) {
1753 mono_raise_exception (mono_get_exception_cannot_unload_appdomain ("The default appdomain can not be unloaded."));
1758 * Unloading seems to cause problems when running NUnit/NAnt, hence
1761 if (g_getenv ("MONO_NO_UNLOAD"))
1764 mono_domain_unload (domain);
1768 ves_icall_System_AppDomain_InternalIsFinalizingForUnload (gint32 domain_id)
1770 MonoDomain *domain = mono_domain_get_by_id (domain_id);
1775 return mono_domain_is_unloading (domain);
1779 ves_icall_System_AppDomain_ExecuteAssembly (MonoAppDomain *ad,
1780 MonoReflectionAssembly *refass, MonoArray *args)
1785 MONO_ARCH_SAVE_REGS;
1788 image = refass->assembly->image;
1791 method = mono_get_method (image, mono_image_get_entry_point (image), NULL);
1794 g_error ("No entry point method found in %s", image->name);
1797 args = (MonoArray *) mono_array_new (ad->data, mono_defaults.string_class, 0);
1799 return mono_runtime_exec_main (method, (MonoArray *)args, NULL);
1803 ves_icall_System_AppDomain_GetIDFromDomain (MonoAppDomain * ad)
1805 MONO_ARCH_SAVE_REGS;
1807 return ad->data->domain_id;
1811 ves_icall_System_AppDomain_InternalSetDomain (MonoAppDomain *ad)
1813 MonoDomain *old_domain = mono_domain_get();
1815 MONO_ARCH_SAVE_REGS;
1817 if (!mono_domain_set (ad->data, FALSE))
1818 mono_raise_exception (mono_get_exception_appdomain_unloaded ());
1820 return old_domain->domain;
1824 ves_icall_System_AppDomain_InternalSetDomainByID (gint32 domainid)
1826 MonoDomain *current_domain = mono_domain_get ();
1827 MonoDomain *domain = mono_domain_get_by_id (domainid);
1829 MONO_ARCH_SAVE_REGS;
1831 if (!domain || !mono_domain_set (domain, FALSE))
1832 mono_raise_exception (mono_get_exception_appdomain_unloaded ());
1834 return current_domain->domain;
1838 ves_icall_System_AppDomain_InternalPushDomainRef (MonoAppDomain *ad)
1840 MONO_ARCH_SAVE_REGS;
1842 mono_thread_push_appdomain_ref (ad->data);
1846 ves_icall_System_AppDomain_InternalPushDomainRefByID (gint32 domain_id)
1848 MonoDomain *domain = mono_domain_get_by_id (domain_id);
1850 MONO_ARCH_SAVE_REGS;
1854 * Raise an exception to prevent the managed code from executing a pop
1857 mono_raise_exception (mono_get_exception_appdomain_unloaded ());
1859 mono_thread_push_appdomain_ref (domain);
1863 ves_icall_System_AppDomain_InternalPopDomainRef (void)
1865 MONO_ARCH_SAVE_REGS;
1867 mono_thread_pop_appdomain_ref ();
1871 ves_icall_System_AppDomain_InternalGetContext ()
1873 MONO_ARCH_SAVE_REGS;
1875 return mono_context_get ();
1879 ves_icall_System_AppDomain_InternalGetDefaultContext ()
1881 MONO_ARCH_SAVE_REGS;
1883 return mono_domain_get ()->default_context;
1887 ves_icall_System_AppDomain_InternalSetContext (MonoAppContext *mc)
1889 MonoAppContext *old_context = mono_context_get ();
1891 MONO_ARCH_SAVE_REGS;
1893 mono_context_set (mc);
1899 ves_icall_System_AppDomain_InternalGetProcessGuid (MonoString* newguid)
1901 MonoDomain* mono_root_domain = mono_get_root_domain ();
1902 mono_domain_lock (mono_root_domain);
1903 if (process_guid_set) {
1904 mono_domain_unlock (mono_root_domain);
1905 return mono_string_new_utf16 (mono_domain_get (), process_guid, sizeof(process_guid)/2);
1907 memcpy (process_guid, mono_string_chars(newguid), sizeof(process_guid));
1908 process_guid_set = TRUE;
1909 mono_domain_unlock (mono_root_domain);
1914 mono_domain_is_unloading (MonoDomain *domain)
1916 if (domain->state == MONO_APPDOMAIN_UNLOADING || domain->state == MONO_APPDOMAIN_UNLOADED)
1923 clear_cached_vtable (gpointer key, gpointer value, gpointer user_data)
1925 MonoClass *klass = (MonoClass*)key;
1926 MonoDomain *domain = (MonoDomain*)user_data;
1927 MonoClassRuntimeInfo *runtime_info;
1929 runtime_info = klass->runtime_info;
1930 if (runtime_info && runtime_info->max_domain >= domain->domain_id)
1931 runtime_info->domain_vtables [domain->domain_id] = NULL;
1934 typedef struct unload_data {
1936 char *failure_reason;
1940 static guint32 WINAPI
1941 unload_thread_main (void *arg)
1943 unload_data *data = (unload_data*)arg;
1944 MonoDomain *domain = data->domain;
1946 /* Have to attach to the runtime so shutdown can wait for this thread */
1947 mono_thread_attach (mono_get_root_domain ());
1950 * FIXME: Abort our parent thread last, so we can return a failure
1951 * indication if aborting times out.
1953 if (!mono_threads_abort_appdomain_threads (domain, -1)) {
1954 data->failure_reason = g_strdup_printf ("Aborting of threads in domain %s timed out.", domain->friendly_name);
1958 if (!mono_thread_pool_remove_domain_jobs (domain, -1)) {
1959 data->failure_reason = g_strdup_printf ("Cleanup of threadpool jobs of domain %s timed out.", domain->friendly_name);
1963 /* Finalize all finalizable objects in the doomed appdomain */
1964 if (!mono_domain_finalize (domain, -1)) {
1965 data->failure_reason = g_strdup_printf ("Finalization of domain %s timed out.", domain->friendly_name);
1969 /* Clear references to our vtables in class->runtime_info.
1970 * We also hold the loader lock because we're going to change
1971 * class->runtime_info.
1974 mono_loader_lock ();
1975 mono_domain_lock (domain);
1976 g_hash_table_foreach (domain->class_vtable_hash, clear_cached_vtable, domain);
1977 mono_domain_unlock (domain);
1978 mono_loader_unlock ();
1980 mono_threads_clear_cached_culture (domain);
1982 domain->state = MONO_APPDOMAIN_UNLOADED;
1984 /* printf ("UNLOADED %s.\n", domain->friendly_name); */
1986 /* remove from the handle table the items related to this domain */
1987 mono_gchandle_free_domain (domain);
1989 mono_domain_free (domain, FALSE);
1991 mono_gc_collect (mono_gc_max_generation ());
1997 * mono_domain_unload:
1998 * @domain: The domain to unload
2000 * Unloads an appdomain. Follows the process outlined in:
2001 * http://blogs.gotdotnet.com/cbrumme
2003 * If doing things the 'right' way is too hard or complex, we do it the
2004 * 'simple' way, which means do everything needed to avoid crashes and
2005 * memory leaks, but not much else.
2008 mono_domain_unload (MonoDomain *domain)
2010 HANDLE thread_handle;
2013 MonoAppDomainState prev_state;
2016 unload_data thread_data;
2017 MonoDomain *caller_domain = mono_domain_get ();
2019 /* printf ("UNLOAD STARTING FOR %s (%p) IN THREAD 0x%x.\n", domain->friendly_name, domain, GetCurrentThreadId ()); */
2021 /* Atomically change our state to UNLOADING */
2022 prev_state = InterlockedCompareExchange ((gint32*)&domain->state,
2023 MONO_APPDOMAIN_UNLOADING_START,
2024 MONO_APPDOMAIN_CREATED);
2025 if (prev_state != MONO_APPDOMAIN_CREATED) {
2026 switch (prev_state) {
2027 case MONO_APPDOMAIN_UNLOADING_START:
2028 case MONO_APPDOMAIN_UNLOADING:
2029 mono_raise_exception (mono_get_exception_cannot_unload_appdomain ("Appdomain is already being unloaded."));
2031 case MONO_APPDOMAIN_UNLOADED:
2032 mono_raise_exception (mono_get_exception_cannot_unload_appdomain ("Appdomain is already unloaded."));
2035 g_warning ("Incalid appdomain state %d", prev_state);
2036 g_assert_not_reached ();
2040 mono_domain_set (domain, FALSE);
2041 /* Notify OnDomainUnload listeners */
2042 method = mono_class_get_method_from_name (domain->domain->mbr.obj.vtable->klass, "DoDomainUnload", -1);
2046 mono_runtime_invoke (method, domain->domain, NULL, &exc);
2048 /* Roll back the state change */
2049 domain->state = MONO_APPDOMAIN_CREATED;
2050 mono_domain_set (caller_domain, FALSE);
2051 mono_raise_exception ((MonoException*)exc);
2054 thread_data.domain = domain;
2055 thread_data.failure_reason = NULL;
2057 /*The managed callback finished successfully, now we start tearing down the appdomain*/
2058 domain->state = MONO_APPDOMAIN_UNLOADING;
2060 * First we create a separate thread for unloading, since
2061 * we might have to abort some threads, including the current one.
2064 * If we create a non-suspended thread, the runtime will hang.
2066 * http://bugzilla.ximian.com/show_bug.cgi?id=27663
2069 thread_handle = CreateThread (NULL, 0, unload_thread_main, &thread_data, 0, &tid);
2071 thread_handle = CreateThread (NULL, 0, (LPTHREAD_START_ROUTINE)unload_thread_main, &thread_data, CREATE_SUSPENDED, &tid);
2072 if (thread_handle == NULL) {
2075 ResumeThread (thread_handle);
2078 /* Wait for the thread */
2079 while ((res = WaitForSingleObjectEx (thread_handle, INFINITE, TRUE) == WAIT_IO_COMPLETION)) {
2080 if (mono_thread_has_appdomain_ref (mono_thread_current (), domain) && (mono_thread_interruption_requested ()))
2081 /* The unload thread tries to abort us */
2082 /* The icall wrapper will execute the abort */
2083 CloseHandle (thread_handle);
2086 CloseHandle (thread_handle);
2088 mono_domain_set (caller_domain, FALSE);
2090 if (thread_data.failure_reason) {
2093 /* Roll back the state change */
2094 domain->state = MONO_APPDOMAIN_CREATED;
2096 g_warning (thread_data.failure_reason);
2098 ex = mono_get_exception_cannot_unload_appdomain (thread_data.failure_reason);
2100 g_free (thread_data.failure_reason);
2101 thread_data.failure_reason = NULL;
2103 mono_raise_exception (ex);