2009-12-02 Rodrigo Kumpera <rkumpera@novell.com>
[mono.git] / mono / metadata / gc.c
index 7dc5de072b24db2f7f0cc1c7ae22b22e4bff921f..ee0f9856c2121bee48013d9a924f901a500cf6c8 100644 (file)
@@ -3,7 +3,8 @@
  *
  * Author: Paolo Molaro <lupus@ximian.com>
  *
- * (C) 2002 Ximian, Inc.
+ * Copyright 2002-2003 Ximian, Inc (http://www.ximian.com)
+ * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
  */
 
 #include <config.h>
 #include <mono/metadata/profiler-private.h>
 #include <mono/metadata/domain-internals.h>
 #include <mono/metadata/class-internals.h>
+#include <mono/metadata/metadata-internals.h>
+#include <mono/metadata/mono-mlist.h>
+#include <mono/metadata/threadpool.h>
+#include <mono/metadata/threads-types.h>
 #include <mono/utils/mono-logger.h>
-#include <mono/os/gc_wrapper.h>
+#include <mono/metadata/gc-internal.h>
 #include <mono/metadata/marshal.h> /* for mono_delegate_free_ftnptr () */
+#include <mono/metadata/attach.h>
+#include <mono/utils/mono-semaphore.h>
+
+#ifndef HOST_WIN32
+#include <pthread.h>
+#endif
 
 typedef struct DomainFinalizationReq {
        MonoDomain *domain;
@@ -36,58 +47,131 @@ extern int __imp_GC_finalize_on_demand;
 
 static gboolean gc_disabled = FALSE;
 
+static gboolean finalizing_root_domain = FALSE;
+
 #define mono_finalizer_lock() EnterCriticalSection (&finalizer_mutex)
 #define mono_finalizer_unlock() LeaveCriticalSection (&finalizer_mutex)
 static CRITICAL_SECTION finalizer_mutex;
 
 static GSList *domains_to_finalize= NULL;
+static MonoMList *threads_to_finalize = NULL;
 
-static MonoThread *gc_thread;
+static MonoInternalThread *gc_thread;
 
 static void object_register_finalizer (MonoObject *obj, void (*callback)(void *, void*));
 
+static void mono_gchandle_set_target (guint32 gchandle, MonoObject *obj);
+
 #ifndef HAVE_NULL_GC
 static HANDLE pending_done_event;
 static HANDLE shutdown_event;
-static HANDLE thread_started_event;
 #endif
 
+static void
+add_thread_to_finalize (MonoInternalThread *thread)
+{
+       mono_finalizer_lock ();
+       if (!threads_to_finalize)
+               MONO_GC_REGISTER_ROOT (threads_to_finalize);
+       threads_to_finalize = mono_mlist_append (threads_to_finalize, (MonoObject*)thread);
+       mono_finalizer_unlock ();
+}
+
+static gboolean suspend_finalizers = FALSE;
 /* 
  * actually, we might want to queue the finalize requests in a separate thread,
  * but we need to be careful about the execution domain of the thread...
  */
-static void
-run_finalize (void *obj, void *data)
+void
+mono_gc_run_finalize (void *obj, void *data)
 {
        MonoObject *exc = NULL;
-       MonoObject *o, *o2;
+       MonoObject *o;
+#ifndef HAVE_SGEN_GC
+       MonoObject *o2;
+#endif
+       MonoMethod* finalizer = NULL;
+       MonoDomain *caller_domain = mono_domain_get ();
+       MonoDomain *domain;
+       RuntimeInvokeFunction runtime_invoke;
+       GSList *l, *refs = NULL;
+
        o = (MonoObject*)((char*)obj + GPOINTER_TO_UINT (data));
 
+       if (suspend_finalizers)
+               return;
+
+       domain = o->vtable->domain;
+
 #ifndef HAVE_SGEN_GC
-       mono_domain_lock (o->vtable->domain);
+       mono_domain_finalizers_lock (domain);
 
-       o2 = g_hash_table_lookup (o->vtable->domain->finalizable_objects_hash, o);
+       o2 = g_hash_table_lookup (domain->finalizable_objects_hash, o);
 
-       mono_domain_unlock (o->vtable->domain);
+       refs = mono_gc_remove_weak_track_object (domain, o);
+
+       mono_domain_finalizers_unlock (domain);
 
        if (!o2)
                /* Already finalized somehow */
                return;
 #endif
 
+       if (refs) {
+               /*
+                * Support for GCHandles of type WeakTrackResurrection:
+                *
+                *   Its not exactly clear how these are supposed to work, or how their
+                * semantics can be implemented. We only implement one crucial thing:
+                * these handles are only cleared after the finalizer has ran.
+                */
+               for (l = refs; l; l = l->next) {
+                       guint32 gchandle = GPOINTER_TO_UINT (l->data);
+
+                       mono_gchandle_set_target (gchandle, o);
+               }
+
+               g_slist_free (refs);
+       }
+               
        /* make sure the finalizer is not called again if the object is resurrected */
        object_register_finalizer (obj, NULL);
 
-       if (o->vtable->klass == mono_get_thread_class ())
-               if (mono_gc_is_finalizer_thread ((MonoThread*)o))
+       if (o->vtable->klass == mono_defaults.internal_thread_class) {
+               MonoInternalThread *t = (MonoInternalThread*)o;
+
+               if (mono_gc_is_finalizer_internal_thread (t))
                        /* Avoid finalizing ourselves */
                        return;
 
+               if (t->threadpool_thread && finalizing_root_domain) {
+                       /* Don't finalize threadpool threads when
+                          shutting down - they're finalized when the
+                          threadpool shuts down. */
+                       add_thread_to_finalize (t);
+                       return;
+               }
+       }
+
+       if (o->vtable->klass->image == mono_defaults.corlib && !strcmp (o->vtable->klass->name, "DynamicMethod") && finalizing_root_domain) {
+               /*
+                * These can't be finalized during unloading/shutdown, since that would
+                * free the native code which can still be referenced by other
+                * finalizers.
+                * FIXME: This is not perfect, objects dying at the same time as 
+                * dynamic methods can still reference them even when !shutdown.
+                */
+               return;
+       }
+
+       if (mono_runtime_get_no_exec ())
+               return;
+
        /* speedup later... and use a timeout */
        /* g_print ("Finalize run on %p %s.%s\n", o, mono_object_class (o)->name_space, mono_object_class (o)->name); */
 
        /* Use _internal here, since this thread can enter a doomed appdomain */
-       mono_domain_set_internal (mono_object_domain (o));              
+       mono_domain_set_internal (mono_object_domain (o));
 
        /* delegates that have a native function pointer allocated are
         * registered for finalization, but they don't have a Finalize
@@ -97,14 +181,63 @@ run_finalize (void *obj, void *data)
                MonoDelegate* del = (MonoDelegate*)o;
                if (del->delegate_trampoline)
                        mono_delegate_free_ftnptr ((MonoDelegate*)o);
+               mono_domain_set_internal (caller_domain);
                return;
        }
 
-       mono_runtime_invoke (mono_class_get_finalizer (o->vtable->klass), o, NULL, &exc);
+       finalizer = mono_class_get_finalizer (o->vtable->klass);
+
+#ifndef DISABLE_COM
+       /* If object has a CCW but has no finalizer, it was only
+        * registered for finalization in order to free the CCW.
+        * Else it needs the regular finalizer run.
+        * FIXME: what to do about ressurection and suppression
+        * of finalizer on object with CCW.
+        */
+       if (mono_marshal_free_ccw (o) && !finalizer) {
+               mono_domain_set_internal (caller_domain);
+               return;
+       }
+#endif
+
+       /* 
+        * To avoid the locking plus the other overhead of mono_runtime_invoke (),
+        * create and precompile a wrapper which calls the finalize method using
+        * a CALLVIRT.
+        */
+       if (!domain->finalize_runtime_invoke) {
+               MonoMethod *invoke = mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE);
+
+               domain->finalize_runtime_invoke = mono_compile_method (invoke);
+       }
+
+       runtime_invoke = domain->finalize_runtime_invoke;
+
+       mono_runtime_class_init (o->vtable);
+
+       runtime_invoke (o, NULL, &exc, NULL);
 
        if (exc) {
                /* fixme: do something useful */
        }
+
+       mono_domain_set_internal (caller_domain);
+}
+
+void
+mono_gc_finalize_threadpool_threads (void)
+{
+       while (threads_to_finalize) {
+               MonoInternalThread *thread = (MonoInternalThread*) mono_mlist_get_data (threads_to_finalize);
+
+               /* Force finalization of the thread. */
+               thread->threadpool_thread = FALSE;
+               mono_object_register_finalizer ((MonoObject*)thread);
+
+               mono_gc_run_finalize (thread, NULL);
+
+               threads_to_finalize = mono_mlist_next (threads_to_finalize);
+       }
 }
 
 gpointer
@@ -133,31 +266,39 @@ object_register_finalizer (MonoObject *obj, void (*callback)(void *, void*))
 {
 #if HAVE_BOEHM_GC
        guint offset = 0;
+       MonoDomain *domain;
+
+       if (obj == NULL)
+               mono_raise_exception (mono_get_exception_argument_null ("obj"));
+       
+       domain = obj->vtable->domain;
 
 #ifndef GC_DEBUG
        /* This assertion is not valid when GC_DEBUG is defined */
        g_assert (GC_base (obj) == (char*)obj - offset);
 #endif
 
-       if (mono_domain_is_unloading (obj->vtable->domain) && (callback != NULL))
+       if (mono_domain_is_unloading (domain) && (callback != NULL))
                /*
                 * Can't register finalizers in a dying appdomain, since they
                 * could be invoked after the appdomain has been unloaded.
                 */
                return;
 
-       mono_domain_lock (obj->vtable->domain);
+       mono_domain_finalizers_lock (domain);
 
        if (callback)
-               g_hash_table_insert (obj->vtable->domain->finalizable_objects_hash, obj,
-                                                        obj);
+               g_hash_table_insert (domain->finalizable_objects_hash, obj, obj);
        else
-               g_hash_table_remove (obj->vtable->domain->finalizable_objects_hash, obj);
+               g_hash_table_remove (domain->finalizable_objects_hash, obj);
 
-       mono_domain_unlock (obj->vtable->domain);
+       mono_domain_finalizers_unlock (domain);
 
        GC_REGISTER_FINALIZER_NO_ORDER ((char*)obj - offset, callback, GUINT_TO_POINTER (offset), NULL, NULL);
 #elif defined(HAVE_SGEN_GC)
+       if (obj == NULL)
+               mono_raise_exception (mono_get_exception_argument_null ("obj"));
+                                     
        mono_gc_register_for_finalization (obj, callback);
 #endif
 }
@@ -174,13 +315,13 @@ void
 mono_object_register_finalizer (MonoObject *obj)
 {
        /* g_print ("Registered finalizer on %p %s.%s\n", obj, mono_object_class (obj)->name_space, mono_object_class (obj)->name); */
-       object_register_finalizer (obj, run_finalize);
+       object_register_finalizer (obj, mono_gc_run_finalize);
 }
 
 /**
  * mono_domain_finalize:
  * @domain: the domain to finalize
- * @timeout: msects to wait for the finalization to complete
+ * @timeout: msects to wait for the finalization to complete, -1 to wait indefinitely
  *
  *  Request finalization of all finalizable objects inside @domain. Wait
  * @timeout msecs for the finalization to complete.
@@ -195,12 +336,10 @@ mono_domain_finalize (MonoDomain *domain, guint32 timeout)
        guint32 res;
        HANDLE done_event;
 
-       if (mono_thread_current () == gc_thread)
+       if (mono_thread_internal_current () == gc_thread)
                /* We are called from inside a finalizer, not much we can do here */
                return FALSE;
 
-       mono_profiler_appdomain_event (domain, MONO_PROFILE_START_UNLOAD);
-
        /* 
         * No need to create another thread 'cause the finalizer thread
         * is still working and will take care of running the finalizers
@@ -213,10 +352,16 @@ mono_domain_finalize (MonoDomain *domain, guint32 timeout)
        mono_gc_collect (mono_gc_max_generation ());
 
        done_event = CreateEvent (NULL, TRUE, FALSE, NULL);
+       if (done_event == NULL) {
+               return FALSE;
+       }
 
        req = g_new0 (DomainFinalizationReq, 1);
        req->domain = domain;
        req->done_event = done_event;
+
+       if (domain == mono_get_root_domain ())
+               finalizing_root_domain = TRUE;
        
        mono_finalizer_lock ();
 
@@ -227,6 +372,9 @@ mono_domain_finalize (MonoDomain *domain, guint32 timeout)
        /* Tell the finalizer thread to finalize this appdomain */
        mono_gc_finalize_notify ();
 
+       if (timeout == -1)
+               timeout = INFINITE;
+
        res = WaitForSingleObjectEx (done_event, timeout, TRUE);
 
        /* printf ("WAIT RES: %d.\n", res); */
@@ -236,6 +384,12 @@ mono_domain_finalize (MonoDomain *domain, guint32 timeout)
        }
 
        CloseHandle (done_event);
+
+       if (domain == mono_get_root_domain ()) {
+               mono_thread_pool_cleanup ();
+               mono_gc_finalize_threadpool_threads ();
+       }
+
        return TRUE;
 #else
        /* We don't support domain finalization without a GC */
@@ -272,15 +426,28 @@ ves_icall_System_GC_KeepAlive (MonoObject *obj)
 void
 ves_icall_System_GC_ReRegisterForFinalize (MonoObject *obj)
 {
-       MONO_ARCH_SAVE_REGS;
+       if (!obj)
+               mono_raise_exception (mono_get_exception_argument_null ("obj"));
 
-       object_register_finalizer (obj, run_finalize);
+       object_register_finalizer (obj, mono_gc_run_finalize);
 }
 
 void
 ves_icall_System_GC_SuppressFinalize (MonoObject *obj)
 {
-       MONO_ARCH_SAVE_REGS;
+       if (!obj)
+               mono_raise_exception (mono_get_exception_argument_null ("obj"));
+
+       /* delegates have no finalizers, but we register them to deal with the
+        * unmanaged->managed trampoline. We don't let the user suppress it
+        * otherwise we'd leak it.
+        */
+       if (obj->vtable->klass->delegate)
+               return;
+
+       /* FIXME: Need to handle case where obj has COM Callable Wrapper
+        * generated for it that needs cleaned up, but user wants to suppress
+        * their derived object finalizer. */
 
        object_register_finalizer (obj, NULL);
 }
@@ -288,13 +455,11 @@ ves_icall_System_GC_SuppressFinalize (MonoObject *obj)
 void
 ves_icall_System_GC_WaitForPendingFinalizers (void)
 {
-       MONO_ARCH_SAVE_REGS;
-       
 #ifndef HAVE_NULL_GC
        if (!mono_gc_pending_finalizers ())
                return;
 
-       if (mono_thread_current () == gc_thread)
+       if (mono_thread_internal_current () == gc_thread)
                /* Avoid deadlocks */
                return;
 
@@ -303,9 +468,9 @@ ves_icall_System_GC_WaitForPendingFinalizers (void)
        /* g_print ("Waiting for pending finalizers....\n"); */
        WaitForSingleObjectEx (pending_done_event, INFINITE, TRUE);
        /* g_print ("Done pending....\n"); */
-#else
 #endif
 }
+
 #define mono_allocator_lock() EnterCriticalSection (&allocator_section)
 #define mono_allocator_unlock() LeaveCriticalSection (&allocator_section)
 static CRITICAL_SECTION allocator_section;
@@ -318,7 +483,7 @@ typedef enum {
        HANDLE_PINNED
 } HandleType;
 
-static void mono_gchandle_set_target (guint32 gchandle, MonoObject *obj);
+static HandleType mono_gchandle_get_type (guint32 gchandle);
 
 MonoObject *
 ves_icall_System_GCHandle_GetTarget (guint32 handle)
@@ -363,6 +528,8 @@ ves_icall_System_GCHandle_GetAddrOfPinnedObject (guint32 handle)
 {
        MonoObject *obj;
 
+       if (mono_gchandle_get_type (handle) != HANDLE_PINNED)
+               return (gpointer)-2;
        obj = mono_gchandle_get_target (handle);
        if (obj) {
                MonoClass *klass = mono_object_class (obj);
@@ -416,7 +583,7 @@ find_first_unset (guint32 bitmap)
 }
 
 static guint32
-alloc_handle (HandleData *handles, MonoObject *obj)
+alloc_handle (HandleData *handles, MonoObject *obj, gboolean track)
 {
        gint slot, i;
        lock_handles (handles);
@@ -479,7 +646,7 @@ alloc_handle (HandleData *handles, MonoObject *obj)
                                        mono_gc_weak_link_remove (&(handles->entries [i]));
                                /*g_print ("reg/unreg entry %d of type %d at %p to object %p (%p), was: %p\n", i, handles->type, &(entries [i]), obj, entries [i], handles->entries [i]);*/
                                if (obj) {
-                                       mono_gc_weak_link_add (&(entries [i]), obj);
+                                       mono_gc_weak_link_add (&(entries [i]), obj, track);
                                }
                        }
                        g_free (handles->entries);
@@ -500,9 +667,10 @@ alloc_handle (HandleData *handles, MonoObject *obj)
        handles->entries [slot] = obj;
        if (handles->type <= HANDLE_WEAK_TRACK) {
                if (obj)
-                       mono_gc_weak_link_add (&(handles->entries [slot]), obj);
+                       mono_gc_weak_link_add (&(handles->entries [slot]), obj, track);
        }
 
+       mono_perfcounters->gc_num_handles++;
        unlock_handles (handles);
        /*g_print ("allocated entry %d of type %d to object %p (in slot: %p)\n", slot, handles->type, obj, handles->entries [slot]);*/
        return (slot << 3) | (handles->type + 1);
@@ -528,7 +696,7 @@ alloc_handle (HandleData *handles, MonoObject *obj)
 guint32
 mono_gchandle_new (MonoObject *obj, gboolean pinned)
 {
-       return alloc_handle (&gc_handles [pinned? HANDLE_PINNED: HANDLE_NORMAL], obj);
+       return alloc_handle (&gc_handles [pinned? HANDLE_PINNED: HANDLE_NORMAL], obj, FALSE);
 }
 
 /**
@@ -553,7 +721,22 @@ mono_gchandle_new (MonoObject *obj, gboolean pinned)
 guint32
 mono_gchandle_new_weakref (MonoObject *obj, gboolean track_resurrection)
 {
-       return alloc_handle (&gc_handles [track_resurrection? HANDLE_WEAK_TRACK: HANDLE_WEAK], obj);
+       guint32 handle = alloc_handle (&gc_handles [track_resurrection? HANDLE_WEAK_TRACK: HANDLE_WEAK], obj, track_resurrection);
+
+#ifndef HAVE_SGEN_GC
+       if (track_resurrection)
+               mono_gc_add_weak_track_handle (obj, handle);
+#endif
+
+       return handle;
+}
+
+static HandleType
+mono_gchandle_get_type (guint32 gchandle)
+{
+       guint type = (gchandle & 7) - 1;
+
+       return type;
 }
 
 /**
@@ -596,15 +779,18 @@ mono_gchandle_set_target (guint32 gchandle, MonoObject *obj)
        guint slot = gchandle >> 3;
        guint type = (gchandle & 7) - 1;
        HandleData *handles = &gc_handles [type];
+       MonoObject *old_obj = NULL;
+
        if (type > 3)
                return;
        lock_handles (handles);
        if (slot < handles->size && (handles->bitmap [slot / 32] & (1 << (slot % 32)))) {
                if (handles->type <= HANDLE_WEAK_TRACK) {
+                       old_obj = handles->entries [slot];
                        if (handles->entries [slot])
                                mono_gc_weak_link_remove (&handles->entries [slot]);
                        if (obj)
-                               mono_gc_weak_link_add (&handles->entries [slot], obj);
+                               mono_gc_weak_link_add (&handles->entries [slot], obj, handles->type == HANDLE_WEAK_TRACK);
                } else {
                        handles->entries [slot] = obj;
                }
@@ -613,6 +799,11 @@ mono_gchandle_set_target (guint32 gchandle, MonoObject *obj)
        }
        /*g_print ("changed entry %d of type %d to object %p (in slot: %p)\n", slot, handles->type, obj, handles->entries [slot]);*/
        unlock_handles (handles);
+
+#ifndef HAVE_SGEN_GC
+       if (type == HANDLE_WEAK_TRACK)
+               mono_gc_change_weak_track_handle (old_obj, obj, gchandle);
+#endif
 }
 
 /**
@@ -666,6 +857,11 @@ mono_gchandle_free (guint32 gchandle)
        HandleData *handles = &gc_handles [type];
        if (type > 3)
                return;
+#ifndef HAVE_SGEN_GC
+       if (type == HANDLE_WEAK_TRACK)
+               mono_gc_remove_weak_track_handle (gchandle);
+#endif
+
        lock_handles (handles);
        if (slot < handles->size && (handles->bitmap [slot / 32] & (1 << (slot % 32)))) {
                if (handles->type <= HANDLE_WEAK_TRACK) {
@@ -678,6 +874,7 @@ mono_gchandle_free (guint32 gchandle)
        } else {
                /* print a warning? */
        }
+       mono_perfcounters->gc_num_handles--;
        /*g_print ("freed entry %d of type %d\n", slot, handles->type);*/
        unlock_handles (handles);
 }
@@ -719,8 +916,17 @@ mono_gchandle_free_domain (MonoDomain *domain)
 
 }
 
+MonoBoolean
+GCHandle_CheckCurrentDomain (guint32 gchandle)
+{
+       return mono_gchandle_is_in_domain (gchandle, mono_domain_get ());
+}
+
 #ifndef HAVE_NULL_GC
 
+#ifdef MONO_HAS_SEMAPHORES
+static MonoSemType finalizer_sem;
+#endif
 static HANDLE finalizer_event;
 static volatile gboolean finished=FALSE;
 
@@ -728,12 +934,18 @@ void
 mono_gc_finalize_notify (void)
 {
 #ifdef DEBUG
-       g_message (G_GNUC_PRETTY_FUNCTION ": prodding finalizer");
+       g_message ( "%s: prodding finalizer", __func__);
 #endif
 
+#ifdef MONO_HAS_SEMAPHORES
+       MONO_SEM_POST (&finalizer_sem);
+#else
        SetEvent (finalizer_event);
+#endif
 }
 
+#ifdef HAVE_BOEHM_GC
+
 static void
 collect_objects (gpointer key, gpointer value, gpointer user_data)
 {
@@ -741,6 +953,8 @@ collect_objects (gpointer key, gpointer value, gpointer user_data)
        g_ptr_array_add (arr, key);
 }
 
+#endif
+
 /*
  * finalize_domain_objects:
  *
@@ -749,29 +963,40 @@ collect_objects (gpointer key, gpointer value, gpointer user_data)
 static void
 finalize_domain_objects (DomainFinalizationReq *req)
 {
-       int i;
-       GPtrArray *objs;
        MonoDomain *domain = req->domain;
-       
+
+#ifdef HAVE_BOEHM_GC
        while (g_hash_table_size (domain->finalizable_objects_hash) > 0) {
+               int i;
+               GPtrArray *objs;
                /* 
                 * Since the domain is unloading, nobody is allowed to put
                 * new entries into the hash table. But finalize_object might
                 * remove entries from the hash table, so we make a copy.
                 */
                objs = g_ptr_array_new ();
-               g_hash_table_foreach (domain->finalizable_objects_hash, 
-                                                         collect_objects, objs);
+               g_hash_table_foreach (domain->finalizable_objects_hash, collect_objects, objs);
                /* printf ("FINALIZING %d OBJECTS.\n", objs->len); */
 
                for (i = 0; i < objs->len; ++i) {
                        MonoObject *o = (MonoObject*)g_ptr_array_index (objs, i);
                        /* FIXME: Avoid finalizing threads, etc */
-                       run_finalize (o, 0);
+                       mono_gc_run_finalize (o, 0);
                }
 
                g_ptr_array_free (objs, TRUE);
        }
+#elif defined(HAVE_SGEN_GC)
+#define NUM_FOBJECTS 64
+       MonoObject *to_finalize [NUM_FOBJECTS];
+       int count;
+       while ((count = mono_gc_finalizers_for_domain (domain, to_finalize, NUM_FOBJECTS))) {
+               int i;
+               for (i = 0; i < count; ++i) {
+                       mono_gc_run_finalize (to_finalize [i], 0);
+               }
+       }
+#endif
 
        /* Process finalizers which are already in the queue */
        mono_gc_invoke_finalizers ();
@@ -783,17 +1008,26 @@ finalize_domain_objects (DomainFinalizationReq *req)
        g_free (req);
 }
 
-static guint32 finalizer_thread (gpointer unused)
+static guint32
+finalizer_thread (gpointer unused)
 {
-       gc_thread = mono_thread_current ();
-
-       SetEvent (thread_started_event);
-
-       while(!finished) {
+       while (!finished) {
                /* Wait to be notified that there's at least one
                 * finaliser to run
                 */
-               WaitForSingleObjectEx (finalizer_event, INFINITE, TRUE);
+
+               g_assert (mono_domain_get () == mono_get_root_domain ());
+
+#ifdef MONO_HAS_SEMAPHORES
+               MONO_SEM_WAIT (&finalizer_sem);
+#else
+               /* Use alertable=FALSE since we will be asked to exit using the event too */
+               WaitForSingleObjectEx (finalizer_event, INFINITE, FALSE);
+#endif
+
+#ifndef DISABLE_ATTACH
+               mono_attach_maybe_start ();
+#endif
 
                if (domains_to_finalize) {
                        mono_finalizer_lock ();
@@ -803,15 +1037,11 @@ static guint32 finalizer_thread (gpointer unused)
                                mono_finalizer_unlock ();
 
                                finalize_domain_objects (req);
-                       }
-                       else
+                       } else {
                                mono_finalizer_unlock ();
+                       }
                }                               
 
-#ifdef DEBUG
-               g_message (G_GNUC_PRETTY_FUNCTION ": invoking finalizers");
-#endif
-
                /* If finished == TRUE, mono_gc_cleanup has been called (from mono_runtime_cleanup),
                 * before the domain is unloaded.
                 */
@@ -821,15 +1051,12 @@ static guint32 finalizer_thread (gpointer unused)
        }
 
        SetEvent (shutdown_event);
-       return(0);
+       return 0;
 }
 
-/* 
- * Enable or disable the separate finalizer thread.
- * It's currently disabled because it still requires some
- * work in the rest of the runtime.
- */
-#define ENABLE_FINALIZER_THREAD
+#ifdef HAVE_SGEN_GC
+#define GC_dont_gc 0
+#endif
 
 void
 mono_gc_init (void)
@@ -844,9 +1071,7 @@ mono_gc_init (void)
 
        mono_gc_base_init ();
 
-#ifdef ENABLE_FINALIZER_THREAD
-
-       if (g_getenv ("GC_DONT_GC")) {
+       if (GC_dont_gc || g_getenv ("GC_DONT_GC")) {
                gc_disabled = TRUE;
                return;
        }
@@ -854,36 +1079,57 @@ mono_gc_init (void)
        finalizer_event = CreateEvent (NULL, FALSE, FALSE, NULL);
        pending_done_event = CreateEvent (NULL, TRUE, FALSE, NULL);
        shutdown_event = CreateEvent (NULL, TRUE, FALSE, NULL);
-       thread_started_event = CreateEvent (NULL, TRUE, FALSE, NULL);
-       if (finalizer_event == NULL || pending_done_event == NULL || shutdown_event == NULL || thread_started_event == NULL) {
+       if (finalizer_event == NULL || pending_done_event == NULL || shutdown_event == NULL) {
                g_assert_not_reached ();
        }
-
-       mono_thread_create (mono_domain_get (), finalizer_thread, NULL);
-       /*
-        * Wait until the finalizer thread sets gc_thread since its value is needed
-        * by mono_thread_attach ()
-        */
-       WaitForSingleObjectEx (thread_started_event, INFINITE, FALSE);
+#ifdef MONO_HAS_SEMAPHORES
+       MONO_SEM_INIT (&finalizer_sem, 0);
 #endif
+
+       gc_thread = mono_thread_create_internal (mono_domain_get (), finalizer_thread, NULL, FALSE);
 }
 
-void mono_gc_cleanup (void)
+void
+mono_gc_cleanup (void)
 {
 #ifdef DEBUG
-       g_message (G_GNUC_PRETTY_FUNCTION ": cleaning up finalizer");
+       g_message ("%s: cleaning up finalizer", __func__);
 #endif
 
-#ifdef ENABLE_FINALIZER_THREAD
        if (!gc_disabled) {
                ResetEvent (shutdown_event);
                finished = TRUE;
-               if (mono_thread_current () != gc_thread) {
+               if (mono_thread_internal_current () != gc_thread) {
                        mono_gc_finalize_notify ();
                        /* Finishing the finalizer thread, so wait a little bit... */
                        /* MS seems to wait for about 2 seconds */
                        if (WaitForSingleObjectEx (shutdown_event, 2000, FALSE) == WAIT_TIMEOUT) {
-                               mono_thread_stop (gc_thread);
+                               int ret;
+
+                               /* Set a flag which the finalizer thread can check */
+                               suspend_finalizers = TRUE;
+
+                               /* Try to abort the thread, in the hope that it is running managed code */
+                               mono_thread_internal_stop (gc_thread);
+
+                               /* Wait for it to stop */
+                               ret = WaitForSingleObjectEx (gc_thread->handle, 100, TRUE);
+
+                               if (ret == WAIT_TIMEOUT) {
+                                       /* 
+                                        * The finalizer thread refused to die. There is not much we 
+                                        * can do here, since the runtime is shutting down so the 
+                                        * state the finalizer thread depends on will vanish.
+                                        */
+                                       g_warning ("Shutting down finalizer thread timed out.");
+                               } else {
+                                       /*
+                                        * FIXME: On unix, when the above wait returns, the thread 
+                                        * might still be running io-layer code, or pthreads code.
+                                        */
+                                       Sleep (100);
+                               }
+
                        }
                }
                gc_thread = NULL;
@@ -892,8 +1138,6 @@ void mono_gc_cleanup (void)
 #endif
        }
 
-#endif
-
        DeleteCriticalSection (&handle_section);
        DeleteCriticalSection (&allocator_section);
        DeleteCriticalSection (&finalizer_mutex);
@@ -901,7 +1145,12 @@ void mono_gc_cleanup (void)
 
 #else
 
-/* no Boehm GC support. */
+/* Null GC dummy functions */
+void
+mono_gc_finalize_notify (void)
+{
+}
+
 void mono_gc_init (void)
 {
        InitializeCriticalSection (&handle_section);
@@ -913,6 +1162,12 @@ void mono_gc_cleanup (void)
 
 #endif
 
+gboolean
+mono_gc_is_finalizer_internal_thread (MonoInternalThread *thread)
+{
+       return thread == gc_thread;
+}
+
 /**
  * mono_gc_is_finalizer_thread:
  * @thread: the thread to test.
@@ -926,7 +1181,5 @@ void mono_gc_cleanup (void)
 gboolean
 mono_gc_is_finalizer_thread (MonoThread *thread)
 {
-       return thread == gc_thread;
+       return mono_gc_is_finalizer_internal_thread (thread->internal_thread);
 }
-
-