2 * appdomain.c: AppDomain functions
5 * Dietmar Maurer (dietmar@ximian.com)
7 * Gonzalo Paniagua Javier (gonzalo@ximian.com)
9 * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
10 * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
12 #undef ASSEMBLY_LOAD_DEBUG
21 #include <sys/types.h>
22 #ifdef HAVE_SYS_TIME_H
28 #ifdef HAVE_SYS_UTIME_H
29 #include <sys/utime.h>
33 #include <mono/metadata/gc-internal.h>
34 #include <mono/metadata/object.h>
35 #include <mono/metadata/domain-internals.h>
36 #include "mono/metadata/metadata-internals.h"
37 #include <mono/metadata/assembly.h>
38 #include <mono/metadata/exception.h>
39 #include <mono/metadata/threads.h>
40 #include <mono/metadata/socket-io.h>
41 #include <mono/metadata/tabledefs.h>
42 #include <mono/metadata/gc-internal.h>
43 #include <mono/metadata/mono-gc.h>
44 #include <mono/metadata/marshal.h>
45 #include <mono/metadata/monitor.h>
46 #include <mono/metadata/threadpool.h>
47 #include <mono/metadata/mono-debug.h>
48 #include <mono/metadata/attach.h>
49 #include <mono/metadata/file-io.h>
50 #include <mono/metadata/lock-tracer.h>
51 #include <mono/metadata/console-io.h>
52 #include <mono/metadata/threads-types.h>
53 #include <mono/utils/mono-uri.h>
54 #include <mono/utils/mono-logger.h>
55 #include <mono/utils/mono-path.h>
56 #include <mono/utils/mono-stdlib.h>
57 #include <mono/utils/mono-io-portability.h>
63 * This is the version number of the corlib-runtime interface. When
64 * making changes to this interface (by changing the layout
65 * of classes the runtime knows about, changing icall signature or
66 * semantics etc), increment this variable. Also increment the
67 * pair of this variable in mscorlib in:
68 * mcs/class/mscorlib/System/Environment.cs
70 * Changes which are already detected at runtime, like the addition
71 * of icalls, do not require an increment.
73 #define MONO_CORLIB_VERSION 74
78 int assemblybinding_count;
82 CRITICAL_SECTION mono_delegate_section;
85 /* Need to lock here because EGLIB has locking defined as no-ops, we can not depend on mono_strtod do the right locking */
86 /* Ideally this will be fixed in eglib */
87 CRITICAL_SECTION mono_strtod_mutex;
91 static gunichar2 process_guid [36];
92 static gboolean process_guid_set = FALSE;
94 static gboolean shutting_down = FALSE;
96 static gboolean no_exec = FALSE;
99 mono_domain_assembly_preload (MonoAssemblyName *aname,
100 gchar **assemblies_path,
103 static MonoAssembly *
104 mono_domain_assembly_search (MonoAssemblyName *aname,
107 static MonoAssembly *
108 mono_domain_assembly_postload_search (MonoAssemblyName *aname,
112 mono_domain_fire_assembly_load (MonoAssembly *assembly, gpointer user_data);
115 add_assemblies_to_domain (MonoDomain *domain, MonoAssembly *ass, GHashTable *hash);
117 static MonoAppDomain *
118 mono_domain_create_appdomain_internal (char *friendly_name, MonoAppDomainSetup *setup);
120 static MonoLoadFunc load_function = NULL;
123 mono_install_runtime_load (MonoLoadFunc func)
125 load_function = func;
129 mono_runtime_load (const char *filename, const char *runtime_version)
131 g_assert (load_function);
132 return load_function (filename, runtime_version);
136 * mono_runtime_set_no_exec:
138 * Instructs the runtime to operate in static mode, i.e. avoid/do not allow managed
139 * code execution. This is useful for running the AOT compiler on platforms which
140 * allow full-aot execution only.
141 * This should be called before mono_runtime_init ().
144 mono_runtime_set_no_exec (gboolean val)
150 mono_runtime_get_no_exec (void)
157 * @domain: domain returned by mono_init ()
159 * Initialize the core AppDomain: this function will run also some
160 * IL initialization code, so it needs the execution engine to be fully
163 * AppDomain.SetupInformation is set up in mono_runtime_exec_main, where
164 * we know the entry_assembly.
168 mono_runtime_init (MonoDomain *domain, MonoThreadStartCB start_cb,
169 MonoThreadAttachCB attach_cb)
171 MonoAppDomainSetup *setup;
176 mono_portability_helpers_init ();
178 mono_gc_base_init ();
179 mono_monitor_init ();
180 mono_thread_pool_init ();
181 mono_marshal_init ();
183 mono_install_assembly_preload_hook (mono_domain_assembly_preload, GUINT_TO_POINTER (FALSE));
184 mono_install_assembly_refonly_preload_hook (mono_domain_assembly_preload, GUINT_TO_POINTER (TRUE));
185 mono_install_assembly_search_hook (mono_domain_assembly_search, GUINT_TO_POINTER (FALSE));
186 mono_install_assembly_refonly_search_hook (mono_domain_assembly_search, GUINT_TO_POINTER (TRUE));
187 mono_install_assembly_postload_search_hook (mono_domain_assembly_postload_search, GUINT_TO_POINTER (FALSE));
188 mono_install_assembly_postload_refonly_search_hook (mono_domain_assembly_postload_search, GUINT_TO_POINTER (TRUE));
189 mono_install_assembly_load_hook (mono_domain_fire_assembly_load, NULL);
190 mono_install_lookup_dynamic_token (mono_reflection_lookup_dynamic_token);
192 mono_thread_init (start_cb, attach_cb);
194 class = mono_class_from_name (mono_defaults.corlib, "System", "AppDomainSetup");
195 setup = (MonoAppDomainSetup *) mono_object_new (domain, class);
197 class = mono_class_from_name (mono_defaults.corlib, "System", "AppDomain");
198 ad = (MonoAppDomain *) mono_object_new (domain, class);
201 domain->setup = setup;
203 InitializeCriticalSection (&mono_delegate_section);
206 /* Needed until EGLIB is fixed #464316 */
207 InitializeCriticalSection (&mono_strtod_mutex);
210 mono_thread_attach (domain);
211 mono_context_init (domain);
212 mono_context_set (domain->default_context);
214 mono_type_initialization_init ();
216 if (!mono_runtime_get_no_exec ()) {
218 * Create an instance early since we can't do it when there is no memory.
220 arg = mono_string_new (domain, "Out of memory");
221 domain->out_of_memory_ex = mono_exception_from_name_two_strings (mono_defaults.corlib, "System", "OutOfMemoryException", arg, NULL);
224 * These two are needed because the signal handlers might be executing on
225 * an alternate stack, and Boehm GC can't handle that.
227 arg = mono_string_new (domain, "A null value was found where an object instance was required");
228 domain->null_reference_ex = mono_exception_from_name_two_strings (mono_defaults.corlib, "System", "NullReferenceException", arg, NULL);
229 arg = mono_string_new (domain, "The requested operation caused a stack overflow.");
230 domain->stack_overflow_ex = mono_exception_from_name_two_strings (mono_defaults.corlib, "System", "StackOverflowException", arg, NULL);
233 /* GC init has to happen after thread init */
236 #ifndef DISABLE_SOCKETS
237 mono_network_init ();
240 mono_console_init ();
243 mono_locks_tracer_init ();
245 /* mscorlib is loaded before we install the load hook */
246 mono_domain_fire_assembly_load (mono_defaults.corlib->assembly, NULL);
252 mono_get_corlib_version (void)
255 MonoClassField *field;
258 klass = mono_class_from_name (mono_defaults.corlib, "System", "Environment");
259 mono_class_init (klass);
260 field = mono_class_get_field_from_name (klass, "mono_corlib_version");
263 if (! (field->type->attrs & FIELD_ATTRIBUTE_STATIC))
265 value = mono_field_get_value_object (mono_domain_get (), field, NULL);
266 return *(gint32*)((gchar*)value + sizeof (MonoObject));
270 mono_check_corlib_version (void)
272 int version = mono_get_corlib_version ();
273 if (version != MONO_CORLIB_VERSION)
274 return g_strdup_printf ("expected corlib version %d, found %d.", MONO_CORLIB_VERSION, version);
280 mono_context_init (MonoDomain *domain)
283 MonoAppContext *context;
285 class = mono_class_from_name (mono_defaults.corlib, "System.Runtime.Remoting.Contexts", "Context");
286 context = (MonoAppContext *) mono_object_new (domain, class);
287 context->domain_id = domain->domain_id;
288 context->context_id = 0;
289 domain->default_context = context;
293 * mono_runtime_cleanup:
298 * This must not be called while there are still running threads executing
302 mono_runtime_cleanup (MonoDomain *domain)
304 shutting_down = TRUE;
306 mono_attach_cleanup ();
308 /* This ends up calling any pending pending (for at most 2 seconds) */
311 mono_thread_cleanup ();
313 #ifndef DISABLE_SOCKETS
314 mono_network_cleanup ();
316 mono_marshal_cleanup ();
318 mono_type_initialization_cleanup ();
320 mono_monitor_cleanup ();
322 #ifndef PLATFORM_WIN32
327 static MonoDomainFunc quit_function = NULL;
330 mono_install_runtime_cleanup (MonoDomainFunc func)
332 quit_function = func;
338 if (quit_function != NULL)
339 quit_function (mono_get_root_domain (), NULL);
343 * mono_runtime_set_shutting_down:
345 * Invoked by System.Environment.Exit to flag that the runtime
349 mono_runtime_set_shutting_down (void)
351 shutting_down = TRUE;
355 * mono_runtime_is_shutting_down:
357 * Returns whether the runtime has been flagged for shutdown.
359 * This is consumed by the P:System.Environment.HasShutdownStarted
364 mono_runtime_is_shutting_down (void)
366 return shutting_down;
370 * mono_domain_create_appdomain:
371 * @friendly_name: The friendly name of the appdomain to create
372 * @configuration_file: The configuration file to initialize the appdomain with
374 * Returns a MonoDomain initialized with the appdomain
377 mono_domain_create_appdomain (char *friendly_name, char *configuration_file)
380 MonoAppDomainSetup *setup;
383 class = mono_class_from_name (mono_defaults.corlib, "System", "AppDomainSetup");
384 setup = (MonoAppDomainSetup *) mono_object_new (mono_domain_get (), class);
385 setup->configuration_file = configuration_file != NULL ? mono_string_new (mono_domain_get (), configuration_file) : NULL;
387 ad = mono_domain_create_appdomain_internal (friendly_name, setup);
389 return mono_domain_from_appdomain (ad);
392 static MonoAppDomain *
393 mono_domain_create_appdomain_internal (char *friendly_name, MonoAppDomainSetup *setup)
401 adclass = mono_class_from_name (mono_defaults.corlib, "System", "AppDomain");
403 /* FIXME: pin all those objects */
404 data = mono_domain_create();
406 ad = (MonoAppDomain *) mono_object_new (data, adclass);
410 data->friendly_name = g_strdup (friendly_name);
411 // FIXME: The ctor runs in the current domain
412 // FIXME: Initialize null_reference_ex and stack_overflow_ex
413 data->out_of_memory_ex = mono_exception_from_name_domain (data, mono_defaults.corlib, "System", "OutOfMemoryException");
415 if (!setup->application_base) {
416 /* Inherit from the root domain since MS.NET does this */
417 MonoDomain *root = mono_get_root_domain ();
418 if (root->setup->application_base)
419 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)));
422 mono_context_init (data);
424 mono_set_private_bin_path_from_config (data);
426 add_assemblies_to_domain (data, mono_defaults.corlib->assembly, NULL);
432 * mono_domain_has_type_resolve:
433 * @domain: application domains being looked up
435 * Returns true if the AppDomain.TypeResolve field has been
439 mono_domain_has_type_resolve (MonoDomain *domain)
441 static MonoClassField *field = NULL;
445 field = mono_class_get_field_from_name (mono_defaults.appdomain_class, "TypeResolve");
449 mono_field_get_value ((MonoObject*)(domain->domain), field, &o);
454 * mono_domain_try_type_resolve:
455 * @domain: application domainwhere the name where the type is going to be resolved
456 * @name: the name of the type to resolve or NULL.
457 * @tb: A System.Reflection.Emit.TypeBuilder, used if name is NULL.
459 * This routine invokes the internal System.AppDomain.DoTypeResolve and returns
460 * the assembly that matches name.
462 * If @name is null, the value of ((TypeBuilder)tb).FullName is used instead
464 * Returns: A MonoReflectionAssembly or NULL if not found
466 MonoReflectionAssembly *
467 mono_domain_try_type_resolve (MonoDomain *domain, char *name, MonoObject *tb)
471 static MonoMethod *method = NULL;
473 g_assert (domain != NULL && ((name != NULL) || (tb != NULL)));
475 if (method == NULL) {
476 klass = domain->domain->mbr.obj.vtable->klass;
479 method = mono_class_get_method_from_name (klass, "DoTypeResolve", -1);
480 if (method == NULL) {
481 g_warning ("Method AppDomain.DoTypeResolve not found.\n");
487 *params = (MonoObject*)mono_string_new (mono_domain_get (), name);
490 return (MonoReflectionAssembly *) mono_runtime_invoke (method, domain->domain, params, NULL);
494 * mono_domain_owns_vtable_slot:
496 * Returns whenever VTABLE_SLOT is inside a vtable which belongs to DOMAIN.
499 mono_domain_owns_vtable_slot (MonoDomain *domain, gpointer vtable_slot)
503 mono_domain_lock (domain);
504 res = mono_mempool_contains_addr (domain->mp, vtable_slot);
505 mono_domain_unlock (domain);
512 * @force: force setting.
514 * Set the current appdomain to @domain. If @force is set, set it even
515 * if it is being unloaded.
519 * FALSE if the domain is unloaded
522 mono_domain_set (MonoDomain *domain, gboolean force)
524 if (!force && domain->state == MONO_APPDOMAIN_UNLOADED)
527 mono_domain_set_internal (domain);
533 ves_icall_System_AppDomain_GetData (MonoAppDomain *ad, MonoString *name)
541 g_assert (ad != NULL);
543 g_assert (add != NULL);
546 mono_raise_exception (mono_get_exception_argument_null ("name"));
548 str = mono_string_to_utf8 (name);
550 mono_domain_lock (add);
552 if (!strcmp (str, "APPBASE"))
553 o = (MonoObject *)add->setup->application_base;
554 else if (!strcmp (str, "APP_CONFIG_FILE"))
555 o = (MonoObject *)add->setup->configuration_file;
556 else if (!strcmp (str, "DYNAMIC_BASE"))
557 o = (MonoObject *)add->setup->dynamic_base;
558 else if (!strcmp (str, "APP_NAME"))
559 o = (MonoObject *)add->setup->application_name;
560 else if (!strcmp (str, "CACHE_BASE"))
561 o = (MonoObject *)add->setup->cache_path;
562 else if (!strcmp (str, "PRIVATE_BINPATH"))
563 o = (MonoObject *)add->setup->private_bin_path;
564 else if (!strcmp (str, "BINPATH_PROBE_ONLY"))
565 o = (MonoObject *)add->setup->private_bin_path_probe;
566 else if (!strcmp (str, "SHADOW_COPY_DIRS"))
567 o = (MonoObject *)add->setup->shadow_copy_directories;
568 else if (!strcmp (str, "FORCE_CACHE_INSTALL"))
569 o = (MonoObject *)add->setup->shadow_copy_files;
571 o = mono_g_hash_table_lookup (add->env, name);
573 mono_domain_unlock (add);
583 ves_icall_System_AppDomain_SetData (MonoAppDomain *ad, MonoString *name, MonoObject *data)
589 g_assert (ad != NULL);
591 g_assert (add != NULL);
594 mono_raise_exception (mono_get_exception_argument_null ("name"));
596 mono_domain_lock (add);
598 mono_g_hash_table_insert (add->env, name, data);
600 mono_domain_unlock (add);
604 ves_icall_System_AppDomain_getSetup (MonoAppDomain *ad)
608 g_assert (ad != NULL);
609 g_assert (ad->data != NULL);
611 return ad->data->setup;
615 ves_icall_System_AppDomain_getFriendlyName (MonoAppDomain *ad)
619 g_assert (ad != NULL);
620 g_assert (ad->data != NULL);
622 return mono_string_new (ad->data, ad->data->friendly_name);
626 ves_icall_System_AppDomain_getCurDomain ()
628 MonoDomain *add = mono_domain_get ();
636 ves_icall_System_AppDomain_getRootDomain ()
638 MonoDomain *root = mono_get_root_domain ();
646 get_attribute_value (const gchar **attribute_names,
647 const gchar **attribute_values,
648 const char *att_name)
651 for (n = 0; attribute_names [n] != NULL; n++) {
652 if (strcmp (attribute_names [n], att_name) == 0)
653 return g_strdup (attribute_values [n]);
659 start_element (GMarkupParseContext *context,
660 const gchar *element_name,
661 const gchar **attribute_names,
662 const gchar **attribute_values,
666 RuntimeConfig *runtime_config = user_data;
668 if (strcmp (element_name, "runtime") == 0) {
669 runtime_config->runtime_count++;
673 if (strcmp (element_name, "assemblyBinding") == 0) {
674 runtime_config->assemblybinding_count++;
678 if (runtime_config->runtime_count != 1 || runtime_config->assemblybinding_count != 1)
681 if (strcmp (element_name, "probing") != 0)
684 g_free (runtime_config->domain->private_bin_path);
685 runtime_config->domain->private_bin_path = get_attribute_value (attribute_names, attribute_values, "privatePath");
686 if (runtime_config->domain->private_bin_path && !runtime_config->domain->private_bin_path [0]) {
687 g_free (runtime_config->domain->private_bin_path);
688 runtime_config->domain->private_bin_path = NULL;
694 end_element (GMarkupParseContext *context,
695 const gchar *element_name,
699 RuntimeConfig *runtime_config = user_data;
700 if (strcmp (element_name, "runtime") == 0)
701 runtime_config->runtime_count--;
702 else if (strcmp (element_name, "assemblyBinding") == 0)
703 runtime_config->assemblybinding_count--;
706 static const GMarkupParser
716 mono_set_private_bin_path_from_config (MonoDomain *domain)
718 gchar *config_file, *text;
720 GMarkupParseContext *context;
721 RuntimeConfig runtime_config;
723 if (!domain || !domain->setup || !domain->setup->configuration_file)
726 config_file = mono_string_to_utf8 (domain->setup->configuration_file);
728 if (!g_file_get_contents (config_file, &text, &len, NULL)) {
729 g_free (config_file);
732 g_free (config_file);
734 runtime_config.runtime_count = 0;
735 runtime_config.assemblybinding_count = 0;
736 runtime_config.domain = domain;
738 context = g_markup_parse_context_new (&mono_parser, 0, &runtime_config, NULL);
739 if (g_markup_parse_context_parse (context, text, len, NULL))
740 g_markup_parse_context_end_parse (context, NULL);
741 g_markup_parse_context_free (context);
746 ves_icall_System_AppDomain_createDomain (MonoString *friendly_name, MonoAppDomainSetup *setup)
748 char *fname = mono_string_to_utf8 (friendly_name);
749 MonoAppDomain *ad = mono_domain_create_appdomain_internal (fname, setup);
757 ves_icall_System_AppDomain_GetAssemblies (MonoAppDomain *ad, MonoBoolean refonly)
759 MonoDomain *domain = ad->data;
761 static MonoClass *System_Reflection_Assembly;
765 GPtrArray *assemblies;
769 if (!System_Reflection_Assembly)
770 System_Reflection_Assembly = mono_class_from_name (
771 mono_defaults.corlib, "System.Reflection", "Assembly");
774 * Make a copy of the list of assemblies because we can't hold the assemblies
775 * lock while creating objects etc.
777 assemblies = g_ptr_array_new ();
778 /* Need to skip internal assembly builders created by remoting */
779 mono_domain_assemblies_lock (domain);
780 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
782 if (refonly && !ass->ref_only)
784 if (ass->corlib_internal)
786 g_ptr_array_add (assemblies, ass);
788 mono_domain_assemblies_unlock (domain);
790 res = mono_array_new (domain, System_Reflection_Assembly, assemblies->len);
791 for (i = 0; i < assemblies->len; ++i) {
792 ass = g_ptr_array_index (assemblies, i);
793 mono_array_setref (res, i, mono_assembly_get_object (domain, ass));
796 g_ptr_array_free (assemblies, TRUE);
801 MonoReflectionAssembly *
802 mono_try_assembly_resolve (MonoDomain *domain, MonoString *fname, gboolean refonly)
806 MonoBoolean isrefonly;
809 g_assert (domain != NULL && fname != NULL);
811 klass = domain->domain->mbr.obj.vtable->klass;
814 method = mono_class_get_method_from_name (klass, "DoAssemblyResolve", -1);
815 if (method == NULL) {
816 g_warning ("Method AppDomain.DoAssemblyResolve not found.\n");
820 isrefonly = refonly ? 1 : 0;
822 params [1] = &isrefonly;
823 return (MonoReflectionAssembly *) mono_runtime_invoke (method, domain->domain, params, NULL);
826 static MonoAssembly *
827 mono_domain_assembly_postload_search (MonoAssemblyName *aname,
830 gboolean refonly = GPOINTER_TO_UINT (user_data);
831 MonoReflectionAssembly *assembly;
832 MonoDomain *domain = mono_domain_get ();
835 aname_str = mono_stringify_assembly_name (aname);
837 /* FIXME: We invoke managed code here, so there is a potential for deadlocks */
838 assembly = mono_try_assembly_resolve (domain, mono_string_new (domain, aname_str), refonly);
843 return assembly->assembly;
849 * LOCKING: assumes assemblies_lock in the domain is already locked.
852 add_assemblies_to_domain (MonoDomain *domain, MonoAssembly *ass, GHashTable *ht)
856 gboolean destroy_ht = FALSE;
858 if (!ass->aname.name)
862 ht = g_hash_table_new (mono_aligned_addr_hash, NULL);
866 /* FIXME: handle lazy loaded assemblies */
867 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
868 g_hash_table_insert (ht, tmp->data, tmp->data);
870 if (!g_hash_table_lookup (ht, ass)) {
871 mono_assembly_addref (ass);
872 g_hash_table_insert (ht, ass, ass);
873 domain->domain_assemblies = g_slist_prepend (domain->domain_assemblies, ass);
874 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);
877 if (ass->image->references) {
878 for (i = 0; ass->image->references [i] != NULL; i++) {
879 if (ass->image->references [i] != REFERENCE_MISSING)
880 if (!g_hash_table_lookup (ht, ass->image->references [i])) {
881 add_assemblies_to_domain (domain, ass->image->references [i], ht);
886 g_hash_table_destroy (ht);
890 mono_domain_fire_assembly_load (MonoAssembly *assembly, gpointer user_data)
892 static MonoClassField *assembly_load_field;
893 static MonoMethod *assembly_load_method;
894 MonoDomain *domain = mono_domain_get ();
895 MonoReflectionAssembly *ref_assembly;
901 /* This can happen during startup */
903 #ifdef ASSEMBLY_LOAD_DEBUG
904 fprintf (stderr, "Loading %s into domain %s\n", assembly->aname.name, domain->friendly_name);
906 klass = domain->domain->mbr.obj.vtable->klass;
908 mono_domain_assemblies_lock (domain);
909 add_assemblies_to_domain (domain, assembly, NULL);
910 mono_domain_assemblies_unlock (domain);
912 if (assembly_load_field == NULL) {
913 assembly_load_field = mono_class_get_field_from_name (klass, "AssemblyLoad");
914 g_assert (assembly_load_field);
917 mono_field_get_value ((MonoObject*) domain->domain, assembly_load_field, &load_value);
918 if (load_value == NULL) {
919 /* No events waiting to be triggered */
923 ref_assembly = mono_assembly_get_object (domain, assembly);
924 g_assert (ref_assembly);
926 if (assembly_load_method == NULL) {
927 assembly_load_method = mono_class_get_method_from_name (klass, "DoAssemblyLoad", -1);
928 g_assert (assembly_load_method);
931 *params = ref_assembly;
932 mono_runtime_invoke (assembly_load_method, domain->domain, params, NULL);
936 * LOCKING: Acquires the domain assemblies lock.
939 set_domain_search_path (MonoDomain *domain)
941 MonoAppDomainSetup *setup;
943 gchar *search_path = NULL;
946 gchar **pvt_split = NULL;
947 GError *error = NULL;
948 gint appbaselen = -1;
951 * We use the low-level domain assemblies lock, since this is called from
952 * assembly loads hooks, which means this thread might hold the loader lock.
954 mono_domain_assemblies_lock (domain);
956 if (!domain->setup) {
957 mono_domain_assemblies_unlock (domain);
961 if ((domain->search_path != NULL) && !domain->setup->path_changed) {
962 mono_domain_assemblies_unlock (domain);
965 setup = domain->setup;
966 if (!setup->application_base) {
967 mono_domain_assemblies_unlock (domain);
968 return; /* Must set application base to get private path working */
973 if (setup->private_bin_path)
974 search_path = mono_string_to_utf8 (setup->private_bin_path);
976 if (domain->private_bin_path) {
977 if (search_path == NULL)
978 search_path = domain->private_bin_path;
980 gchar *tmp2 = search_path;
981 search_path = g_strjoin (";", search_path, domain->private_bin_path, NULL);
988 * As per MSDN documentation, AppDomainSetup.PrivateBinPath contains a list of
989 * directories relative to ApplicationBase separated by semicolons (see
990 * http://msdn2.microsoft.com/en-us/library/system.appdomainsetup.privatebinpath.aspx)
991 * The loop below copes with the fact that some Unix applications may use ':' (or
992 * System.IO.Path.PathSeparator) as the path search separator. We replace it with
993 * ';' for the subsequent split.
995 * The issue was reported in bug #81446
998 #ifndef PLATFORM_WIN32
1001 slen = strlen (search_path);
1002 for (i = 0; i < slen; i++)
1003 if (search_path [i] == ':')
1004 search_path [i] = ';';
1007 pvt_split = g_strsplit (search_path, ";", 1000);
1008 g_free (search_path);
1009 for (tmp = pvt_split; *tmp; tmp++, npaths++);
1014 g_strfreev (pvt_split);
1016 * Don't do this because the first time is called, the domain
1017 * setup is not finished.
1019 * domain->search_path = g_malloc (sizeof (char *));
1020 * domain->search_path [0] = NULL;
1022 mono_domain_assemblies_unlock (domain);
1026 if (domain->search_path)
1027 g_strfreev (domain->search_path);
1029 domain->search_path = tmp = g_malloc ((npaths + 1) * sizeof (gchar *));
1030 tmp [npaths] = NULL;
1032 *tmp = mono_string_to_utf8 (setup->application_base);
1034 /* FIXME: is this needed? */
1035 if (strncmp (*tmp, "file://", 7) == 0) {
1041 uri = g_strdup_printf ("file:///%s", uri + 7);
1044 uri = mono_escape_uri_string (tmpuri);
1045 *tmp = g_filename_from_uri (uri, NULL, &error);
1051 if (error != NULL) {
1052 g_warning ("%s\n", error->message);
1053 g_error_free (error);
1060 for (i = 1; pvt_split && i < npaths; i++) {
1061 if (g_path_is_absolute (pvt_split [i - 1])) {
1062 tmp [i] = g_strdup (pvt_split [i - 1]);
1064 tmp [i] = g_build_filename (tmp [0], pvt_split [i - 1], NULL);
1067 if (strchr (tmp [i], '.')) {
1071 reduced = mono_path_canonicalize (tmp [i]);
1072 if (appbaselen == -1)
1073 appbaselen = strlen (tmp [0]);
1075 if (strncmp (tmp [0], reduced, appbaselen)) {
1078 tmp [i] = g_strdup ("");
1088 if (setup->private_bin_path_probe != NULL) {
1090 tmp [0] = g_strdup ("");
1093 domain->setup->path_changed = FALSE;
1095 g_strfreev (pvt_split);
1097 mono_domain_assemblies_unlock (domain);
1100 #ifdef DISABLE_SHADOW_COPY
1102 mono_is_shadow_copy_enabled (MonoDomain *domain, const gchar *dir_name)
1108 mono_make_shadow_copy (const char *filename)
1110 return (char *) filename;
1114 shadow_copy_sibling (gchar *src, gint srclen, const char *extension, gchar *target, gint targetlen, gint tail_len)
1116 guint16 *orig, *dest;
1117 gboolean copy_result;
1119 strcpy (src + srclen - tail_len, extension);
1120 if (!g_file_test (src, G_FILE_TEST_IS_REGULAR))
1122 orig = g_utf8_to_utf16 (src, strlen (src), NULL, NULL, NULL);
1124 strcpy (target + targetlen - tail_len, extension);
1125 dest = g_utf8_to_utf16 (target, strlen (target), NULL, NULL, NULL);
1128 copy_result = CopyFile (orig, dest, FALSE);
1136 get_cstring_hash (const char *str)
1142 if (!str || !str [0])
1147 for (i = 0; i < len; i++) {
1148 h = (h << 5) - h + *p;
1156 get_shadow_assembly_location_base (MonoDomain *domain)
1158 MonoAppDomainSetup *setup;
1159 char *cache_path, *appname;
1163 setup = domain->setup;
1164 if (setup->cache_path != NULL && setup->application_name != NULL) {
1165 cache_path = mono_string_to_utf8 (setup->cache_path);
1166 #ifndef PLATFORM_WIN32
1169 for (i = strlen (cache_path) - 1; i >= 0; i--)
1170 if (cache_path [i] == '\\')
1171 cache_path [i] = '/';
1175 appname = mono_string_to_utf8 (setup->application_name);
1176 location = g_build_filename (cache_path, appname, "assembly", "shadow", NULL);
1178 g_free (cache_path);
1180 userdir = g_strdup_printf ("%s-mono-cachepath", g_get_user_name ());
1181 location = g_build_filename (g_get_tmp_dir (), userdir, "assembly", "shadow", NULL);
1188 get_shadow_assembly_location (const char *filename)
1190 gint32 hash = 0, hash2 = 0;
1192 char path_hash [30];
1193 char *bname = g_path_get_basename (filename);
1194 char *dirname = g_path_get_dirname (filename);
1195 char *location, *tmploc;
1196 MonoDomain *domain = mono_domain_get ();
1198 hash = get_cstring_hash (bname);
1199 hash2 = get_cstring_hash (dirname);
1200 g_snprintf (name_hash, sizeof (name_hash), "%08x", hash);
1201 g_snprintf (path_hash, sizeof (path_hash), "%08x_%08x_%08x", hash ^ hash2, hash2, domain->shadow_serial);
1202 tmploc = get_shadow_assembly_location_base (domain);
1203 location = g_build_filename (tmploc, name_hash, path_hash, bname, NULL);
1211 ensure_directory_exists (const char *filename)
1213 #ifdef PLATFORM_WIN32
1214 gchar *dir_utf8 = g_path_get_dirname (filename);
1216 gunichar2 *dir_utf16 = NULL;
1219 if (!dir_utf8 || !dir_utf8 [0])
1222 dir_utf16 = g_utf8_to_utf16 (dir_utf8, strlen (dir_utf8), NULL, NULL, NULL);
1230 /* make life easy and only use one directory seperator */
1241 while (*p++ != '\\')
1247 p = wcschr (p, '\\');
1250 retval = _wmkdir (dir_utf16);
1251 if (retval != 0 && errno != EEXIST) {
1264 gchar *dir = g_path_get_dirname (filename);
1268 if (!dir || !dir [0]) {
1273 if (stat (dir, &sbuf) == 0 && S_ISDIR (sbuf.st_mode)) {
1283 p = strchr (p, '/');
1286 retval = mkdir (dir, 0777);
1287 if (retval != 0 && errno != EEXIST) {
1302 private_file_needs_copying (const char *src, struct stat *sbuf_src, char *dest)
1304 struct stat sbuf_dest;
1306 if (stat (src, sbuf_src) == -1 || stat (dest, &sbuf_dest) == -1)
1309 if (sbuf_src->st_mode == sbuf_dest.st_mode &&
1310 sbuf_src->st_size == sbuf_dest.st_size &&
1311 sbuf_src->st_mtime == sbuf_dest.st_mtime)
1318 shadow_copy_create_ini (const char *shadow, const char *filename)
1328 dir_name = g_path_get_dirname (shadow);
1329 ini_file = g_build_filename (dir_name, "__AssemblyInfo__.ini", NULL);
1331 if (g_file_test (ini_file, G_FILE_TEST_IS_REGULAR)) {
1336 u16_ini = g_utf8_to_utf16 (ini_file, strlen (ini_file), NULL, NULL, NULL);
1341 handle = CreateFile (u16_ini, GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE,
1342 NULL, CREATE_NEW, FileAttributes_Normal, NULL);
1344 if (handle == INVALID_HANDLE_VALUE) {
1348 full_path = mono_path_resolve_symlinks (filename);
1349 result = WriteFile (handle, full_path, strlen (full_path), &n, NULL);
1351 CloseHandle (handle);
1356 mono_is_shadow_copy_enabled (MonoDomain *domain, const gchar *dir_name)
1358 const char *version;
1359 MonoAppDomainSetup *setup;
1362 gchar **directories;
1363 gchar *shadow_status_string;
1365 gboolean shadow_enabled;
1366 gboolean found = FALSE;
1371 setup = domain->setup;
1372 if (setup == NULL || setup->shadow_copy_files == NULL)
1375 version = mono_get_runtime_info ()->framework_version;
1376 shadow_status_string = mono_string_to_utf8 (setup->shadow_copy_files);
1377 /* For 1.x, not NULL is enough. In 2.0 it has to be "true" */
1378 shadow_enabled = (*version <= '1' || !g_ascii_strncasecmp (shadow_status_string, "true", 4));
1379 g_free (shadow_status_string);
1380 if (!shadow_enabled)
1383 if (setup->shadow_copy_directories == NULL)
1386 /* Is dir_name a shadow_copy destination already? */
1387 base_dir = get_shadow_assembly_location_base (domain);
1388 if (strstr (dir_name, base_dir)) {
1394 all_dirs = mono_string_to_utf8 (setup->shadow_copy_directories);
1395 directories = g_strsplit (all_dirs, G_SEARCHPATH_SEPARATOR_S, 1000);
1396 dir_ptr = directories;
1398 if (**dir_ptr != '\0' && !strcmp (*dir_ptr, dir_name)) {
1404 g_strfreev (directories);
1410 mono_make_shadow_copy (const char *filename)
1412 gchar *sibling_source, *sibling_target;
1413 gint sibling_source_len, sibling_target_len;
1414 guint16 *orig, *dest;
1416 gboolean copy_result;
1418 struct stat src_sbuf;
1419 struct utimbuf utbuf;
1420 char *dir_name = g_path_get_dirname (filename);
1421 MonoDomain *domain = mono_domain_get ();
1424 set_domain_search_path (domain);
1426 if (!mono_is_shadow_copy_enabled (domain, dir_name)) {
1428 return (char *) filename;
1430 /* Is dir_name a shadow_copy destination already? */
1431 shadow_dir = get_shadow_assembly_location_base (domain);
1432 if (strstr (dir_name, shadow_dir)) {
1433 g_free (shadow_dir);
1435 return (char *) filename;
1437 g_free (shadow_dir);
1440 shadow = get_shadow_assembly_location (filename);
1441 if (ensure_directory_exists (shadow) == FALSE) {
1443 exc = mono_get_exception_execution_engine ("Failed to create shadow copy (ensure directory exists).");
1444 mono_raise_exception (exc);
1447 if (!private_file_needs_copying (filename, &src_sbuf, shadow))
1448 return (char*) shadow;
1450 orig = g_utf8_to_utf16 (filename, strlen (filename), NULL, NULL, NULL);
1451 dest = g_utf8_to_utf16 (shadow, strlen (shadow), NULL, NULL, NULL);
1453 copy_result = CopyFile (orig, dest, FALSE);
1457 if (copy_result == FALSE) {
1459 exc = mono_get_exception_execution_engine ("Failed to create shadow copy (CopyFile).");
1460 mono_raise_exception (exc);
1463 /* attempt to copy .mdb, .config if they exist */
1464 sibling_source = g_strconcat (filename, ".config", NULL);
1465 sibling_source_len = strlen (sibling_source);
1466 sibling_target = g_strconcat (shadow, ".config", NULL);
1467 sibling_target_len = strlen (sibling_target);
1469 copy_result = shadow_copy_sibling (sibling_source, sibling_source_len, ".mdb", sibling_target, sibling_target_len, 7);
1470 if (copy_result == TRUE)
1471 copy_result = shadow_copy_sibling (sibling_source, sibling_source_len, ".config", sibling_target, sibling_target_len, 7);
1473 g_free (sibling_source);
1474 g_free (sibling_target);
1476 if (copy_result == FALSE) {
1478 exc = mono_get_exception_execution_engine ("Failed to create shadow copy of sibling data (CopyFile).");
1479 mono_raise_exception (exc);
1482 /* Create a .ini file containing the original assembly location */
1483 if (!shadow_copy_create_ini (shadow, filename)) {
1485 exc = mono_get_exception_execution_engine ("Failed to create shadow copy .ini file.");
1486 mono_raise_exception (exc);
1489 utbuf.actime = src_sbuf.st_atime;
1490 utbuf.modtime = src_sbuf.st_mtime;
1491 utime (shadow, &utbuf);
1495 #endif /* DISABLE_SHADOW_COPY */
1498 mono_domain_from_appdomain (MonoAppDomain *appdomain)
1500 if (appdomain == NULL)
1503 return appdomain->data;
1507 try_load_from (MonoAssembly **assembly, const gchar *path1, const gchar *path2,
1508 const gchar *path3, const gchar *path4,
1509 gboolean refonly, gboolean is_private)
1512 gboolean found = FALSE;
1515 fullpath = g_build_filename (path1, path2, path3, path4, NULL);
1517 if (IS_PORTABILITY_SET) {
1518 gchar *new_fullpath = mono_portability_find_file (fullpath, TRUE);
1521 fullpath = new_fullpath;
1525 found = g_file_test (fullpath, G_FILE_TEST_IS_REGULAR);
1528 *assembly = mono_assembly_open_full (fullpath, NULL, refonly);
1531 return (*assembly != NULL);
1534 static MonoAssembly *
1535 real_load (gchar **search_path, const gchar *culture, const gchar *name, gboolean refonly)
1537 MonoAssembly *result = NULL;
1540 const gchar *local_culture;
1542 gboolean is_private = FALSE;
1544 if (!culture || *culture == '\0') {
1547 local_culture = culture;
1550 filename = g_strconcat (name, ".dll", NULL);
1551 len = strlen (filename);
1553 for (path = search_path; *path; path++) {
1554 if (**path == '\0') {
1556 continue; /* Ignore empty ApplicationBase */
1559 /* See test cases in bug #58992 and bug #57710 */
1560 /* 1st try: [culture]/[name].dll (culture may be empty) */
1561 strcpy (filename + len - 4, ".dll");
1562 if (try_load_from (&result, *path, local_culture, "", filename, refonly, is_private))
1565 /* 2nd try: [culture]/[name].exe (culture may be empty) */
1566 strcpy (filename + len - 4, ".exe");
1567 if (try_load_from (&result, *path, local_culture, "", filename, refonly, is_private))
1570 /* 3rd try: [culture]/[name]/[name].dll (culture may be empty) */
1571 strcpy (filename + len - 4, ".dll");
1572 if (try_load_from (&result, *path, local_culture, name, filename, refonly, is_private))
1575 /* 4th try: [culture]/[name]/[name].exe (culture may be empty) */
1576 strcpy (filename + len - 4, ".exe");
1577 if (try_load_from (&result, *path, local_culture, name, filename, refonly, is_private))
1586 * Try loading the assembly from ApplicationBase and PrivateBinPath
1587 * and then from assemblies_path if any.
1588 * LOCKING: This is called from the assembly loading code, which means the caller
1589 * might hold the loader lock. Thus, this function must not acquire the domain lock.
1591 static MonoAssembly *
1592 mono_domain_assembly_preload (MonoAssemblyName *aname,
1593 gchar **assemblies_path,
1596 MonoDomain *domain = mono_domain_get ();
1597 MonoAssembly *result = NULL;
1598 gboolean refonly = GPOINTER_TO_UINT (user_data);
1600 set_domain_search_path (domain);
1602 if (domain->search_path && domain->search_path [0] != NULL) {
1603 result = real_load (domain->search_path, aname->culture, aname->name, refonly);
1606 if (result == NULL && assemblies_path && assemblies_path [0] != NULL) {
1607 result = real_load (assemblies_path, aname->culture, aname->name, refonly);
1614 * Check whenever a given assembly was already loaded in the current appdomain.
1616 static MonoAssembly *
1617 mono_domain_assembly_search (MonoAssemblyName *aname,
1620 MonoDomain *domain = mono_domain_get ();
1623 gboolean refonly = GPOINTER_TO_UINT (user_data);
1625 mono_domain_assemblies_lock (domain);
1626 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
1628 /* Dynamic assemblies can't match here in MS.NET */
1629 if (ass->dynamic || refonly != ass->ref_only || !mono_assembly_names_equal (aname, &ass->aname))
1632 mono_domain_assemblies_unlock (domain);
1635 mono_domain_assemblies_unlock (domain);
1640 MonoReflectionAssembly *
1641 ves_icall_System_Reflection_Assembly_LoadFrom (MonoString *fname, MonoBoolean refOnly)
1643 MonoDomain *domain = mono_domain_get ();
1644 char *name, *filename;
1645 MonoImageOpenStatus status = MONO_IMAGE_OK;
1648 MONO_ARCH_SAVE_REGS;
1650 if (fname == NULL) {
1651 MonoException *exc = mono_get_exception_argument_null ("assemblyFile");
1652 mono_raise_exception (exc);
1655 name = filename = mono_string_to_utf8 (fname);
1657 ass = mono_assembly_open_full (filename, &status, refOnly);
1662 if (status == MONO_IMAGE_IMAGE_INVALID)
1663 exc = mono_get_exception_bad_image_format2 (NULL, fname);
1665 exc = mono_get_exception_file_not_found2 (NULL, fname);
1667 mono_raise_exception (exc);
1672 return mono_assembly_get_object (domain, ass);
1675 MonoReflectionAssembly *
1676 ves_icall_System_AppDomain_LoadAssemblyRaw (MonoAppDomain *ad,
1677 MonoArray *raw_assembly,
1678 MonoArray *raw_symbol_store, MonoObject *evidence,
1679 MonoBoolean refonly)
1682 MonoReflectionAssembly *refass = NULL;
1683 MonoDomain *domain = ad->data;
1684 MonoImageOpenStatus status;
1685 guint32 raw_assembly_len = mono_array_length (raw_assembly);
1686 MonoImage *image = mono_image_open_from_data_full (mono_array_addr (raw_assembly, gchar, 0), raw_assembly_len, TRUE, NULL, refonly);
1689 mono_raise_exception (mono_get_exception_bad_image_format (""));
1693 if (raw_symbol_store != NULL)
1694 mono_debug_open_image_from_memory (image, mono_array_addr (raw_symbol_store, guint8, 0), mono_array_length (raw_symbol_store));
1696 ass = mono_assembly_load_from_full (image, "", &status, refonly);
1700 mono_image_close (image);
1701 mono_raise_exception (mono_get_exception_bad_image_format (""));
1705 refass = mono_assembly_get_object (domain, ass);
1706 MONO_OBJECT_SETREF (refass, evidence, evidence);
1710 MonoReflectionAssembly *
1711 ves_icall_System_AppDomain_LoadAssembly (MonoAppDomain *ad, MonoString *assRef, MonoObject *evidence, MonoBoolean refOnly)
1713 MonoDomain *domain = ad->data;
1714 MonoImageOpenStatus status = MONO_IMAGE_OK;
1716 MonoAssemblyName aname;
1717 MonoReflectionAssembly *refass = NULL;
1721 MONO_ARCH_SAVE_REGS;
1723 g_assert (assRef != NULL);
1725 name = mono_string_to_utf8 (assRef);
1726 parsed = mono_assembly_name_parse (name, &aname);
1730 /* This is a parse error... */
1734 ass = mono_assembly_load_full_nosearch (&aname, NULL, &status, refOnly);
1735 mono_assembly_name_free (&aname);
1738 /* MS.NET doesn't seem to call the assembly resolve handler for refonly assemblies */
1740 refass = mono_try_assembly_resolve (domain, assRef, refOnly);
1749 refass = mono_assembly_get_object (domain, ass);
1751 MONO_OBJECT_SETREF (refass, evidence, evidence);
1756 ves_icall_System_AppDomain_InternalUnload (gint32 domain_id)
1758 MonoDomain * domain = mono_domain_get_by_id (domain_id);
1760 MONO_ARCH_SAVE_REGS;
1762 if (NULL == domain) {
1763 MonoException *exc = mono_get_exception_execution_engine ("Failed to unload domain, domain id not found");
1764 mono_raise_exception (exc);
1767 if (domain == mono_get_root_domain ()) {
1768 mono_raise_exception (mono_get_exception_cannot_unload_appdomain ("The default appdomain can not be unloaded."));
1773 * Unloading seems to cause problems when running NUnit/NAnt, hence
1776 if (g_getenv ("MONO_NO_UNLOAD"))
1779 mono_domain_unload (domain);
1783 ves_icall_System_AppDomain_InternalIsFinalizingForUnload (gint32 domain_id)
1785 MonoDomain *domain = mono_domain_get_by_id (domain_id);
1790 return mono_domain_is_unloading (domain);
1794 ves_icall_System_AppDomain_ExecuteAssembly (MonoAppDomain *ad,
1795 MonoReflectionAssembly *refass, MonoArray *args)
1800 MONO_ARCH_SAVE_REGS;
1803 image = refass->assembly->image;
1806 method = mono_get_method (image, mono_image_get_entry_point (image), NULL);
1809 g_error ("No entry point method found in %s", image->name);
1812 args = (MonoArray *) mono_array_new (ad->data, mono_defaults.string_class, 0);
1814 return mono_runtime_exec_main (method, (MonoArray *)args, NULL);
1818 ves_icall_System_AppDomain_GetIDFromDomain (MonoAppDomain * ad)
1820 MONO_ARCH_SAVE_REGS;
1822 return ad->data->domain_id;
1826 ves_icall_System_AppDomain_InternalSetDomain (MonoAppDomain *ad)
1828 MonoDomain *old_domain = mono_domain_get();
1830 MONO_ARCH_SAVE_REGS;
1832 if (!mono_domain_set (ad->data, FALSE))
1833 mono_raise_exception (mono_get_exception_appdomain_unloaded ());
1835 return old_domain->domain;
1839 ves_icall_System_AppDomain_InternalSetDomainByID (gint32 domainid)
1841 MonoDomain *current_domain = mono_domain_get ();
1842 MonoDomain *domain = mono_domain_get_by_id (domainid);
1844 MONO_ARCH_SAVE_REGS;
1846 if (!domain || !mono_domain_set (domain, FALSE))
1847 mono_raise_exception (mono_get_exception_appdomain_unloaded ());
1849 return current_domain->domain;
1853 ves_icall_System_AppDomain_InternalPushDomainRef (MonoAppDomain *ad)
1855 MONO_ARCH_SAVE_REGS;
1857 mono_thread_push_appdomain_ref (ad->data);
1861 ves_icall_System_AppDomain_InternalPushDomainRefByID (gint32 domain_id)
1863 MonoDomain *domain = mono_domain_get_by_id (domain_id);
1865 MONO_ARCH_SAVE_REGS;
1869 * Raise an exception to prevent the managed code from executing a pop
1872 mono_raise_exception (mono_get_exception_appdomain_unloaded ());
1874 mono_thread_push_appdomain_ref (domain);
1878 ves_icall_System_AppDomain_InternalPopDomainRef (void)
1880 MONO_ARCH_SAVE_REGS;
1882 mono_thread_pop_appdomain_ref ();
1886 ves_icall_System_AppDomain_InternalGetContext ()
1888 MONO_ARCH_SAVE_REGS;
1890 return mono_context_get ();
1894 ves_icall_System_AppDomain_InternalGetDefaultContext ()
1896 MONO_ARCH_SAVE_REGS;
1898 return mono_domain_get ()->default_context;
1902 ves_icall_System_AppDomain_InternalSetContext (MonoAppContext *mc)
1904 MonoAppContext *old_context = mono_context_get ();
1906 MONO_ARCH_SAVE_REGS;
1908 mono_context_set (mc);
1914 ves_icall_System_AppDomain_InternalGetProcessGuid (MonoString* newguid)
1916 MonoDomain* mono_root_domain = mono_get_root_domain ();
1917 mono_domain_lock (mono_root_domain);
1918 if (process_guid_set) {
1919 mono_domain_unlock (mono_root_domain);
1920 return mono_string_new_utf16 (mono_domain_get (), process_guid, sizeof(process_guid)/2);
1922 memcpy (process_guid, mono_string_chars(newguid), sizeof(process_guid));
1923 process_guid_set = TRUE;
1924 mono_domain_unlock (mono_root_domain);
1929 mono_domain_is_unloading (MonoDomain *domain)
1931 if (domain->state == MONO_APPDOMAIN_UNLOADING || domain->state == MONO_APPDOMAIN_UNLOADED)
1938 clear_cached_vtable (gpointer key, gpointer value, gpointer user_data)
1940 MonoClass *klass = (MonoClass*)key;
1941 MonoDomain *domain = (MonoDomain*)user_data;
1942 MonoClassRuntimeInfo *runtime_info;
1944 runtime_info = klass->runtime_info;
1945 if (runtime_info && runtime_info->max_domain >= domain->domain_id)
1946 runtime_info->domain_vtables [domain->domain_id] = NULL;
1949 typedef struct unload_data {
1951 char *failure_reason;
1955 static guint32 WINAPI
1956 unload_thread_main (void *arg)
1958 unload_data *data = (unload_data*)arg;
1959 MonoDomain *domain = data->domain;
1961 /* Have to attach to the runtime so shutdown can wait for this thread */
1962 mono_thread_attach (mono_get_root_domain ());
1965 * FIXME: Abort our parent thread last, so we can return a failure
1966 * indication if aborting times out.
1968 if (!mono_threads_abort_appdomain_threads (domain, -1)) {
1969 data->failure_reason = g_strdup_printf ("Aborting of threads in domain %s timed out.", domain->friendly_name);
1973 if (!mono_thread_pool_remove_domain_jobs (domain, -1)) {
1974 data->failure_reason = g_strdup_printf ("Cleanup of threadpool jobs of domain %s timed out.", domain->friendly_name);
1978 /* Finalize all finalizable objects in the doomed appdomain */
1979 if (!mono_domain_finalize (domain, -1)) {
1980 data->failure_reason = g_strdup_printf ("Finalization of domain %s timed out.", domain->friendly_name);
1984 /* Clear references to our vtables in class->runtime_info.
1985 * We also hold the loader lock because we're going to change
1986 * class->runtime_info.
1989 mono_loader_lock ();
1990 mono_domain_lock (domain);
1991 g_hash_table_foreach (domain->class_vtable_hash, clear_cached_vtable, domain);
1992 mono_domain_unlock (domain);
1993 mono_loader_unlock ();
1995 mono_threads_clear_cached_culture (domain);
1997 domain->state = MONO_APPDOMAIN_UNLOADED;
1999 /* printf ("UNLOADED %s.\n", domain->friendly_name); */
2001 /* remove from the handle table the items related to this domain */
2002 mono_gchandle_free_domain (domain);
2004 mono_domain_free (domain, FALSE);
2006 mono_gc_collect (mono_gc_max_generation ());
2012 * mono_domain_unload:
2013 * @domain: The domain to unload
2015 * Unloads an appdomain. Follows the process outlined in:
2016 * http://blogs.gotdotnet.com/cbrumme
2018 * If doing things the 'right' way is too hard or complex, we do it the
2019 * 'simple' way, which means do everything needed to avoid crashes and
2020 * memory leaks, but not much else.
2023 mono_domain_unload (MonoDomain *domain)
2025 HANDLE thread_handle;
2028 MonoAppDomainState prev_state;
2031 unload_data thread_data;
2032 MonoDomain *caller_domain = mono_domain_get ();
2034 /* printf ("UNLOAD STARTING FOR %s (%p) IN THREAD 0x%x.\n", domain->friendly_name, domain, GetCurrentThreadId ()); */
2036 /* Atomically change our state to UNLOADING */
2037 prev_state = InterlockedCompareExchange ((gint32*)&domain->state,
2038 MONO_APPDOMAIN_UNLOADING_START,
2039 MONO_APPDOMAIN_CREATED);
2040 if (prev_state != MONO_APPDOMAIN_CREATED) {
2041 switch (prev_state) {
2042 case MONO_APPDOMAIN_UNLOADING_START:
2043 case MONO_APPDOMAIN_UNLOADING:
2044 mono_raise_exception (mono_get_exception_cannot_unload_appdomain ("Appdomain is already being unloaded."));
2046 case MONO_APPDOMAIN_UNLOADED:
2047 mono_raise_exception (mono_get_exception_cannot_unload_appdomain ("Appdomain is already unloaded."));
2050 g_warning ("Incalid appdomain state %d", prev_state);
2051 g_assert_not_reached ();
2055 mono_domain_set (domain, FALSE);
2056 /* Notify OnDomainUnload listeners */
2057 method = mono_class_get_method_from_name (domain->domain->mbr.obj.vtable->klass, "DoDomainUnload", -1);
2061 mono_runtime_invoke (method, domain->domain, NULL, &exc);
2063 /* Roll back the state change */
2064 domain->state = MONO_APPDOMAIN_CREATED;
2065 mono_domain_set (caller_domain, FALSE);
2066 mono_raise_exception ((MonoException*)exc);
2069 thread_data.domain = domain;
2070 thread_data.failure_reason = NULL;
2072 /*The managed callback finished successfully, now we start tearing down the appdomain*/
2073 domain->state = MONO_APPDOMAIN_UNLOADING;
2075 * First we create a separate thread for unloading, since
2076 * we might have to abort some threads, including the current one.
2079 * If we create a non-suspended thread, the runtime will hang.
2081 * http://bugzilla.ximian.com/show_bug.cgi?id=27663
2084 thread_handle = mono_create_thread (NULL, 0, unload_thread_main, &thread_data, 0, &tid);
2086 thread_handle = mono_create_thread (NULL, 0, (LPTHREAD_START_ROUTINE)unload_thread_main, &thread_data, CREATE_SUSPENDED, &tid);
2087 if (thread_handle == NULL) {
2090 ResumeThread (thread_handle);
2093 /* Wait for the thread */
2094 while ((res = WaitForSingleObjectEx (thread_handle, INFINITE, TRUE) == WAIT_IO_COMPLETION)) {
2095 if (mono_thread_has_appdomain_ref (mono_thread_current (), domain) && (mono_thread_interruption_requested ()))
2096 /* The unload thread tries to abort us */
2097 /* The icall wrapper will execute the abort */
2098 CloseHandle (thread_handle);
2101 CloseHandle (thread_handle);
2103 mono_domain_set (caller_domain, FALSE);
2105 if (thread_data.failure_reason) {
2108 /* Roll back the state change */
2109 domain->state = MONO_APPDOMAIN_CREATED;
2111 g_warning ("%s", thread_data.failure_reason);
2113 ex = mono_get_exception_cannot_unload_appdomain (thread_data.failure_reason);
2115 g_free (thread_data.failure_reason);
2116 thread_data.failure_reason = NULL;
2118 mono_raise_exception (ex);