Merge branch 'BigIntegerParse'
[mono.git] / mono / metadata / appdomain.c
index 13a3d5f54d9560fd569e7ff2ca63b74224d73837..11b6fa58c0980e51b90c9faf16a99d1442065f61 100644 (file)
@@ -8,20 +8,22 @@
  *
  * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
  * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
+ * Copyright 2012 Xamarin Inc
  */
 #undef ASSEMBLY_LOAD_DEBUG
 #include <config.h>
 #include <glib.h>
 #include <string.h>
-#ifdef HAVE_UNISTD_H
-#include <unistd.h>
-#endif
 #include <errno.h>
-#include <sys/stat.h>
+#include <time.h>
 #include <sys/types.h>
+#include <sys/stat.h>
 #ifdef HAVE_SYS_TIME_H
 #include <sys/time.h>
 #endif
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>
+#endif
 #ifdef HAVE_UTIME_H
 #include <utime.h>
 #else
@@ -58,6 +60,9 @@
 #include <mono/utils/mono-stdlib.h>
 #include <mono/utils/mono-io-portability.h>
 #include <mono/utils/mono-error-internals.h>
+#include <mono/utils/atomic.h>
+#include <mono/utils/mono-memory-model.h>
+#include <mono/utils/mono-threads.h>
 #ifdef HOST_WIN32
 #include <direct.h>
 #endif
@@ -73,7 +78,7 @@
  * Changes which are already detected at runtime, like the addition
  * of icalls, do not require an increment.
  */
-#define MONO_CORLIB_VERSION 90
+#define MONO_CORLIB_VERSION 111
 
 typedef struct
 {
@@ -85,18 +90,11 @@ typedef struct
 
 CRITICAL_SECTION mono_delegate_section;
 
-#ifdef _EGLIB_MAJOR
-/* Need to lock here because EGLIB has locking defined as no-ops, we can not depend on mono_strtod do the right locking */
-/* Ideally this will be fixed in eglib */
 CRITICAL_SECTION mono_strtod_mutex;
-#endif
-
 
 static gunichar2 process_guid [36];
 static gboolean process_guid_set = FALSE;
 
-static gboolean shutting_down = FALSE;
-
 static gboolean no_exec = FALSE;
 
 static MonoAssembly *
@@ -165,7 +163,7 @@ mono_runtime_get_no_exec (void)
 }
 
 static void
-create_exceptions (MonoDomain *domain)
+create_domain_objects (MonoDomain *domain)
 {
        MonoDomain *old_domain = mono_domain_get ();
        MonoString *arg;
@@ -190,6 +188,9 @@ create_exceptions (MonoDomain *domain)
        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);
@@ -251,10 +252,7 @@ mono_runtime_init (MonoDomain *domain, MonoThreadStartCB start_cb,
 
        InitializeCriticalSection (&mono_delegate_section);
 
-#ifdef _EGLIB_MAJOR
-       /* Needed until EGLIB is fixed #464316 */
        InitializeCriticalSection (&mono_strtod_mutex);
-#endif
        
        mono_thread_attach (domain);
        mono_context_init (domain);
@@ -263,7 +261,7 @@ mono_runtime_init (MonoDomain *domain, MonoThreadStartCB start_cb,
        mono_type_initialization_init ();
 
        if (!mono_runtime_get_no_exec ())
-               create_exceptions (domain);
+               create_domain_objects (domain);
 
        /* GC init has to happen after thread init */
        mono_gc_init ();
@@ -350,8 +348,6 @@ mono_context_init (MonoDomain *domain)
 void
 mono_runtime_cleanup (MonoDomain *domain)
 {
-       shutting_down = TRUE;
-
        mono_attach_cleanup ();
 
        /* This ends up calling any pending pending (for at most 2 seconds) */
@@ -367,10 +363,6 @@ mono_runtime_cleanup (MonoDomain *domain)
        mono_type_initialization_cleanup ();
 
        mono_monitor_cleanup ();
-
-#ifndef HOST_WIN32
-       _wapi_cleanup ();
-#endif
 }
 
 static MonoDomainFunc quit_function = NULL;
@@ -388,33 +380,6 @@ mono_runtime_quit ()
                quit_function (mono_get_root_domain (), NULL);
 }
 
-/** 
- * mono_runtime_set_shutting_down:
- *
- * Invoked by System.Environment.Exit to flag that the runtime
- * is shutting down.
- */
-void
-mono_runtime_set_shutting_down (void)
-{
-       shutting_down = TRUE;
-}
-
-/**
- * mono_runtime_is_shutting_down:
- *
- * Returns whether the runtime has been flagged for shutdown.
- *
- * This is consumed by the P:System.Environment.HasShutdownStarted
- * property.
- *
- */
-gboolean
-mono_runtime_is_shutting_down (void)
-{
-       return shutting_down;
-}
-
 /**
  * mono_domain_create_appdomain:
  * @friendly_name: The friendly name of the appdomain to create
@@ -512,11 +477,10 @@ mono_domain_create_appdomain_internal (char *friendly_name, MonoAppDomainSetup *
        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_exceptions (data);
+       create_domain_objects (data);
 
        return ad;
 }
@@ -539,6 +503,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;
 }
@@ -821,7 +789,7 @@ void
 mono_set_private_bin_path_from_config (MonoDomain *domain)
 {
        MonoError error;
-       gchar *config_file, *text;
+       gchar *config_file_name = NULL, *text = NULL, *config_file_path = NULL;
        gsize len;
        GMarkupParseContext *context;
        RuntimeConfig runtime_config;
@@ -830,21 +798,23 @@ mono_set_private_bin_path_from_config (MonoDomain *domain)
        if (!domain || !domain->setup || !domain->setup->configuration_file)
                return;
 
-       config_file = mono_string_to_utf8_checked (domain->setup->configuration_file, &error); 
+       config_file_name = mono_string_to_utf8_checked (domain->setup->configuration_file, &error);
        if (!mono_error_ok (&error)) {
                mono_error_cleanup (&error);
-               return;
+               goto free_and_out;
        }
 
-       if (!g_file_get_contents (config_file, &text, &len, NULL)) {
-               g_free (config_file);
-               return;
-       }
+       config_file_path = mono_portability_find_file (config_file_name, TRUE);
+       if (!config_file_path)
+               config_file_path = config_file_name;
+
+       if (!g_file_get_contents (config_file_path, &text, &len, NULL))
+               goto free_and_out;
 
        runtime_config.runtime_count = 0;
        runtime_config.assemblybinding_count = 0;
        runtime_config.domain = domain;
-       runtime_config.filename = config_file;
+       runtime_config.filename = config_file_path;
        
        offset = 0;
        if (len > 3 && text [0] == '\xef' && text [1] == (gchar) '\xbb' && text [2] == '\xbf')
@@ -854,19 +824,28 @@ mono_set_private_bin_path_from_config (MonoDomain *domain)
        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);
+
+  free_and_out:
        g_free (text);
-       g_free (config_file);
+       if (config_file_name != config_file_path)
+               g_free (config_file_name);
+       g_free (config_file_path);
 }
 
 MonoAppDomain *
 ves_icall_System_AppDomain_createDomain (MonoString *friendly_name, MonoAppDomainSetup *setup)
 {
+#ifdef DISABLE_APPDOMAINS
+       mono_raise_exception (mono_get_exception_not_supported ("AppDomain creation is not supported on this runtime."));
+       return NULL;
+#else
        char *fname = mono_string_to_utf8 (friendly_name);
        MonoAppDomain *ad = mono_domain_create_appdomain_internal (fname, setup);
        
        g_free (fname);
 
        return ad;
+#endif
 }
 
 MonoArray *
@@ -994,8 +973,8 @@ add_assemblies_to_domain (MonoDomain *domain, MonoAssembly *ass, GHashTable *ht)
        if (!g_hash_table_lookup (ht, ass)) {
                mono_assembly_addref (ass);
                g_hash_table_insert (ht, ass, ass);
-               domain->domain_assemblies = g_slist_prepend (domain->domain_assemblies, ass);
-               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);
+               domain->domain_assemblies = g_slist_append (domain->domain_assemblies, ass);
+               mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_ASSEMBLY, "Assembly %s[%p] added to domain %s, ref_count=%d", ass->aname.name, ass, domain->friendly_name, ass->ref_count);
        }
 
        if (ass->image->references) {
@@ -1098,7 +1077,7 @@ set_domain_search_path (MonoDomain *domain)
        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");
+                       g_warning ("Could not decode AppDomain search path since it contains invalid characters");
                        mono_error_cleanup (&error);
                        mono_domain_assemblies_unlock (domain);
                        return;
@@ -1259,8 +1238,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);
@@ -1470,10 +1459,32 @@ static gboolean
 private_file_needs_copying (const char *src, struct stat *sbuf_src, char *dest)
 {
        struct stat sbuf_dest;
-       
-       if (stat (src, sbuf_src) == -1 || stat (dest, &sbuf_dest) == -1)
+       gchar *stat_src;
+       gchar *real_src = mono_portability_find_file (src, TRUE);
+
+       if (!real_src)
+               stat_src = (gchar*)src;
+       else
+               stat_src = real_src;
+
+       if (stat (stat_src, sbuf_src) == -1) {
+               time_t tnow = time (NULL);
+
+               if (real_src)
+                       g_free (real_src);
+
+               memset (sbuf_src, 0, sizeof (*sbuf_src));
+               sbuf_src->st_mtime = tnow;
+               sbuf_src->st_atime = tnow;
                return TRUE;
+       }
 
+       if (real_src)
+               g_free (real_src);
+
+       if (stat (dest, &sbuf_dest) == -1)
+               return TRUE;
+       
        if (sbuf_src->st_size == sbuf_dest.st_size &&
            sbuf_src->st_mtime == sbuf_dest.st_mtime)
                return FALSE;
@@ -1589,6 +1600,8 @@ mono_is_shadow_copy_enabled (MonoDomain *domain, const gchar *dir_name)
 /*
 This function raises exceptions so it can cause as sorts of nasty stuff if called
 while holding a lock.
+Returns old file name if shadow copy is disabled, new shadow copy file name if successful
+or NULL if source file not found.
 FIXME bubble up the error instead of raising it here
 */
 char *
@@ -1598,6 +1611,7 @@ mono_make_shadow_copy (const char *filename)
        gchar *sibling_source, *sibling_target;
        gint sibling_source_len, sibling_target_len;
        guint16 *orig, *dest;
+       guint32 attrs;
        char *shadow;
        gboolean copy_result;
        MonoException *exc;
@@ -1650,6 +1664,16 @@ mono_make_shadow_copy (const char *filename)
        orig = g_utf8_to_utf16 (filename, strlen (filename), NULL, NULL, NULL);
        dest = g_utf8_to_utf16 (shadow, strlen (shadow), NULL, NULL, NULL);
        DeleteFile (dest);
+
+       /* Fix for bug #17066 - make sure we can read the file. if not then don't error but rather 
+        * let the assembly fail to load. This ensures you can do Type.GetType("NS.T, NonExistantAssembly)
+        * and not have it runtime error" */
+       attrs = GetFileAttributes (orig);
+       if (attrs == INVALID_FILE_ATTRIBUTES) {
+               g_free (shadow);
+               return (char *)filename;
+       }
+
        copy_result = CopyFile (orig, dest, FALSE);
 
        /* Fix for bug #556884 - make sure the files have the correct mode so that they can be
@@ -1662,6 +1686,11 @@ mono_make_shadow_copy (const char *filename)
 
        if (copy_result == FALSE) {
                g_free (shadow);
+
+               /* Fix for bug #17251 - if file not found try finding assembly by other means (it is not fatal error) */
+               if (GetLastError() == ERROR_FILE_NOT_FOUND || GetLastError() == ERROR_PATH_NOT_FOUND)
+                       return NULL; /* file not found, shadow copy failed */
+
                exc = mono_get_exception_execution_engine ("Failed to create shadow copy (CopyFile).");
                mono_raise_exception (exc);
        }
@@ -1934,7 +1963,9 @@ ves_icall_System_AppDomain_LoadAssembly (MonoAppDomain *ad,  MonoString *assRef,
 
        if (!parsed) {
                /* This is a parse error... */
-               return NULL;
+               if (!refOnly)
+                       refass = mono_try_assembly_resolve (domain, assRef, refOnly);
+               return refass;
        }
 
        ass = mono_assembly_load_full_nosearch (&aname, NULL, &status, refOnly);
@@ -1981,6 +2012,9 @@ ves_icall_System_AppDomain_InternalUnload (gint32 domain_id)
         */
        if (g_getenv ("MONO_NO_UNLOAD"))
                return;
+#ifdef __native_client__
+       return;
+#endif
 
        mono_domain_unload (domain);
 }
@@ -2146,44 +2180,44 @@ clear_cached_vtable (MonoVTable *vtable)
        MonoClass *klass = vtable->klass;
        MonoDomain *domain = vtable->domain;
        MonoClassRuntimeInfo *runtime_info;
+       void *data;
 
        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);
+       if (klass->has_static_refs && (data = mono_vtable_get_static_field_data (vtable)))
+               mono_gc_free_fixed (data);
 }
 
 static G_GNUC_UNUSED void
 zero_static_data (MonoVTable *vtable)
 {
        MonoClass *klass = vtable->klass;
+       void *data;
 
-       if (vtable->data && klass->has_static_refs)
-               memset (vtable->data, 0, mono_class_data_size (klass));
+       if (klass->has_static_refs && (data = mono_vtable_get_static_field_data (vtable)))
+               mono_gc_bzero (data, mono_class_data_size (klass));
 }
 
 typedef struct unload_data {
+       gboolean done;
        MonoDomain *domain;
        char *failure_reason;
+       gint32 refcount;
 } 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);
+unload_data_unref (unload_data *data)
+{
+       gint32 count;
+       do {
+               mono_atomic_load_acquire (count, gint32, &data->refcount);
+               g_assert (count >= 1 && count <= 2);
+               if (count == 1) {
+                       g_free (data);
+                       return;
+               }
+       } while (InterlockedCompareExchange (&data->refcount, count, count - 1) != count);
 }
 
 static void
@@ -2199,7 +2233,6 @@ deregister_reflection_info_roots_from_list (MonoImage *image)
                list = list->next;
        }
 
-       g_slist_free (image->reflection_info_unregister_classes);
        image->reflection_info_unregister_classes = NULL;
 }
 
@@ -2208,31 +2241,29 @@ 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);
+
+               /*
+                * No need to take the image lock here since dynamic images are appdomain bound and
+                * at this point the mutator is gone.  Taking the image lock here would mean
+                * promoting it from a simple lock to a complex lock, which we better avoid if
+                * possible.
+                */
+               if (image->dynamic)
+                       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);
-                               }
+                       if (module && module->dynamic)
                                deregister_reflection_info_roots_from_list (module);
-                       }
                }
        }
        mono_domain_assemblies_unlock (domain);
-       mono_loader_unlock ();
 }
-#endif
 
 static guint32 WINAPI
 unload_thread_main (void *arg)
@@ -2243,7 +2274,8 @@ unload_thread_main (void *arg)
        int i;
 
        /* Have to attach to the runtime so shutdown can wait for this thread */
-       thread = mono_thread_attach (mono_get_root_domain ());
+       /* Force it to be attached to avoid racing during shutdown. */
+       thread = mono_thread_attach_full (mono_get_root_domain (), TRUE);
 
        /* 
         * FIXME: Abort our parent thread last, so we can return a failure 
@@ -2251,18 +2283,18 @@ unload_thread_main (void *arg)
         */
        if (!mono_threads_abort_appdomain_threads (domain, -1)) {
                data->failure_reason = g_strdup_printf ("Aborting of threads in domain %s timed out.", domain->friendly_name);
-               return 1;
+               goto failure;
        }
 
        if (!mono_thread_pool_remove_domain_jobs (domain, -1)) {
                data->failure_reason = g_strdup_printf ("Cleanup of threadpool jobs of domain %s timed out.", domain->friendly_name);
-               return 1;
+               goto failure;
        }
 
        /* Finalize all finalizable objects in the doomed appdomain */
        if (!mono_domain_finalize (domain, -1)) {
                data->failure_reason = g_strdup_printf ("Finalization of domain %s timed out.", domain->friendly_name);
-               return 1;
+               goto failure;
        }
 
        /* Clear references to our vtables in class->runtime_info.
@@ -2288,9 +2320,10 @@ unload_thread_main (void *arg)
 #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_assembly_cleanup_domain_bindings (domain->domain_id);
+
        mono_domain_unlock (domain);
        mono_loader_unlock ();
 
@@ -2307,9 +2340,16 @@ unload_thread_main (void *arg)
 
        mono_gc_collect (mono_gc_max_generation ());
 
-       mono_thread_detach  (thread);
-
+       mono_atomic_store_release (&data->done, TRUE);
+       unload_data_unref (data);
+       mono_thread_detach (thread);
        return 0;
+
+failure:
+       mono_atomic_store_release (&data->done, TRUE);
+       unload_data_unref (data);
+       mono_thread_detach (thread);
+       return 1;
 }
 
 /*
@@ -2351,11 +2391,10 @@ void
 mono_domain_try_unload (MonoDomain *domain, MonoObject **exc)
 {
        HANDLE thread_handle;
-       gsize tid;
-       guint32 res;
        MonoAppDomainState prev_state;
        MonoMethod *method;
-       unload_data thread_data;
+       unload_data *thread_data;
+       MonoNativeThreadId tid;
        MonoDomain *caller_domain = mono_domain_get ();
 
        /* printf ("UNLOAD STARTING FOR %s (%p) IN THREAD 0x%x.\n", domain->friendly_name, domain, GetCurrentThreadId ()); */
@@ -2379,8 +2418,6 @@ mono_domain_try_unload (MonoDomain *domain, MonoObject **exc)
                }
        }
 
-       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); 
@@ -2395,8 +2432,11 @@ mono_domain_try_unload (MonoDomain *domain, MonoObject **exc)
        }
        mono_domain_set (caller_domain, FALSE);
 
-       thread_data.domain = domain;
-       thread_data.failure_reason = NULL;
+       thread_data = g_new0 (unload_data, 1);
+       thread_data->domain = domain;
+       thread_data->failure_reason = NULL;
+       thread_data->done = FALSE;
+       thread_data->refcount = 2; /*Must be 2: unload thread + initiator */
 
        /*The managed callback finished successfully, now we start tearing down the appdomain*/
        domain->state = MONO_APPDOMAIN_UNLOADING;
@@ -2404,41 +2444,34 @@ mono_domain_try_unload (MonoDomain *domain, MonoObject **exc)
         * First we create a separate thread for unloading, since
         * we might have to abort some threads, including the current one.
         */
-       /*
-        * If we create a non-suspended thread, the runtime will hang.
-        * See:
-        * http://bugzilla.ximian.com/show_bug.cgi?id=27663
-        */ 
-#if 0
-       thread_handle = mono_create_thread (NULL, 0, unload_thread_main, &thread_data, 0, &tid);
-#else
-       thread_handle = mono_create_thread (NULL, 0, (LPTHREAD_START_ROUTINE)unload_thread_main, &thread_data, CREATE_SUSPENDED, &tid);
-       if (thread_handle == NULL) {
+       thread_handle = mono_threads_create_thread ((LPTHREAD_START_ROUTINE)unload_thread_main, thread_data, 0, CREATE_SUSPENDED, &tid);
+       if (thread_handle == NULL)
                return;
-       }
-       ResumeThread (thread_handle);
-#endif
+       mono_thread_info_resume (tid);
 
        /* Wait for the thread */       
-       while ((res = WaitForSingleObjectEx (thread_handle, INFINITE, TRUE) == WAIT_IO_COMPLETION)) {
+       while (!thread_data->done && WaitForSingleObjectEx (thread_handle, INFINITE, TRUE) == WAIT_IO_COMPLETION) {
                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);
+                       unload_data_unref (thread_data);
                        return;
                }
        }
        CloseHandle (thread_handle);
 
-       if (thread_data.failure_reason) {
+       if (thread_data->failure_reason) {
                /* Roll back the state change */
                domain->state = MONO_APPDOMAIN_CREATED;
 
-               g_warning ("%s", thread_data.failure_reason);
+               g_warning ("%s", thread_data->failure_reason);
 
-               *exc = (MonoObject *) 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;
+               g_free (thread_data->failure_reason);
+               thread_data->failure_reason = NULL;
        }
+
+       unload_data_unref (thread_data);
 }