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/mono-debug-debugger.h>
49 #include <mono/metadata/attach.h>
50 #include <mono/metadata/file-io.h>
51 #include <mono/metadata/lock-tracer.h>
52 #include <mono/metadata/console-io.h>
53 #include <mono/metadata/threads-types.h>
54 #include <mono/utils/mono-uri.h>
55 #include <mono/utils/mono-logger.h>
56 #include <mono/utils/mono-path.h>
57 #include <mono/utils/mono-stdlib.h>
58 #include <mono/utils/mono-io-portability.h>
64 * This is the version number of the corlib-runtime interface. When
65 * making changes to this interface (by changing the layout
66 * of classes the runtime knows about, changing icall signature or
67 * semantics etc), increment this variable. Also increment the
68 * pair of this variable in mscorlib in:
69 * mcs/class/mscorlib/System/Environment.cs
71 * Changes which are already detected at runtime, like the addition
72 * of icalls, do not require an increment.
74 #define MONO_CORLIB_VERSION 74
79 int assemblybinding_count;
83 CRITICAL_SECTION mono_delegate_section;
86 /* Need to lock here because EGLIB has locking defined as no-ops, we can not depend on mono_strtod do the right locking */
87 /* Ideally this will be fixed in eglib */
88 CRITICAL_SECTION mono_strtod_mutex;
92 static gunichar2 process_guid [36];
93 static gboolean process_guid_set = FALSE;
95 static gboolean shutting_down = FALSE;
97 static gboolean no_exec = FALSE;
100 mono_domain_assembly_preload (MonoAssemblyName *aname,
101 gchar **assemblies_path,
104 static MonoAssembly *
105 mono_domain_assembly_search (MonoAssemblyName *aname,
108 static MonoAssembly *
109 mono_domain_assembly_postload_search (MonoAssemblyName *aname,
113 mono_domain_fire_assembly_load (MonoAssembly *assembly, gpointer user_data);
116 add_assemblies_to_domain (MonoDomain *domain, MonoAssembly *ass, GHashTable *hash);
118 static MonoAppDomain *
119 mono_domain_create_appdomain_internal (char *friendly_name, MonoAppDomainSetup *setup);
122 get_shadow_assembly_location_base (MonoDomain *domain);
124 static MonoLoadFunc load_function = NULL;
127 mono_install_runtime_load (MonoLoadFunc func)
129 load_function = func;
133 mono_runtime_load (const char *filename, const char *runtime_version)
135 g_assert (load_function);
136 return load_function (filename, runtime_version);
140 * mono_runtime_set_no_exec:
142 * Instructs the runtime to operate in static mode, i.e. avoid/do not allow managed
143 * code execution. This is useful for running the AOT compiler on platforms which
144 * allow full-aot execution only.
145 * This should be called before mono_runtime_init ().
148 mono_runtime_set_no_exec (gboolean val)
154 mono_runtime_get_no_exec (void)
161 * @domain: domain returned by mono_init ()
163 * Initialize the core AppDomain: this function will run also some
164 * IL initialization code, so it needs the execution engine to be fully
167 * AppDomain.SetupInformation is set up in mono_runtime_exec_main, where
168 * we know the entry_assembly.
172 mono_runtime_init (MonoDomain *domain, MonoThreadStartCB start_cb,
173 MonoThreadAttachCB attach_cb)
175 MonoAppDomainSetup *setup;
180 mono_portability_helpers_init ();
182 mono_gc_base_init ();
183 mono_monitor_init ();
184 mono_thread_pool_init ();
185 mono_marshal_init ();
187 mono_install_assembly_preload_hook (mono_domain_assembly_preload, GUINT_TO_POINTER (FALSE));
188 mono_install_assembly_refonly_preload_hook (mono_domain_assembly_preload, GUINT_TO_POINTER (TRUE));
189 mono_install_assembly_search_hook (mono_domain_assembly_search, GUINT_TO_POINTER (FALSE));
190 mono_install_assembly_refonly_search_hook (mono_domain_assembly_search, GUINT_TO_POINTER (TRUE));
191 mono_install_assembly_postload_search_hook (mono_domain_assembly_postload_search, GUINT_TO_POINTER (FALSE));
192 mono_install_assembly_postload_refonly_search_hook (mono_domain_assembly_postload_search, GUINT_TO_POINTER (TRUE));
193 mono_install_assembly_load_hook (mono_domain_fire_assembly_load, NULL);
194 mono_install_lookup_dynamic_token (mono_reflection_lookup_dynamic_token);
196 mono_thread_init (start_cb, attach_cb);
198 class = mono_class_from_name (mono_defaults.corlib, "System", "AppDomainSetup");
199 setup = (MonoAppDomainSetup *) mono_object_new (domain, class);
201 class = mono_class_from_name (mono_defaults.corlib, "System", "AppDomain");
202 ad = (MonoAppDomain *) mono_object_new (domain, class);
205 domain->setup = setup;
207 InitializeCriticalSection (&mono_delegate_section);
210 /* Needed until EGLIB is fixed #464316 */
211 InitializeCriticalSection (&mono_strtod_mutex);
214 mono_thread_attach (domain);
215 mono_context_init (domain);
216 mono_context_set (domain->default_context);
218 mono_type_initialization_init ();
220 if (!mono_runtime_get_no_exec ()) {
222 * Create an instance early since we can't do it when there is no memory.
224 arg = mono_string_new (domain, "Out of memory");
225 domain->out_of_memory_ex = mono_exception_from_name_two_strings (mono_defaults.corlib, "System", "OutOfMemoryException", arg, NULL);
228 * These two are needed because the signal handlers might be executing on
229 * an alternate stack, and Boehm GC can't handle that.
231 arg = mono_string_new (domain, "A null value was found where an object instance was required");
232 domain->null_reference_ex = mono_exception_from_name_two_strings (mono_defaults.corlib, "System", "NullReferenceException", arg, NULL);
233 arg = mono_string_new (domain, "The requested operation caused a stack overflow.");
234 domain->stack_overflow_ex = mono_exception_from_name_two_strings (mono_defaults.corlib, "System", "StackOverflowException", arg, NULL);
237 /* GC init has to happen after thread init */
240 #ifndef DISABLE_SOCKETS
241 mono_network_init ();
244 mono_console_init ();
247 mono_locks_tracer_init ();
249 /* mscorlib is loaded before we install the load hook */
250 mono_domain_fire_assembly_load (mono_defaults.corlib->assembly, NULL);
256 mono_get_corlib_version (void)
259 MonoClassField *field;
262 klass = mono_class_from_name (mono_defaults.corlib, "System", "Environment");
263 mono_class_init (klass);
264 field = mono_class_get_field_from_name (klass, "mono_corlib_version");
267 if (! (field->type->attrs & FIELD_ATTRIBUTE_STATIC))
269 value = mono_field_get_value_object (mono_domain_get (), field, NULL);
270 return *(gint32*)((gchar*)value + sizeof (MonoObject));
274 mono_check_corlib_version (void)
276 int version = mono_get_corlib_version ();
277 if (version != MONO_CORLIB_VERSION)
278 return g_strdup_printf ("expected corlib version %d, found %d.", MONO_CORLIB_VERSION, version);
284 mono_context_init (MonoDomain *domain)
287 MonoAppContext *context;
289 class = mono_class_from_name (mono_defaults.corlib, "System.Runtime.Remoting.Contexts", "Context");
290 context = (MonoAppContext *) mono_object_new (domain, class);
291 context->domain_id = domain->domain_id;
292 context->context_id = 0;
293 domain->default_context = context;
297 * mono_runtime_cleanup:
302 * This must not be called while there are still running threads executing
306 mono_runtime_cleanup (MonoDomain *domain)
308 shutting_down = TRUE;
310 mono_attach_cleanup ();
312 /* This ends up calling any pending pending (for at most 2 seconds) */
315 mono_thread_cleanup ();
317 #ifndef DISABLE_SOCKETS
318 mono_network_cleanup ();
320 mono_marshal_cleanup ();
322 mono_type_initialization_cleanup ();
324 mono_monitor_cleanup ();
326 #ifndef PLATFORM_WIN32
331 static MonoDomainFunc quit_function = NULL;
334 mono_install_runtime_cleanup (MonoDomainFunc func)
336 quit_function = func;
342 if (quit_function != NULL)
343 quit_function (mono_get_root_domain (), NULL);
347 * mono_runtime_set_shutting_down:
349 * Invoked by System.Environment.Exit to flag that the runtime
353 mono_runtime_set_shutting_down (void)
355 shutting_down = TRUE;
359 * mono_runtime_is_shutting_down:
361 * Returns whether the runtime has been flagged for shutdown.
363 * This is consumed by the P:System.Environment.HasShutdownStarted
368 mono_runtime_is_shutting_down (void)
370 return shutting_down;
374 * mono_domain_create_appdomain:
375 * @friendly_name: The friendly name of the appdomain to create
376 * @configuration_file: The configuration file to initialize the appdomain with
378 * Returns a MonoDomain initialized with the appdomain
381 mono_domain_create_appdomain (char *friendly_name, char *configuration_file)
384 MonoAppDomainSetup *setup;
387 class = mono_class_from_name (mono_defaults.corlib, "System", "AppDomainSetup");
388 setup = (MonoAppDomainSetup *) mono_object_new (mono_domain_get (), class);
389 setup->configuration_file = configuration_file != NULL ? mono_string_new (mono_domain_get (), configuration_file) : NULL;
391 ad = mono_domain_create_appdomain_internal (friendly_name, setup);
393 return mono_domain_from_appdomain (ad);
396 static MonoAppDomain *
397 mono_domain_create_appdomain_internal (char *friendly_name, MonoAppDomainSetup *setup)
405 adclass = mono_class_from_name (mono_defaults.corlib, "System", "AppDomain");
407 /* FIXME: pin all those objects */
408 data = mono_domain_create();
410 ad = (MonoAppDomain *) mono_object_new (data, adclass);
414 data->friendly_name = g_strdup (friendly_name);
415 // FIXME: The ctor runs in the current domain
416 // FIXME: Initialize null_reference_ex and stack_overflow_ex
417 data->out_of_memory_ex = mono_exception_from_name_domain (data, mono_defaults.corlib, "System", "OutOfMemoryException");
419 if (!setup->application_base) {
420 /* Inherit from the root domain since MS.NET does this */
421 MonoDomain *root = mono_get_root_domain ();
422 if (root->setup->application_base)
423 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)));
426 mono_context_init (data);
428 mono_set_private_bin_path_from_config (data);
430 add_assemblies_to_domain (data, mono_defaults.corlib->assembly, NULL);
432 mono_debugger_event_create_appdomain (data, get_shadow_assembly_location_base (data));
438 * mono_domain_has_type_resolve:
439 * @domain: application domains being looked up
441 * Returns true if the AppDomain.TypeResolve field has been
445 mono_domain_has_type_resolve (MonoDomain *domain)
447 static MonoClassField *field = NULL;
451 field = mono_class_get_field_from_name (mono_defaults.appdomain_class, "TypeResolve");
455 mono_field_get_value ((MonoObject*)(domain->domain), field, &o);
460 * mono_domain_try_type_resolve:
461 * @domain: application domainwhere the name where the type is going to be resolved
462 * @name: the name of the type to resolve or NULL.
463 * @tb: A System.Reflection.Emit.TypeBuilder, used if name is NULL.
465 * This routine invokes the internal System.AppDomain.DoTypeResolve and returns
466 * the assembly that matches name.
468 * If @name is null, the value of ((TypeBuilder)tb).FullName is used instead
470 * Returns: A MonoReflectionAssembly or NULL if not found
472 MonoReflectionAssembly *
473 mono_domain_try_type_resolve (MonoDomain *domain, char *name, MonoObject *tb)
477 static MonoMethod *method = NULL;
479 g_assert (domain != NULL && ((name != NULL) || (tb != NULL)));
481 if (method == NULL) {
482 klass = domain->domain->mbr.obj.vtable->klass;
485 method = mono_class_get_method_from_name (klass, "DoTypeResolve", -1);
486 if (method == NULL) {
487 g_warning ("Method AppDomain.DoTypeResolve not found.\n");
493 *params = (MonoObject*)mono_string_new (mono_domain_get (), name);
496 return (MonoReflectionAssembly *) mono_runtime_invoke (method, domain->domain, params, NULL);
500 * mono_domain_owns_vtable_slot:
502 * Returns whenever VTABLE_SLOT is inside a vtable which belongs to DOMAIN.
505 mono_domain_owns_vtable_slot (MonoDomain *domain, gpointer vtable_slot)
509 mono_domain_lock (domain);
510 res = mono_mempool_contains_addr (domain->mp, vtable_slot);
511 mono_domain_unlock (domain);
518 * @force: force setting.
520 * Set the current appdomain to @domain. If @force is set, set it even
521 * if it is being unloaded.
525 * FALSE if the domain is unloaded
528 mono_domain_set (MonoDomain *domain, gboolean force)
530 if (!force && domain->state == MONO_APPDOMAIN_UNLOADED)
533 mono_domain_set_internal (domain);
539 ves_icall_System_AppDomain_GetData (MonoAppDomain *ad, MonoString *name)
547 g_assert (ad != NULL);
549 g_assert (add != NULL);
552 mono_raise_exception (mono_get_exception_argument_null ("name"));
554 str = mono_string_to_utf8 (name);
556 mono_domain_lock (add);
558 if (!strcmp (str, "APPBASE"))
559 o = (MonoObject *)add->setup->application_base;
560 else if (!strcmp (str, "APP_CONFIG_FILE"))
561 o = (MonoObject *)add->setup->configuration_file;
562 else if (!strcmp (str, "DYNAMIC_BASE"))
563 o = (MonoObject *)add->setup->dynamic_base;
564 else if (!strcmp (str, "APP_NAME"))
565 o = (MonoObject *)add->setup->application_name;
566 else if (!strcmp (str, "CACHE_BASE"))
567 o = (MonoObject *)add->setup->cache_path;
568 else if (!strcmp (str, "PRIVATE_BINPATH"))
569 o = (MonoObject *)add->setup->private_bin_path;
570 else if (!strcmp (str, "BINPATH_PROBE_ONLY"))
571 o = (MonoObject *)add->setup->private_bin_path_probe;
572 else if (!strcmp (str, "SHADOW_COPY_DIRS"))
573 o = (MonoObject *)add->setup->shadow_copy_directories;
574 else if (!strcmp (str, "FORCE_CACHE_INSTALL"))
575 o = (MonoObject *)add->setup->shadow_copy_files;
577 o = mono_g_hash_table_lookup (add->env, name);
579 mono_domain_unlock (add);
589 ves_icall_System_AppDomain_SetData (MonoAppDomain *ad, MonoString *name, MonoObject *data)
595 g_assert (ad != NULL);
597 g_assert (add != NULL);
600 mono_raise_exception (mono_get_exception_argument_null ("name"));
602 mono_domain_lock (add);
604 mono_g_hash_table_insert (add->env, name, data);
606 mono_domain_unlock (add);
610 ves_icall_System_AppDomain_getSetup (MonoAppDomain *ad)
614 g_assert (ad != NULL);
615 g_assert (ad->data != NULL);
617 return ad->data->setup;
621 ves_icall_System_AppDomain_getFriendlyName (MonoAppDomain *ad)
625 g_assert (ad != NULL);
626 g_assert (ad->data != NULL);
628 return mono_string_new (ad->data, ad->data->friendly_name);
632 ves_icall_System_AppDomain_getCurDomain ()
634 MonoDomain *add = mono_domain_get ();
642 ves_icall_System_AppDomain_getRootDomain ()
644 MonoDomain *root = mono_get_root_domain ();
652 get_attribute_value (const gchar **attribute_names,
653 const gchar **attribute_values,
654 const char *att_name)
657 for (n = 0; attribute_names [n] != NULL; n++) {
658 if (strcmp (attribute_names [n], att_name) == 0)
659 return g_strdup (attribute_values [n]);
665 start_element (GMarkupParseContext *context,
666 const gchar *element_name,
667 const gchar **attribute_names,
668 const gchar **attribute_values,
672 RuntimeConfig *runtime_config = user_data;
674 if (strcmp (element_name, "runtime") == 0) {
675 runtime_config->runtime_count++;
679 if (strcmp (element_name, "assemblyBinding") == 0) {
680 runtime_config->assemblybinding_count++;
684 if (runtime_config->runtime_count != 1 || runtime_config->assemblybinding_count != 1)
687 if (strcmp (element_name, "probing") != 0)
690 g_free (runtime_config->domain->private_bin_path);
691 runtime_config->domain->private_bin_path = get_attribute_value (attribute_names, attribute_values, "privatePath");
692 if (runtime_config->domain->private_bin_path && !runtime_config->domain->private_bin_path [0]) {
693 g_free (runtime_config->domain->private_bin_path);
694 runtime_config->domain->private_bin_path = NULL;
700 end_element (GMarkupParseContext *context,
701 const gchar *element_name,
705 RuntimeConfig *runtime_config = user_data;
706 if (strcmp (element_name, "runtime") == 0)
707 runtime_config->runtime_count--;
708 else if (strcmp (element_name, "assemblyBinding") == 0)
709 runtime_config->assemblybinding_count--;
712 static const GMarkupParser
722 mono_set_private_bin_path_from_config (MonoDomain *domain)
724 gchar *config_file, *text;
726 GMarkupParseContext *context;
727 RuntimeConfig runtime_config;
729 if (!domain || !domain->setup || !domain->setup->configuration_file)
732 config_file = mono_string_to_utf8 (domain->setup->configuration_file);
734 if (!g_file_get_contents (config_file, &text, &len, NULL)) {
735 g_free (config_file);
738 g_free (config_file);
740 runtime_config.runtime_count = 0;
741 runtime_config.assemblybinding_count = 0;
742 runtime_config.domain = domain;
744 context = g_markup_parse_context_new (&mono_parser, 0, &runtime_config, NULL);
745 if (g_markup_parse_context_parse (context, text, len, NULL))
746 g_markup_parse_context_end_parse (context, NULL);
747 g_markup_parse_context_free (context);
752 ves_icall_System_AppDomain_createDomain (MonoString *friendly_name, MonoAppDomainSetup *setup)
754 char *fname = mono_string_to_utf8 (friendly_name);
755 MonoAppDomain *ad = mono_domain_create_appdomain_internal (fname, setup);
763 ves_icall_System_AppDomain_GetAssemblies (MonoAppDomain *ad, MonoBoolean refonly)
765 MonoDomain *domain = ad->data;
767 static MonoClass *System_Reflection_Assembly;
771 GPtrArray *assemblies;
775 if (!System_Reflection_Assembly)
776 System_Reflection_Assembly = mono_class_from_name (
777 mono_defaults.corlib, "System.Reflection", "Assembly");
780 * Make a copy of the list of assemblies because we can't hold the assemblies
781 * lock while creating objects etc.
783 assemblies = g_ptr_array_new ();
784 /* Need to skip internal assembly builders created by remoting */
785 mono_domain_assemblies_lock (domain);
786 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
788 if (refonly && !ass->ref_only)
790 if (ass->corlib_internal)
792 g_ptr_array_add (assemblies, ass);
794 mono_domain_assemblies_unlock (domain);
796 res = mono_array_new (domain, System_Reflection_Assembly, assemblies->len);
797 for (i = 0; i < assemblies->len; ++i) {
798 ass = g_ptr_array_index (assemblies, i);
799 mono_array_setref (res, i, mono_assembly_get_object (domain, ass));
802 g_ptr_array_free (assemblies, TRUE);
807 MonoReflectionAssembly *
808 mono_try_assembly_resolve (MonoDomain *domain, MonoString *fname, gboolean refonly)
812 MonoBoolean isrefonly;
815 g_assert (domain != NULL && fname != NULL);
817 klass = domain->domain->mbr.obj.vtable->klass;
820 method = mono_class_get_method_from_name (klass, "DoAssemblyResolve", -1);
821 if (method == NULL) {
822 g_warning ("Method AppDomain.DoAssemblyResolve not found.\n");
826 isrefonly = refonly ? 1 : 0;
828 params [1] = &isrefonly;
829 return (MonoReflectionAssembly *) mono_runtime_invoke (method, domain->domain, params, NULL);
832 static MonoAssembly *
833 mono_domain_assembly_postload_search (MonoAssemblyName *aname,
836 gboolean refonly = GPOINTER_TO_UINT (user_data);
837 MonoReflectionAssembly *assembly;
838 MonoDomain *domain = mono_domain_get ();
841 aname_str = mono_stringify_assembly_name (aname);
843 /* FIXME: We invoke managed code here, so there is a potential for deadlocks */
844 assembly = mono_try_assembly_resolve (domain, mono_string_new (domain, aname_str), refonly);
849 return assembly->assembly;
855 * LOCKING: assumes assemblies_lock in the domain is already locked.
858 add_assemblies_to_domain (MonoDomain *domain, MonoAssembly *ass, GHashTable *ht)
862 gboolean destroy_ht = FALSE;
864 if (!ass->aname.name)
868 ht = g_hash_table_new (mono_aligned_addr_hash, NULL);
872 /* FIXME: handle lazy loaded assemblies */
873 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
874 g_hash_table_insert (ht, tmp->data, tmp->data);
876 if (!g_hash_table_lookup (ht, ass)) {
877 mono_assembly_addref (ass);
878 g_hash_table_insert (ht, ass, ass);
879 domain->domain_assemblies = g_slist_prepend (domain->domain_assemblies, ass);
880 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);
883 if (ass->image->references) {
884 for (i = 0; ass->image->references [i] != NULL; i++) {
885 if (ass->image->references [i] != REFERENCE_MISSING)
886 if (!g_hash_table_lookup (ht, ass->image->references [i])) {
887 add_assemblies_to_domain (domain, ass->image->references [i], ht);
892 g_hash_table_destroy (ht);
896 mono_domain_fire_assembly_load (MonoAssembly *assembly, gpointer user_data)
898 static MonoClassField *assembly_load_field;
899 static MonoMethod *assembly_load_method;
900 MonoDomain *domain = mono_domain_get ();
901 MonoReflectionAssembly *ref_assembly;
907 /* This can happen during startup */
909 #ifdef ASSEMBLY_LOAD_DEBUG
910 fprintf (stderr, "Loading %s into domain %s\n", assembly->aname.name, domain->friendly_name);
912 klass = domain->domain->mbr.obj.vtable->klass;
914 mono_domain_assemblies_lock (domain);
915 add_assemblies_to_domain (domain, assembly, NULL);
916 mono_domain_assemblies_unlock (domain);
918 if (assembly_load_field == NULL) {
919 assembly_load_field = mono_class_get_field_from_name (klass, "AssemblyLoad");
920 g_assert (assembly_load_field);
923 mono_field_get_value ((MonoObject*) domain->domain, assembly_load_field, &load_value);
924 if (load_value == NULL) {
925 /* No events waiting to be triggered */
929 ref_assembly = mono_assembly_get_object (domain, assembly);
930 g_assert (ref_assembly);
932 if (assembly_load_method == NULL) {
933 assembly_load_method = mono_class_get_method_from_name (klass, "DoAssemblyLoad", -1);
934 g_assert (assembly_load_method);
937 *params = ref_assembly;
938 mono_runtime_invoke (assembly_load_method, domain->domain, params, NULL);
942 * LOCKING: Acquires the domain assemblies lock.
945 set_domain_search_path (MonoDomain *domain)
947 MonoAppDomainSetup *setup;
949 gchar *search_path = NULL;
952 gchar **pvt_split = NULL;
953 GError *error = NULL;
954 gint appbaselen = -1;
957 * We use the low-level domain assemblies lock, since this is called from
958 * assembly loads hooks, which means this thread might hold the loader lock.
960 mono_domain_assemblies_lock (domain);
962 if (!domain->setup) {
963 mono_domain_assemblies_unlock (domain);
967 if ((domain->search_path != NULL) && !domain->setup->path_changed) {
968 mono_domain_assemblies_unlock (domain);
971 setup = domain->setup;
972 if (!setup->application_base) {
973 mono_domain_assemblies_unlock (domain);
974 return; /* Must set application base to get private path working */
979 if (setup->private_bin_path)
980 search_path = mono_string_to_utf8 (setup->private_bin_path);
982 if (domain->private_bin_path) {
983 if (search_path == NULL)
984 search_path = domain->private_bin_path;
986 gchar *tmp2 = search_path;
987 search_path = g_strjoin (";", search_path, domain->private_bin_path, NULL);
994 * As per MSDN documentation, AppDomainSetup.PrivateBinPath contains a list of
995 * directories relative to ApplicationBase separated by semicolons (see
996 * http://msdn2.microsoft.com/en-us/library/system.appdomainsetup.privatebinpath.aspx)
997 * The loop below copes with the fact that some Unix applications may use ':' (or
998 * System.IO.Path.PathSeparator) as the path search separator. We replace it with
999 * ';' for the subsequent split.
1001 * The issue was reported in bug #81446
1004 #ifndef PLATFORM_WIN32
1007 slen = strlen (search_path);
1008 for (i = 0; i < slen; i++)
1009 if (search_path [i] == ':')
1010 search_path [i] = ';';
1013 pvt_split = g_strsplit (search_path, ";", 1000);
1014 g_free (search_path);
1015 for (tmp = pvt_split; *tmp; tmp++, npaths++);
1020 g_strfreev (pvt_split);
1022 * Don't do this because the first time is called, the domain
1023 * setup is not finished.
1025 * domain->search_path = g_malloc (sizeof (char *));
1026 * domain->search_path [0] = NULL;
1028 mono_domain_assemblies_unlock (domain);
1032 if (domain->search_path)
1033 g_strfreev (domain->search_path);
1035 domain->search_path = tmp = g_malloc ((npaths + 1) * sizeof (gchar *));
1036 tmp [npaths] = NULL;
1038 *tmp = mono_string_to_utf8 (setup->application_base);
1040 /* FIXME: is this needed? */
1041 if (strncmp (*tmp, "file://", 7) == 0) {
1047 uri = g_strdup_printf ("file:///%s", uri + 7);
1050 uri = mono_escape_uri_string (tmpuri);
1051 *tmp = g_filename_from_uri (uri, NULL, &error);
1057 if (error != NULL) {
1058 g_warning ("%s\n", error->message);
1059 g_error_free (error);
1066 for (i = 1; pvt_split && i < npaths; i++) {
1067 if (g_path_is_absolute (pvt_split [i - 1])) {
1068 tmp [i] = g_strdup (pvt_split [i - 1]);
1070 tmp [i] = g_build_filename (tmp [0], pvt_split [i - 1], NULL);
1073 if (strchr (tmp [i], '.')) {
1077 reduced = mono_path_canonicalize (tmp [i]);
1078 if (appbaselen == -1)
1079 appbaselen = strlen (tmp [0]);
1081 if (strncmp (tmp [0], reduced, appbaselen)) {
1084 tmp [i] = g_strdup ("");
1094 if (setup->private_bin_path_probe != NULL) {
1096 tmp [0] = g_strdup ("");
1099 domain->setup->path_changed = FALSE;
1101 g_strfreev (pvt_split);
1103 mono_domain_assemblies_unlock (domain);
1106 #ifdef DISABLE_SHADOW_COPY
1108 mono_is_shadow_copy_enabled (MonoDomain *domain, const gchar *dir_name)
1114 mono_make_shadow_copy (const char *filename)
1116 return (char *) filename;
1120 shadow_copy_sibling (gchar *src, gint srclen, const char *extension, gchar *target, gint targetlen, gint tail_len)
1122 guint16 *orig, *dest;
1123 gboolean copy_result;
1125 strcpy (src + srclen - tail_len, extension);
1126 if (!g_file_test (src, G_FILE_TEST_IS_REGULAR))
1128 orig = g_utf8_to_utf16 (src, strlen (src), NULL, NULL, NULL);
1130 strcpy (target + targetlen - tail_len, extension);
1131 dest = g_utf8_to_utf16 (target, strlen (target), NULL, NULL, NULL);
1134 copy_result = CopyFile (orig, dest, FALSE);
1142 get_cstring_hash (const char *str)
1148 if (!str || !str [0])
1153 for (i = 0; i < len; i++) {
1154 h = (h << 5) - h + *p;
1162 get_shadow_assembly_location_base (MonoDomain *domain)
1164 MonoAppDomainSetup *setup;
1165 char *cache_path, *appname;
1169 setup = domain->setup;
1170 if (setup->cache_path != NULL && setup->application_name != NULL) {
1171 cache_path = mono_string_to_utf8 (setup->cache_path);
1172 #ifndef PLATFORM_WIN32
1175 for (i = strlen (cache_path) - 1; i >= 0; i--)
1176 if (cache_path [i] == '\\')
1177 cache_path [i] = '/';
1181 appname = mono_string_to_utf8 (setup->application_name);
1182 location = g_build_filename (cache_path, appname, "assembly", "shadow", NULL);
1184 g_free (cache_path);
1186 userdir = g_strdup_printf ("%s-mono-cachepath", g_get_user_name ());
1187 location = g_build_filename (g_get_tmp_dir (), userdir, "assembly", "shadow", NULL);
1194 get_shadow_assembly_location (const char *filename)
1196 gint32 hash = 0, hash2 = 0;
1198 char path_hash [30];
1199 char *bname = g_path_get_basename (filename);
1200 char *dirname = g_path_get_dirname (filename);
1201 char *location, *tmploc;
1202 MonoDomain *domain = mono_domain_get ();
1204 hash = get_cstring_hash (bname);
1205 hash2 = get_cstring_hash (dirname);
1206 g_snprintf (name_hash, sizeof (name_hash), "%08x", hash);
1207 g_snprintf (path_hash, sizeof (path_hash), "%08x_%08x_%08x", hash ^ hash2, hash2, domain->shadow_serial);
1208 tmploc = get_shadow_assembly_location_base (domain);
1209 location = g_build_filename (tmploc, name_hash, path_hash, bname, NULL);
1217 ensure_directory_exists (const char *filename)
1219 #ifdef PLATFORM_WIN32
1220 gchar *dir_utf8 = g_path_get_dirname (filename);
1222 gunichar2 *dir_utf16 = NULL;
1225 if (!dir_utf8 || !dir_utf8 [0])
1228 dir_utf16 = g_utf8_to_utf16 (dir_utf8, strlen (dir_utf8), NULL, NULL, NULL);
1236 /* make life easy and only use one directory seperator */
1247 while (*p++ != '\\')
1253 p = wcschr (p, '\\');
1256 retval = _wmkdir (dir_utf16);
1257 if (retval != 0 && errno != EEXIST) {
1270 gchar *dir = g_path_get_dirname (filename);
1274 if (!dir || !dir [0]) {
1279 if (stat (dir, &sbuf) == 0 && S_ISDIR (sbuf.st_mode)) {
1289 p = strchr (p, '/');
1292 retval = mkdir (dir, 0777);
1293 if (retval != 0 && errno != EEXIST) {
1308 private_file_needs_copying (const char *src, struct stat *sbuf_src, char *dest)
1310 struct stat sbuf_dest;
1312 if (stat (src, sbuf_src) == -1 || stat (dest, &sbuf_dest) == -1)
1315 if (sbuf_src->st_mode == sbuf_dest.st_mode &&
1316 sbuf_src->st_size == sbuf_dest.st_size &&
1317 sbuf_src->st_mtime == sbuf_dest.st_mtime)
1324 shadow_copy_create_ini (const char *shadow, const char *filename)
1334 dir_name = g_path_get_dirname (shadow);
1335 ini_file = g_build_filename (dir_name, "__AssemblyInfo__.ini", NULL);
1337 if (g_file_test (ini_file, G_FILE_TEST_IS_REGULAR)) {
1342 u16_ini = g_utf8_to_utf16 (ini_file, strlen (ini_file), NULL, NULL, NULL);
1347 handle = CreateFile (u16_ini, GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE,
1348 NULL, CREATE_NEW, FileAttributes_Normal, NULL);
1350 if (handle == INVALID_HANDLE_VALUE) {
1354 full_path = mono_path_resolve_symlinks (filename);
1355 result = WriteFile (handle, full_path, strlen (full_path), &n, NULL);
1357 CloseHandle (handle);
1362 mono_is_shadow_copy_enabled (MonoDomain *domain, const gchar *dir_name)
1364 const char *version;
1365 MonoAppDomainSetup *setup;
1368 gchar **directories;
1369 gchar *shadow_status_string;
1371 gboolean shadow_enabled;
1372 gboolean found = FALSE;
1377 setup = domain->setup;
1378 if (setup == NULL || setup->shadow_copy_files == NULL)
1381 version = mono_get_runtime_info ()->framework_version;
1382 shadow_status_string = mono_string_to_utf8 (setup->shadow_copy_files);
1383 /* For 1.x, not NULL is enough. In 2.0 it has to be "true" */
1384 shadow_enabled = (*version <= '1' || !g_ascii_strncasecmp (shadow_status_string, "true", 4));
1385 g_free (shadow_status_string);
1386 if (!shadow_enabled)
1389 if (setup->shadow_copy_directories == NULL)
1392 /* Is dir_name a shadow_copy destination already? */
1393 base_dir = get_shadow_assembly_location_base (domain);
1394 if (strstr (dir_name, base_dir)) {
1400 all_dirs = mono_string_to_utf8 (setup->shadow_copy_directories);
1401 directories = g_strsplit (all_dirs, G_SEARCHPATH_SEPARATOR_S, 1000);
1402 dir_ptr = directories;
1404 if (**dir_ptr != '\0' && !strcmp (*dir_ptr, dir_name)) {
1410 g_strfreev (directories);
1416 mono_make_shadow_copy (const char *filename)
1418 gchar *sibling_source, *sibling_target;
1419 gint sibling_source_len, sibling_target_len;
1420 guint16 *orig, *dest;
1422 gboolean copy_result;
1424 struct stat src_sbuf;
1425 struct utimbuf utbuf;
1426 char *dir_name = g_path_get_dirname (filename);
1427 MonoDomain *domain = mono_domain_get ();
1430 set_domain_search_path (domain);
1432 if (!mono_is_shadow_copy_enabled (domain, dir_name)) {
1434 return (char *) filename;
1436 /* Is dir_name a shadow_copy destination already? */
1437 shadow_dir = get_shadow_assembly_location_base (domain);
1438 if (strstr (dir_name, shadow_dir)) {
1439 g_free (shadow_dir);
1441 return (char *) filename;
1443 g_free (shadow_dir);
1446 shadow = get_shadow_assembly_location (filename);
1447 if (ensure_directory_exists (shadow) == FALSE) {
1449 exc = mono_get_exception_execution_engine ("Failed to create shadow copy (ensure directory exists).");
1450 mono_raise_exception (exc);
1453 if (!private_file_needs_copying (filename, &src_sbuf, shadow))
1454 return (char*) shadow;
1456 orig = g_utf8_to_utf16 (filename, strlen (filename), NULL, NULL, NULL);
1457 dest = g_utf8_to_utf16 (shadow, strlen (shadow), NULL, NULL, NULL);
1459 copy_result = CopyFile (orig, dest, FALSE);
1463 if (copy_result == FALSE) {
1465 exc = mono_get_exception_execution_engine ("Failed to create shadow copy (CopyFile).");
1466 mono_raise_exception (exc);
1469 /* attempt to copy .mdb, .config if they exist */
1470 sibling_source = g_strconcat (filename, ".config", NULL);
1471 sibling_source_len = strlen (sibling_source);
1472 sibling_target = g_strconcat (shadow, ".config", NULL);
1473 sibling_target_len = strlen (sibling_target);
1475 copy_result = shadow_copy_sibling (sibling_source, sibling_source_len, ".mdb", sibling_target, sibling_target_len, 7);
1476 if (copy_result == TRUE)
1477 copy_result = shadow_copy_sibling (sibling_source, sibling_source_len, ".config", sibling_target, sibling_target_len, 7);
1479 g_free (sibling_source);
1480 g_free (sibling_target);
1482 if (copy_result == FALSE) {
1484 exc = mono_get_exception_execution_engine ("Failed to create shadow copy of sibling data (CopyFile).");
1485 mono_raise_exception (exc);
1488 /* Create a .ini file containing the original assembly location */
1489 if (!shadow_copy_create_ini (shadow, filename)) {
1491 exc = mono_get_exception_execution_engine ("Failed to create shadow copy .ini file.");
1492 mono_raise_exception (exc);
1495 utbuf.actime = src_sbuf.st_atime;
1496 utbuf.modtime = src_sbuf.st_mtime;
1497 utime (shadow, &utbuf);
1501 #endif /* DISABLE_SHADOW_COPY */
1504 mono_domain_from_appdomain (MonoAppDomain *appdomain)
1506 if (appdomain == NULL)
1509 return appdomain->data;
1513 try_load_from (MonoAssembly **assembly, const gchar *path1, const gchar *path2,
1514 const gchar *path3, const gchar *path4,
1515 gboolean refonly, gboolean is_private)
1518 gboolean found = FALSE;
1521 fullpath = g_build_filename (path1, path2, path3, path4, NULL);
1523 if (IS_PORTABILITY_SET) {
1524 gchar *new_fullpath = mono_portability_find_file (fullpath, TRUE);
1527 fullpath = new_fullpath;
1531 found = g_file_test (fullpath, G_FILE_TEST_IS_REGULAR);
1534 *assembly = mono_assembly_open_full (fullpath, NULL, refonly);
1537 return (*assembly != NULL);
1540 static MonoAssembly *
1541 real_load (gchar **search_path, const gchar *culture, const gchar *name, gboolean refonly)
1543 MonoAssembly *result = NULL;
1546 const gchar *local_culture;
1548 gboolean is_private = FALSE;
1550 if (!culture || *culture == '\0') {
1553 local_culture = culture;
1556 filename = g_strconcat (name, ".dll", NULL);
1557 len = strlen (filename);
1559 for (path = search_path; *path; path++) {
1560 if (**path == '\0') {
1562 continue; /* Ignore empty ApplicationBase */
1565 /* See test cases in bug #58992 and bug #57710 */
1566 /* 1st try: [culture]/[name].dll (culture may be empty) */
1567 strcpy (filename + len - 4, ".dll");
1568 if (try_load_from (&result, *path, local_culture, "", filename, refonly, is_private))
1571 /* 2nd try: [culture]/[name].exe (culture may be empty) */
1572 strcpy (filename + len - 4, ".exe");
1573 if (try_load_from (&result, *path, local_culture, "", filename, refonly, is_private))
1576 /* 3rd try: [culture]/[name]/[name].dll (culture may be empty) */
1577 strcpy (filename + len - 4, ".dll");
1578 if (try_load_from (&result, *path, local_culture, name, filename, refonly, is_private))
1581 /* 4th try: [culture]/[name]/[name].exe (culture may be empty) */
1582 strcpy (filename + len - 4, ".exe");
1583 if (try_load_from (&result, *path, local_culture, name, filename, refonly, is_private))
1592 * Try loading the assembly from ApplicationBase and PrivateBinPath
1593 * and then from assemblies_path if any.
1594 * LOCKING: This is called from the assembly loading code, which means the caller
1595 * might hold the loader lock. Thus, this function must not acquire the domain lock.
1597 static MonoAssembly *
1598 mono_domain_assembly_preload (MonoAssemblyName *aname,
1599 gchar **assemblies_path,
1602 MonoDomain *domain = mono_domain_get ();
1603 MonoAssembly *result = NULL;
1604 gboolean refonly = GPOINTER_TO_UINT (user_data);
1606 set_domain_search_path (domain);
1608 if (domain->search_path && domain->search_path [0] != NULL) {
1609 result = real_load (domain->search_path, aname->culture, aname->name, refonly);
1612 if (result == NULL && assemblies_path && assemblies_path [0] != NULL) {
1613 result = real_load (assemblies_path, aname->culture, aname->name, refonly);
1620 * Check whenever a given assembly was already loaded in the current appdomain.
1622 static MonoAssembly *
1623 mono_domain_assembly_search (MonoAssemblyName *aname,
1626 MonoDomain *domain = mono_domain_get ();
1629 gboolean refonly = GPOINTER_TO_UINT (user_data);
1631 mono_domain_assemblies_lock (domain);
1632 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
1634 /* Dynamic assemblies can't match here in MS.NET */
1635 if (ass->dynamic || refonly != ass->ref_only || !mono_assembly_names_equal (aname, &ass->aname))
1638 mono_domain_assemblies_unlock (domain);
1641 mono_domain_assemblies_unlock (domain);
1646 MonoReflectionAssembly *
1647 ves_icall_System_Reflection_Assembly_LoadFrom (MonoString *fname, MonoBoolean refOnly)
1649 MonoDomain *domain = mono_domain_get ();
1650 char *name, *filename;
1651 MonoImageOpenStatus status = MONO_IMAGE_OK;
1654 MONO_ARCH_SAVE_REGS;
1656 if (fname == NULL) {
1657 MonoException *exc = mono_get_exception_argument_null ("assemblyFile");
1658 mono_raise_exception (exc);
1661 name = filename = mono_string_to_utf8 (fname);
1663 ass = mono_assembly_open_full (filename, &status, refOnly);
1668 if (status == MONO_IMAGE_IMAGE_INVALID)
1669 exc = mono_get_exception_bad_image_format2 (NULL, fname);
1671 exc = mono_get_exception_file_not_found2 (NULL, fname);
1673 mono_raise_exception (exc);
1678 return mono_assembly_get_object (domain, ass);
1681 MonoReflectionAssembly *
1682 ves_icall_System_AppDomain_LoadAssemblyRaw (MonoAppDomain *ad,
1683 MonoArray *raw_assembly,
1684 MonoArray *raw_symbol_store, MonoObject *evidence,
1685 MonoBoolean refonly)
1688 MonoReflectionAssembly *refass = NULL;
1689 MonoDomain *domain = ad->data;
1690 MonoImageOpenStatus status;
1691 guint32 raw_assembly_len = mono_array_length (raw_assembly);
1692 MonoImage *image = mono_image_open_from_data_full (mono_array_addr (raw_assembly, gchar, 0), raw_assembly_len, TRUE, NULL, refonly);
1695 mono_raise_exception (mono_get_exception_bad_image_format (""));
1699 if (raw_symbol_store != NULL)
1700 mono_debug_open_image_from_memory (image, mono_array_addr (raw_symbol_store, guint8, 0), mono_array_length (raw_symbol_store));
1702 ass = mono_assembly_load_from_full (image, "", &status, refonly);
1706 mono_image_close (image);
1707 mono_raise_exception (mono_get_exception_bad_image_format (""));
1711 refass = mono_assembly_get_object (domain, ass);
1712 MONO_OBJECT_SETREF (refass, evidence, evidence);
1716 MonoReflectionAssembly *
1717 ves_icall_System_AppDomain_LoadAssembly (MonoAppDomain *ad, MonoString *assRef, MonoObject *evidence, MonoBoolean refOnly)
1719 MonoDomain *domain = ad->data;
1720 MonoImageOpenStatus status = MONO_IMAGE_OK;
1722 MonoAssemblyName aname;
1723 MonoReflectionAssembly *refass = NULL;
1727 MONO_ARCH_SAVE_REGS;
1729 g_assert (assRef != NULL);
1731 name = mono_string_to_utf8 (assRef);
1732 parsed = mono_assembly_name_parse (name, &aname);
1736 /* This is a parse error... */
1740 ass = mono_assembly_load_full_nosearch (&aname, NULL, &status, refOnly);
1741 mono_assembly_name_free (&aname);
1744 /* MS.NET doesn't seem to call the assembly resolve handler for refonly assemblies */
1746 refass = mono_try_assembly_resolve (domain, assRef, refOnly);
1755 refass = mono_assembly_get_object (domain, ass);
1757 MONO_OBJECT_SETREF (refass, evidence, evidence);
1762 ves_icall_System_AppDomain_InternalUnload (gint32 domain_id)
1764 MonoDomain * domain = mono_domain_get_by_id (domain_id);
1766 MONO_ARCH_SAVE_REGS;
1768 if (NULL == domain) {
1769 MonoException *exc = mono_get_exception_execution_engine ("Failed to unload domain, domain id not found");
1770 mono_raise_exception (exc);
1773 if (domain == mono_get_root_domain ()) {
1774 mono_raise_exception (mono_get_exception_cannot_unload_appdomain ("The default appdomain can not be unloaded."));
1779 * Unloading seems to cause problems when running NUnit/NAnt, hence
1782 if (g_getenv ("MONO_NO_UNLOAD"))
1785 mono_domain_unload (domain);
1789 ves_icall_System_AppDomain_InternalIsFinalizingForUnload (gint32 domain_id)
1791 MonoDomain *domain = mono_domain_get_by_id (domain_id);
1796 return mono_domain_is_unloading (domain);
1800 ves_icall_System_AppDomain_ExecuteAssembly (MonoAppDomain *ad,
1801 MonoReflectionAssembly *refass, MonoArray *args)
1806 MONO_ARCH_SAVE_REGS;
1809 image = refass->assembly->image;
1812 method = mono_get_method (image, mono_image_get_entry_point (image), NULL);
1815 g_error ("No entry point method found in %s", image->name);
1818 args = (MonoArray *) mono_array_new (ad->data, mono_defaults.string_class, 0);
1820 return mono_runtime_exec_main (method, (MonoArray *)args, NULL);
1824 ves_icall_System_AppDomain_GetIDFromDomain (MonoAppDomain * ad)
1826 MONO_ARCH_SAVE_REGS;
1828 return ad->data->domain_id;
1832 ves_icall_System_AppDomain_InternalSetDomain (MonoAppDomain *ad)
1834 MonoDomain *old_domain = mono_domain_get();
1836 MONO_ARCH_SAVE_REGS;
1838 if (!mono_domain_set (ad->data, FALSE))
1839 mono_raise_exception (mono_get_exception_appdomain_unloaded ());
1841 return old_domain->domain;
1845 ves_icall_System_AppDomain_InternalSetDomainByID (gint32 domainid)
1847 MonoDomain *current_domain = mono_domain_get ();
1848 MonoDomain *domain = mono_domain_get_by_id (domainid);
1850 MONO_ARCH_SAVE_REGS;
1852 if (!domain || !mono_domain_set (domain, FALSE))
1853 mono_raise_exception (mono_get_exception_appdomain_unloaded ());
1855 return current_domain->domain;
1859 ves_icall_System_AppDomain_InternalPushDomainRef (MonoAppDomain *ad)
1861 MONO_ARCH_SAVE_REGS;
1863 mono_thread_push_appdomain_ref (ad->data);
1867 ves_icall_System_AppDomain_InternalPushDomainRefByID (gint32 domain_id)
1869 MonoDomain *domain = mono_domain_get_by_id (domain_id);
1871 MONO_ARCH_SAVE_REGS;
1875 * Raise an exception to prevent the managed code from executing a pop
1878 mono_raise_exception (mono_get_exception_appdomain_unloaded ());
1880 mono_thread_push_appdomain_ref (domain);
1884 ves_icall_System_AppDomain_InternalPopDomainRef (void)
1886 MONO_ARCH_SAVE_REGS;
1888 mono_thread_pop_appdomain_ref ();
1892 ves_icall_System_AppDomain_InternalGetContext ()
1894 MONO_ARCH_SAVE_REGS;
1896 return mono_context_get ();
1900 ves_icall_System_AppDomain_InternalGetDefaultContext ()
1902 MONO_ARCH_SAVE_REGS;
1904 return mono_domain_get ()->default_context;
1908 ves_icall_System_AppDomain_InternalSetContext (MonoAppContext *mc)
1910 MonoAppContext *old_context = mono_context_get ();
1912 MONO_ARCH_SAVE_REGS;
1914 mono_context_set (mc);
1920 ves_icall_System_AppDomain_InternalGetProcessGuid (MonoString* newguid)
1922 MonoDomain* mono_root_domain = mono_get_root_domain ();
1923 mono_domain_lock (mono_root_domain);
1924 if (process_guid_set) {
1925 mono_domain_unlock (mono_root_domain);
1926 return mono_string_new_utf16 (mono_domain_get (), process_guid, sizeof(process_guid)/2);
1928 memcpy (process_guid, mono_string_chars(newguid), sizeof(process_guid));
1929 process_guid_set = TRUE;
1930 mono_domain_unlock (mono_root_domain);
1935 mono_domain_is_unloading (MonoDomain *domain)
1937 if (domain->state == MONO_APPDOMAIN_UNLOADING || domain->state == MONO_APPDOMAIN_UNLOADED)
1944 clear_cached_vtable (gpointer key, gpointer value, gpointer user_data)
1946 MonoClass *klass = (MonoClass*)key;
1947 MonoDomain *domain = (MonoDomain*)user_data;
1948 MonoClassRuntimeInfo *runtime_info;
1950 runtime_info = klass->runtime_info;
1951 if (runtime_info && runtime_info->max_domain >= domain->domain_id)
1952 runtime_info->domain_vtables [domain->domain_id] = NULL;
1955 typedef struct unload_data {
1957 char *failure_reason;
1961 static guint32 WINAPI
1962 unload_thread_main (void *arg)
1964 unload_data *data = (unload_data*)arg;
1965 MonoDomain *domain = data->domain;
1967 /* Have to attach to the runtime so shutdown can wait for this thread */
1968 mono_thread_attach (mono_get_root_domain ());
1971 * FIXME: Abort our parent thread last, so we can return a failure
1972 * indication if aborting times out.
1974 if (!mono_threads_abort_appdomain_threads (domain, -1)) {
1975 data->failure_reason = g_strdup_printf ("Aborting of threads in domain %s timed out.", domain->friendly_name);
1979 if (!mono_thread_pool_remove_domain_jobs (domain, -1)) {
1980 data->failure_reason = g_strdup_printf ("Cleanup of threadpool jobs of domain %s timed out.", domain->friendly_name);
1984 /* Finalize all finalizable objects in the doomed appdomain */
1985 if (!mono_domain_finalize (domain, -1)) {
1986 data->failure_reason = g_strdup_printf ("Finalization of domain %s timed out.", domain->friendly_name);
1990 /* Clear references to our vtables in class->runtime_info.
1991 * We also hold the loader lock because we're going to change
1992 * class->runtime_info.
1995 mono_loader_lock ();
1996 mono_domain_lock (domain);
1997 g_hash_table_foreach (domain->class_vtable_hash, clear_cached_vtable, domain);
1998 mono_domain_unlock (domain);
1999 mono_loader_unlock ();
2001 mono_threads_clear_cached_culture (domain);
2003 domain->state = MONO_APPDOMAIN_UNLOADED;
2005 /* printf ("UNLOADED %s.\n", domain->friendly_name); */
2007 /* remove from the handle table the items related to this domain */
2008 mono_gchandle_free_domain (domain);
2010 mono_domain_free (domain, FALSE);
2012 mono_gc_collect (mono_gc_max_generation ());
2018 * mono_domain_unload:
2019 * @domain: The domain to unload
2021 * Unloads an appdomain. Follows the process outlined in:
2022 * http://blogs.gotdotnet.com/cbrumme
2024 * If doing things the 'right' way is too hard or complex, we do it the
2025 * 'simple' way, which means do everything needed to avoid crashes and
2026 * memory leaks, but not much else.
2029 mono_domain_unload (MonoDomain *domain)
2031 HANDLE thread_handle;
2034 MonoAppDomainState prev_state;
2037 unload_data thread_data;
2038 MonoDomain *caller_domain = mono_domain_get ();
2040 /* printf ("UNLOAD STARTING FOR %s (%p) IN THREAD 0x%x.\n", domain->friendly_name, domain, GetCurrentThreadId ()); */
2042 /* Atomically change our state to UNLOADING */
2043 prev_state = InterlockedCompareExchange ((gint32*)&domain->state,
2044 MONO_APPDOMAIN_UNLOADING_START,
2045 MONO_APPDOMAIN_CREATED);
2046 if (prev_state != MONO_APPDOMAIN_CREATED) {
2047 switch (prev_state) {
2048 case MONO_APPDOMAIN_UNLOADING_START:
2049 case MONO_APPDOMAIN_UNLOADING:
2050 mono_raise_exception (mono_get_exception_cannot_unload_appdomain ("Appdomain is already being unloaded."));
2052 case MONO_APPDOMAIN_UNLOADED:
2053 mono_raise_exception (mono_get_exception_cannot_unload_appdomain ("Appdomain is already unloaded."));
2056 g_warning ("Incalid appdomain state %d", prev_state);
2057 g_assert_not_reached ();
2061 mono_debugger_event_unload_appdomain (domain);
2063 mono_domain_set (domain, FALSE);
2064 /* Notify OnDomainUnload listeners */
2065 method = mono_class_get_method_from_name (domain->domain->mbr.obj.vtable->klass, "DoDomainUnload", -1);
2069 mono_runtime_invoke (method, domain->domain, NULL, &exc);
2071 /* Roll back the state change */
2072 domain->state = MONO_APPDOMAIN_CREATED;
2073 mono_domain_set (caller_domain, FALSE);
2074 mono_raise_exception ((MonoException*)exc);
2077 thread_data.domain = domain;
2078 thread_data.failure_reason = NULL;
2080 /*The managed callback finished successfully, now we start tearing down the appdomain*/
2081 domain->state = MONO_APPDOMAIN_UNLOADING;
2083 * First we create a separate thread for unloading, since
2084 * we might have to abort some threads, including the current one.
2087 * If we create a non-suspended thread, the runtime will hang.
2089 * http://bugzilla.ximian.com/show_bug.cgi?id=27663
2092 thread_handle = mono_create_thread (NULL, 0, unload_thread_main, &thread_data, 0, &tid);
2094 thread_handle = mono_create_thread (NULL, 0, (LPTHREAD_START_ROUTINE)unload_thread_main, &thread_data, CREATE_SUSPENDED, &tid);
2095 if (thread_handle == NULL) {
2098 ResumeThread (thread_handle);
2101 /* Wait for the thread */
2102 while ((res = WaitForSingleObjectEx (thread_handle, INFINITE, TRUE) == WAIT_IO_COMPLETION)) {
2103 if (mono_thread_has_appdomain_ref (mono_thread_current (), domain) && (mono_thread_interruption_requested ()))
2104 /* The unload thread tries to abort us */
2105 /* The icall wrapper will execute the abort */
2106 CloseHandle (thread_handle);
2109 CloseHandle (thread_handle);
2111 mono_domain_set (caller_domain, FALSE);
2113 if (thread_data.failure_reason) {
2116 /* Roll back the state change */
2117 domain->state = MONO_APPDOMAIN_CREATED;
2119 g_warning ("%s", thread_data.failure_reason);
2121 ex = mono_get_exception_cannot_unload_appdomain (thread_data.failure_reason);
2123 g_free (thread_data.failure_reason);
2124 thread_data.failure_reason = NULL;
2126 mono_raise_exception (ex);