2009-03-11 Zoltan Varga <vargaz@gmail.com>
[mono-debugger.git] / mono / metadata / appdomain.c
blob42b734187ad9533c96adeb03f15322469db2e9de
1 /*
2 * appdomain.c: AppDomain functions
4 * Authors:
5 * Dietmar Maurer (dietmar@ximian.com)
6 * Patrik Torstensson
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
13 #include <config.h>
14 #include <glib.h>
15 #include <string.h>
16 #ifdef HAVE_UNISTD_H
17 #include <unistd.h>
18 #endif
19 #include <errno.h>
20 #include <sys/stat.h>
21 #include <sys/types.h>
22 #ifdef HAVE_SYS_TIME_H
23 #include <sys/time.h>
24 #endif
25 #ifdef HAVE_UTIME_H
26 #include <utime.h>
27 #else
28 #ifdef HAVE_SYS_UTIME_H
29 #include <sys/utime.h>
30 #endif
31 #endif
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>
56 #ifdef PLATFORM_WIN32
57 #include <direct.h>
58 #endif
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
73 typedef struct
75 int runtime_count;
76 int assemblybinding_count;
77 MonoDomain *domain;
78 } RuntimeConfig;
80 CRITICAL_SECTION mono_delegate_section;
82 #ifdef _EGLIB_MAJOR
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;
86 #endif
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;
96 static MonoAssembly *
97 mono_domain_assembly_preload (MonoAssemblyName *aname,
98 gchar **assemblies_path,
99 gpointer user_data);
101 static MonoAssembly *
102 mono_domain_assembly_search (MonoAssemblyName *aname,
103 gpointer user_data);
105 static MonoAssembly *
106 mono_domain_assembly_postload_search (MonoAssemblyName *aname,
107 gpointer user_data);
109 static void
110 mono_domain_fire_assembly_load (MonoAssembly *assembly, gpointer user_data);
112 static void
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;
120 void
121 mono_install_runtime_load (MonoLoadFunc func)
123 load_function = func;
126 MonoDomain*
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 ().
141 void
142 mono_runtime_set_no_exec (gboolean val)
144 no_exec = val;
147 gboolean
148 mono_runtime_get_no_exec (void)
150 return no_exec;
154 * mono_runtime_init:
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
159 * operational.
161 * AppDomain.SetupInformation is set up in mono_runtime_exec_main, where
162 * we know the entry_assembly.
165 void
166 mono_runtime_init (MonoDomain *domain, MonoThreadStartCB start_cb,
167 MonoThreadAttachCB attach_cb)
169 MonoAppDomainSetup *setup;
170 MonoAppDomain *ad;
171 MonoClass *class;
172 MonoString *arg;
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);
197 ad->data = domain;
198 domain->domain = ad;
199 domain->setup = setup;
201 InitializeCriticalSection (&mono_delegate_section);
203 #ifdef _EGLIB_MAJOR
204 /* Needed until EGLIB is fixed #464316 */
205 InitializeCriticalSection (&mono_strtod_mutex);
206 #endif
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 */
232 mono_gc_init ();
234 #ifndef DISABLE_SOCKETS
235 mono_network_init ();
236 #endif
238 mono_attach_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);
245 return;
248 static int
249 mono_get_corlib_version (void)
251 MonoClass *klass;
252 MonoClassField *field;
253 MonoObject *value;
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");
258 if (!field)
259 return -1;
260 if (! (field->type->attrs & FIELD_ATTRIBUTE_STATIC))
261 return -1;
262 value = mono_field_get_value_object (mono_domain_get (), field, NULL);
263 return *(gint32*)((gchar*)value + sizeof (MonoObject));
266 const char*
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);
272 else
273 return NULL;
276 void
277 mono_context_init (MonoDomain *domain)
279 MonoClass *class;
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:
291 * @domain: unused.
293 * Internal routine.
295 * This must not be called while there are still running threads executing
296 * managed code.
298 void
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) */
306 mono_gc_cleanup ();
308 mono_thread_cleanup ();
310 #ifndef DISABLE_SOCKETS
311 mono_network_cleanup ();
312 #endif
313 mono_marshal_cleanup ();
315 mono_type_initialization_cleanup ();
317 mono_monitor_cleanup ();
319 #ifndef PLATFORM_WIN32
320 _wapi_cleanup ();
321 #endif
324 static MonoDomainFunc quit_function = NULL;
326 void
327 mono_install_runtime_cleanup (MonoDomainFunc func)
329 quit_function = func;
332 void
333 mono_runtime_quit ()
335 if (quit_function != NULL)
336 quit_function (mono_get_root_domain (), NULL);
339 /**
340 * mono_runtime_set_shutting_down:
342 * Invoked by System.Environment.Exit to flag that the runtime
343 * is shutting down.
345 void
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
357 * property.
360 gboolean
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
373 MonoDomain *
374 mono_domain_create_appdomain (char *friendly_name, char *configuration_file)
376 MonoAppDomain *ad;
377 MonoAppDomainSetup *setup;
378 MonoClass *class;
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)
392 MonoClass *adclass;
393 MonoAppDomain *ad;
394 MonoDomain *data;
396 MONO_ARCH_SAVE_REGS;
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);
404 ad->data = data;
405 data->domain = ad;
406 data->setup = setup;
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);
425 return ad;
429 * mono_domain_has_type_resolve:
430 * @domain: application domains being looked up
432 * Returns true if the AppDomain.TypeResolve field has been
433 * set.
435 gboolean
436 mono_domain_has_type_resolve (MonoDomain *domain)
438 static MonoClassField *field = NULL;
439 MonoObject *o;
441 if (field == NULL) {
442 field = mono_class_get_field_from_name (mono_defaults.appdomain_class, "TypeResolve");
443 g_assert (field);
446 mono_field_get_value ((MonoObject*)(domain->domain), field, &o);
447 return o != NULL;
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)
466 MonoClass *klass;
467 void *params [1];
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;
474 g_assert (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");
479 return NULL;
483 if (name)
484 *params = (MonoObject*)mono_string_new (mono_domain_get (), name);
485 else
486 *params = tb;
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.
495 gboolean
496 mono_domain_owns_vtable_slot (MonoDomain *domain, gpointer vtable_slot)
498 gboolean res;
500 mono_domain_lock (domain);
501 res = mono_mempool_contains_addr (domain->mp, vtable_slot);
502 mono_domain_unlock (domain);
503 return res;
507 * mono_domain_set:
508 * @domain: 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.
514 * Returns:
515 * TRUE on success;
516 * FALSE if the domain is unloaded
518 gboolean
519 mono_domain_set (MonoDomain *domain, gboolean force)
521 if (!force && domain->state == MONO_APPDOMAIN_UNLOADED)
522 return FALSE;
524 mono_domain_set_internal (domain);
526 return TRUE;
529 MonoObject *
530 ves_icall_System_AppDomain_GetData (MonoAppDomain *ad, MonoString *name)
532 MonoDomain *add;
533 MonoObject *o;
534 char *str;
536 MONO_ARCH_SAVE_REGS;
538 g_assert (ad != NULL);
539 add = ad->data;
540 g_assert (add != NULL);
542 if (name == 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;
567 else
568 o = mono_g_hash_table_lookup (add->env, name);
570 mono_domain_unlock (add);
571 g_free (str);
573 if (!o)
574 return NULL;
576 return o;
579 void
580 ves_icall_System_AppDomain_SetData (MonoAppDomain *ad, MonoString *name, MonoObject *data)
582 MonoDomain *add;
584 MONO_ARCH_SAVE_REGS;
586 g_assert (ad != NULL);
587 add = ad->data;
588 g_assert (add != NULL);
590 if (name == 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);
600 MonoAppDomainSetup *
601 ves_icall_System_AppDomain_getSetup (MonoAppDomain *ad)
603 MONO_ARCH_SAVE_REGS;
605 g_assert (ad != NULL);
606 g_assert (ad->data != NULL);
608 return ad->data->setup;
611 MonoString *
612 ves_icall_System_AppDomain_getFriendlyName (MonoAppDomain *ad)
614 MONO_ARCH_SAVE_REGS;
616 g_assert (ad != NULL);
617 g_assert (ad->data != NULL);
619 return mono_string_new (ad->data, ad->data->friendly_name);
622 MonoAppDomain *
623 ves_icall_System_AppDomain_getCurDomain ()
625 MonoDomain *add = mono_domain_get ();
627 MONO_ARCH_SAVE_REGS;
629 return add->domain;
632 MonoAppDomain *
633 ves_icall_System_AppDomain_getRootDomain ()
635 MonoDomain *root = mono_get_root_domain ();
637 MONO_ARCH_SAVE_REGS;
639 return root->domain;
642 static char*
643 get_attribute_value (const gchar **attribute_names,
644 const gchar **attribute_values,
645 const char *att_name)
647 int n;
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]);
652 return NULL;
655 static void
656 start_element (GMarkupParseContext *context,
657 const gchar *element_name,
658 const gchar **attribute_names,
659 const gchar **attribute_values,
660 gpointer user_data,
661 GError **error)
663 RuntimeConfig *runtime_config = user_data;
665 if (strcmp (element_name, "runtime") == 0) {
666 runtime_config->runtime_count++;
667 return;
670 if (strcmp (element_name, "assemblyBinding") == 0) {
671 runtime_config->assemblybinding_count++;
672 return;
675 if (runtime_config->runtime_count != 1 || runtime_config->assemblybinding_count != 1)
676 return;
678 if (strcmp (element_name, "probing") != 0)
679 return;
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;
686 return;
690 static void
691 end_element (GMarkupParseContext *context,
692 const gchar *element_name,
693 gpointer user_data,
694 GError **error)
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
704 mono_parser = {
705 start_element,
706 end_element,
707 NULL,
708 NULL,
709 NULL
712 void
713 mono_set_private_bin_path_from_config (MonoDomain *domain)
715 gchar *config_file, *text;
716 gsize len;
717 GMarkupParseContext *context;
718 RuntimeConfig runtime_config;
720 if (!domain || !domain->setup || !domain->setup->configuration_file)
721 return;
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);
727 return;
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);
739 g_free (text);
742 MonoAppDomain *
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);
748 g_free (fname);
750 return ad;
753 MonoArray *
754 ves_icall_System_AppDomain_GetAssemblies (MonoAppDomain *ad, MonoBoolean refonly)
756 MonoDomain *domain = ad->data;
757 MonoAssembly* ass;
758 static MonoClass *System_Reflection_Assembly;
759 MonoArray *res;
760 GSList *tmp;
761 int i;
762 GPtrArray *assemblies;
764 MONO_ARCH_SAVE_REGS;
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) {
778 ass = tmp->data;
779 if (refonly && !ass->ref_only)
780 continue;
781 if (ass->corlib_internal)
782 continue;
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);
795 return res;
798 MonoReflectionAssembly *
799 mono_try_assembly_resolve (MonoDomain *domain, MonoString *fname, gboolean refonly)
801 MonoClass *klass;
802 MonoMethod *method;
803 MonoBoolean isrefonly;
804 gpointer params [2];
806 g_assert (domain != NULL && fname != NULL);
808 klass = domain->domain->mbr.obj.vtable->klass;
809 g_assert (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");
814 return NULL;
817 isrefonly = refonly ? 1 : 0;
818 params [0] = fname;
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,
825 gpointer user_data)
827 gboolean refonly = GPOINTER_TO_UINT (user_data);
828 MonoReflectionAssembly *assembly;
829 MonoDomain *domain = mono_domain_get ();
830 char *aname_str;
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);
837 g_free (aname_str);
839 if (assembly)
840 return assembly->assembly;
841 else
842 return NULL;
846 * LOCKING: assumes assemblies_lock in the domain is already locked.
848 static void
849 add_assemblies_to_domain (MonoDomain *domain, MonoAssembly *ass, GHashTable *ht)
851 gint i;
852 GSList *tmp;
853 gboolean destroy_ht = FALSE;
855 if (!ass->aname.name)
856 return;
858 if (!ht) {
859 ht = g_hash_table_new (mono_aligned_addr_hash, NULL);
860 destroy_ht = TRUE;
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);
882 if (destroy_ht)
883 g_hash_table_destroy (ht);
886 static void
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;
893 MonoClass *klass;
894 gpointer load_value;
895 void *params [1];
897 if (!domain->domain)
898 /* This can happen during startup */
899 return;
900 #ifdef ASSEMBLY_LOAD_DEBUG
901 fprintf (stderr, "Loading %s into domain %s\n", assembly->aname.name, domain->friendly_name);
902 #endif
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 */
917 return;
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.
935 static void
936 set_domain_search_path (MonoDomain *domain)
938 MonoAppDomainSetup *setup;
939 gchar **tmp;
940 gchar *search_path = NULL;
941 gint i;
942 gint npaths = 0;
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);
955 return;
958 if ((domain->search_path != NULL) && !domain->setup->path_changed) {
959 mono_domain_assemblies_unlock (domain);
960 return;
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 */
968 npaths++;
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;
976 else {
977 gchar *tmp2 = search_path;
978 search_path = g_strjoin (";", search_path, domain->private_bin_path, NULL);
979 g_free (tmp2);
983 if (search_path) {
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
996 gint slen;
998 slen = strlen (search_path);
999 for (i = 0; i < slen; i++)
1000 if (search_path [i] == ':')
1001 search_path [i] = ';';
1002 #endif
1004 pvt_split = g_strsplit (search_path, ";", 1000);
1005 g_free (search_path);
1006 for (tmp = pvt_split; *tmp; tmp++, npaths++);
1009 if (!npaths) {
1010 if (pvt_split)
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);
1020 return;
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) {
1033 gchar *file = *tmp;
1034 gchar *uri = *tmp;
1035 gchar *tmpuri;
1037 if (uri [7] != '/')
1038 uri = g_strdup_printf ("file:///%s", uri + 7);
1040 tmpuri = uri;
1041 uri = mono_escape_uri_string (tmpuri);
1042 *tmp = g_filename_from_uri (uri, NULL, &error);
1043 g_free (uri);
1045 if (tmpuri != file)
1046 g_free (tmpuri);
1048 if (error != NULL) {
1049 g_warning ("%s\n", error->message);
1050 g_error_free (error);
1051 *tmp = file;
1052 } else {
1053 g_free (file);
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]);
1060 } else {
1061 tmp [i] = g_build_filename (tmp [0], pvt_split [i - 1], NULL);
1064 if (strchr (tmp [i], '.')) {
1065 gchar *reduced;
1066 gchar *freeme;
1068 reduced = mono_path_canonicalize (tmp [i]);
1069 if (appbaselen == -1)
1070 appbaselen = strlen (tmp [0]);
1072 if (strncmp (tmp [0], reduced, appbaselen)) {
1073 g_free (reduced);
1074 g_free (tmp [i]);
1075 tmp [i] = g_strdup ("");
1076 continue;
1079 freeme = tmp [i];
1080 tmp [i] = reduced;
1081 g_free (freeme);
1085 if (setup->private_bin_path_probe != NULL) {
1086 g_free (tmp [0]);
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
1098 gboolean
1099 mono_is_shadow_copy_enabled (MonoDomain *domain, const gchar *dir_name)
1101 return FALSE;
1104 char *
1105 mono_make_shadow_copy (const char *filename)
1107 return (char *) filename;
1109 #else
1110 static gboolean
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))
1118 return TRUE;
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);
1124 DeleteFile (dest);
1125 copy_result = CopyFile (orig, dest, FALSE);
1126 g_free (orig);
1127 g_free (dest);
1129 return copy_result;
1132 static gint32
1133 get_cstring_hash (const char *str)
1135 int len, i;
1136 const char *p;
1137 gint32 h = 0;
1139 if (!str || !str [0])
1140 return 0;
1142 len = strlen (str);
1143 p = str;
1144 for (i = 0; i < len; i++) {
1145 h = (h << 5) - h + *p;
1146 p++;
1149 return h;
1152 static char *
1153 get_shadow_assembly_location_base (MonoDomain *domain)
1155 MonoAppDomainSetup *setup;
1156 char *cache_path, *appname;
1157 char *userdir;
1158 char *location;
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
1165 gint i;
1166 for (i = strlen (cache_path) - 1; i >= 0; i--)
1167 if (cache_path [i] == '\\')
1168 cache_path [i] = '/';
1170 #endif
1172 appname = mono_string_to_utf8 (setup->application_name);
1173 location = g_build_filename (cache_path, appname, "assembly", "shadow", NULL);
1174 g_free (appname);
1175 g_free (cache_path);
1176 } else {
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);
1179 g_free (userdir);
1181 return location;
1184 static char *
1185 get_shadow_assembly_location (const char *filename)
1187 gint32 hash = 0, hash2 = 0;
1188 char name_hash [9];
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);
1201 g_free (tmploc);
1202 g_free (bname);
1203 g_free (dirname);
1204 return location;
1207 static gboolean
1208 ensure_directory_exists (const char *filename)
1210 #ifdef PLATFORM_WIN32
1211 gchar *dir_utf8 = g_path_get_dirname (filename);
1212 gunichar2 *p;
1213 gunichar2 *dir_utf16 = NULL;
1214 int retval;
1216 if (!dir_utf8 || !dir_utf8 [0])
1217 return FALSE;
1219 dir_utf16 = g_utf8_to_utf16 (dir_utf8, strlen (dir_utf8), NULL, NULL, NULL);
1220 g_free (dir_utf8);
1222 if (!dir_utf16)
1223 return FALSE;
1225 p = dir_utf16;
1227 /* make life easy and only use one directory seperator */
1228 while (*p != '\0')
1230 if (*p == '/')
1231 *p = '\\';
1232 p++;
1235 p = dir_utf16;
1237 /* get past C:\ )*/
1238 while (*p++ != '\\')
1242 while (1) {
1243 BOOL bRet = FALSE;
1244 p = wcschr (p, '\\');
1245 if (p)
1246 *p = '\0';
1247 retval = _wmkdir (dir_utf16);
1248 if (retval != 0 && errno != EEXIST) {
1249 g_free (dir_utf16);
1250 return FALSE;
1252 if (!p)
1253 break;
1254 *p++ = '\\';
1257 g_free (dir_utf16);
1258 return TRUE;
1259 #else
1260 char *p;
1261 gchar *dir = g_path_get_dirname (filename);
1262 int retval;
1263 struct stat sbuf;
1265 if (!dir || !dir [0]) {
1266 g_free (dir);
1267 return FALSE;
1270 if (stat (dir, &sbuf) == 0 && S_ISDIR (sbuf.st_mode)) {
1271 g_free (dir);
1272 return TRUE;
1275 p = dir;
1276 while (*p == '/')
1277 p++;
1279 while (1) {
1280 p = strchr (p, '/');
1281 if (p)
1282 *p = '\0';
1283 retval = mkdir (dir, 0777);
1284 if (retval != 0 && errno != EEXIST) {
1285 g_free (dir);
1286 return FALSE;
1288 if (!p)
1289 break;
1290 *p++ = '/';
1293 g_free (dir);
1294 return TRUE;
1295 #endif
1298 static gboolean
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)
1304 return TRUE;
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)
1309 return FALSE;
1311 return TRUE;
1314 static gboolean
1315 shadow_copy_create_ini (const char *shadow, const char *filename)
1317 char *dir_name;
1318 char *ini_file;
1319 guint16 *u16_ini;
1320 gboolean result;
1321 guint32 n;
1322 HANDLE *handle;
1323 gchar *full_path;
1325 dir_name = g_path_get_dirname (shadow);
1326 ini_file = g_build_filename (dir_name, "__AssemblyInfo__.ini", NULL);
1327 g_free (dir_name);
1328 if (g_file_test (ini_file, G_FILE_TEST_IS_REGULAR)) {
1329 g_free (ini_file);
1330 return TRUE;
1333 u16_ini = g_utf8_to_utf16 (ini_file, strlen (ini_file), NULL, NULL, NULL);
1334 g_free (ini_file);
1335 if (!u16_ini) {
1336 return FALSE;
1338 handle = CreateFile (u16_ini, GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE,
1339 NULL, CREATE_NEW, FileAttributes_Normal, NULL);
1340 g_free (u16_ini);
1341 if (handle == INVALID_HANDLE_VALUE) {
1342 return FALSE;
1345 full_path = mono_path_resolve_symlinks (filename);
1346 result = WriteFile (handle, full_path, strlen (full_path), &n, NULL);
1347 g_free (full_path);
1348 CloseHandle (handle);
1349 return result;
1352 gboolean
1353 mono_is_shadow_copy_enabled (MonoDomain *domain, const gchar *dir_name)
1355 const char *version;
1356 MonoAppDomainSetup *setup;
1357 gchar *all_dirs;
1358 gchar **dir_ptr;
1359 gchar **directories;
1360 gchar *shadow_status_string;
1361 gchar *base_dir;
1362 gboolean shadow_enabled;
1363 gboolean found = FALSE;
1365 if (domain == NULL)
1366 return FALSE;
1368 setup = domain->setup;
1369 if (setup == NULL || setup->shadow_copy_files == NULL)
1370 return FALSE;
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)
1378 return FALSE;
1380 if (setup->shadow_copy_directories == NULL)
1381 return TRUE;
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) {
1386 g_free (base_dir);
1387 return FALSE;
1389 g_free (base_dir);
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;
1394 while (*dir_ptr) {
1395 if (**dir_ptr != '\0' && !strcmp (*dir_ptr, dir_name)) {
1396 found = TRUE;
1397 break;
1399 dir_ptr++;
1401 g_strfreev (directories);
1402 g_free (all_dirs);
1403 return found;
1406 char *
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;
1412 char *shadow;
1413 gboolean copy_result;
1414 MonoException *exc;
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)) {
1422 g_free (dir_name);
1423 return (char *) filename;
1425 g_free (dir_name);
1427 shadow = get_shadow_assembly_location (filename);
1428 if (ensure_directory_exists (shadow) == FALSE) {
1429 g_free (shadow);
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);
1439 DeleteFile (dest);
1440 copy_result = CopyFile (orig, dest, FALSE);
1441 g_free (dest);
1442 g_free (orig);
1444 if (copy_result == FALSE) {
1445 g_free (shadow);
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) {
1464 g_free (shadow);
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)) {
1471 g_free (shadow);
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);
1480 return shadow;
1482 #endif /* DISABLE_SHADOW_COPY */
1484 MonoDomain *
1485 mono_domain_from_appdomain (MonoAppDomain *appdomain)
1487 if (appdomain == NULL)
1488 return NULL;
1490 return appdomain->data;
1493 static gboolean
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)
1498 gchar *fullpath;
1499 gboolean found = FALSE;
1501 *assembly = NULL;
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);
1506 if (new_fullpath) {
1507 g_free (fullpath);
1508 fullpath = new_fullpath;
1509 found = TRUE;
1511 } else
1512 found = g_file_test (fullpath, G_FILE_TEST_IS_REGULAR);
1514 if (found)
1515 *assembly = mono_assembly_open_full (fullpath, NULL, refonly);
1517 g_free (fullpath);
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;
1525 gchar **path;
1526 gchar *filename;
1527 const gchar *local_culture;
1528 gint len;
1529 gboolean is_private = FALSE;
1531 if (!culture || *culture == '\0') {
1532 local_culture = "";
1533 } else {
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') {
1542 is_private = TRUE;
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))
1550 break;
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))
1555 break;
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))
1560 break;
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))
1565 break;
1568 g_free (filename);
1569 return result;
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,
1581 gpointer user_data)
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);
1597 return result;
1601 * Check whenever a given assembly was already loaded in the current appdomain.
1603 static MonoAssembly *
1604 mono_domain_assembly_search (MonoAssemblyName *aname,
1605 gpointer user_data)
1607 MonoDomain *domain = mono_domain_get ();
1608 GSList *tmp;
1609 MonoAssembly *ass;
1610 gboolean refonly = GPOINTER_TO_UINT (user_data);
1612 mono_domain_assemblies_lock (domain);
1613 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
1614 ass = tmp->data;
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))
1617 continue;
1619 mono_domain_assemblies_unlock (domain);
1620 return ass;
1622 mono_domain_assemblies_unlock (domain);
1624 return NULL;
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;
1633 MonoAssembly *ass;
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);
1646 if (!ass){
1647 MonoException *exc;
1649 if (status == MONO_IMAGE_IMAGE_INVALID)
1650 exc = mono_get_exception_bad_image_format2 (NULL, fname);
1651 else
1652 exc = mono_get_exception_file_not_found2 (NULL, fname);
1653 g_free (name);
1654 mono_raise_exception (exc);
1657 g_free (name);
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)
1668 MonoAssembly *ass;
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);
1675 if (!image) {
1676 mono_raise_exception (mono_get_exception_bad_image_format (""));
1677 return NULL;
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);
1686 if (!ass) {
1687 mono_image_close (image);
1688 mono_raise_exception (mono_get_exception_bad_image_format (""));
1689 return NULL;
1692 refass = mono_assembly_get_object (domain, ass);
1693 MONO_OBJECT_SETREF (refass, evidence, evidence);
1694 return refass;
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;
1702 MonoAssembly *ass;
1703 MonoAssemblyName aname;
1704 MonoReflectionAssembly *refass = NULL;
1705 gchar *name;
1706 gboolean parsed;
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);
1714 g_free (name);
1716 if (!parsed) {
1717 /* This is a parse error... */
1718 return NULL;
1721 ass = mono_assembly_load_full_nosearch (&aname, NULL, &status, refOnly);
1722 mono_assembly_name_free (&aname);
1724 if (!ass) {
1725 /* MS.NET doesn't seem to call the assembly resolve handler for refonly assemblies */
1726 if (!refOnly)
1727 refass = mono_try_assembly_resolve (domain, assRef, refOnly);
1728 else
1729 refass = NULL;
1730 if (!refass) {
1731 return NULL;
1735 if (refass == NULL)
1736 refass = mono_assembly_get_object (domain, ass);
1738 MONO_OBJECT_SETREF (refass, evidence, evidence);
1739 return refass;
1742 void
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."));
1756 return;
1760 * Unloading seems to cause problems when running NUnit/NAnt, hence
1761 * this workaround.
1763 if (g_getenv ("MONO_NO_UNLOAD"))
1764 return;
1766 mono_domain_unload (domain);
1769 gboolean
1770 ves_icall_System_AppDomain_InternalIsFinalizingForUnload (gint32 domain_id)
1772 MonoDomain *domain = mono_domain_get_by_id (domain_id);
1774 if (!domain)
1775 return TRUE;
1777 return mono_domain_is_unloading (domain);
1780 gint32
1781 ves_icall_System_AppDomain_ExecuteAssembly (MonoAppDomain *ad,
1782 MonoReflectionAssembly *refass, MonoArray *args)
1784 MonoImage *image;
1785 MonoMethod *method;
1787 MONO_ARCH_SAVE_REGS;
1789 g_assert (refass);
1790 image = refass->assembly->image;
1791 g_assert (image);
1793 method = mono_get_method (image, mono_image_get_entry_point (image), NULL);
1795 if (!method)
1796 g_error ("No entry point method found in %s", image->name);
1798 if (!args)
1799 args = (MonoArray *) mono_array_new (ad->data, mono_defaults.string_class, 0);
1801 return mono_runtime_exec_main (method, (MonoArray *)args, NULL);
1804 gint32
1805 ves_icall_System_AppDomain_GetIDFromDomain (MonoAppDomain * ad)
1807 MONO_ARCH_SAVE_REGS;
1809 return ad->data->domain_id;
1812 MonoAppDomain *
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;
1825 MonoAppDomain *
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;
1839 void
1840 ves_icall_System_AppDomain_InternalPushDomainRef (MonoAppDomain *ad)
1842 MONO_ARCH_SAVE_REGS;
1844 mono_thread_push_appdomain_ref (ad->data);
1847 void
1848 ves_icall_System_AppDomain_InternalPushDomainRefByID (gint32 domain_id)
1850 MonoDomain *domain = mono_domain_get_by_id (domain_id);
1852 MONO_ARCH_SAVE_REGS;
1854 if (!domain)
1856 * Raise an exception to prevent the managed code from executing a pop
1857 * later.
1859 mono_raise_exception (mono_get_exception_appdomain_unloaded ());
1861 mono_thread_push_appdomain_ref (domain);
1864 void
1865 ves_icall_System_AppDomain_InternalPopDomainRef (void)
1867 MONO_ARCH_SAVE_REGS;
1869 mono_thread_pop_appdomain_ref ();
1872 MonoAppContext *
1873 ves_icall_System_AppDomain_InternalGetContext ()
1875 MONO_ARCH_SAVE_REGS;
1877 return mono_context_get ();
1880 MonoAppContext *
1881 ves_icall_System_AppDomain_InternalGetDefaultContext ()
1883 MONO_ARCH_SAVE_REGS;
1885 return mono_domain_get ()->default_context;
1888 MonoAppContext *
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);
1897 return old_context;
1900 MonoString *
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);
1912 return newguid;
1915 gboolean
1916 mono_domain_is_unloading (MonoDomain *domain)
1918 if (domain->state == MONO_APPDOMAIN_UNLOADING || domain->state == MONO_APPDOMAIN_UNLOADED)
1919 return TRUE;
1920 else
1921 return FALSE;
1924 static void
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 {
1937 MonoDomain *domain;
1938 char *failure_reason;
1939 } unload_data;
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);
1957 return 1;
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);
1962 return 1;
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);
1968 return 1;
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 ());
1995 return 0;
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.
2009 void
2010 mono_domain_unload (MonoDomain *domain)
2012 HANDLE thread_handle;
2013 gsize tid;
2014 guint32 res;
2015 MonoAppDomainState prev_state;
2016 MonoMethod *method;
2017 MonoObject *exc;
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."));
2032 break;
2033 case MONO_APPDOMAIN_UNLOADED:
2034 mono_raise_exception (mono_get_exception_cannot_unload_appdomain ("Appdomain is already unloaded."));
2035 break;
2036 default:
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);
2045 g_assert (method);
2047 exc = NULL;
2048 mono_runtime_invoke (method, domain->domain, NULL, &exc);
2049 if (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.
2067 * See:
2068 * http://bugzilla.ximian.com/show_bug.cgi?id=27663
2070 #if 0
2071 thread_handle = CreateThread (NULL, 0, unload_thread_main, &thread_data, 0, &tid);
2072 #else
2073 thread_handle = CreateThread (NULL, 0, (LPTHREAD_START_ROUTINE)unload_thread_main, &thread_data, CREATE_SUSPENDED, &tid);
2074 if (thread_handle == NULL) {
2075 return;
2077 ResumeThread (thread_handle);
2078 #endif
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);
2086 return;
2088 CloseHandle (thread_handle);
2090 mono_domain_set (caller_domain, FALSE);
2092 if (thread_data.failure_reason) {
2093 MonoException *ex;
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);