2 * appdomain.c: AppDomain functions
5 * Dietmar Maurer (dietmar@ximian.com)
7 * Gonzalo Paniagua Javier (gonzalo@ximian.com)
9 * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
10 * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
12 #undef ASSEMBLY_LOAD_DEBUG
21 #include <sys/types.h>
22 #ifdef HAVE_SYS_TIME_H
28 #ifdef HAVE_SYS_UTIME_H
29 #include <sys/utime.h>
33 #include <mono/metadata/gc-internal.h>
34 #include <mono/metadata/object.h>
35 #include <mono/metadata/domain-internals.h>
36 #include "mono/metadata/metadata-internals.h"
37 #include <mono/metadata/assembly.h>
38 #include <mono/metadata/exception.h>
39 #include <mono/metadata/threads.h>
40 #include <mono/metadata/socket-io.h>
41 #include <mono/metadata/tabledefs.h>
42 #include <mono/metadata/gc-internal.h>
43 #include <mono/metadata/mono-gc.h>
44 #include <mono/metadata/marshal.h>
45 #include <mono/metadata/monitor.h>
46 #include <mono/metadata/threadpool.h>
47 #include <mono/metadata/mono-debug.h>
48 #include <mono/metadata/attach.h>
49 #include <mono/metadata/file-io.h>
50 #include <mono/metadata/lock-tracer.h>
51 #include <mono/utils/mono-uri.h>
52 #include <mono/utils/mono-logger.h>
53 #include <mono/utils/mono-path.h>
54 #include <mono/utils/mono-stdlib.h>
55 #include <mono/utils/mono-io-portability.h>
61 * This is the version number of the corlib-runtime interface. When
62 * making changes to this interface (by changing the layout
63 * of classes the runtime knows about, changing icall signature or
64 * semantics etc), increment this variable. Also increment the
65 * pair of this variable in mscorlib in:
66 * mcs/class/mscorlib/System/Environment.cs
68 * Changes which are already detected at runtime, like the addition
69 * of icalls, do not require an increment.
71 #define MONO_CORLIB_VERSION 71
76 int assemblybinding_count
;
80 CRITICAL_SECTION mono_delegate_section
;
83 /* Need to lock here because EGLIB has locking defined as no-ops, we can not depend on mono_strtod do the right locking */
84 /* Ideally this will be fixed in eglib */
85 CRITICAL_SECTION mono_strtod_mutex
;
89 static gunichar2 process_guid
[36];
90 static gboolean process_guid_set
= FALSE
;
92 static gboolean shutting_down
= FALSE
;
94 static gboolean no_exec
= FALSE
;
97 mono_domain_assembly_preload (MonoAssemblyName
*aname
,
98 gchar
**assemblies_path
,
101 static MonoAssembly
*
102 mono_domain_assembly_search (MonoAssemblyName
*aname
,
105 static MonoAssembly
*
106 mono_domain_assembly_postload_search (MonoAssemblyName
*aname
,
110 mono_domain_fire_assembly_load (MonoAssembly
*assembly
, gpointer user_data
);
113 add_assemblies_to_domain (MonoDomain
*domain
, MonoAssembly
*ass
, GHashTable
*hash
);
115 static MonoAppDomain
*
116 mono_domain_create_appdomain_internal (char *friendly_name
, MonoAppDomainSetup
*setup
);
118 static MonoLoadFunc load_function
= NULL
;
121 mono_install_runtime_load (MonoLoadFunc func
)
123 load_function
= func
;
127 mono_runtime_load (const char *filename
, const char *runtime_version
)
129 g_assert (load_function
);
130 return load_function (filename
, runtime_version
);
134 * mono_runtime_set_no_exec:
136 * Instructs the runtime to operate in static mode, i.e. avoid/do not allow managed
137 * code execution. This is useful for running the AOT compiler on platforms which
138 * allow full-aot execution only.
139 * This should be called before mono_runtime_init ().
142 mono_runtime_set_no_exec (gboolean val
)
148 mono_runtime_get_no_exec (void)
155 * @domain: domain returned by mono_init ()
157 * Initialize the core AppDomain: this function will run also some
158 * IL initialization code, so it needs the execution engine to be fully
161 * AppDomain.SetupInformation is set up in mono_runtime_exec_main, where
162 * we know the entry_assembly.
166 mono_runtime_init (MonoDomain
*domain
, MonoThreadStartCB start_cb
,
167 MonoThreadAttachCB attach_cb
)
169 MonoAppDomainSetup
*setup
;
174 mono_portability_helpers_init ();
176 mono_gc_base_init ();
177 mono_monitor_init ();
178 mono_thread_pool_init ();
179 mono_marshal_init ();
181 mono_install_assembly_preload_hook (mono_domain_assembly_preload
, GUINT_TO_POINTER (FALSE
));
182 mono_install_assembly_refonly_preload_hook (mono_domain_assembly_preload
, GUINT_TO_POINTER (TRUE
));
183 mono_install_assembly_search_hook (mono_domain_assembly_search
, GUINT_TO_POINTER (FALSE
));
184 mono_install_assembly_refonly_search_hook (mono_domain_assembly_search
, GUINT_TO_POINTER (TRUE
));
185 mono_install_assembly_postload_search_hook (mono_domain_assembly_postload_search
, GUINT_TO_POINTER (FALSE
));
186 mono_install_assembly_postload_refonly_search_hook (mono_domain_assembly_postload_search
, GUINT_TO_POINTER (TRUE
));
187 mono_install_assembly_load_hook (mono_domain_fire_assembly_load
, NULL
);
188 mono_install_lookup_dynamic_token (mono_reflection_lookup_dynamic_token
);
190 mono_thread_init (start_cb
, attach_cb
);
192 class = mono_class_from_name (mono_defaults
.corlib
, "System", "AppDomainSetup");
193 setup
= (MonoAppDomainSetup
*) mono_object_new (domain
, class);
195 class = mono_class_from_name (mono_defaults
.corlib
, "System", "AppDomain");
196 ad
= (MonoAppDomain
*) mono_object_new (domain
, class);
199 domain
->setup
= setup
;
201 InitializeCriticalSection (&mono_delegate_section
);
204 /* Needed until EGLIB is fixed #464316 */
205 InitializeCriticalSection (&mono_strtod_mutex
);
208 mono_thread_attach (domain
);
209 mono_context_init (domain
);
210 mono_context_set (domain
->default_context
);
212 mono_type_initialization_init ();
214 if (!mono_runtime_get_no_exec ()) {
216 * Create an instance early since we can't do it when there is no memory.
218 arg
= mono_string_new (domain
, "Out of memory");
219 domain
->out_of_memory_ex
= mono_exception_from_name_two_strings (mono_defaults
.corlib
, "System", "OutOfMemoryException", arg
, NULL
);
222 * These two are needed because the signal handlers might be executing on
223 * an alternate stack, and Boehm GC can't handle that.
225 arg
= mono_string_new (domain
, "A null value was found where an object instance was required");
226 domain
->null_reference_ex
= mono_exception_from_name_two_strings (mono_defaults
.corlib
, "System", "NullReferenceException", arg
, NULL
);
227 arg
= mono_string_new (domain
, "The requested operation caused a stack overflow.");
228 domain
->stack_overflow_ex
= mono_exception_from_name_two_strings (mono_defaults
.corlib
, "System", "StackOverflowException", arg
, NULL
);
231 /* GC init has to happen after thread init */
234 #ifndef DISABLE_SOCKETS
235 mono_network_init ();
240 mono_locks_tracer_init ();
242 /* mscorlib is loaded before we install the load hook */
243 mono_domain_fire_assembly_load (mono_defaults
.corlib
->assembly
, NULL
);
249 mono_get_corlib_version (void)
252 MonoClassField
*field
;
255 klass
= mono_class_from_name (mono_defaults
.corlib
, "System", "Environment");
256 mono_class_init (klass
);
257 field
= mono_class_get_field_from_name (klass
, "mono_corlib_version");
260 if (! (field
->type
->attrs
& FIELD_ATTRIBUTE_STATIC
))
262 value
= mono_field_get_value_object (mono_domain_get (), field
, NULL
);
263 return *(gint32
*)((gchar
*)value
+ sizeof (MonoObject
));
267 mono_check_corlib_version (void)
269 int version
= mono_get_corlib_version ();
270 if (version
!= MONO_CORLIB_VERSION
)
271 return g_strdup_printf ("expected corlib version %d, found %d.", MONO_CORLIB_VERSION
, version
);
277 mono_context_init (MonoDomain
*domain
)
280 MonoAppContext
*context
;
282 class = mono_class_from_name (mono_defaults
.corlib
, "System.Runtime.Remoting.Contexts", "Context");
283 context
= (MonoAppContext
*) mono_object_new (domain
, class);
284 context
->domain_id
= domain
->domain_id
;
285 context
->context_id
= 0;
286 domain
->default_context
= context
;
290 * mono_runtime_cleanup:
295 * This must not be called while there are still running threads executing
299 mono_runtime_cleanup (MonoDomain
*domain
)
301 shutting_down
= TRUE
;
303 mono_attach_cleanup ();
305 /* This ends up calling any pending pending (for at most 2 seconds) */
308 mono_thread_cleanup ();
310 #ifndef DISABLE_SOCKETS
311 mono_network_cleanup ();
313 mono_marshal_cleanup ();
315 mono_type_initialization_cleanup ();
317 mono_monitor_cleanup ();
319 #ifndef PLATFORM_WIN32
324 static MonoDomainFunc quit_function
= NULL
;
327 mono_install_runtime_cleanup (MonoDomainFunc func
)
329 quit_function
= func
;
335 if (quit_function
!= NULL
)
336 quit_function (mono_get_root_domain (), NULL
);
340 * mono_runtime_set_shutting_down:
342 * Invoked by System.Environment.Exit to flag that the runtime
346 mono_runtime_set_shutting_down (void)
348 shutting_down
= TRUE
;
352 * mono_runtime_is_shutting_down:
354 * Returns whether the runtime has been flagged for shutdown.
356 * This is consumed by the P:System.Environment.HasShutdownStarted
361 mono_runtime_is_shutting_down (void)
363 return shutting_down
;
367 * mono_domain_create_appdomain:
368 * @friendly_name: The friendly name of the appdomain to create
369 * @configuration_file: The configuration file to initialize the appdomain with
371 * Returns a MonoDomain initialized with the appdomain
374 mono_domain_create_appdomain (char *friendly_name
, char *configuration_file
)
377 MonoAppDomainSetup
*setup
;
380 class = mono_class_from_name (mono_defaults
.corlib
, "System", "AppDomainSetup");
381 setup
= (MonoAppDomainSetup
*) mono_object_new (mono_domain_get (), class);
382 setup
->configuration_file
= configuration_file
!= NULL
? mono_string_new (mono_domain_get (), configuration_file
) : NULL
;
384 ad
= mono_domain_create_appdomain_internal (friendly_name
, setup
);
386 return mono_domain_from_appdomain (ad
);
389 static MonoAppDomain
*
390 mono_domain_create_appdomain_internal (char *friendly_name
, MonoAppDomainSetup
*setup
)
398 adclass
= mono_class_from_name (mono_defaults
.corlib
, "System", "AppDomain");
400 /* FIXME: pin all those objects */
401 data
= mono_domain_create();
403 ad
= (MonoAppDomain
*) mono_object_new (data
, adclass
);
407 data
->friendly_name
= g_strdup (friendly_name
);
408 // FIXME: The ctor runs in the current domain
409 // FIXME: Initialize null_reference_ex and stack_overflow_ex
410 data
->out_of_memory_ex
= mono_exception_from_name_domain (data
, mono_defaults
.corlib
, "System", "OutOfMemoryException");
412 if (!setup
->application_base
) {
413 /* Inherit from the root domain since MS.NET does this */
414 MonoDomain
*root
= mono_get_root_domain ();
415 if (root
->setup
->application_base
)
416 MONO_OBJECT_SETREF (setup
, application_base
, mono_string_new_utf16 (data
, mono_string_chars (root
->setup
->application_base
), mono_string_length (root
->setup
->application_base
)));
419 mono_context_init (data
);
421 mono_set_private_bin_path_from_config (data
);
423 add_assemblies_to_domain (data
, mono_defaults
.corlib
->assembly
, NULL
);
429 * mono_domain_has_type_resolve:
430 * @domain: application domains being looked up
432 * Returns true if the AppDomain.TypeResolve field has been
436 mono_domain_has_type_resolve (MonoDomain
*domain
)
438 static MonoClassField
*field
= NULL
;
442 field
= mono_class_get_field_from_name (mono_defaults
.appdomain_class
, "TypeResolve");
446 mono_field_get_value ((MonoObject
*)(domain
->domain
), field
, &o
);
451 * mono_domain_try_type_resolve:
452 * @domain: application domainwhere the name where the type is going to be resolved
453 * @name: the name of the type to resolve or NULL.
454 * @tb: A System.Reflection.Emit.TypeBuilder, used if name is NULL.
456 * This routine invokes the internal System.AppDomain.DoTypeResolve and returns
457 * the assembly that matches name.
459 * If @name is null, the value of ((TypeBuilder)tb).FullName is used instead
461 * Returns: A MonoReflectionAssembly or NULL if not found
463 MonoReflectionAssembly
*
464 mono_domain_try_type_resolve (MonoDomain
*domain
, char *name
, MonoObject
*tb
)
468 static MonoMethod
*method
= NULL
;
470 g_assert (domain
!= NULL
&& ((name
!= NULL
) || (tb
!= NULL
)));
472 if (method
== NULL
) {
473 klass
= domain
->domain
->mbr
.obj
.vtable
->klass
;
476 method
= mono_class_get_method_from_name (klass
, "DoTypeResolve", -1);
477 if (method
== NULL
) {
478 g_warning ("Method AppDomain.DoTypeResolve not found.\n");
484 *params
= (MonoObject
*)mono_string_new (mono_domain_get (), name
);
487 return (MonoReflectionAssembly
*) mono_runtime_invoke (method
, domain
->domain
, params
, NULL
);
491 * mono_domain_owns_vtable_slot:
493 * Returns whenever VTABLE_SLOT is inside a vtable which belongs to DOMAIN.
496 mono_domain_owns_vtable_slot (MonoDomain
*domain
, gpointer vtable_slot
)
500 mono_domain_lock (domain
);
501 res
= mono_mempool_contains_addr (domain
->mp
, vtable_slot
);
502 mono_domain_unlock (domain
);
509 * @force: force setting.
511 * Set the current appdomain to @domain. If @force is set, set it even
512 * if it is being unloaded.
516 * FALSE if the domain is unloaded
519 mono_domain_set (MonoDomain
*domain
, gboolean force
)
521 if (!force
&& domain
->state
== MONO_APPDOMAIN_UNLOADED
)
524 mono_domain_set_internal (domain
);
530 ves_icall_System_AppDomain_GetData (MonoAppDomain
*ad
, MonoString
*name
)
538 g_assert (ad
!= NULL
);
540 g_assert (add
!= NULL
);
543 mono_raise_exception (mono_get_exception_argument_null ("name"));
545 str
= mono_string_to_utf8 (name
);
547 mono_domain_lock (add
);
549 if (!strcmp (str
, "APPBASE"))
550 o
= (MonoObject
*)add
->setup
->application_base
;
551 else if (!strcmp (str
, "APP_CONFIG_FILE"))
552 o
= (MonoObject
*)add
->setup
->configuration_file
;
553 else if (!strcmp (str
, "DYNAMIC_BASE"))
554 o
= (MonoObject
*)add
->setup
->dynamic_base
;
555 else if (!strcmp (str
, "APP_NAME"))
556 o
= (MonoObject
*)add
->setup
->application_name
;
557 else if (!strcmp (str
, "CACHE_BASE"))
558 o
= (MonoObject
*)add
->setup
->cache_path
;
559 else if (!strcmp (str
, "PRIVATE_BINPATH"))
560 o
= (MonoObject
*)add
->setup
->private_bin_path
;
561 else if (!strcmp (str
, "BINPATH_PROBE_ONLY"))
562 o
= (MonoObject
*)add
->setup
->private_bin_path_probe
;
563 else if (!strcmp (str
, "SHADOW_COPY_DIRS"))
564 o
= (MonoObject
*)add
->setup
->shadow_copy_directories
;
565 else if (!strcmp (str
, "FORCE_CACHE_INSTALL"))
566 o
= (MonoObject
*)add
->setup
->shadow_copy_files
;
568 o
= mono_g_hash_table_lookup (add
->env
, name
);
570 mono_domain_unlock (add
);
580 ves_icall_System_AppDomain_SetData (MonoAppDomain
*ad
, MonoString
*name
, MonoObject
*data
)
586 g_assert (ad
!= NULL
);
588 g_assert (add
!= NULL
);
591 mono_raise_exception (mono_get_exception_argument_null ("name"));
593 mono_domain_lock (add
);
595 mono_g_hash_table_insert (add
->env
, name
, data
);
597 mono_domain_unlock (add
);
601 ves_icall_System_AppDomain_getSetup (MonoAppDomain
*ad
)
605 g_assert (ad
!= NULL
);
606 g_assert (ad
->data
!= NULL
);
608 return ad
->data
->setup
;
612 ves_icall_System_AppDomain_getFriendlyName (MonoAppDomain
*ad
)
616 g_assert (ad
!= NULL
);
617 g_assert (ad
->data
!= NULL
);
619 return mono_string_new (ad
->data
, ad
->data
->friendly_name
);
623 ves_icall_System_AppDomain_getCurDomain ()
625 MonoDomain
*add
= mono_domain_get ();
633 ves_icall_System_AppDomain_getRootDomain ()
635 MonoDomain
*root
= mono_get_root_domain ();
643 get_attribute_value (const gchar
**attribute_names
,
644 const gchar
**attribute_values
,
645 const char *att_name
)
648 for (n
= 0; attribute_names
[n
] != NULL
; n
++) {
649 if (strcmp (attribute_names
[n
], att_name
) == 0)
650 return g_strdup (attribute_values
[n
]);
656 start_element (GMarkupParseContext
*context
,
657 const gchar
*element_name
,
658 const gchar
**attribute_names
,
659 const gchar
**attribute_values
,
663 RuntimeConfig
*runtime_config
= user_data
;
665 if (strcmp (element_name
, "runtime") == 0) {
666 runtime_config
->runtime_count
++;
670 if (strcmp (element_name
, "assemblyBinding") == 0) {
671 runtime_config
->assemblybinding_count
++;
675 if (runtime_config
->runtime_count
!= 1 || runtime_config
->assemblybinding_count
!= 1)
678 if (strcmp (element_name
, "probing") != 0)
681 g_free (runtime_config
->domain
->private_bin_path
);
682 runtime_config
->domain
->private_bin_path
= get_attribute_value (attribute_names
, attribute_values
, "privatePath");
683 if (runtime_config
->domain
->private_bin_path
&& !runtime_config
->domain
->private_bin_path
[0]) {
684 g_free (runtime_config
->domain
->private_bin_path
);
685 runtime_config
->domain
->private_bin_path
= NULL
;
691 end_element (GMarkupParseContext
*context
,
692 const gchar
*element_name
,
696 RuntimeConfig
*runtime_config
= user_data
;
697 if (strcmp (element_name
, "runtime") == 0)
698 runtime_config
->runtime_count
--;
699 else if (strcmp (element_name
, "assemblyBinding") == 0)
700 runtime_config
->assemblybinding_count
--;
703 static const GMarkupParser
713 mono_set_private_bin_path_from_config (MonoDomain
*domain
)
715 gchar
*config_file
, *text
;
717 GMarkupParseContext
*context
;
718 RuntimeConfig runtime_config
;
720 if (!domain
|| !domain
->setup
|| !domain
->setup
->configuration_file
)
723 config_file
= mono_string_to_utf8 (domain
->setup
->configuration_file
);
725 if (!g_file_get_contents (config_file
, &text
, &len
, NULL
)) {
726 g_free (config_file
);
729 g_free (config_file
);
731 runtime_config
.runtime_count
= 0;
732 runtime_config
.assemblybinding_count
= 0;
733 runtime_config
.domain
= domain
;
735 context
= g_markup_parse_context_new (&mono_parser
, 0, &runtime_config
, NULL
);
736 if (g_markup_parse_context_parse (context
, text
, len
, NULL
))
737 g_markup_parse_context_end_parse (context
, NULL
);
738 g_markup_parse_context_free (context
);
743 ves_icall_System_AppDomain_createDomain (MonoString
*friendly_name
, MonoAppDomainSetup
*setup
)
745 char *fname
= mono_string_to_utf8 (friendly_name
);
746 MonoAppDomain
*ad
= mono_domain_create_appdomain_internal (fname
, setup
);
754 ves_icall_System_AppDomain_GetAssemblies (MonoAppDomain
*ad
, MonoBoolean refonly
)
756 MonoDomain
*domain
= ad
->data
;
758 static MonoClass
*System_Reflection_Assembly
;
762 GPtrArray
*assemblies
;
766 if (!System_Reflection_Assembly
)
767 System_Reflection_Assembly
= mono_class_from_name (
768 mono_defaults
.corlib
, "System.Reflection", "Assembly");
771 * Make a copy of the list of assemblies because we can't hold the assemblies
772 * lock while creating objects etc.
774 assemblies
= g_ptr_array_new ();
775 /* Need to skip internal assembly builders created by remoting */
776 mono_domain_assemblies_lock (domain
);
777 for (tmp
= domain
->domain_assemblies
; tmp
; tmp
= tmp
->next
) {
779 if (refonly
&& !ass
->ref_only
)
781 if (ass
->corlib_internal
)
783 g_ptr_array_add (assemblies
, ass
);
785 mono_domain_assemblies_unlock (domain
);
787 res
= mono_array_new (domain
, System_Reflection_Assembly
, assemblies
->len
);
788 for (i
= 0; i
< assemblies
->len
; ++i
) {
789 ass
= g_ptr_array_index (assemblies
, i
);
790 mono_array_setref (res
, i
, mono_assembly_get_object (domain
, ass
));
793 g_ptr_array_free (assemblies
, TRUE
);
798 MonoReflectionAssembly
*
799 mono_try_assembly_resolve (MonoDomain
*domain
, MonoString
*fname
, gboolean refonly
)
803 MonoBoolean isrefonly
;
806 g_assert (domain
!= NULL
&& fname
!= NULL
);
808 klass
= domain
->domain
->mbr
.obj
.vtable
->klass
;
811 method
= mono_class_get_method_from_name (klass
, "DoAssemblyResolve", -1);
812 if (method
== NULL
) {
813 g_warning ("Method AppDomain.DoAssemblyResolve not found.\n");
817 isrefonly
= refonly
? 1 : 0;
819 params
[1] = &isrefonly
;
820 return (MonoReflectionAssembly
*) mono_runtime_invoke (method
, domain
->domain
, params
, NULL
);
823 static MonoAssembly
*
824 mono_domain_assembly_postload_search (MonoAssemblyName
*aname
,
827 gboolean refonly
= GPOINTER_TO_UINT (user_data
);
828 MonoReflectionAssembly
*assembly
;
829 MonoDomain
*domain
= mono_domain_get ();
832 aname_str
= mono_stringify_assembly_name (aname
);
834 /* FIXME: We invoke managed code here, so there is a potential for deadlocks */
835 assembly
= mono_try_assembly_resolve (domain
, mono_string_new (domain
, aname_str
), refonly
);
840 return assembly
->assembly
;
846 * LOCKING: assumes assemblies_lock in the domain is already locked.
849 add_assemblies_to_domain (MonoDomain
*domain
, MonoAssembly
*ass
, GHashTable
*ht
)
853 gboolean destroy_ht
= FALSE
;
855 if (!ass
->aname
.name
)
859 ht
= g_hash_table_new (mono_aligned_addr_hash
, NULL
);
863 /* FIXME: handle lazy loaded assemblies */
864 for (tmp
= domain
->domain_assemblies
; tmp
; tmp
= tmp
->next
) {
865 g_hash_table_insert (ht
, tmp
->data
, tmp
->data
);
867 if (!g_hash_table_lookup (ht
, ass
)) {
868 mono_assembly_addref (ass
);
869 g_hash_table_insert (ht
, ass
, ass
);
870 domain
->domain_assemblies
= g_slist_prepend (domain
->domain_assemblies
, ass
);
871 mono_trace (G_LOG_LEVEL_INFO
, MONO_TRACE_ASSEMBLY
, "Assembly %s %p added to domain %s, ref_count=%d\n", ass
->aname
.name
, ass
, domain
->friendly_name
, ass
->ref_count
);
874 if (ass
->image
->references
) {
875 for (i
= 0; ass
->image
->references
[i
] != NULL
; i
++) {
876 if (ass
->image
->references
[i
] != REFERENCE_MISSING
)
877 if (!g_hash_table_lookup (ht
, ass
->image
->references
[i
])) {
878 add_assemblies_to_domain (domain
, ass
->image
->references
[i
], ht
);
883 g_hash_table_destroy (ht
);
887 mono_domain_fire_assembly_load (MonoAssembly
*assembly
, gpointer user_data
)
889 static MonoClassField
*assembly_load_field
;
890 static MonoMethod
*assembly_load_method
;
891 MonoDomain
*domain
= mono_domain_get ();
892 MonoReflectionAssembly
*ref_assembly
;
898 /* This can happen during startup */
900 #ifdef ASSEMBLY_LOAD_DEBUG
901 fprintf (stderr
, "Loading %s into domain %s\n", assembly
->aname
.name
, domain
->friendly_name
);
903 klass
= domain
->domain
->mbr
.obj
.vtable
->klass
;
905 mono_domain_assemblies_lock (domain
);
906 add_assemblies_to_domain (domain
, assembly
, NULL
);
907 mono_domain_assemblies_unlock (domain
);
909 if (assembly_load_field
== NULL
) {
910 assembly_load_field
= mono_class_get_field_from_name (klass
, "AssemblyLoad");
911 g_assert (assembly_load_field
);
914 mono_field_get_value ((MonoObject
*) domain
->domain
, assembly_load_field
, &load_value
);
915 if (load_value
== NULL
) {
916 /* No events waiting to be triggered */
920 ref_assembly
= mono_assembly_get_object (domain
, assembly
);
921 g_assert (ref_assembly
);
923 if (assembly_load_method
== NULL
) {
924 assembly_load_method
= mono_class_get_method_from_name (klass
, "DoAssemblyLoad", -1);
925 g_assert (assembly_load_method
);
928 *params
= ref_assembly
;
929 mono_runtime_invoke (assembly_load_method
, domain
->domain
, params
, NULL
);
933 * LOCKING: Acquires the domain assemblies lock.
936 set_domain_search_path (MonoDomain
*domain
)
938 MonoAppDomainSetup
*setup
;
940 gchar
*search_path
= NULL
;
943 gchar
**pvt_split
= NULL
;
944 GError
*error
= NULL
;
945 gint appbaselen
= -1;
948 * We use the low-level domain assemblies lock, since this is called from
949 * assembly loads hooks, which means this thread might hold the loader lock.
951 mono_domain_assemblies_lock (domain
);
953 if (!domain
->setup
) {
954 mono_domain_assemblies_unlock (domain
);
958 if ((domain
->search_path
!= NULL
) && !domain
->setup
->path_changed
) {
959 mono_domain_assemblies_unlock (domain
);
962 setup
= domain
->setup
;
963 if (!setup
->application_base
) {
964 mono_domain_assemblies_unlock (domain
);
965 return; /* Must set application base to get private path working */
970 if (setup
->private_bin_path
)
971 search_path
= mono_string_to_utf8 (setup
->private_bin_path
);
973 if (domain
->private_bin_path
) {
974 if (search_path
== NULL
)
975 search_path
= domain
->private_bin_path
;
977 gchar
*tmp2
= search_path
;
978 search_path
= g_strjoin (";", search_path
, domain
->private_bin_path
, NULL
);
985 * As per MSDN documentation, AppDomainSetup.PrivateBinPath contains a list of
986 * directories relative to ApplicationBase separated by semicolons (see
987 * http://msdn2.microsoft.com/en-us/library/system.appdomainsetup.privatebinpath.aspx)
988 * The loop below copes with the fact that some Unix applications may use ':' (or
989 * System.IO.Path.PathSeparator) as the path search separator. We replace it with
990 * ';' for the subsequent split.
992 * The issue was reported in bug #81446
995 #ifndef PLATFORM_WIN32
998 slen
= strlen (search_path
);
999 for (i
= 0; i
< slen
; i
++)
1000 if (search_path
[i
] == ':')
1001 search_path
[i
] = ';';
1004 pvt_split
= g_strsplit (search_path
, ";", 1000);
1005 g_free (search_path
);
1006 for (tmp
= pvt_split
; *tmp
; tmp
++, npaths
++);
1011 g_strfreev (pvt_split
);
1013 * Don't do this because the first time is called, the domain
1014 * setup is not finished.
1016 * domain->search_path = g_malloc (sizeof (char *));
1017 * domain->search_path [0] = NULL;
1019 mono_domain_assemblies_unlock (domain
);
1023 if (domain
->search_path
)
1024 g_strfreev (domain
->search_path
);
1026 domain
->search_path
= tmp
= g_malloc ((npaths
+ 1) * sizeof (gchar
*));
1027 tmp
[npaths
] = NULL
;
1029 *tmp
= mono_string_to_utf8 (setup
->application_base
);
1031 /* FIXME: is this needed? */
1032 if (strncmp (*tmp
, "file://", 7) == 0) {
1038 uri
= g_strdup_printf ("file:///%s", uri
+ 7);
1041 uri
= mono_escape_uri_string (tmpuri
);
1042 *tmp
= g_filename_from_uri (uri
, NULL
, &error
);
1048 if (error
!= NULL
) {
1049 g_warning ("%s\n", error
->message
);
1050 g_error_free (error
);
1057 for (i
= 1; pvt_split
&& i
< npaths
; i
++) {
1058 if (g_path_is_absolute (pvt_split
[i
- 1])) {
1059 tmp
[i
] = g_strdup (pvt_split
[i
- 1]);
1061 tmp
[i
] = g_build_filename (tmp
[0], pvt_split
[i
- 1], NULL
);
1064 if (strchr (tmp
[i
], '.')) {
1068 reduced
= mono_path_canonicalize (tmp
[i
]);
1069 if (appbaselen
== -1)
1070 appbaselen
= strlen (tmp
[0]);
1072 if (strncmp (tmp
[0], reduced
, appbaselen
)) {
1075 tmp
[i
] = g_strdup ("");
1085 if (setup
->private_bin_path_probe
!= NULL
) {
1087 tmp
[0] = g_strdup ("");
1090 domain
->setup
->path_changed
= FALSE
;
1092 g_strfreev (pvt_split
);
1094 mono_domain_assemblies_unlock (domain
);
1097 #ifdef DISABLE_SHADOW_COPY
1099 mono_is_shadow_copy_enabled (MonoDomain
*domain
, const gchar
*dir_name
)
1105 mono_make_shadow_copy (const char *filename
)
1107 return (char *) filename
;
1111 shadow_copy_sibling (gchar
*src
, gint srclen
, const char *extension
, gchar
*target
, gint targetlen
, gint tail_len
)
1113 guint16
*orig
, *dest
;
1114 gboolean copy_result
;
1116 strcpy (src
+ srclen
- tail_len
, extension
);
1117 if (!g_file_test (src
, G_FILE_TEST_IS_REGULAR
))
1119 orig
= g_utf8_to_utf16 (src
, strlen (src
), NULL
, NULL
, NULL
);
1121 strcpy (target
+ targetlen
- tail_len
, extension
);
1122 dest
= g_utf8_to_utf16 (target
, strlen (target
), NULL
, NULL
, NULL
);
1125 copy_result
= CopyFile (orig
, dest
, FALSE
);
1133 get_cstring_hash (const char *str
)
1139 if (!str
|| !str
[0])
1144 for (i
= 0; i
< len
; i
++) {
1145 h
= (h
<< 5) - h
+ *p
;
1153 get_shadow_assembly_location_base (MonoDomain
*domain
)
1155 MonoAppDomainSetup
*setup
;
1156 char *cache_path
, *appname
;
1160 setup
= domain
->setup
;
1161 if (setup
->cache_path
!= NULL
&& setup
->application_name
!= NULL
) {
1162 cache_path
= mono_string_to_utf8 (setup
->cache_path
);
1163 #ifndef PLATFORM_WIN32
1166 for (i
= strlen (cache_path
) - 1; i
>= 0; i
--)
1167 if (cache_path
[i
] == '\\')
1168 cache_path
[i
] = '/';
1172 appname
= mono_string_to_utf8 (setup
->application_name
);
1173 location
= g_build_filename (cache_path
, appname
, "assembly", "shadow", NULL
);
1175 g_free (cache_path
);
1177 userdir
= g_strdup_printf ("%s-mono-cachepath", g_get_user_name ());
1178 location
= g_build_filename (g_get_tmp_dir (), userdir
, "assembly", "shadow", NULL
);
1185 get_shadow_assembly_location (const char *filename
)
1187 gint32 hash
= 0, hash2
= 0;
1189 char path_hash
[30];
1190 char *bname
= g_path_get_basename (filename
);
1191 char *dirname
= g_path_get_dirname (filename
);
1192 char *location
, *tmploc
;
1193 MonoDomain
*domain
= mono_domain_get ();
1195 hash
= get_cstring_hash (bname
);
1196 hash2
= get_cstring_hash (dirname
);
1197 g_snprintf (name_hash
, sizeof (name_hash
), "%08x", hash
);
1198 g_snprintf (path_hash
, sizeof (path_hash
), "%08x_%08x_%08x", hash
^ hash2
, hash2
, domain
->shadow_serial
);
1199 tmploc
= get_shadow_assembly_location_base (domain
);
1200 location
= g_build_filename (tmploc
, name_hash
, path_hash
, bname
, NULL
);
1208 ensure_directory_exists (const char *filename
)
1210 #ifdef PLATFORM_WIN32
1211 gchar
*dir_utf8
= g_path_get_dirname (filename
);
1213 gunichar2
*dir_utf16
= NULL
;
1216 if (!dir_utf8
|| !dir_utf8
[0])
1219 dir_utf16
= g_utf8_to_utf16 (dir_utf8
, strlen (dir_utf8
), NULL
, NULL
, NULL
);
1227 /* make life easy and only use one directory seperator */
1238 while (*p
++ != '\\')
1244 p
= wcschr (p
, '\\');
1247 retval
= _wmkdir (dir_utf16
);
1248 if (retval
!= 0 && errno
!= EEXIST
) {
1261 gchar
*dir
= g_path_get_dirname (filename
);
1265 if (!dir
|| !dir
[0]) {
1270 if (stat (dir
, &sbuf
) == 0 && S_ISDIR (sbuf
.st_mode
)) {
1280 p
= strchr (p
, '/');
1283 retval
= mkdir (dir
, 0777);
1284 if (retval
!= 0 && errno
!= EEXIST
) {
1299 private_file_needs_copying (const char *src
, struct stat
*sbuf_src
, char *dest
)
1301 struct stat sbuf_dest
;
1303 if (stat (src
, sbuf_src
) == -1 || stat (dest
, &sbuf_dest
) == -1)
1306 if (sbuf_src
->st_mode
== sbuf_dest
.st_mode
&&
1307 sbuf_src
->st_size
== sbuf_dest
.st_size
&&
1308 sbuf_src
->st_mtime
== sbuf_dest
.st_mtime
)
1315 shadow_copy_create_ini (const char *shadow
, const char *filename
)
1325 dir_name
= g_path_get_dirname (shadow
);
1326 ini_file
= g_build_filename (dir_name
, "__AssemblyInfo__.ini", NULL
);
1328 if (g_file_test (ini_file
, G_FILE_TEST_IS_REGULAR
)) {
1333 u16_ini
= g_utf8_to_utf16 (ini_file
, strlen (ini_file
), NULL
, NULL
, NULL
);
1338 handle
= CreateFile (u16_ini
, GENERIC_WRITE
, FILE_SHARE_READ
|FILE_SHARE_WRITE
,
1339 NULL
, CREATE_NEW
, FileAttributes_Normal
, NULL
);
1341 if (handle
== INVALID_HANDLE_VALUE
) {
1345 full_path
= mono_path_resolve_symlinks (filename
);
1346 result
= WriteFile (handle
, full_path
, strlen (full_path
), &n
, NULL
);
1348 CloseHandle (handle
);
1353 mono_is_shadow_copy_enabled (MonoDomain
*domain
, const gchar
*dir_name
)
1355 const char *version
;
1356 MonoAppDomainSetup
*setup
;
1359 gchar
**directories
;
1360 gchar
*shadow_status_string
;
1362 gboolean shadow_enabled
;
1363 gboolean found
= FALSE
;
1368 setup
= domain
->setup
;
1369 if (setup
== NULL
|| setup
->shadow_copy_files
== NULL
)
1372 version
= mono_get_runtime_info ()->framework_version
;
1373 shadow_status_string
= mono_string_to_utf8 (setup
->shadow_copy_files
);
1374 /* For 1.x, not NULL is enough. In 2.0 it has to be "true" */
1375 shadow_enabled
= (*version
<= '1' || !g_ascii_strncasecmp (shadow_status_string
, "true", 4));
1376 g_free (shadow_status_string
);
1377 if (!shadow_enabled
)
1380 if (setup
->shadow_copy_directories
== NULL
)
1383 /* Is dir_name a shadow_copy destination already? */
1384 base_dir
= get_shadow_assembly_location_base (domain
);
1385 if (strstr (dir_name
, base_dir
) == dir_name
) {
1391 all_dirs
= mono_string_to_utf8 (setup
->shadow_copy_directories
);
1392 directories
= g_strsplit (all_dirs
, G_SEARCHPATH_SEPARATOR_S
, 1000);
1393 dir_ptr
= directories
;
1395 if (**dir_ptr
!= '\0' && !strcmp (*dir_ptr
, dir_name
)) {
1401 g_strfreev (directories
);
1407 mono_make_shadow_copy (const char *filename
)
1409 gchar
*sibling_source
, *sibling_target
;
1410 gint sibling_source_len
, sibling_target_len
;
1411 guint16
*orig
, *dest
;
1413 gboolean copy_result
;
1415 struct stat src_sbuf
;
1416 struct utimbuf utbuf
;
1417 char *dir_name
= g_path_get_dirname (filename
);
1418 MonoDomain
*domain
= mono_domain_get ();
1419 set_domain_search_path (domain
);
1421 if (!mono_is_shadow_copy_enabled (domain
, dir_name
)) {
1423 return (char *) filename
;
1427 shadow
= get_shadow_assembly_location (filename
);
1428 if (ensure_directory_exists (shadow
) == FALSE
) {
1430 exc
= mono_get_exception_execution_engine ("Failed to create shadow copy (ensure directory exists).");
1431 mono_raise_exception (exc
);
1434 if (!private_file_needs_copying (filename
, &src_sbuf
, shadow
))
1435 return (char*) shadow
;
1437 orig
= g_utf8_to_utf16 (filename
, strlen (filename
), NULL
, NULL
, NULL
);
1438 dest
= g_utf8_to_utf16 (shadow
, strlen (shadow
), NULL
, NULL
, NULL
);
1440 copy_result
= CopyFile (orig
, dest
, FALSE
);
1444 if (copy_result
== FALSE
) {
1446 exc
= mono_get_exception_execution_engine ("Failed to create shadow copy (CopyFile).");
1447 mono_raise_exception (exc
);
1450 /* attempt to copy .mdb, .config if they exist */
1451 sibling_source
= g_strconcat (filename
, ".config", NULL
);
1452 sibling_source_len
= strlen (sibling_source
);
1453 sibling_target
= g_strconcat (shadow
, ".config", NULL
);
1454 sibling_target_len
= strlen (sibling_target
);
1456 copy_result
= shadow_copy_sibling (sibling_source
, sibling_source_len
, ".mdb", sibling_target
, sibling_target_len
, 7);
1457 if (copy_result
== TRUE
)
1458 copy_result
= shadow_copy_sibling (sibling_source
, sibling_source_len
, ".config", sibling_target
, sibling_target_len
, 7);
1460 g_free (sibling_source
);
1461 g_free (sibling_target
);
1463 if (copy_result
== FALSE
) {
1465 exc
= mono_get_exception_execution_engine ("Failed to create shadow copy of sibling data (CopyFile).");
1466 mono_raise_exception (exc
);
1469 /* Create a .ini file containing the original assembly location */
1470 if (!shadow_copy_create_ini (shadow
, filename
)) {
1472 exc
= mono_get_exception_execution_engine ("Failed to create shadow copy .ini file.");
1473 mono_raise_exception (exc
);
1476 utbuf
.actime
= src_sbuf
.st_atime
;
1477 utbuf
.modtime
= src_sbuf
.st_mtime
;
1478 utime (shadow
, &utbuf
);
1482 #endif /* DISABLE_SHADOW_COPY */
1485 mono_domain_from_appdomain (MonoAppDomain
*appdomain
)
1487 if (appdomain
== NULL
)
1490 return appdomain
->data
;
1494 try_load_from (MonoAssembly
**assembly
, const gchar
*path1
, const gchar
*path2
,
1495 const gchar
*path3
, const gchar
*path4
,
1496 gboolean refonly
, gboolean is_private
)
1499 gboolean found
= FALSE
;
1502 fullpath
= g_build_filename (path1
, path2
, path3
, path4
, NULL
);
1504 if (IS_PORTABILITY_SET
) {
1505 gchar
*new_fullpath
= mono_portability_find_file (fullpath
, TRUE
);
1508 fullpath
= new_fullpath
;
1512 found
= g_file_test (fullpath
, G_FILE_TEST_IS_REGULAR
);
1515 *assembly
= mono_assembly_open_full (fullpath
, NULL
, refonly
);
1518 return (*assembly
!= NULL
);
1521 static MonoAssembly
*
1522 real_load (gchar
**search_path
, const gchar
*culture
, const gchar
*name
, gboolean refonly
)
1524 MonoAssembly
*result
= NULL
;
1527 const gchar
*local_culture
;
1529 gboolean is_private
= FALSE
;
1531 if (!culture
|| *culture
== '\0') {
1534 local_culture
= culture
;
1537 filename
= g_strconcat (name
, ".dll", NULL
);
1538 len
= strlen (filename
);
1540 for (path
= search_path
; *path
; path
++) {
1541 if (**path
== '\0') {
1543 continue; /* Ignore empty ApplicationBase */
1546 /* See test cases in bug #58992 and bug #57710 */
1547 /* 1st try: [culture]/[name].dll (culture may be empty) */
1548 strcpy (filename
+ len
- 4, ".dll");
1549 if (try_load_from (&result
, *path
, local_culture
, "", filename
, refonly
, is_private
))
1552 /* 2nd try: [culture]/[name].exe (culture may be empty) */
1553 strcpy (filename
+ len
- 4, ".exe");
1554 if (try_load_from (&result
, *path
, local_culture
, "", filename
, refonly
, is_private
))
1557 /* 3rd try: [culture]/[name]/[name].dll (culture may be empty) */
1558 strcpy (filename
+ len
- 4, ".dll");
1559 if (try_load_from (&result
, *path
, local_culture
, name
, filename
, refonly
, is_private
))
1562 /* 4th try: [culture]/[name]/[name].exe (culture may be empty) */
1563 strcpy (filename
+ len
- 4, ".exe");
1564 if (try_load_from (&result
, *path
, local_culture
, name
, filename
, refonly
, is_private
))
1573 * Try loading the assembly from ApplicationBase and PrivateBinPath
1574 * and then from assemblies_path if any.
1575 * LOCKING: This is called from the assembly loading code, which means the caller
1576 * might hold the loader lock. Thus, this function must not acquire the domain lock.
1578 static MonoAssembly
*
1579 mono_domain_assembly_preload (MonoAssemblyName
*aname
,
1580 gchar
**assemblies_path
,
1583 MonoDomain
*domain
= mono_domain_get ();
1584 MonoAssembly
*result
= NULL
;
1585 gboolean refonly
= GPOINTER_TO_UINT (user_data
);
1587 set_domain_search_path (domain
);
1589 if (domain
->search_path
&& domain
->search_path
[0] != NULL
) {
1590 result
= real_load (domain
->search_path
, aname
->culture
, aname
->name
, refonly
);
1593 if (result
== NULL
&& assemblies_path
&& assemblies_path
[0] != NULL
) {
1594 result
= real_load (assemblies_path
, aname
->culture
, aname
->name
, refonly
);
1601 * Check whenever a given assembly was already loaded in the current appdomain.
1603 static MonoAssembly
*
1604 mono_domain_assembly_search (MonoAssemblyName
*aname
,
1607 MonoDomain
*domain
= mono_domain_get ();
1610 gboolean refonly
= GPOINTER_TO_UINT (user_data
);
1612 mono_domain_assemblies_lock (domain
);
1613 for (tmp
= domain
->domain_assemblies
; tmp
; tmp
= tmp
->next
) {
1615 /* Dynamic assemblies can't match here in MS.NET */
1616 if (ass
->dynamic
|| refonly
!= ass
->ref_only
|| !mono_assembly_names_equal (aname
, &ass
->aname
))
1619 mono_domain_assemblies_unlock (domain
);
1622 mono_domain_assemblies_unlock (domain
);
1627 MonoReflectionAssembly
*
1628 ves_icall_System_Reflection_Assembly_LoadFrom (MonoString
*fname
, MonoBoolean refOnly
)
1630 MonoDomain
*domain
= mono_domain_get ();
1631 char *name
, *filename
;
1632 MonoImageOpenStatus status
= MONO_IMAGE_OK
;
1635 MONO_ARCH_SAVE_REGS
;
1637 if (fname
== NULL
) {
1638 MonoException
*exc
= mono_get_exception_argument_null ("assemblyFile");
1639 mono_raise_exception (exc
);
1642 name
= filename
= mono_string_to_utf8 (fname
);
1644 ass
= mono_assembly_open_full (filename
, &status
, refOnly
);
1649 if (status
== MONO_IMAGE_IMAGE_INVALID
)
1650 exc
= mono_get_exception_bad_image_format2 (NULL
, fname
);
1652 exc
= mono_get_exception_file_not_found2 (NULL
, fname
);
1654 mono_raise_exception (exc
);
1659 return mono_assembly_get_object (domain
, ass
);
1662 MonoReflectionAssembly
*
1663 ves_icall_System_AppDomain_LoadAssemblyRaw (MonoAppDomain
*ad
,
1664 MonoArray
*raw_assembly
,
1665 MonoArray
*raw_symbol_store
, MonoObject
*evidence
,
1666 MonoBoolean refonly
)
1669 MonoReflectionAssembly
*refass
= NULL
;
1670 MonoDomain
*domain
= ad
->data
;
1671 MonoImageOpenStatus status
;
1672 guint32 raw_assembly_len
= mono_array_length (raw_assembly
);
1673 MonoImage
*image
= mono_image_open_from_data_full (mono_array_addr (raw_assembly
, gchar
, 0), raw_assembly_len
, TRUE
, NULL
, refonly
);
1676 mono_raise_exception (mono_get_exception_bad_image_format (""));
1680 if (raw_symbol_store
!= NULL
)
1681 mono_debug_open_image_from_memory (image
, mono_array_addr (raw_symbol_store
, guint8
, 0), mono_array_length (raw_symbol_store
));
1683 ass
= mono_assembly_load_from_full (image
, "", &status
, refonly
);
1687 mono_image_close (image
);
1688 mono_raise_exception (mono_get_exception_bad_image_format (""));
1692 refass
= mono_assembly_get_object (domain
, ass
);
1693 MONO_OBJECT_SETREF (refass
, evidence
, evidence
);
1697 MonoReflectionAssembly
*
1698 ves_icall_System_AppDomain_LoadAssembly (MonoAppDomain
*ad
, MonoString
*assRef
, MonoObject
*evidence
, MonoBoolean refOnly
)
1700 MonoDomain
*domain
= ad
->data
;
1701 MonoImageOpenStatus status
= MONO_IMAGE_OK
;
1703 MonoAssemblyName aname
;
1704 MonoReflectionAssembly
*refass
= NULL
;
1708 MONO_ARCH_SAVE_REGS
;
1710 g_assert (assRef
!= NULL
);
1712 name
= mono_string_to_utf8 (assRef
);
1713 parsed
= mono_assembly_name_parse (name
, &aname
);
1717 /* This is a parse error... */
1721 ass
= mono_assembly_load_full_nosearch (&aname
, NULL
, &status
, refOnly
);
1722 mono_assembly_name_free (&aname
);
1725 /* MS.NET doesn't seem to call the assembly resolve handler for refonly assemblies */
1727 refass
= mono_try_assembly_resolve (domain
, assRef
, refOnly
);
1736 refass
= mono_assembly_get_object (domain
, ass
);
1738 MONO_OBJECT_SETREF (refass
, evidence
, evidence
);
1743 ves_icall_System_AppDomain_InternalUnload (gint32 domain_id
)
1745 MonoDomain
* domain
= mono_domain_get_by_id (domain_id
);
1747 MONO_ARCH_SAVE_REGS
;
1749 if (NULL
== domain
) {
1750 MonoException
*exc
= mono_get_exception_execution_engine ("Failed to unload domain, domain id not found");
1751 mono_raise_exception (exc
);
1754 if (domain
== mono_get_root_domain ()) {
1755 mono_raise_exception (mono_get_exception_cannot_unload_appdomain ("The default appdomain can not be unloaded."));
1760 * Unloading seems to cause problems when running NUnit/NAnt, hence
1763 if (g_getenv ("MONO_NO_UNLOAD"))
1766 mono_domain_unload (domain
);
1770 ves_icall_System_AppDomain_InternalIsFinalizingForUnload (gint32 domain_id
)
1772 MonoDomain
*domain
= mono_domain_get_by_id (domain_id
);
1777 return mono_domain_is_unloading (domain
);
1781 ves_icall_System_AppDomain_ExecuteAssembly (MonoAppDomain
*ad
,
1782 MonoReflectionAssembly
*refass
, MonoArray
*args
)
1787 MONO_ARCH_SAVE_REGS
;
1790 image
= refass
->assembly
->image
;
1793 method
= mono_get_method (image
, mono_image_get_entry_point (image
), NULL
);
1796 g_error ("No entry point method found in %s", image
->name
);
1799 args
= (MonoArray
*) mono_array_new (ad
->data
, mono_defaults
.string_class
, 0);
1801 return mono_runtime_exec_main (method
, (MonoArray
*)args
, NULL
);
1805 ves_icall_System_AppDomain_GetIDFromDomain (MonoAppDomain
* ad
)
1807 MONO_ARCH_SAVE_REGS
;
1809 return ad
->data
->domain_id
;
1813 ves_icall_System_AppDomain_InternalSetDomain (MonoAppDomain
*ad
)
1815 MonoDomain
*old_domain
= mono_domain_get();
1817 MONO_ARCH_SAVE_REGS
;
1819 if (!mono_domain_set (ad
->data
, FALSE
))
1820 mono_raise_exception (mono_get_exception_appdomain_unloaded ());
1822 return old_domain
->domain
;
1826 ves_icall_System_AppDomain_InternalSetDomainByID (gint32 domainid
)
1828 MonoDomain
*current_domain
= mono_domain_get ();
1829 MonoDomain
*domain
= mono_domain_get_by_id (domainid
);
1831 MONO_ARCH_SAVE_REGS
;
1833 if (!domain
|| !mono_domain_set (domain
, FALSE
))
1834 mono_raise_exception (mono_get_exception_appdomain_unloaded ());
1836 return current_domain
->domain
;
1840 ves_icall_System_AppDomain_InternalPushDomainRef (MonoAppDomain
*ad
)
1842 MONO_ARCH_SAVE_REGS
;
1844 mono_thread_push_appdomain_ref (ad
->data
);
1848 ves_icall_System_AppDomain_InternalPushDomainRefByID (gint32 domain_id
)
1850 MonoDomain
*domain
= mono_domain_get_by_id (domain_id
);
1852 MONO_ARCH_SAVE_REGS
;
1856 * Raise an exception to prevent the managed code from executing a pop
1859 mono_raise_exception (mono_get_exception_appdomain_unloaded ());
1861 mono_thread_push_appdomain_ref (domain
);
1865 ves_icall_System_AppDomain_InternalPopDomainRef (void)
1867 MONO_ARCH_SAVE_REGS
;
1869 mono_thread_pop_appdomain_ref ();
1873 ves_icall_System_AppDomain_InternalGetContext ()
1875 MONO_ARCH_SAVE_REGS
;
1877 return mono_context_get ();
1881 ves_icall_System_AppDomain_InternalGetDefaultContext ()
1883 MONO_ARCH_SAVE_REGS
;
1885 return mono_domain_get ()->default_context
;
1889 ves_icall_System_AppDomain_InternalSetContext (MonoAppContext
*mc
)
1891 MonoAppContext
*old_context
= mono_context_get ();
1893 MONO_ARCH_SAVE_REGS
;
1895 mono_context_set (mc
);
1901 ves_icall_System_AppDomain_InternalGetProcessGuid (MonoString
* newguid
)
1903 MonoDomain
* mono_root_domain
= mono_get_root_domain ();
1904 mono_domain_lock (mono_root_domain
);
1905 if (process_guid_set
) {
1906 mono_domain_unlock (mono_root_domain
);
1907 return mono_string_new_utf16 (mono_domain_get (), process_guid
, sizeof(process_guid
)/2);
1909 memcpy (process_guid
, mono_string_chars(newguid
), sizeof(process_guid
));
1910 process_guid_set
= TRUE
;
1911 mono_domain_unlock (mono_root_domain
);
1916 mono_domain_is_unloading (MonoDomain
*domain
)
1918 if (domain
->state
== MONO_APPDOMAIN_UNLOADING
|| domain
->state
== MONO_APPDOMAIN_UNLOADED
)
1925 clear_cached_vtable (gpointer key
, gpointer value
, gpointer user_data
)
1927 MonoClass
*klass
= (MonoClass
*)key
;
1928 MonoDomain
*domain
= (MonoDomain
*)user_data
;
1929 MonoClassRuntimeInfo
*runtime_info
;
1931 runtime_info
= klass
->runtime_info
;
1932 if (runtime_info
&& runtime_info
->max_domain
>= domain
->domain_id
)
1933 runtime_info
->domain_vtables
[domain
->domain_id
] = NULL
;
1936 typedef struct unload_data
{
1938 char *failure_reason
;
1942 static guint32 WINAPI
1943 unload_thread_main (void *arg
)
1945 unload_data
*data
= (unload_data
*)arg
;
1946 MonoDomain
*domain
= data
->domain
;
1948 /* Have to attach to the runtime so shutdown can wait for this thread */
1949 mono_thread_attach (mono_get_root_domain ());
1952 * FIXME: Abort our parent thread last, so we can return a failure
1953 * indication if aborting times out.
1955 if (!mono_threads_abort_appdomain_threads (domain
, -1)) {
1956 data
->failure_reason
= g_strdup_printf ("Aborting of threads in domain %s timed out.", domain
->friendly_name
);
1960 if (!mono_thread_pool_remove_domain_jobs (domain
, -1)) {
1961 data
->failure_reason
= g_strdup_printf ("Cleanup of threadpool jobs of domain %s timed out.", domain
->friendly_name
);
1965 /* Finalize all finalizable objects in the doomed appdomain */
1966 if (!mono_domain_finalize (domain
, -1)) {
1967 data
->failure_reason
= g_strdup_printf ("Finalization of domain %s timed out.", domain
->friendly_name
);
1971 /* Clear references to our vtables in class->runtime_info.
1972 * We also hold the loader lock because we're going to change
1973 * class->runtime_info.
1976 mono_loader_lock ();
1977 mono_domain_lock (domain
);
1978 g_hash_table_foreach (domain
->class_vtable_hash
, clear_cached_vtable
, domain
);
1979 mono_domain_unlock (domain
);
1980 mono_loader_unlock ();
1982 mono_threads_clear_cached_culture (domain
);
1984 domain
->state
= MONO_APPDOMAIN_UNLOADED
;
1986 /* printf ("UNLOADED %s.\n", domain->friendly_name); */
1988 /* remove from the handle table the items related to this domain */
1989 mono_gchandle_free_domain (domain
);
1991 mono_domain_free (domain
, FALSE
);
1993 mono_gc_collect (mono_gc_max_generation ());
1999 * mono_domain_unload:
2000 * @domain: The domain to unload
2002 * Unloads an appdomain. Follows the process outlined in:
2003 * http://blogs.gotdotnet.com/cbrumme
2005 * If doing things the 'right' way is too hard or complex, we do it the
2006 * 'simple' way, which means do everything needed to avoid crashes and
2007 * memory leaks, but not much else.
2010 mono_domain_unload (MonoDomain
*domain
)
2012 HANDLE thread_handle
;
2015 MonoAppDomainState prev_state
;
2018 unload_data thread_data
;
2019 MonoDomain
*caller_domain
= mono_domain_get ();
2021 /* printf ("UNLOAD STARTING FOR %s (%p) IN THREAD 0x%x.\n", domain->friendly_name, domain, GetCurrentThreadId ()); */
2023 /* Atomically change our state to UNLOADING */
2024 prev_state
= InterlockedCompareExchange ((gint32
*)&domain
->state
,
2025 MONO_APPDOMAIN_UNLOADING_START
,
2026 MONO_APPDOMAIN_CREATED
);
2027 if (prev_state
!= MONO_APPDOMAIN_CREATED
) {
2028 switch (prev_state
) {
2029 case MONO_APPDOMAIN_UNLOADING_START
:
2030 case MONO_APPDOMAIN_UNLOADING
:
2031 mono_raise_exception (mono_get_exception_cannot_unload_appdomain ("Appdomain is already being unloaded."));
2033 case MONO_APPDOMAIN_UNLOADED
:
2034 mono_raise_exception (mono_get_exception_cannot_unload_appdomain ("Appdomain is already unloaded."));
2037 g_warning ("Incalid appdomain state %d", prev_state
);
2038 g_assert_not_reached ();
2042 mono_domain_set (domain
, FALSE
);
2043 /* Notify OnDomainUnload listeners */
2044 method
= mono_class_get_method_from_name (domain
->domain
->mbr
.obj
.vtable
->klass
, "DoDomainUnload", -1);
2048 mono_runtime_invoke (method
, domain
->domain
, NULL
, &exc
);
2050 /* Roll back the state change */
2051 domain
->state
= MONO_APPDOMAIN_CREATED
;
2052 mono_domain_set (caller_domain
, FALSE
);
2053 mono_raise_exception ((MonoException
*)exc
);
2056 thread_data
.domain
= domain
;
2057 thread_data
.failure_reason
= NULL
;
2059 /*The managed callback finished successfully, now we start tearing down the appdomain*/
2060 domain
->state
= MONO_APPDOMAIN_UNLOADING
;
2062 * First we create a separate thread for unloading, since
2063 * we might have to abort some threads, including the current one.
2066 * If we create a non-suspended thread, the runtime will hang.
2068 * http://bugzilla.ximian.com/show_bug.cgi?id=27663
2071 thread_handle
= CreateThread (NULL
, 0, unload_thread_main
, &thread_data
, 0, &tid
);
2073 thread_handle
= CreateThread (NULL
, 0, (LPTHREAD_START_ROUTINE
)unload_thread_main
, &thread_data
, CREATE_SUSPENDED
, &tid
);
2074 if (thread_handle
== NULL
) {
2077 ResumeThread (thread_handle
);
2080 /* Wait for the thread */
2081 while ((res
= WaitForSingleObjectEx (thread_handle
, INFINITE
, TRUE
) == WAIT_IO_COMPLETION
)) {
2082 if (mono_thread_has_appdomain_ref (mono_thread_current (), domain
) && (mono_thread_interruption_requested ()))
2083 /* The unload thread tries to abort us */
2084 /* The icall wrapper will execute the abort */
2085 CloseHandle (thread_handle
);
2088 CloseHandle (thread_handle
);
2090 mono_domain_set (caller_domain
, FALSE
);
2092 if (thread_data
.failure_reason
) {
2095 /* Roll back the state change */
2096 domain
->state
= MONO_APPDOMAIN_CREATED
;
2098 g_warning (thread_data
.failure_reason
);
2100 ex
= mono_get_exception_cannot_unload_appdomain (thread_data
.failure_reason
);
2102 g_free (thread_data
.failure_reason
);
2103 thread_data
.failure_reason
= NULL
;
2105 mono_raise_exception (ex
);