Move wapi shutdown to mono_cleanup () as TlsGetValue()/TlsSetValue() is used
[mono.git] / mono / metadata / appdomain.c
index 5b53274e272eb32da3f2d41b3765f00242366723..47d2febbf4a543749a04d7a736acb7b738b055ac 100644 (file)
@@ -6,7 +6,8 @@
  *     Patrik Torstensson
  *     Gonzalo Paniagua Javier (gonzalo@ximian.com)
  *
- * (c) 2001-2003 Ximian, Inc. (http://www.ximian.com)
+ * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
+ * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
  */
 #undef ASSEMBLY_LOAD_DEBUG
 #include <config.h>
@@ -18,6 +19,9 @@
 #include <errno.h>
 #include <sys/stat.h>
 #include <sys/types.h>
+#ifdef HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
 #ifdef HAVE_UTIME_H
 #include <utime.h>
 #else
 #include <mono/metadata/monitor.h>
 #include <mono/metadata/threadpool.h>
 #include <mono/metadata/mono-debug.h>
+#include <mono/metadata/mono-debug-debugger.h>
 #include <mono/metadata/attach.h>
 #include <mono/metadata/file-io.h>
+#include <mono/metadata/lock-tracer.h>
+#include <mono/metadata/console-io.h>
+#include <mono/metadata/threads-types.h>
+#include <mono/metadata/tokentype.h>
 #include <mono/utils/mono-uri.h>
-#include <mono/utils/mono-logger.h>
+#include <mono/utils/mono-logger-internal.h>
 #include <mono/utils/mono-path.h>
 #include <mono/utils/mono-stdlib.h>
 #include <mono/utils/mono-io-portability.h>
-#ifdef PLATFORM_WIN32
+#include <mono/utils/mono-error-internals.h>
+#ifdef HOST_WIN32
 #include <direct.h>
 #endif
 
  * Changes which are already detected at runtime, like the addition
  * of icalls, do not require an increment.
  */
-#define MONO_CORLIB_VERSION 69
+#define MONO_CORLIB_VERSION 91
 
 typedef struct
 {
        int runtime_count;
        int assemblybinding_count;
        MonoDomain *domain;
+       gchar *filename;
 } RuntimeConfig;
 
 CRITICAL_SECTION mono_delegate_section;
@@ -110,6 +121,9 @@ add_assemblies_to_domain (MonoDomain *domain, MonoAssembly *ass, GHashTable *has
 static MonoAppDomain *
 mono_domain_create_appdomain_internal (char *friendly_name, MonoAppDomainSetup *setup);
 
+static char *
+get_shadow_assembly_location_base (MonoDomain *domain, MonoError *error);
+
 static MonoLoadFunc load_function = NULL;
 
 void
@@ -125,13 +139,13 @@ mono_runtime_load (const char *filename, const char *runtime_version)
        return load_function (filename, runtime_version);
 }
 
-/*
+/**
  * mono_runtime_set_no_exec:
  *
- *   Instructs the runtime to operate in static mode, i.e. avoid/do not allow managed
- * code execution. This is useful for running the AOT compiler on platforms which
- * allow full-aot execution only.
- * This should be called before mono_runtime_init ().
+ * Instructs the runtime to operate in static mode, i.e. avoid/do not
+ * allow managed code execution. This is useful for running the AOT
+ * compiler on platforms which allow full-aot execution only.  This
+ * should be called before mono_runtime_init ().
  */
 void
 mono_runtime_set_no_exec (gboolean val)
@@ -139,12 +153,58 @@ mono_runtime_set_no_exec (gboolean val)
        no_exec = val;
 }
 
+/**
+ * mono_runtime_get_no_exec:
+ *
+ * If true, then the runtime will not allow managed code execution.
+ */
 gboolean
 mono_runtime_get_no_exec (void)
 {
        return no_exec;
 }
 
+static void
+create_domain_objects (MonoDomain *domain)
+{
+       MonoDomain *old_domain = mono_domain_get ();
+       MonoString *arg;
+
+       if (domain != old_domain) {
+               mono_thread_push_appdomain_ref (domain);
+               mono_domain_set_internal_with_options (domain, FALSE);
+       }
+
+       /*
+        * Create an instance early since we can't do it when there is no memory.
+        */
+       arg = mono_string_new (domain, "Out of memory");
+       domain->out_of_memory_ex = mono_exception_from_name_two_strings (mono_defaults.corlib, "System", "OutOfMemoryException", arg, NULL);
+
+       /* 
+        * These two are needed because the signal handlers might be executing on
+        * an alternate stack, and Boehm GC can't handle that.
+        */
+       arg = mono_string_new (domain, "A null value was found where an object instance was required");
+       domain->null_reference_ex = mono_exception_from_name_two_strings (mono_defaults.corlib, "System", "NullReferenceException", arg, NULL);
+       arg = mono_string_new (domain, "The requested operation caused a stack overflow.");
+       domain->stack_overflow_ex = mono_exception_from_name_two_strings (mono_defaults.corlib, "System", "StackOverflowException", arg, NULL);
+
+       /*The ephemeron tombstone i*/
+       domain->ephemeron_tombstone = mono_object_new (domain, mono_defaults.object_class);
+
+       if (domain != old_domain) {
+               mono_thread_pop_appdomain_ref ();
+               mono_domain_set_internal_with_options (old_domain, FALSE);
+       }
+
+       /* 
+        * This class is used during exception handling, so initialize it here, to prevent
+        * stack overflows while handling stack overflows.
+        */
+       mono_class_init (mono_array_class_get (mono_defaults.int_class, 1));
+}
+
 /**
  * mono_runtime_init:
  * @domain: domain returned by mono_init ()
@@ -164,7 +224,6 @@ mono_runtime_init (MonoDomain *domain, MonoThreadStartCB start_cb,
        MonoAppDomainSetup *setup;
        MonoAppDomain *ad;
        MonoClass *class;
-       MonoString *arg;
 
        mono_portability_helpers_init ();
        
@@ -206,30 +265,21 @@ mono_runtime_init (MonoDomain *domain, MonoThreadStartCB start_cb,
 
        mono_type_initialization_init ();
 
-       if (!mono_runtime_get_no_exec ()) {
-               /*
-                * Create an instance early since we can't do it when there is no memory.
-                */
-               arg = mono_string_new (domain, "Out of memory");
-               domain->out_of_memory_ex = mono_exception_from_name_two_strings (mono_defaults.corlib, "System", "OutOfMemoryException", arg, NULL);
-       
-               /* 
-                * These two are needed because the signal handlers might be executing on
-                * an alternate stack, and Boehm GC can't handle that.
-                */
-               arg = mono_string_new (domain, "A null value was found where an object instance was required");
-               domain->null_reference_ex = mono_exception_from_name_two_strings (mono_defaults.corlib, "System", "NullReferenceException", arg, NULL);
-               arg = mono_string_new (domain, "The requested operation caused a stack overflow.");
-               domain->stack_overflow_ex = mono_exception_from_name_two_strings (mono_defaults.corlib, "System", "StackOverflowException", arg, NULL);
-       }
+       if (!mono_runtime_get_no_exec ())
+               create_domain_objects (domain);
 
        /* GC init has to happen after thread init */
        mono_gc_init ();
 
+#ifndef DISABLE_SOCKETS
        mono_network_init ();
-
+#endif
+       
+       mono_console_init ();
        mono_attach_init ();
 
+       mono_locks_tracer_init ();
+
        /* mscorlib is loaded before we install the load hook */
        mono_domain_fire_assembly_load (mono_defaults.corlib->assembly, NULL);
        
@@ -254,6 +304,14 @@ mono_get_corlib_version (void)
        return *(gint32*)((gchar*)value + sizeof (MonoObject));
 }
 
+/**
+ * mono_check_corlib_version
+ *
+ * Checks that the corlib that is loaded matches the version of this runtime.
+ *
+ * Returns: NULL if the runtime will work with the corlib, or a g_malloc
+ * allocated string with the error otherwise.
+ */
 const char*
 mono_check_corlib_version (void)
 {
@@ -264,6 +322,12 @@ mono_check_corlib_version (void)
                return NULL;
 }
 
+/**
+ * mono_context_init:
+ * @domain: The domain where the System.Runtime.Remoting.Context.Context is initialized
+ *
+ * Initializes the @domain's default System.Runtime.Remoting's Context.
+ */
 void
 mono_context_init (MonoDomain *domain)
 {
@@ -298,17 +362,14 @@ mono_runtime_cleanup (MonoDomain *domain)
 
        mono_thread_cleanup ();
 
+#ifndef DISABLE_SOCKETS
        mono_network_cleanup ();
-
+#endif
        mono_marshal_cleanup ();
 
        mono_type_initialization_cleanup ();
 
        mono_monitor_cleanup ();
-
-#ifndef PLATFORM_WIN32
-       _wapi_cleanup ();
-#endif
 }
 
 static MonoDomainFunc quit_function = NULL;
@@ -376,12 +437,49 @@ mono_domain_create_appdomain (char *friendly_name, char *configuration_file)
        return mono_domain_from_appdomain (ad);
 }
 
+static MonoAppDomainSetup*
+copy_app_domain_setup (MonoDomain *domain, MonoAppDomainSetup *setup)
+{
+       MonoDomain *caller_domain = mono_domain_get ();
+       MonoClass *ads_class = mono_class_from_name (mono_defaults.corlib, "System", "AppDomainSetup");
+       MonoAppDomainSetup *copy = (MonoAppDomainSetup*)mono_object_new (domain, ads_class);
+
+       mono_domain_set_internal (domain);
+
+       MONO_OBJECT_SETREF (copy, application_base, mono_marshal_xdomain_copy_value ((MonoObject*)setup->application_base));
+       MONO_OBJECT_SETREF (copy, application_name, mono_marshal_xdomain_copy_value ((MonoObject*)setup->application_name));
+       MONO_OBJECT_SETREF (copy, cache_path, mono_marshal_xdomain_copy_value ((MonoObject*)setup->cache_path));
+       MONO_OBJECT_SETREF (copy, configuration_file, mono_marshal_xdomain_copy_value ((MonoObject*)setup->configuration_file));
+       MONO_OBJECT_SETREF (copy, dynamic_base, mono_marshal_xdomain_copy_value ((MonoObject*)setup->dynamic_base));
+       MONO_OBJECT_SETREF (copy, license_file, mono_marshal_xdomain_copy_value ((MonoObject*)setup->license_file));
+       MONO_OBJECT_SETREF (copy, private_bin_path, mono_marshal_xdomain_copy_value ((MonoObject*)setup->private_bin_path));
+       MONO_OBJECT_SETREF (copy, private_bin_path_probe, mono_marshal_xdomain_copy_value ((MonoObject*)setup->private_bin_path_probe));
+       MONO_OBJECT_SETREF (copy, shadow_copy_directories, mono_marshal_xdomain_copy_value ((MonoObject*)setup->shadow_copy_directories));
+       MONO_OBJECT_SETREF (copy, shadow_copy_files, mono_marshal_xdomain_copy_value ((MonoObject*)setup->shadow_copy_files));
+       copy->publisher_policy = setup->publisher_policy;
+       copy->path_changed = setup->path_changed;
+       copy->loader_optimization = setup->loader_optimization;
+       copy->disallow_binding_redirects = setup->disallow_binding_redirects;
+       copy->disallow_code_downloads = setup->disallow_code_downloads;
+       MONO_OBJECT_SETREF (copy, domain_initializer_args, mono_marshal_xdomain_copy_value ((MonoObject*)setup->domain_initializer_args));
+       copy->disallow_appbase_probe = setup->disallow_appbase_probe;
+       MONO_OBJECT_SETREF (copy, application_trust, mono_marshal_xdomain_copy_value ((MonoObject*)setup->application_trust));
+       MONO_OBJECT_SETREF (copy, configuration_bytes, mono_marshal_xdomain_copy_value ((MonoObject*)setup->configuration_bytes));
+       MONO_OBJECT_SETREF (copy, serialized_non_primitives, mono_marshal_xdomain_copy_value ((MonoObject*)setup->serialized_non_primitives));
+
+       mono_domain_set_internal (caller_domain);
+
+       return copy;
+}
+
 static MonoAppDomain *
 mono_domain_create_appdomain_internal (char *friendly_name, MonoAppDomainSetup *setup)
 {
+       MonoError error;
        MonoClass *adclass;
        MonoAppDomain *ad;
        MonoDomain *data;
+       char *shadow_location;
        
        MONO_ARCH_SAVE_REGS;
 
@@ -393,11 +491,7 @@ mono_domain_create_appdomain_internal (char *friendly_name, MonoAppDomainSetup *
        ad = (MonoAppDomain *) mono_object_new (data, adclass);
        ad->data = data;
        data->domain = ad;
-       data->setup = setup;
        data->friendly_name = g_strdup (friendly_name);
-       // FIXME: The ctor runs in the current domain
-       // FIXME: Initialize null_reference_ex and stack_overflow_ex
-       data->out_of_memory_ex = mono_exception_from_name_domain (data, mono_defaults.corlib, "System", "OutOfMemoryException");
 
        if (!setup->application_base) {
                /* Inherit from the root domain since MS.NET does this */
@@ -408,10 +502,21 @@ mono_domain_create_appdomain_internal (char *friendly_name, MonoAppDomainSetup *
 
        mono_context_init (data);
 
+       data->setup = copy_app_domain_setup (data, setup);
        mono_set_private_bin_path_from_config (data);
-       
        add_assemblies_to_domain (data, mono_defaults.corlib->assembly, NULL);
 
+#ifndef DISABLE_SHADOW_COPY
+       /*FIXME, guard this for when the debugger is not running */
+       shadow_location = get_shadow_assembly_location_base (data, &error);
+       if (!mono_error_ok (&error))
+               mono_error_raise_exception (&error);
+       mono_debugger_event_create_appdomain (data, shadow_location);
+       g_free (shadow_location);
+#endif
+
+       create_domain_objects (data);
+
        return ad;
 }
 
@@ -433,6 +538,10 @@ mono_domain_has_type_resolve (MonoDomain *domain)
                g_assert (field);
        }
 
+       /*pedump doesn't create an appdomin, so the domain object doesn't exist.*/
+       if (!domain->domain)
+               return FALSE;
+
        mono_field_get_value ((MonoObject*)(domain->domain), field, &o);
        return o != NULL;
 }
@@ -690,30 +799,43 @@ end_element (GMarkupParseContext *context,
                runtime_config->assemblybinding_count--;
 }
 
+static void
+parse_error   (GMarkupParseContext *context, GError *error, gpointer user_data)
+{
+       RuntimeConfig *state = user_data;
+       const gchar *msg;
+       const gchar *filename;
+
+       filename = state && state->filename ? (gchar *) state->filename : "<unknown>";
+       msg = error && error->message ? error->message : "";
+       g_warning ("Error parsing %s: %s", filename, msg);
+}
+
 static const GMarkupParser
 mono_parser = {
        start_element,
        end_element,
        NULL,
        NULL,
-       NULL
+       parse_error
 };
 
 void
 mono_set_private_bin_path_from_config (MonoDomain *domain)
 {
+       MonoError error;
        gchar *config_file, *text;
        gsize len;
-       struct stat sbuf;
        GMarkupParseContext *context;
        RuntimeConfig runtime_config;
+       gint offset;
        
        if (!domain || !domain->setup || !domain->setup->configuration_file)
                return;
 
-       config_file = mono_string_to_utf8 (domain->setup->configuration_file);
-       if (stat (config_file, &sbuf) != 0) {
-               g_free (config_file);
+       config_file = mono_string_to_utf8_checked (domain->setup->configuration_file, &error); 
+       if (!mono_error_ok (&error)) {
+               mono_error_cleanup (&error);
                return;
        }
 
@@ -721,17 +843,22 @@ mono_set_private_bin_path_from_config (MonoDomain *domain)
                g_free (config_file);
                return;
        }
-       g_free (config_file);
 
        runtime_config.runtime_count = 0;
        runtime_config.assemblybinding_count = 0;
        runtime_config.domain = domain;
+       runtime_config.filename = config_file;
        
+       offset = 0;
+       if (len > 3 && text [0] == '\xef' && text [1] == (gchar) '\xbb' && text [2] == '\xbf')
+               offset = 3; /* Skip UTF-8 BOM */
+
        context = g_markup_parse_context_new (&mono_parser, 0, &runtime_config, NULL);
-       if (g_markup_parse_context_parse (context, text, len, NULL))
+       if (g_markup_parse_context_parse (context, text + offset, len - offset, NULL))
                g_markup_parse_context_end_parse (context, NULL);
        g_markup_parse_context_free (context);
        g_free (text);
+       g_free (config_file);
 }
 
 MonoAppDomain *
@@ -771,7 +898,7 @@ ves_icall_System_AppDomain_GetAssemblies (MonoAppDomain *ad, MonoBoolean refonly
        mono_domain_assemblies_lock (domain);
        for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
                ass = tmp->data;
-               if (refonly && !ass->ref_only)
+               if (refonly != ass->ref_only)
                        continue;
                if (ass->corlib_internal)
                        continue;
@@ -798,6 +925,9 @@ mono_try_assembly_resolve (MonoDomain *domain, MonoString *fname, gboolean refon
        MonoBoolean isrefonly;
        gpointer params [2];
 
+       if (mono_runtime_get_no_exec ())
+               return NULL;
+
        g_assert (domain != NULL && fname != NULL);
 
        klass = domain->domain->mbr.obj.vtable->klass;
@@ -823,12 +953,17 @@ mono_domain_assembly_postload_search (MonoAssemblyName *aname,
        MonoReflectionAssembly *assembly;
        MonoDomain *domain = mono_domain_get ();
        char *aname_str;
+       MonoString *str;
 
        aname_str = mono_stringify_assembly_name (aname);
 
        /* FIXME: We invoke managed code here, so there is a potential for deadlocks */
-       assembly = mono_try_assembly_resolve (domain, mono_string_new (domain, aname_str), refonly);
-
+       str = mono_string_new (domain, aname_str);
+       if (!str) {
+               g_free (aname_str);
+               return NULL;
+       }
+       assembly = mono_try_assembly_resolve (domain, str, refonly);
        g_free (aname_str);
 
        if (assembly)
@@ -930,13 +1065,14 @@ mono_domain_fire_assembly_load (MonoAssembly *assembly, gpointer user_data)
 static void
 set_domain_search_path (MonoDomain *domain)
 {
+       MonoError error;
        MonoAppDomainSetup *setup;
        gchar **tmp;
        gchar *search_path = NULL;
        gint i;
        gint npaths = 0;
        gchar **pvt_split = NULL;
-       GError *error = NULL;
+       GError *gerror = NULL;
        gint appbaselen = -1;
 
        /* 
@@ -962,8 +1098,15 @@ set_domain_search_path (MonoDomain *domain)
 
        npaths++;
        
-       if (setup->private_bin_path)
-               search_path = mono_string_to_utf8 (setup->private_bin_path);
+       if (setup->private_bin_path) {
+               search_path = mono_string_to_utf8_checked (setup->private_bin_path, &error);
+               if (!mono_error_ok (&error)) { /*FIXME maybe we should bubble up the error.*/
+                       g_warning ("Could not decode AppDomain search path since it contains invalid caracters");
+                       mono_error_cleanup (&error);
+                       mono_domain_assemblies_unlock (domain);
+                       return;
+               }
+       }
        
        if (domain->private_bin_path) {
                if (search_path == NULL)
@@ -987,7 +1130,7 @@ set_domain_search_path (MonoDomain *domain)
                 * The issue was reported in bug #81446
                 */
 
-#ifndef PLATFORM_WIN32
+#ifndef TARGET_WIN32
                gint slen;
 
                slen = strlen (search_path);
@@ -1018,10 +1161,20 @@ set_domain_search_path (MonoDomain *domain)
        if (domain->search_path)
                g_strfreev (domain->search_path);
 
-       domain->search_path = tmp = g_malloc ((npaths + 1) * sizeof (gchar *));
+       tmp = g_malloc ((npaths + 1) * sizeof (gchar *));
        tmp [npaths] = NULL;
 
-       *tmp = mono_string_to_utf8 (setup->application_base);
+       *tmp = mono_string_to_utf8_checked (setup->application_base, &error);
+       if (!mono_error_ok (&error)) {
+               mono_error_cleanup (&error);
+               g_strfreev (pvt_split);
+               g_free (tmp);
+
+               mono_domain_assemblies_unlock (domain);
+               return;
+       }
+
+       domain->search_path = tmp;
 
        /* FIXME: is this needed? */
        if (strncmp (*tmp, "file://", 7) == 0) {
@@ -1034,15 +1187,15 @@ set_domain_search_path (MonoDomain *domain)
 
                tmpuri = uri;
                uri = mono_escape_uri_string (tmpuri);
-               *tmp = g_filename_from_uri (uri, NULL, &error);
+               *tmp = g_filename_from_uri (uri, NULL, &gerror);
                g_free (uri);
 
                if (tmpuri != file)
                        g_free (tmpuri);
 
-               if (error != NULL) {
-                       g_warning ("%s\n", error->message);
-                       g_error_free (error);
+               if (gerror != NULL) {
+                       g_warning ("%s\n", gerror->message);
+                       g_error_free (gerror);
                        *tmp = file;
                } else {
                        g_free (file);
@@ -1089,6 +1242,19 @@ set_domain_search_path (MonoDomain *domain)
        mono_domain_assemblies_unlock (domain);
 }
 
+#ifdef DISABLE_SHADOW_COPY
+gboolean
+mono_is_shadow_copy_enabled (MonoDomain *domain, const gchar *dir_name)
+{
+       return FALSE;
+}
+
+char *
+mono_make_shadow_copy (const char *filename)
+{
+       return (char *) filename;
+}
+#else
 static gboolean
 shadow_copy_sibling (gchar *src, gint srclen, const char *extension, gchar *target, gint targetlen, gint tail_len)
 {
@@ -1096,8 +1262,18 @@ shadow_copy_sibling (gchar *src, gint srclen, const char *extension, gchar *targ
        gboolean copy_result;
        
        strcpy (src + srclen - tail_len, extension);
-       if (!g_file_test (src, G_FILE_TEST_IS_REGULAR))
+
+       if (IS_PORTABILITY_CASE) {
+               gchar *file = mono_portability_find_file (src, TRUE);
+
+               if (file == NULL)
+                       return TRUE;
+
+               g_free (file);
+       } else if (!g_file_test (src, G_FILE_TEST_IS_REGULAR)) {
                return TRUE;
+       }
+
        orig = g_utf8_to_utf16 (src, strlen (src), NULL, NULL, NULL);
 
        strcpy (target + targetlen - tail_len, extension);
@@ -1105,6 +1281,12 @@ shadow_copy_sibling (gchar *src, gint srclen, const char *extension, gchar *targ
        
        DeleteFile (dest);
        copy_result = CopyFile (orig, dest, FALSE);
+
+       /* Fix for bug #556884 - make sure the files have the correct mode so that they can be
+        * overwritten when updated in their original locations. */
+       if (copy_result)
+               copy_result = SetFileAttributes (dest, FILE_ATTRIBUTE_NORMAL);
+
        g_free (orig);
        g_free (dest);
        
@@ -1131,18 +1313,25 @@ get_cstring_hash (const char *str)
        return h;
 }
 
+/*
+ * Returned memory is malloc'd. Called must free it 
+ */
 static char *
-get_shadow_assembly_location_base (MonoDomain *domain)
+get_shadow_assembly_location_base (MonoDomain *domain, MonoError *error)
 {
        MonoAppDomainSetup *setup;
        char *cache_path, *appname;
        char *userdir;
        char *location;
+
+       mono_error_init (error);
        
        setup = domain->setup;
        if (setup->cache_path != NULL && setup->application_name != NULL) {
-               cache_path = mono_string_to_utf8 (setup->cache_path);
-#ifndef PLATFORM_WIN32
+               cache_path = mono_string_to_utf8_checked (setup->cache_path, error);
+               if (!mono_error_ok (error))
+                       return NULL;
+#ifndef TARGET_WIN32
                {
                        gint i;
                        for (i = strlen (cache_path) - 1; i >= 0; i--)
@@ -1151,7 +1340,12 @@ get_shadow_assembly_location_base (MonoDomain *domain)
                }
 #endif
 
-               appname = mono_string_to_utf8 (setup->application_name);
+               appname = mono_string_to_utf8_checked (setup->application_name, error);
+               if (!mono_error_ok (error)) {
+                       g_free (cache_path);
+                       return NULL;
+               }
+
                location = g_build_filename (cache_path, appname, "assembly", "shadow", NULL);
                g_free (appname);
                g_free (cache_path);
@@ -1164,7 +1358,7 @@ get_shadow_assembly_location_base (MonoDomain *domain)
 }
 
 static char *
-get_shadow_assembly_location (const char *filename)
+get_shadow_assembly_location (const char *filename, MonoError *error)
 {
        gint32 hash = 0, hash2 = 0;
        char name_hash [9];
@@ -1173,21 +1367,31 @@ get_shadow_assembly_location (const char *filename)
        char *dirname = g_path_get_dirname (filename);
        char *location, *tmploc;
        MonoDomain *domain = mono_domain_get ();
+
+       mono_error_init (error);
        
        hash = get_cstring_hash (bname);
        hash2 = get_cstring_hash (dirname);
        g_snprintf (name_hash, sizeof (name_hash), "%08x", hash);
        g_snprintf (path_hash, sizeof (path_hash), "%08x_%08x_%08x", hash ^ hash2, hash2, domain->shadow_serial);
-       tmploc = get_shadow_assembly_location_base (domain);
+       tmploc = get_shadow_assembly_location_base (domain, error);
+       if (!mono_error_ok (error)) {
+               g_free (bname);
+               g_free (dirname);
+               return NULL;
+       }
+
        location = g_build_filename (tmploc, name_hash, path_hash, bname, NULL);
        g_free (tmploc);
+       g_free (bname);
+       g_free (dirname);
        return location;
 }
 
 static gboolean
 ensure_directory_exists (const char *filename)
 {
-#ifdef PLATFORM_WIN32
+#ifdef HOST_WIN32
        gchar *dir_utf8 = g_path_get_dirname (filename);
        gunichar2 *p;
        gunichar2 *dir_utf16 = NULL;
@@ -1283,8 +1487,7 @@ private_file_needs_copying (const char *src, struct stat *sbuf_src, char *dest)
        if (stat (src, sbuf_src) == -1 || stat (dest, &sbuf_dest) == -1)
                return TRUE;
 
-       if (sbuf_src->st_mode == sbuf_dest.st_mode &&
-           sbuf_src->st_size == sbuf_dest.st_size &&
+       if (sbuf_src->st_size == sbuf_dest.st_size &&
            sbuf_src->st_mtime == sbuf_dest.st_mtime)
                return FALSE;
 
@@ -1332,7 +1535,7 @@ shadow_copy_create_ini (const char *shadow, const char *filename)
 gboolean
 mono_is_shadow_copy_enabled (MonoDomain *domain, const gchar *dir_name)
 {
-       const char *version;
+       MonoError error;
        MonoAppDomainSetup *setup;
        gchar *all_dirs;
        gchar **dir_ptr;
@@ -1349,11 +1552,14 @@ mono_is_shadow_copy_enabled (MonoDomain *domain, const gchar *dir_name)
        if (setup == NULL || setup->shadow_copy_files == NULL)
                return FALSE;
 
-       version = mono_get_runtime_info ()->framework_version;
-       shadow_status_string = mono_string_to_utf8 (setup->shadow_copy_files);
-       /* For 1.x, not NULL is enough. In 2.0 it has to be "true" */
-       shadow_enabled = (*version <= '1' || !g_ascii_strncasecmp (shadow_status_string, "true", 4));
+       shadow_status_string = mono_string_to_utf8_checked (setup->shadow_copy_files, &error);
+       if (!mono_error_ok (&error)) {
+               mono_error_cleanup (&error);
+               return FALSE;
+       }
+       shadow_enabled = !g_ascii_strncasecmp (shadow_status_string, "true", 4);
        g_free (shadow_status_string);
+
        if (!shadow_enabled)
                return FALSE;
 
@@ -1361,14 +1567,24 @@ mono_is_shadow_copy_enabled (MonoDomain *domain, const gchar *dir_name)
                return TRUE;
 
        /* Is dir_name a shadow_copy destination already? */
-       base_dir = get_shadow_assembly_location_base (domain);
-       if (strstr (dir_name, base_dir) == dir_name) {
+       base_dir = get_shadow_assembly_location_base (domain, &error);
+       if (!mono_error_ok (&error)) {
+               mono_error_cleanup (&error);
+               return FALSE;
+       }
+
+       if (strstr (dir_name, base_dir)) {
                g_free (base_dir);
                return TRUE;
        }
        g_free (base_dir);
 
-       all_dirs = mono_string_to_utf8 (setup->shadow_copy_directories);
+       all_dirs = mono_string_to_utf8_checked (setup->shadow_copy_directories, &error);
+       if (!mono_error_ok (&error)) {
+               mono_error_cleanup (&error);
+               return FALSE;
+       }
+
        directories = g_strsplit (all_dirs, G_SEARCHPATH_SEPARATOR_S, 1000);
        dir_ptr = directories;
        while (*dir_ptr) {
@@ -1383,9 +1599,15 @@ mono_is_shadow_copy_enabled (MonoDomain *domain, const gchar *dir_name)
        return found;
 }
 
+/*
+This function raises exceptions so it can cause as sorts of nasty stuff if called
+while holding a lock.
+FIXME bubble up the error instead of raising it here
+*/
 char *
 mono_make_shadow_copy (const char *filename)
 {
+       MonoError error;
        gchar *sibling_source, *sibling_target;
        gint sibling_source_len, sibling_target_len;
        guint16 *orig, *dest;
@@ -1396,15 +1618,39 @@ mono_make_shadow_copy (const char *filename)
        struct utimbuf utbuf;
        char *dir_name = g_path_get_dirname (filename);
        MonoDomain *domain = mono_domain_get ();
+       char *shadow_dir;
+
        set_domain_search_path (domain);
 
        if (!mono_is_shadow_copy_enabled (domain, dir_name)) {
                g_free (dir_name);
                return (char *) filename;
        }
+
+       /* Is dir_name a shadow_copy destination already? */
+       shadow_dir = get_shadow_assembly_location_base (domain, &error);
+       if (!mono_error_ok (&error)) {
+               mono_error_cleanup (&error);
+               g_free (dir_name);
+               exc = mono_get_exception_execution_engine ("Failed to create shadow copy (invalid characters in shadow directory name).");
+               mono_raise_exception (exc);
+       }
+
+       if (strstr (dir_name, shadow_dir)) {
+               g_free (shadow_dir);
+               g_free (dir_name);
+               return (char *) filename;
+       }
+       g_free (shadow_dir);
        g_free (dir_name);
-       
-       shadow = get_shadow_assembly_location (filename);
+
+       shadow = get_shadow_assembly_location (filename, &error);
+       if (!mono_error_ok (&error)) {
+               mono_error_cleanup (&error);
+               exc = mono_get_exception_execution_engine ("Failed to create shadow copy (invalid characters in file name).");
+               mono_raise_exception (exc);
+       }
+
        if (ensure_directory_exists (shadow) == FALSE) {
                g_free (shadow);
                exc = mono_get_exception_execution_engine ("Failed to create shadow copy (ensure directory exists).");
@@ -1418,6 +1664,12 @@ mono_make_shadow_copy (const char *filename)
        dest = g_utf8_to_utf16 (shadow, strlen (shadow), NULL, NULL, NULL);
        DeleteFile (dest);
        copy_result = CopyFile (orig, dest, FALSE);
+
+       /* Fix for bug #556884 - make sure the files have the correct mode so that they can be
+        * overwritten when updated in their original locations. */
+       if (copy_result)
+               copy_result = SetFileAttributes (dest, FILE_ATTRIBUTE_NORMAL);
+
        g_free (dest);
        g_free (orig);
 
@@ -1459,7 +1711,7 @@ mono_make_shadow_copy (const char *filename)
        
        return shadow;
 }
-
+#endif /* DISABLE_SHADOW_COPY */
 
 MonoDomain *
 mono_domain_from_appdomain (MonoAppDomain *appdomain)
@@ -1694,11 +1946,8 @@ ves_icall_System_AppDomain_LoadAssembly (MonoAppDomain *ad,  MonoString *assRef,
        g_free (name);
 
        if (!parsed) {
-               MonoException *exc;
-
                /* This is a parse error... */
-               exc = mono_get_exception_file_not_found2 (NULL, assRef);
-               mono_raise_exception (exc);
+               return NULL;
        }
 
        ass = mono_assembly_load_full_nosearch (&aname, NULL, &status, refOnly);
@@ -1711,9 +1960,7 @@ ves_icall_System_AppDomain_LoadAssembly (MonoAppDomain *ad,  MonoString *assRef,
                else
                        refass = NULL;
                if (!refass) {
-                       /* FIXME: it doesn't make much sense since we really don't have a filename ... */
-                       MonoException *exc = mono_get_exception_file_not_found2 (NULL, assRef);
-                       mono_raise_exception (exc);
+                       return NULL;
                }
        }
 
@@ -1907,15 +2154,26 @@ mono_domain_is_unloading (MonoDomain *domain)
 }
 
 static void
-clear_cached_vtable (gpointer key, gpointer value, gpointer user_data)
+clear_cached_vtable (MonoVTable *vtable)
 {
-       MonoClass *klass = (MonoClass*)key;
-       MonoDomain *domain = (MonoDomain*)user_data;
+       MonoClass *klass = vtable->klass;
+       MonoDomain *domain = vtable->domain;
        MonoClassRuntimeInfo *runtime_info;
 
        runtime_info = klass->runtime_info;
        if (runtime_info && runtime_info->max_domain >= domain->domain_id)
                runtime_info->domain_vtables [domain->domain_id] = NULL;
+       if (vtable->data && klass->has_static_refs)
+               mono_gc_free_fixed (vtable->data);
+}
+
+static G_GNUC_UNUSED void
+zero_static_data (MonoVTable *vtable)
+{
+       MonoClass *klass = vtable->klass;
+
+       if (vtable->data && klass->has_static_refs)
+               memset (vtable->data, 0, mono_class_data_size (klass));
 }
 
 typedef struct unload_data {
@@ -1923,15 +2181,82 @@ typedef struct unload_data {
        char *failure_reason;
 } unload_data;
 
+#ifdef HAVE_SGEN_GC
+static void
+deregister_reflection_info_roots_nspace_table (gpointer key, gpointer value, gpointer image)
+{
+       guint32 index = GPOINTER_TO_UINT (value);
+       MonoClass *class = mono_class_get (image, MONO_TOKEN_TYPE_DEF | index);
+
+       g_assert (class);
+
+       mono_class_free_ref_info (class);
+}
+
+static void
+deregister_reflection_info_roots_name_space (gpointer key, gpointer value, gpointer user_data)
+{
+       g_hash_table_foreach (value, deregister_reflection_info_roots_nspace_table, user_data);
+}
+
+static void
+deregister_reflection_info_roots_from_list (MonoImage *image)
+{
+       GSList *list = image->reflection_info_unregister_classes;
+
+       while (list) {
+               MonoClass *class = list->data;
+
+               mono_class_free_ref_info (class);
+
+               list = list->next;
+       }
+
+       g_slist_free (image->reflection_info_unregister_classes);
+       image->reflection_info_unregister_classes = NULL;
+}
+
+static void
+deregister_reflection_info_roots (MonoDomain *domain)
+{
+       GSList *list;
+
+       mono_loader_lock ();
+       mono_domain_assemblies_lock (domain);
+       for (list = domain->domain_assemblies; list; list = list->next) {
+               MonoAssembly *assembly = list->data;
+               MonoImage *image = assembly->image;
+               int i;
+               /*No need to take the image lock here since dynamic images are appdomain bound and at this point the mutator is gone.*/
+               if (image->dynamic && image->name_cache)
+                       g_hash_table_foreach (image->name_cache, deregister_reflection_info_roots_name_space, image);
+               deregister_reflection_info_roots_from_list (image);
+               for (i = 0; i < image->module_count; ++i) {
+                       MonoImage *module = image->modules [i];
+                       if (module) {
+                               if (module->dynamic && module->name_cache) {
+                                       g_hash_table_foreach (module->name_cache,
+                                                       deregister_reflection_info_roots_name_space, module);
+                               }
+                               deregister_reflection_info_roots_from_list (module);
+                       }
+               }
+       }
+       mono_domain_assemblies_unlock (domain);
+       mono_loader_unlock ();
+}
+#endif
 
 static guint32 WINAPI
 unload_thread_main (void *arg)
 {
        unload_data *data = (unload_data*)arg;
        MonoDomain *domain = data->domain;
+       MonoThread *thread;
+       int i;
 
        /* Have to attach to the runtime so shutdown can wait for this thread */
-       mono_thread_attach (mono_get_root_domain ());
+       thread = mono_thread_attach (mono_get_root_domain ());
 
        /* 
         * FIXME: Abort our parent thread last, so we can return a failure 
@@ -1957,11 +2282,30 @@ unload_thread_main (void *arg)
         * We also hold the loader lock because we're going to change
         * class->runtime_info.
         */
-       mono_domain_lock (domain);
+
        mono_loader_lock ();
-       g_hash_table_foreach (domain->class_vtable_hash, clear_cached_vtable, domain);
-       mono_loader_unlock ();
+       mono_domain_lock (domain);
+#ifdef HAVE_SGEN_GC
+       /*
+        * We need to make sure that we don't have any remsets
+        * pointing into static data of the to-be-freed domain because
+        * at the next collections they would be invalid.  So what we
+        * do is we first zero all static data and then do a minor
+        * collection.  Because all references in the static data will
+        * now be null we won't do any unnecessary copies and after
+        * the collection there won't be any more remsets.
+        */
+       for (i = 0; i < domain->class_vtable_array->len; ++i)
+               zero_static_data (g_ptr_array_index (domain->class_vtable_array, i));
+       mono_gc_collect (0);
+#endif
+       for (i = 0; i < domain->class_vtable_array->len; ++i)
+               clear_cached_vtable (g_ptr_array_index (domain->class_vtable_array, i));
+#ifdef HAVE_SGEN_GC
+       deregister_reflection_info_roots (domain);
+#endif
        mono_domain_unlock (domain);
+       mono_loader_unlock ();
 
        mono_threads_clear_cached_culture (domain);
 
@@ -1976,6 +2320,8 @@ unload_thread_main (void *arg)
 
        mono_gc_collect (mono_gc_max_generation ());
 
+       mono_thread_detach  (thread);
+
        return 0;
 }
 
@@ -1983,22 +2329,45 @@ unload_thread_main (void *arg)
  * mono_domain_unload:
  * @domain: The domain to unload
  *
+ *  Unloads an appdomain. Follows the process outlined in the comment
+ *  for mono_domain_try_unload.
+ */
+void
+mono_domain_unload (MonoDomain *domain)
+{
+       MonoObject *exc = NULL;
+       mono_domain_try_unload (domain, &exc);
+       if (exc)
+               mono_raise_exception ((MonoException*)exc);
+}
+
+/*
+ * mono_domain_unload:
+ * @domain: The domain to unload
+ * @exc: Exception information
+ *
  *  Unloads an appdomain. Follows the process outlined in:
  *  http://blogs.gotdotnet.com/cbrumme
  *
  *  If doing things the 'right' way is too hard or complex, we do it the 
  *  'simple' way, which means do everything needed to avoid crashes and
  *  memory leaks, but not much else.
+ *
+ *  It is required to pass a valid reference to the exc argument, upon return
+ *  from this function *exc will be set to the exception thrown, if any.
+ *
+ *  If this method is not called from an icall (embedded scenario for instance),
+ *  it must not be called with any managed frames on the stack, since the unload
+ *  process could end up trying to abort the current thread.
  */
 void
-mono_domain_unload (MonoDomain *domain)
+mono_domain_try_unload (MonoDomain *domain, MonoObject **exc)
 {
        HANDLE thread_handle;
        gsize tid;
        guint32 res;
        MonoAppDomainState prev_state;
        MonoMethod *method;
-       MonoObject *exc;
        unload_data thread_data;
        MonoDomain *caller_domain = mono_domain_get ();
 
@@ -2012,36 +2381,38 @@ mono_domain_unload (MonoDomain *domain)
                switch (prev_state) {
                case MONO_APPDOMAIN_UNLOADING_START:
                case MONO_APPDOMAIN_UNLOADING:
-                       mono_raise_exception (mono_get_exception_cannot_unload_appdomain ("Appdomain is already being unloaded."));
-                       break;
+                       *exc = (MonoObject *) mono_get_exception_cannot_unload_appdomain ("Appdomain is already being unloaded.");
+                       return;
                case MONO_APPDOMAIN_UNLOADED:
-                       mono_raise_exception (mono_get_exception_cannot_unload_appdomain ("Appdomain is already unloaded."));
-                       break;
+                       *exc = (MonoObject *) mono_get_exception_cannot_unload_appdomain ("Appdomain is already unloaded.");
+                       return;
                default:
-                       g_warning ("Incalid appdomain state %d", prev_state);
+                       g_warning ("Invalid appdomain state %d", prev_state);
                        g_assert_not_reached ();
                }
        }
 
+       mono_debugger_event_unload_appdomain (domain);
+
        mono_domain_set (domain, FALSE);
        /* Notify OnDomainUnload listeners */
        method = mono_class_get_method_from_name (domain->domain->mbr.obj.vtable->klass, "DoDomainUnload", -1); 
        g_assert (method);
 
-       exc = NULL;
-       mono_runtime_invoke (method, domain->domain, NULL, &exc);
-       if (exc) {
+       mono_runtime_invoke (method, domain->domain, NULL, exc);
+       if (*exc) {
                /* Roll back the state change */
                domain->state = MONO_APPDOMAIN_CREATED;
                mono_domain_set (caller_domain, FALSE);
-               mono_raise_exception ((MonoException*)exc);
+               return;
        }
+       mono_domain_set (caller_domain, FALSE);
 
        thread_data.domain = domain;
        thread_data.failure_reason = NULL;
 
-       /*Move from unloading_start to unloading. Now no new TP jobs are going to be accepted.*/
-       InterlockedIncrement ((gint32*)&domain->state);
+       /*The managed callback finished successfully, now we start tearing down the appdomain*/
+       domain->state = MONO_APPDOMAIN_UNLOADING;
        /* 
         * First we create a separate thread for unloading, since
         * we might have to abort some threads, including the current one.
@@ -2052,9 +2423,9 @@ mono_domain_unload (MonoDomain *domain)
         * http://bugzilla.ximian.com/show_bug.cgi?id=27663
         */ 
 #if 0
-       thread_handle = CreateThread (NULL, 0, unload_thread_main, &thread_data, 0, &tid);
+       thread_handle = mono_create_thread (NULL, 0, unload_thread_main, &thread_data, 0, &tid);
 #else
-       thread_handle = CreateThread (NULL, 0, (LPTHREAD_START_ROUTINE)unload_thread_main, &thread_data, CREATE_SUSPENDED, &tid);
+       thread_handle = mono_create_thread (NULL, 0, (LPTHREAD_START_ROUTINE)unload_thread_main, &thread_data, CREATE_SUSPENDED, &tid);
        if (thread_handle == NULL) {
                return;
        }
@@ -2063,29 +2434,24 @@ mono_domain_unload (MonoDomain *domain)
 
        /* Wait for the thread */       
        while ((res = WaitForSingleObjectEx (thread_handle, INFINITE, TRUE) == WAIT_IO_COMPLETION)) {
-               if (mono_thread_has_appdomain_ref (mono_thread_current (), domain) && (mono_thread_interruption_requested ()))
+               if (mono_thread_internal_has_appdomain_ref (mono_thread_internal_current (), domain) && (mono_thread_interruption_requested ())) {
                        /* The unload thread tries to abort us */
                        /* The icall wrapper will execute the abort */
                        CloseHandle (thread_handle);
                        return;
+               }
        }
        CloseHandle (thread_handle);
 
-       mono_domain_set (caller_domain, FALSE);
-
        if (thread_data.failure_reason) {
-               MonoException *ex;
-
                /* Roll back the state change */
                domain->state = MONO_APPDOMAIN_CREATED;
 
-               g_warning (thread_data.failure_reason);
+               g_warning ("%s", thread_data.failure_reason);
 
-               ex = mono_get_exception_cannot_unload_appdomain (thread_data.failure_reason);
+               *exc = (MonoObject *) mono_get_exception_cannot_unload_appdomain (thread_data.failure_reason);
 
                g_free (thread_data.failure_reason);
                thread_data.failure_reason = NULL;
-
-               mono_raise_exception (ex);
        }
 }