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;
714 GMarkupParseContext *context;
715 RuntimeConfig runtime_config;
717 if (!domain || !domain->setup || !domain->setup->configuration_file)
720 config_file = mono_string_to_utf8 (domain->setup->configuration_file);
722 if (!g_file_get_contents (config_file, &text, &len, NULL)) {
723 g_free (config_file);
726 g_free (config_file);
728 runtime_config.runtime_count = 0;
729 runtime_config.assemblybinding_count = 0;
730 runtime_config.domain = domain;
732 context = g_markup_parse_context_new (&mono_parser, 0, &runtime_config, NULL);
733 if (g_markup_parse_context_parse (context, text, len, NULL))
734 g_markup_parse_context_end_parse (context, NULL);
735 g_markup_parse_context_free (context);
740 ves_icall_System_AppDomain_createDomain (MonoString *friendly_name, MonoAppDomainSetup *setup)
742 char *fname = mono_string_to_utf8 (friendly_name);
743 MonoAppDomain *ad = mono_domain_create_appdomain_internal (fname, setup);
751 ves_icall_System_AppDomain_GetAssemblies (MonoAppDomain *ad, MonoBoolean refonly)
753 MonoDomain *domain = ad->data;
755 static MonoClass *System_Reflection_Assembly;
759 GPtrArray *assemblies;
763 if (!System_Reflection_Assembly)
764 System_Reflection_Assembly = mono_class_from_name (
765 mono_defaults.corlib, "System.Reflection", "Assembly");
768 * Make a copy of the list of assemblies because we can't hold the assemblies
769 * lock while creating objects etc.
771 assemblies = g_ptr_array_new ();
772 /* Need to skip internal assembly builders created by remoting */
773 mono_domain_assemblies_lock (domain);
774 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
776 if (refonly && !ass->ref_only)
778 if (ass->corlib_internal)
780 g_ptr_array_add (assemblies, ass);
782 mono_domain_assemblies_unlock (domain);
784 res = mono_array_new (domain, System_Reflection_Assembly, assemblies->len);
785 for (i = 0; i < assemblies->len; ++i) {
786 ass = g_ptr_array_index (assemblies, i);
787 mono_array_setref (res, i, mono_assembly_get_object (domain, ass));
790 g_ptr_array_free (assemblies, TRUE);
795 MonoReflectionAssembly *
796 mono_try_assembly_resolve (MonoDomain *domain, MonoString *fname, gboolean refonly)
800 MonoBoolean isrefonly;
803 g_assert (domain != NULL && fname != NULL);
805 klass = domain->domain->mbr.obj.vtable->klass;
808 method = mono_class_get_method_from_name (klass, "DoAssemblyResolve", -1);
809 if (method == NULL) {
810 g_warning ("Method AppDomain.DoAssemblyResolve not found.\n");
814 isrefonly = refonly ? 1 : 0;
816 params [1] = &isrefonly;
817 return (MonoReflectionAssembly *) mono_runtime_invoke (method, domain->domain, params, NULL);
820 static MonoAssembly *
821 mono_domain_assembly_postload_search (MonoAssemblyName *aname,
824 gboolean refonly = GPOINTER_TO_UINT (user_data);
825 MonoReflectionAssembly *assembly;
826 MonoDomain *domain = mono_domain_get ();
829 aname_str = mono_stringify_assembly_name (aname);
831 /* FIXME: We invoke managed code here, so there is a potential for deadlocks */
832 assembly = mono_try_assembly_resolve (domain, mono_string_new (domain, aname_str), refonly);
837 return assembly->assembly;
843 * LOCKING: assumes assemblies_lock in the domain is already locked.
846 add_assemblies_to_domain (MonoDomain *domain, MonoAssembly *ass, GHashTable *ht)
850 gboolean destroy_ht = FALSE;
852 if (!ass->aname.name)
856 ht = g_hash_table_new (mono_aligned_addr_hash, NULL);
860 /* FIXME: handle lazy loaded assemblies */
861 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
862 g_hash_table_insert (ht, tmp->data, tmp->data);
864 if (!g_hash_table_lookup (ht, ass)) {
865 mono_assembly_addref (ass);
866 g_hash_table_insert (ht, ass, ass);
867 domain->domain_assemblies = g_slist_prepend (domain->domain_assemblies, ass);
868 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);
871 if (ass->image->references) {
872 for (i = 0; ass->image->references [i] != NULL; i++) {
873 if (ass->image->references [i] != REFERENCE_MISSING)
874 if (!g_hash_table_lookup (ht, ass->image->references [i])) {
875 add_assemblies_to_domain (domain, ass->image->references [i], ht);
880 g_hash_table_destroy (ht);
884 mono_domain_fire_assembly_load (MonoAssembly *assembly, gpointer user_data)
886 static MonoClassField *assembly_load_field;
887 static MonoMethod *assembly_load_method;
888 MonoDomain *domain = mono_domain_get ();
889 MonoReflectionAssembly *ref_assembly;
895 /* This can happen during startup */
897 #ifdef ASSEMBLY_LOAD_DEBUG
898 fprintf (stderr, "Loading %s into domain %s\n", assembly->aname.name, domain->friendly_name);
900 klass = domain->domain->mbr.obj.vtable->klass;
902 mono_domain_assemblies_lock (domain);
903 add_assemblies_to_domain (domain, assembly, NULL);
904 mono_domain_assemblies_unlock (domain);
906 if (assembly_load_field == NULL) {
907 assembly_load_field = mono_class_get_field_from_name (klass, "AssemblyLoad");
908 g_assert (assembly_load_field);
911 mono_field_get_value ((MonoObject*) domain->domain, assembly_load_field, &load_value);
912 if (load_value == NULL) {
913 /* No events waiting to be triggered */
917 ref_assembly = mono_assembly_get_object (domain, assembly);
918 g_assert (ref_assembly);
920 if (assembly_load_method == NULL) {
921 assembly_load_method = mono_class_get_method_from_name (klass, "DoAssemblyLoad", -1);
922 g_assert (assembly_load_method);
925 *params = ref_assembly;
926 mono_runtime_invoke (assembly_load_method, domain->domain, params, NULL);
930 * LOCKING: Acquires the domain assemblies lock.
933 set_domain_search_path (MonoDomain *domain)
935 MonoAppDomainSetup *setup;
937 gchar *search_path = NULL;
940 gchar **pvt_split = NULL;
941 GError *error = NULL;
942 gint appbaselen = -1;
945 * We use the low-level domain assemblies lock, since this is called from
946 * assembly loads hooks, which means this thread might hold the loader lock.
948 mono_domain_assemblies_lock (domain);
950 if (!domain->setup) {
951 mono_domain_assemblies_unlock (domain);
955 if ((domain->search_path != NULL) && !domain->setup->path_changed) {
956 mono_domain_assemblies_unlock (domain);
959 setup = domain->setup;
960 if (!setup->application_base) {
961 mono_domain_assemblies_unlock (domain);
962 return; /* Must set application base to get private path working */
967 if (setup->private_bin_path)
968 search_path = mono_string_to_utf8 (setup->private_bin_path);
970 if (domain->private_bin_path) {
971 if (search_path == NULL)
972 search_path = domain->private_bin_path;
974 gchar *tmp2 = search_path;
975 search_path = g_strjoin (";", search_path, domain->private_bin_path, NULL);
982 * As per MSDN documentation, AppDomainSetup.PrivateBinPath contains a list of
983 * directories relative to ApplicationBase separated by semicolons (see
984 * http://msdn2.microsoft.com/en-us/library/system.appdomainsetup.privatebinpath.aspx)
985 * The loop below copes with the fact that some Unix applications may use ':' (or
986 * System.IO.Path.PathSeparator) as the path search separator. We replace it with
987 * ';' for the subsequent split.
989 * The issue was reported in bug #81446
992 #ifndef PLATFORM_WIN32
995 slen = strlen (search_path);
996 for (i = 0; i < slen; i++)
997 if (search_path [i] == ':')
998 search_path [i] = ';';
1001 pvt_split = g_strsplit (search_path, ";", 1000);
1002 g_free (search_path);
1003 for (tmp = pvt_split; *tmp; tmp++, npaths++);
1008 g_strfreev (pvt_split);
1010 * Don't do this because the first time is called, the domain
1011 * setup is not finished.
1013 * domain->search_path = g_malloc (sizeof (char *));
1014 * domain->search_path [0] = NULL;
1016 mono_domain_assemblies_unlock (domain);
1020 if (domain->search_path)
1021 g_strfreev (domain->search_path);
1023 domain->search_path = tmp = g_malloc ((npaths + 1) * sizeof (gchar *));
1024 tmp [npaths] = NULL;
1026 *tmp = mono_string_to_utf8 (setup->application_base);
1028 /* FIXME: is this needed? */
1029 if (strncmp (*tmp, "file://", 7) == 0) {
1035 uri = g_strdup_printf ("file:///%s", uri + 7);
1038 uri = mono_escape_uri_string (tmpuri);
1039 *tmp = g_filename_from_uri (uri, NULL, &error);
1045 if (error != NULL) {
1046 g_warning ("%s\n", error->message);
1047 g_error_free (error);
1054 for (i = 1; pvt_split && i < npaths; i++) {
1055 if (g_path_is_absolute (pvt_split [i - 1])) {
1056 tmp [i] = g_strdup (pvt_split [i - 1]);
1058 tmp [i] = g_build_filename (tmp [0], pvt_split [i - 1], NULL);
1061 if (strchr (tmp [i], '.')) {
1065 reduced = mono_path_canonicalize (tmp [i]);
1066 if (appbaselen == -1)
1067 appbaselen = strlen (tmp [0]);
1069 if (strncmp (tmp [0], reduced, appbaselen)) {
1072 tmp [i] = g_strdup ("");
1082 if (setup->private_bin_path_probe != NULL) {
1084 tmp [0] = g_strdup ("");
1087 domain->setup->path_changed = FALSE;
1089 g_strfreev (pvt_split);
1091 mono_domain_assemblies_unlock (domain);
1094 #ifdef DISABLE_SHADOW_COPY
1096 mono_is_shadow_copy_enabled (MonoDomain *domain, const gchar *dir_name)
1102 mono_make_shadow_copy (const char *filename)
1104 return (char *) filename;
1108 shadow_copy_sibling (gchar *src, gint srclen, const char *extension, gchar *target, gint targetlen, gint tail_len)
1110 guint16 *orig, *dest;
1111 gboolean copy_result;
1113 strcpy (src + srclen - tail_len, extension);
1114 if (!g_file_test (src, G_FILE_TEST_IS_REGULAR))
1116 orig = g_utf8_to_utf16 (src, strlen (src), NULL, NULL, NULL);
1118 strcpy (target + targetlen - tail_len, extension);
1119 dest = g_utf8_to_utf16 (target, strlen (target), NULL, NULL, NULL);
1122 copy_result = CopyFile (orig, dest, FALSE);
1130 get_cstring_hash (const char *str)
1136 if (!str || !str [0])
1141 for (i = 0; i < len; i++) {
1142 h = (h << 5) - h + *p;
1150 get_shadow_assembly_location_base (MonoDomain *domain)
1152 MonoAppDomainSetup *setup;
1153 char *cache_path, *appname;
1157 setup = domain->setup;
1158 if (setup->cache_path != NULL && setup->application_name != NULL) {
1159 cache_path = mono_string_to_utf8 (setup->cache_path);
1160 #ifndef PLATFORM_WIN32
1163 for (i = strlen (cache_path) - 1; i >= 0; i--)
1164 if (cache_path [i] == '\\')
1165 cache_path [i] = '/';
1169 appname = mono_string_to_utf8 (setup->application_name);
1170 location = g_build_filename (cache_path, appname, "assembly", "shadow", NULL);
1172 g_free (cache_path);
1174 userdir = g_strdup_printf ("%s-mono-cachepath", g_get_user_name ());
1175 location = g_build_filename (g_get_tmp_dir (), userdir, "assembly", "shadow", NULL);
1182 get_shadow_assembly_location (const char *filename)
1184 gint32 hash = 0, hash2 = 0;
1186 char path_hash [30];
1187 char *bname = g_path_get_basename (filename);
1188 char *dirname = g_path_get_dirname (filename);
1189 char *location, *tmploc;
1190 MonoDomain *domain = mono_domain_get ();
1192 hash = get_cstring_hash (bname);
1193 hash2 = get_cstring_hash (dirname);
1194 g_snprintf (name_hash, sizeof (name_hash), "%08x", hash);
1195 g_snprintf (path_hash, sizeof (path_hash), "%08x_%08x_%08x", hash ^ hash2, hash2, domain->shadow_serial);
1196 tmploc = get_shadow_assembly_location_base (domain);
1197 location = g_build_filename (tmploc, name_hash, path_hash, bname, NULL);
1203 ensure_directory_exists (const char *filename)
1205 #ifdef PLATFORM_WIN32
1206 gchar *dir_utf8 = g_path_get_dirname (filename);
1208 gunichar2 *dir_utf16 = NULL;
1211 if (!dir_utf8 || !dir_utf8 [0])
1214 dir_utf16 = g_utf8_to_utf16 (dir_utf8, strlen (dir_utf8), NULL, NULL, NULL);
1222 /* make life easy and only use one directory seperator */
1233 while (*p++ != '\\')
1239 p = wcschr (p, '\\');
1242 retval = _wmkdir (dir_utf16);
1243 if (retval != 0 && errno != EEXIST) {
1256 gchar *dir = g_path_get_dirname (filename);
1260 if (!dir || !dir [0]) {
1265 if (stat (dir, &sbuf) == 0 && S_ISDIR (sbuf.st_mode)) {
1275 p = strchr (p, '/');
1278 retval = mkdir (dir, 0777);
1279 if (retval != 0 && errno != EEXIST) {
1294 private_file_needs_copying (const char *src, struct stat *sbuf_src, char *dest)
1296 struct stat sbuf_dest;
1298 if (stat (src, sbuf_src) == -1 || stat (dest, &sbuf_dest) == -1)
1301 if (sbuf_src->st_mode == sbuf_dest.st_mode &&
1302 sbuf_src->st_size == sbuf_dest.st_size &&
1303 sbuf_src->st_mtime == sbuf_dest.st_mtime)
1310 shadow_copy_create_ini (const char *shadow, const char *filename)
1320 dir_name = g_path_get_dirname (shadow);
1321 ini_file = g_build_filename (dir_name, "__AssemblyInfo__.ini", NULL);
1323 if (g_file_test (ini_file, G_FILE_TEST_IS_REGULAR)) {
1328 u16_ini = g_utf8_to_utf16 (ini_file, strlen (ini_file), NULL, NULL, NULL);
1333 handle = CreateFile (u16_ini, GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE,
1334 NULL, CREATE_NEW, FileAttributes_Normal, NULL);
1336 if (handle == INVALID_HANDLE_VALUE) {
1340 full_path = mono_path_resolve_symlinks (filename);
1341 result = WriteFile (handle, full_path, strlen (full_path), &n, NULL);
1343 CloseHandle (handle);
1348 mono_is_shadow_copy_enabled (MonoDomain *domain, const gchar *dir_name)
1350 const char *version;
1351 MonoAppDomainSetup *setup;
1354 gchar **directories;
1355 gchar *shadow_status_string;
1357 gboolean shadow_enabled;
1358 gboolean found = FALSE;
1363 setup = domain->setup;
1364 if (setup == NULL || setup->shadow_copy_files == NULL)
1367 version = mono_get_runtime_info ()->framework_version;
1368 shadow_status_string = mono_string_to_utf8 (setup->shadow_copy_files);
1369 /* For 1.x, not NULL is enough. In 2.0 it has to be "true" */
1370 shadow_enabled = (*version <= '1' || !g_ascii_strncasecmp (shadow_status_string, "true", 4));
1371 g_free (shadow_status_string);
1372 if (!shadow_enabled)
1375 if (setup->shadow_copy_directories == NULL)
1378 /* Is dir_name a shadow_copy destination already? */
1379 base_dir = get_shadow_assembly_location_base (domain);
1380 if (strstr (dir_name, base_dir) == dir_name) {
1386 all_dirs = mono_string_to_utf8 (setup->shadow_copy_directories);
1387 directories = g_strsplit (all_dirs, G_SEARCHPATH_SEPARATOR_S, 1000);
1388 dir_ptr = directories;
1390 if (**dir_ptr != '\0' && !strcmp (*dir_ptr, dir_name)) {
1396 g_strfreev (directories);
1402 mono_make_shadow_copy (const char *filename)
1404 gchar *sibling_source, *sibling_target;
1405 gint sibling_source_len, sibling_target_len;
1406 guint16 *orig, *dest;
1408 gboolean copy_result;
1410 struct stat src_sbuf;
1411 struct utimbuf utbuf;
1412 char *dir_name = g_path_get_dirname (filename);
1413 MonoDomain *domain = mono_domain_get ();
1414 set_domain_search_path (domain);
1416 if (!mono_is_shadow_copy_enabled (domain, dir_name)) {
1418 return (char *) filename;
1422 shadow = get_shadow_assembly_location (filename);
1423 if (ensure_directory_exists (shadow) == FALSE) {
1425 exc = mono_get_exception_execution_engine ("Failed to create shadow copy (ensure directory exists).");
1426 mono_raise_exception (exc);
1429 if (!private_file_needs_copying (filename, &src_sbuf, shadow))
1430 return (char*) shadow;
1432 orig = g_utf8_to_utf16 (filename, strlen (filename), NULL, NULL, NULL);
1433 dest = g_utf8_to_utf16 (shadow, strlen (shadow), NULL, NULL, NULL);
1435 copy_result = CopyFile (orig, dest, FALSE);
1439 if (copy_result == FALSE) {
1441 exc = mono_get_exception_execution_engine ("Failed to create shadow copy (CopyFile).");
1442 mono_raise_exception (exc);
1445 /* attempt to copy .mdb, .config if they exist */
1446 sibling_source = g_strconcat (filename, ".config", NULL);
1447 sibling_source_len = strlen (sibling_source);
1448 sibling_target = g_strconcat (shadow, ".config", NULL);
1449 sibling_target_len = strlen (sibling_target);
1451 copy_result = shadow_copy_sibling (sibling_source, sibling_source_len, ".mdb", sibling_target, sibling_target_len, 7);
1452 if (copy_result == TRUE)
1453 copy_result = shadow_copy_sibling (sibling_source, sibling_source_len, ".config", sibling_target, sibling_target_len, 7);
1455 g_free (sibling_source);
1456 g_free (sibling_target);
1458 if (copy_result == FALSE) {
1460 exc = mono_get_exception_execution_engine ("Failed to create shadow copy of sibling data (CopyFile).");
1461 mono_raise_exception (exc);
1464 /* Create a .ini file containing the original assembly location */
1465 if (!shadow_copy_create_ini (shadow, filename)) {
1467 exc = mono_get_exception_execution_engine ("Failed to create shadow copy .ini file.");
1468 mono_raise_exception (exc);
1471 utbuf.actime = src_sbuf.st_atime;
1472 utbuf.modtime = src_sbuf.st_mtime;
1473 utime (shadow, &utbuf);
1477 #endif /* DISABLE_SHADOW_COPY */
1480 mono_domain_from_appdomain (MonoAppDomain *appdomain)
1482 if (appdomain == NULL)
1485 return appdomain->data;
1489 try_load_from (MonoAssembly **assembly, const gchar *path1, const gchar *path2,
1490 const gchar *path3, const gchar *path4,
1491 gboolean refonly, gboolean is_private)
1494 gboolean found = FALSE;
1497 fullpath = g_build_filename (path1, path2, path3, path4, NULL);
1499 if (IS_PORTABILITY_SET) {
1500 gchar *new_fullpath = mono_portability_find_file (fullpath, TRUE);
1503 fullpath = new_fullpath;
1507 found = g_file_test (fullpath, G_FILE_TEST_IS_REGULAR);
1510 *assembly = mono_assembly_open_full (fullpath, NULL, refonly);
1513 return (*assembly != NULL);
1516 static MonoAssembly *
1517 real_load (gchar **search_path, const gchar *culture, const gchar *name, gboolean refonly)
1519 MonoAssembly *result = NULL;
1522 const gchar *local_culture;
1524 gboolean is_private = FALSE;
1526 if (!culture || *culture == '\0') {
1529 local_culture = culture;
1532 filename = g_strconcat (name, ".dll", NULL);
1533 len = strlen (filename);
1535 for (path = search_path; *path; path++) {
1536 if (**path == '\0') {
1538 continue; /* Ignore empty ApplicationBase */
1541 /* See test cases in bug #58992 and bug #57710 */
1542 /* 1st try: [culture]/[name].dll (culture may be empty) */
1543 strcpy (filename + len - 4, ".dll");
1544 if (try_load_from (&result, *path, local_culture, "", filename, refonly, is_private))
1547 /* 2nd try: [culture]/[name].exe (culture may be empty) */
1548 strcpy (filename + len - 4, ".exe");
1549 if (try_load_from (&result, *path, local_culture, "", filename, refonly, is_private))
1552 /* 3rd try: [culture]/[name]/[name].dll (culture may be empty) */
1553 strcpy (filename + len - 4, ".dll");
1554 if (try_load_from (&result, *path, local_culture, name, filename, refonly, is_private))
1557 /* 4th try: [culture]/[name]/[name].exe (culture may be empty) */
1558 strcpy (filename + len - 4, ".exe");
1559 if (try_load_from (&result, *path, local_culture, name, filename, refonly, is_private))
1568 * Try loading the assembly from ApplicationBase and PrivateBinPath
1569 * and then from assemblies_path if any.
1570 * LOCKING: This is called from the assembly loading code, which means the caller
1571 * might hold the loader lock. Thus, this function must not acquire the domain lock.
1573 static MonoAssembly *
1574 mono_domain_assembly_preload (MonoAssemblyName *aname,
1575 gchar **assemblies_path,
1578 MonoDomain *domain = mono_domain_get ();
1579 MonoAssembly *result = NULL;
1580 gboolean refonly = GPOINTER_TO_UINT (user_data);
1582 set_domain_search_path (domain);
1584 if (domain->search_path && domain->search_path [0] != NULL) {
1585 result = real_load (domain->search_path, aname->culture, aname->name, refonly);
1588 if (result == NULL && assemblies_path && assemblies_path [0] != NULL) {
1589 result = real_load (assemblies_path, aname->culture, aname->name, refonly);
1596 * Check whenever a given assembly was already loaded in the current appdomain.
1598 static MonoAssembly *
1599 mono_domain_assembly_search (MonoAssemblyName *aname,
1602 MonoDomain *domain = mono_domain_get ();
1605 gboolean refonly = GPOINTER_TO_UINT (user_data);
1607 mono_domain_assemblies_lock (domain);
1608 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
1610 /* Dynamic assemblies can't match here in MS.NET */
1611 if (ass->dynamic || refonly != ass->ref_only || !mono_assembly_names_equal (aname, &ass->aname))
1614 mono_domain_assemblies_unlock (domain);
1617 mono_domain_assemblies_unlock (domain);
1622 MonoReflectionAssembly *
1623 ves_icall_System_Reflection_Assembly_LoadFrom (MonoString *fname, MonoBoolean refOnly)
1625 MonoDomain *domain = mono_domain_get ();
1626 char *name, *filename;
1627 MonoImageOpenStatus status = MONO_IMAGE_OK;
1630 MONO_ARCH_SAVE_REGS;
1632 if (fname == NULL) {
1633 MonoException *exc = mono_get_exception_argument_null ("assemblyFile");
1634 mono_raise_exception (exc);
1637 name = filename = mono_string_to_utf8 (fname);
1639 ass = mono_assembly_open_full (filename, &status, refOnly);
1644 if (status == MONO_IMAGE_IMAGE_INVALID)
1645 exc = mono_get_exception_bad_image_format2 (NULL, fname);
1647 exc = mono_get_exception_file_not_found2 (NULL, fname);
1649 mono_raise_exception (exc);
1654 return mono_assembly_get_object (domain, ass);
1657 MonoReflectionAssembly *
1658 ves_icall_System_AppDomain_LoadAssemblyRaw (MonoAppDomain *ad,
1659 MonoArray *raw_assembly,
1660 MonoArray *raw_symbol_store, MonoObject *evidence,
1661 MonoBoolean refonly)
1664 MonoReflectionAssembly *refass = NULL;
1665 MonoDomain *domain = ad->data;
1666 MonoImageOpenStatus status;
1667 guint32 raw_assembly_len = mono_array_length (raw_assembly);
1668 MonoImage *image = mono_image_open_from_data_full (mono_array_addr (raw_assembly, gchar, 0), raw_assembly_len, TRUE, NULL, refonly);
1671 mono_raise_exception (mono_get_exception_bad_image_format (""));
1675 if (raw_symbol_store != NULL)
1676 mono_debug_open_image_from_memory (image, mono_array_addr (raw_symbol_store, guint8, 0), mono_array_length (raw_symbol_store));
1678 ass = mono_assembly_load_from_full (image, "", &status, refonly);
1682 mono_image_close (image);
1683 mono_raise_exception (mono_get_exception_bad_image_format (""));
1687 refass = mono_assembly_get_object (domain, ass);
1688 MONO_OBJECT_SETREF (refass, evidence, evidence);
1692 MonoReflectionAssembly *
1693 ves_icall_System_AppDomain_LoadAssembly (MonoAppDomain *ad, MonoString *assRef, MonoObject *evidence, MonoBoolean refOnly)
1695 MonoDomain *domain = ad->data;
1696 MonoImageOpenStatus status = MONO_IMAGE_OK;
1698 MonoAssemblyName aname;
1699 MonoReflectionAssembly *refass = NULL;
1703 MONO_ARCH_SAVE_REGS;
1705 g_assert (assRef != NULL);
1707 name = mono_string_to_utf8 (assRef);
1708 parsed = mono_assembly_name_parse (name, &aname);
1712 /* This is a parse error... */
1716 ass = mono_assembly_load_full_nosearch (&aname, NULL, &status, refOnly);
1717 mono_assembly_name_free (&aname);
1720 /* MS.NET doesn't seem to call the assembly resolve handler for refonly assemblies */
1722 refass = mono_try_assembly_resolve (domain, assRef, refOnly);
1731 refass = mono_assembly_get_object (domain, ass);
1733 MONO_OBJECT_SETREF (refass, evidence, evidence);
1738 ves_icall_System_AppDomain_InternalUnload (gint32 domain_id)
1740 MonoDomain * domain = mono_domain_get_by_id (domain_id);
1742 MONO_ARCH_SAVE_REGS;
1744 if (NULL == domain) {
1745 MonoException *exc = mono_get_exception_execution_engine ("Failed to unload domain, domain id not found");
1746 mono_raise_exception (exc);
1749 if (domain == mono_get_root_domain ()) {
1750 mono_raise_exception (mono_get_exception_cannot_unload_appdomain ("The default appdomain can not be unloaded."));
1755 * Unloading seems to cause problems when running NUnit/NAnt, hence
1758 if (g_getenv ("MONO_NO_UNLOAD"))
1761 mono_domain_unload (domain);
1765 ves_icall_System_AppDomain_InternalIsFinalizingForUnload (gint32 domain_id)
1767 MonoDomain *domain = mono_domain_get_by_id (domain_id);
1772 return mono_domain_is_unloading (domain);
1776 ves_icall_System_AppDomain_ExecuteAssembly (MonoAppDomain *ad,
1777 MonoReflectionAssembly *refass, MonoArray *args)
1782 MONO_ARCH_SAVE_REGS;
1785 image = refass->assembly->image;
1788 method = mono_get_method (image, mono_image_get_entry_point (image), NULL);
1791 g_error ("No entry point method found in %s", image->name);
1794 args = (MonoArray *) mono_array_new (ad->data, mono_defaults.string_class, 0);
1796 return mono_runtime_exec_main (method, (MonoArray *)args, NULL);
1800 ves_icall_System_AppDomain_GetIDFromDomain (MonoAppDomain * ad)
1802 MONO_ARCH_SAVE_REGS;
1804 return ad->data->domain_id;
1808 ves_icall_System_AppDomain_InternalSetDomain (MonoAppDomain *ad)
1810 MonoDomain *old_domain = mono_domain_get();
1812 MONO_ARCH_SAVE_REGS;
1814 if (!mono_domain_set (ad->data, FALSE))
1815 mono_raise_exception (mono_get_exception_appdomain_unloaded ());
1817 return old_domain->domain;
1821 ves_icall_System_AppDomain_InternalSetDomainByID (gint32 domainid)
1823 MonoDomain *current_domain = mono_domain_get ();
1824 MonoDomain *domain = mono_domain_get_by_id (domainid);
1826 MONO_ARCH_SAVE_REGS;
1828 if (!domain || !mono_domain_set (domain, FALSE))
1829 mono_raise_exception (mono_get_exception_appdomain_unloaded ());
1831 return current_domain->domain;
1835 ves_icall_System_AppDomain_InternalPushDomainRef (MonoAppDomain *ad)
1837 MONO_ARCH_SAVE_REGS;
1839 mono_thread_push_appdomain_ref (ad->data);
1843 ves_icall_System_AppDomain_InternalPushDomainRefByID (gint32 domain_id)
1845 MonoDomain *domain = mono_domain_get_by_id (domain_id);
1847 MONO_ARCH_SAVE_REGS;
1851 * Raise an exception to prevent the managed code from executing a pop
1854 mono_raise_exception (mono_get_exception_appdomain_unloaded ());
1856 mono_thread_push_appdomain_ref (domain);
1860 ves_icall_System_AppDomain_InternalPopDomainRef (void)
1862 MONO_ARCH_SAVE_REGS;
1864 mono_thread_pop_appdomain_ref ();
1868 ves_icall_System_AppDomain_InternalGetContext ()
1870 MONO_ARCH_SAVE_REGS;
1872 return mono_context_get ();
1876 ves_icall_System_AppDomain_InternalGetDefaultContext ()
1878 MONO_ARCH_SAVE_REGS;
1880 return mono_domain_get ()->default_context;
1884 ves_icall_System_AppDomain_InternalSetContext (MonoAppContext *mc)
1886 MonoAppContext *old_context = mono_context_get ();
1888 MONO_ARCH_SAVE_REGS;
1890 mono_context_set (mc);
1896 ves_icall_System_AppDomain_InternalGetProcessGuid (MonoString* newguid)
1898 MonoDomain* mono_root_domain = mono_get_root_domain ();
1899 mono_domain_lock (mono_root_domain);
1900 if (process_guid_set) {
1901 mono_domain_unlock (mono_root_domain);
1902 return mono_string_new_utf16 (mono_domain_get (), process_guid, sizeof(process_guid)/2);
1904 memcpy (process_guid, mono_string_chars(newguid), sizeof(process_guid));
1905 process_guid_set = TRUE;
1906 mono_domain_unlock (mono_root_domain);
1911 mono_domain_is_unloading (MonoDomain *domain)
1913 if (domain->state == MONO_APPDOMAIN_UNLOADING || domain->state == MONO_APPDOMAIN_UNLOADED)
1920 clear_cached_vtable (gpointer key, gpointer value, gpointer user_data)
1922 MonoClass *klass = (MonoClass*)key;
1923 MonoDomain *domain = (MonoDomain*)user_data;
1924 MonoClassRuntimeInfo *runtime_info;
1926 runtime_info = klass->runtime_info;
1927 if (runtime_info && runtime_info->max_domain >= domain->domain_id)
1928 runtime_info->domain_vtables [domain->domain_id] = NULL;
1931 typedef struct unload_data {
1933 char *failure_reason;
1937 static guint32 WINAPI
1938 unload_thread_main (void *arg)
1940 unload_data *data = (unload_data*)arg;
1941 MonoDomain *domain = data->domain;
1943 /* Have to attach to the runtime so shutdown can wait for this thread */
1944 mono_thread_attach (mono_get_root_domain ());
1947 * FIXME: Abort our parent thread last, so we can return a failure
1948 * indication if aborting times out.
1950 if (!mono_threads_abort_appdomain_threads (domain, -1)) {
1951 data->failure_reason = g_strdup_printf ("Aborting of threads in domain %s timed out.", domain->friendly_name);
1955 if (!mono_thread_pool_remove_domain_jobs (domain, -1)) {
1956 data->failure_reason = g_strdup_printf ("Cleanup of threadpool jobs of domain %s timed out.", domain->friendly_name);
1960 /* Finalize all finalizable objects in the doomed appdomain */
1961 if (!mono_domain_finalize (domain, -1)) {
1962 data->failure_reason = g_strdup_printf ("Finalization of domain %s timed out.", domain->friendly_name);
1966 /* Clear references to our vtables in class->runtime_info.
1967 * We also hold the loader lock because we're going to change
1968 * class->runtime_info.
1970 mono_domain_lock (domain);
1971 mono_loader_lock ();
1972 g_hash_table_foreach (domain->class_vtable_hash, clear_cached_vtable, domain);
1973 mono_loader_unlock ();
1974 mono_domain_unlock (domain);
1976 mono_threads_clear_cached_culture (domain);
1978 domain->state = MONO_APPDOMAIN_UNLOADED;
1980 /* printf ("UNLOADED %s.\n", domain->friendly_name); */
1982 /* remove from the handle table the items related to this domain */
1983 mono_gchandle_free_domain (domain);
1985 mono_domain_free (domain, FALSE);
1987 mono_gc_collect (mono_gc_max_generation ());
1993 * mono_domain_unload:
1994 * @domain: The domain to unload
1996 * Unloads an appdomain. Follows the process outlined in:
1997 * http://blogs.gotdotnet.com/cbrumme
1999 * If doing things the 'right' way is too hard or complex, we do it the
2000 * 'simple' way, which means do everything needed to avoid crashes and
2001 * memory leaks, but not much else.
2004 mono_domain_unload (MonoDomain *domain)
2006 HANDLE thread_handle;
2009 MonoAppDomainState prev_state;
2012 unload_data thread_data;
2013 MonoDomain *caller_domain = mono_domain_get ();
2015 /* printf ("UNLOAD STARTING FOR %s (%p) IN THREAD 0x%x.\n", domain->friendly_name, domain, GetCurrentThreadId ()); */
2017 /* Atomically change our state to UNLOADING */
2018 prev_state = InterlockedCompareExchange ((gint32*)&domain->state,
2019 MONO_APPDOMAIN_UNLOADING_START,
2020 MONO_APPDOMAIN_CREATED);
2021 if (prev_state != MONO_APPDOMAIN_CREATED) {
2022 switch (prev_state) {
2023 case MONO_APPDOMAIN_UNLOADING_START:
2024 case MONO_APPDOMAIN_UNLOADING:
2025 mono_raise_exception (mono_get_exception_cannot_unload_appdomain ("Appdomain is already being unloaded."));
2027 case MONO_APPDOMAIN_UNLOADED:
2028 mono_raise_exception (mono_get_exception_cannot_unload_appdomain ("Appdomain is already unloaded."));
2031 g_warning ("Incalid appdomain state %d", prev_state);
2032 g_assert_not_reached ();
2036 mono_domain_set (domain, FALSE);
2037 /* Notify OnDomainUnload listeners */
2038 method = mono_class_get_method_from_name (domain->domain->mbr.obj.vtable->klass, "DoDomainUnload", -1);
2042 mono_runtime_invoke (method, domain->domain, NULL, &exc);
2044 /* Roll back the state change */
2045 domain->state = MONO_APPDOMAIN_CREATED;
2046 mono_domain_set (caller_domain, FALSE);
2047 mono_raise_exception ((MonoException*)exc);
2050 thread_data.domain = domain;
2051 thread_data.failure_reason = NULL;
2053 /*The managed callback finished successfully, now we start tearing down the appdomain*/
2054 domain->state = MONO_APPDOMAIN_UNLOADING;
2056 * First we create a separate thread for unloading, since
2057 * we might have to abort some threads, including the current one.
2060 * If we create a non-suspended thread, the runtime will hang.
2062 * http://bugzilla.ximian.com/show_bug.cgi?id=27663
2065 thread_handle = CreateThread (NULL, 0, unload_thread_main, &thread_data, 0, &tid);
2067 thread_handle = CreateThread (NULL, 0, (LPTHREAD_START_ROUTINE)unload_thread_main, &thread_data, CREATE_SUSPENDED, &tid);
2068 if (thread_handle == NULL) {
2071 ResumeThread (thread_handle);
2074 /* Wait for the thread */
2075 while ((res = WaitForSingleObjectEx (thread_handle, INFINITE, TRUE) == WAIT_IO_COMPLETION)) {
2076 if (mono_thread_has_appdomain_ref (mono_thread_current (), domain) && (mono_thread_interruption_requested ()))
2077 /* The unload thread tries to abort us */
2078 /* The icall wrapper will execute the abort */
2079 CloseHandle (thread_handle);
2082 CloseHandle (thread_handle);
2084 mono_domain_set (caller_domain, FALSE);
2086 if (thread_data.failure_reason) {
2089 /* Roll back the state change */
2090 domain->state = MONO_APPDOMAIN_CREATED;
2092 g_warning (thread_data.failure_reason);
2094 ex = mono_get_exception_cannot_unload_appdomain (thread_data.failure_reason);
2096 g_free (thread_data.failure_reason);
2097 thread_data.failure_reason = NULL;
2099 mono_raise_exception (ex);