2005-01-31 Zoltan Varga <vargaz@freemail.hu>
[mono.git] / mono / metadata / gc.c
index ed1b2f1c776ea3d838d37a4b169d1c464425099a..a6b81d5b2cda46fc1fbc19955e2556c0fde8d3de 100644 (file)
 #include <string.h>
 
 #include <mono/metadata/gc-internal.h>
+#include <mono/metadata/mono-gc.h>
 #include <mono/metadata/threads.h>
 #include <mono/metadata/tabledefs.h>
 #include <mono/metadata/exception.h>
+#include <mono/metadata/profiler-private.h>
+#include <mono/metadata/domain-internals.h>
+#include <mono/metadata/class-internals.h>
+#include <mono/utils/mono-logger.h>
 #define GC_I_HIDE_POINTERS
 #include <mono/os/gc_wrapper.h>
 
@@ -42,7 +47,7 @@ static CRITICAL_SECTION finalizer_mutex;
 
 static GSList *domains_to_finalize= NULL;
 
-static HANDLE gc_thread;
+static MonoThread *gc_thread;
 
 static void object_register_finalizer (MonoObject *obj, void (*callback)(void *, void*));
 
@@ -50,6 +55,7 @@ static void object_register_finalizer (MonoObject *obj, void (*callback)(void *,
 static void finalize_notify (void);
 static HANDLE pending_done_event;
 static HANDLE shutdown_event;
+static HANDLE thread_started_event;
 #endif
 
 /* 
@@ -65,10 +71,11 @@ run_finalize (void *obj, void *data)
 
        if (finalize_slot < 0) {
                int i;
-               for (i = 0; i < mono_defaults.object_class->vtable_size; ++i) {
-                       MonoMethod *cm = mono_defaults.object_class->vtable [i];
+               MonoClass* obj_class = mono_get_object_class ();
+               for (i = 0; i < obj_class->vtable_size; ++i) {
+                       MonoMethod *cm = obj_class->vtable [i];
               
-                       if (!strcmp (cm->name, "Finalize")) {
+                       if (!strcmp (mono_method_get_name (cm), "Finalize")) {
                                finalize_slot = i;
                                break;
                        }
@@ -87,6 +94,12 @@ run_finalize (void *obj, void *data)
 
        /* 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))
+                       /* Avoid finalizing ourselves */
+                       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); */
 
@@ -100,6 +113,19 @@ run_finalize (void *obj, void *data)
        }
 }
 
+gpointer
+mono_gc_out_of_memory (size_t size)
+{
+       /* 
+        * we could allocate at program startup some memory that we could release 
+        * back to the system at this point if we're really low on memory (ie, size is
+        * lower than the memory we set apart)
+        */
+       mono_raise_exception (mono_domain_get ()->out_of_memory_ex);
+
+       return NULL;
+}
+
 /*
  * Some of our objects may point to a different address than the address returned by GC_malloc()
  * (because of the GetHashCode hack), but we need to pass the real address to register_finalizer.
@@ -162,12 +188,21 @@ mono_domain_finalize (MonoDomain *domain, guint32 timeout)
        guint32 res;
        HANDLE done_event;
 
+       if (mono_thread_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
         */ 
        
 #if HAVE_BOEHM_GC
+       if (gc_disabled)
+               return TRUE;
+
        GC_gcollect ();
 
        done_event = CreateEvent (NULL, TRUE, FALSE, NULL);
@@ -185,13 +220,16 @@ mono_domain_finalize (MonoDomain *domain, guint32 timeout)
        /* Tell the finalizer thread to finalize this appdomain */
        finalize_notify ();
 
-       res = WaitForSingleObject (done_event, timeout);
+       res = WaitForSingleObjectEx (done_event, timeout, TRUE);
 
-       //printf ("WAIT RES: %d.\n", res);
-       if (res == WAIT_TIMEOUT)
+       /* printf ("WAIT RES: %d.\n", res); */
+       if (res == WAIT_TIMEOUT) {
+               /* We leak the handle here */
                return FALSE;
-       else
-               return TRUE;
+       }
+
+       CloseHandle (done_event);
+       return TRUE;
 #else
        /* We don't support domain finalization without a GC */
        return FALSE;
@@ -213,13 +251,9 @@ ves_icall_System_GC_GetTotalMemory (MonoBoolean forceCollection)
 {
        MONO_ARCH_SAVE_REGS;
 
-#if HAVE_BOEHM_GC
        if (forceCollection)
-               GC_gcollect ();
-       return GC_get_heap_size () - GC_get_free_bytes ();
-#else
-       return 0;
-#endif
+               mono_gc_collect (mono_gc_max_generation ());
+       return mono_gc_get_used_size ();
 }
 
 void
@@ -257,14 +291,14 @@ ves_icall_System_GC_WaitForPendingFinalizers (void)
        if (!GC_should_invoke_finalizers ())
                return;
 
-       if (GetCurrentThread () == gc_thread)
+       if (mono_thread_current () == gc_thread)
                /* Avoid deadlocks */
                return;
 
        ResetEvent (pending_done_event);
        finalize_notify ();
        /* g_print ("Waiting for pending finalizers....\n"); */
-       WaitForSingleObject (pending_done_event, INFINITE);
+       WaitForSingleObjectEx (pending_done_event, INFINITE, TRUE);
        /* g_print ("Done pending....\n"); */
 #else
 #endif
@@ -272,17 +306,6 @@ ves_icall_System_GC_WaitForPendingFinalizers (void)
 
 static CRITICAL_SECTION allocator_section;
 static CRITICAL_SECTION handle_section;
-static guint32 next_handle = 0;
-static gpointer *gc_handles = NULL;
-static guint8 *gc_handle_types = NULL;
-static guint32 array_size = 0;
-
-/*
- * The handle type is encoded in the lower two bits of the handle value:
- * 0 -> normal
- * 1 -> pinned
- * 2 -> weak
- */
 
 typedef enum {
        HANDLE_WEAK,
@@ -291,156 +314,280 @@ typedef enum {
        HANDLE_PINNED
 } HandleType;
 
-/*
- * FIXME: make thread safe and reuse the array entries.
- */
+static void mono_gchandle_set_target (guint32 gchandle, MonoObject *obj);
+
 MonoObject *
 ves_icall_System_GCHandle_GetTarget (guint32 handle)
 {
-       MonoObject *obj;
-       gint32 type;
-
-       MONO_ARCH_SAVE_REGS;
-
-       if (gc_handles) {
-               type = handle & 0x3;
-               EnterCriticalSection (&handle_section);
-               g_assert (type == gc_handle_types [handle >> 2]);
-               obj = gc_handles [handle >> 2];
-               LeaveCriticalSection (&handle_section);
-               if (!obj)
-                       return NULL;
-
-               if ((type == HANDLE_WEAK) || (type == HANDLE_WEAK_TRACK))
-                       return REVEAL_POINTER (obj);
-               else
-                       return obj;
-       }
-       return NULL;
+       return mono_gchandle_get_target (handle);
 }
 
+/*
+ * if type == -1, change the target of the handle, otherwise allocate a new handle.
+ */
 guint32
 ves_icall_System_GCHandle_GetTargetHandle (MonoObject *obj, guint32 handle, gint32 type)
 {
-       gpointer val = obj;
-       guint32 h, idx;
-
-       MONO_ARCH_SAVE_REGS;
-
-       EnterCriticalSection (&handle_section);
-       /* Indexes start from 1 since 0 means the handle is not allocated */
-       idx = ++next_handle;
-       if (idx >= array_size) {
-#if HAVE_BOEHM_GC
-               gpointer *new_array;
-               guint8 *new_type_array;
-               if (!array_size)
-                       array_size = 16;
-               new_array = GC_MALLOC (sizeof (gpointer) * (array_size * 2));
-               new_type_array = GC_MALLOC (sizeof (guint8) * (array_size * 2));
-               if (gc_handles) {
-                       int i;
-                       memcpy (new_array, gc_handles, sizeof (gpointer) * array_size);
-                       memcpy (new_type_array, gc_handle_types, sizeof (guint8) * array_size);
-                       /* need to re-register links for weak refs. test if GC_realloc needs the same */
-                       for (i = 0; i < array_size; ++i) {
-#if 0 /* This breaks the threaded finalizer, by causing segfaults deep
-       * inside libgc.  I assume it will also break without the
-       * threaded finalizer, just that the stress test (bug 31333)
-       * deadlocks too early without it.  Reverting to the previous
-       * version here stops the segfault.
-       */
-                               if ((gc_handle_types[i] == HANDLE_WEAK) || (gc_handle_types[i] == HANDLE_WEAK_TRACK)) { /* all and only disguised pointers have it set */
-#else
-                               if (((gulong)new_array [i]) & 0x1) {
-#endif
-                                       if (gc_handles [i] != (gpointer)-1)
-                                               GC_unregister_disappearing_link (&(gc_handles [i]));
-                                       if (new_array [i] != (gpointer)-1)
-                                               GC_GENERAL_REGISTER_DISAPPEARING_LINK (&(new_array [i]), REVEAL_POINTER (new_array [i]));
-                               }
-                       }
-               }
-               array_size *= 2;
-               gc_handles = new_array;
-               gc_handle_types = new_type_array;
-#else
-               mono_raise_exception (mono_get_exception_execution_engine ("No GCHandle support built-in"));
-#endif
+       if (type == -1) {
+               mono_gchandle_set_target (handle, obj);
+               /* the handle doesn't change */
+               return handle;
        }
-
-       /* resuse the type from the old target */
-       if (type == -1)
-               type =  handle & 0x3;
-       h = (idx << 2) | type;
        switch (type) {
        case HANDLE_WEAK:
+               return mono_gchandle_new_weakref (obj, FALSE);
        case HANDLE_WEAK_TRACK:
-               val = (gpointer)HIDE_POINTER (val);
-               gc_handles [idx] = val;
-               gc_handle_types [idx] = type;
-#if HAVE_BOEHM_GC
-               if (gc_handles [idx] != (gpointer)-1)
-                       GC_GENERAL_REGISTER_DISAPPEARING_LINK (&(gc_handles [idx]), obj);
-#else
-               mono_raise_exception (mono_get_exception_execution_engine ("No weakref support"));
-#endif
-               break;
+               return mono_gchandle_new_weakref (obj, TRUE);
+       case HANDLE_NORMAL:
+               return mono_gchandle_new (obj, FALSE);
+       case HANDLE_PINNED:
+               return mono_gchandle_new (obj, TRUE);
        default:
-               gc_handles [idx] = val;
-               gc_handle_types [idx] = type;
-               break;
+               g_assert_not_reached ();
        }
-       LeaveCriticalSection (&handle_section);
-       return h;
+       return -1;
 }
 
 void
 ves_icall_System_GCHandle_FreeHandle (guint32 handle)
 {
-       int idx = handle >> 2;
-       int type = handle & 0x3;
+       mono_gchandle_free (handle);
+}
 
-       MONO_ARCH_SAVE_REGS;
+gpointer
+ves_icall_System_GCHandle_GetAddrOfPinnedObject (guint32 handle)
+{
+       MonoObject *obj;
+
+       obj = mono_gchandle_get_target (handle);
+       if (obj) {
+               MonoClass *klass = mono_object_class (obj);
+               if (klass == mono_defaults.string_class) {
+                       return mono_string_chars ((MonoString*)obj);
+               } else if (klass->rank) {
+                       return mono_array_addr ((MonoArray*)obj, char, 0);
+               } else {
+                       /* the C# code will check and throw the exception */
+                       /* FIXME: missing !klass->blittable test, see bug #61134 */
+                       if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
+                               return (gpointer)-1;
+                       return (char*)obj + sizeof (MonoObject);
+               }
+       }
+       return NULL;
+}
+
+typedef struct {
+       guint32  *bitmap;
+       gpointer *entries;
+       guint32   size;
+       guint8    type;
+       guint     slot_hint : 24; /* starting slot for search */
+} HandleData;
+
+/* weak and weak-track arrays will be allocated in malloc memory 
+ * (sadly libgc still requires REVEAL/HIDE_POINTER)
+ */
+static HandleData gc_handles [] = {
+       {NULL, NULL, 0, HANDLE_WEAK, 0},
+       {NULL, NULL, 0, HANDLE_WEAK_TRACK, 0},
+       {NULL, NULL, 0, HANDLE_NORMAL, 0},
+       {NULL, NULL, 0, HANDLE_PINNED, 0}
+};
 
-       EnterCriticalSection (&handle_section);
+#define lock_handles(handles) EnterCriticalSection (&handle_section)
+#define unlock_handles(handles) LeaveCriticalSection (&handle_section)
 
+static int
+find_first_unset (guint32 bitmap)
+{
+       int i;
+       for (i = 0; i < 32; ++i) {
+               if (!(bitmap & (1 << i)))
+                       return i;
+       }
+       return -1;
+}
+
+static guint32
+alloc_handle (HandleData *handles, MonoObject *obj)
+{
+       gint slot, i;
+       lock_handles (handles);
+       if (!handles->size) {
+               handles->size = 32;
+               if (handles->type > HANDLE_WEAK_TRACK) {
 #ifdef HAVE_BOEHM_GC
-       g_assert (type == gc_handle_types [idx]);
-       if ((type == HANDLE_WEAK) || (type == HANDLE_WEAK_TRACK)) {
-               if (gc_handles [idx] != (gpointer)-1)
-                       GC_unregister_disappearing_link (&(gc_handles [idx]));
+                       handles->entries = GC_MALLOC (sizeof (gpointer) * handles->size);
+#else
+                       handles->entries = g_malloc0 (sizeof (gpointer) * handles->size);
+#endif
+               } else {
+                       handles->entries = g_malloc0 (sizeof (gpointer) * handles->size);
+               }
+               handles->bitmap = g_malloc0 (handles->size / 8);
+       }
+       i = -1;
+       for (slot = handles->slot_hint; slot < handles->size / 32; ++slot) {
+               if (handles->bitmap [slot] != 0xffffffff) {
+                       i = find_first_unset (handles->bitmap [slot]);
+                       handles->slot_hint = slot;
+                       break;
+               }
+       }
+       if (i == -1 && handles->slot_hint != 0) {
+               for (slot = 0; slot < handles->slot_hint; ++slot) {
+                       if (handles->bitmap [slot] != 0xffffffff) {
+                               i = find_first_unset (handles->bitmap [slot]);
+                               handles->slot_hint = slot;
+                               break;
+                       }
+               }
        }
+       if (i == -1) {
+               guint32 *new_bitmap;
+               guint32 new_size = handles->size * 2; /* always double: we memset to 0 based on this below */
+
+               /* resize and copy the bitmap */
+               new_bitmap = g_malloc0 (new_size / 8);
+               memcpy (new_bitmap, handles->bitmap, handles->size / 8);
+               g_free (handles->bitmap);
+               handles->bitmap = new_bitmap;
+
+               /* resize and copy the entries */
+               if (handles->type > HANDLE_WEAK_TRACK) {
+#ifdef HAVE_BOEHM_GC
+                       gpointer *entries;
+                       entries = GC_MALLOC (sizeof (gpointer) * new_size);
+                       memcpy (entries, handles->entries, sizeof (gpointer) * handles->size);
+                       handles->entries = entries;
 #else
-       mono_raise_exception (mono_get_exception_execution_engine ("No GCHandle support"));
+                       handles->entries = g_realloc (handles->entries, sizeof (gpointer) * new_size);
+                       memset (handles->entries + handles->size, 0, sizeof (gpointer) * handles->size);
+#endif
+               } else {
+#ifdef HAVE_BOEHM_GC
+                       gpointer *entries;
+                       entries = g_malloc (sizeof (gpointer) * new_size);
+                       /* we disable GC because we could lose some disappearing link updates */
+                       mono_gc_disable ();
+                       memcpy (entries, handles->entries, sizeof (gpointer) * handles->size);
+                       memset (entries + handles->size, 0, sizeof (gpointer) * handles->size);
+                       for (i = 0; i < handles->size; ++i) {
+                               GC_unregister_disappearing_link (&(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]), REVEAL_POINTER (entries [i]), entries [i], handles->entries [i]);*/
+                               if (entries [i] && entries [i] != (gpointer)-1) {
+                                       GC_GENERAL_REGISTER_DISAPPEARING_LINK (&(entries [i]), REVEAL_POINTER (entries [i]));
+                               }
+                       }
+                       g_free (handles->entries);
+                       handles->entries = entries;
+                       mono_gc_enable ();
+#else
+                       handles->entries = g_realloc (handles->entries, sizeof (gpointer) * new_size);
+                       memset (handles->entries + handles->size, 0, sizeof (gpointer) * handles->size);
+#endif
+               }
+
+               /* set i and slot to the next free position */
+               i = 0;
+               slot = (handles->size + 1) / 32;
+               handles->slot_hint = handles->size + 1;
+               handles->size = new_size;
+       }
+       handles->bitmap [slot] |= 1 << i;
+       slot = slot * 32 + i;
+       handles->entries [slot] = obj;
+#ifdef HAVE_BOEHM_GC
+       if (handles->type <= HANDLE_WEAK_TRACK) {
+               handles->entries [slot] = (void*)HIDE_POINTER (obj);
+               GC_GENERAL_REGISTER_DISAPPEARING_LINK (&(handles->entries [slot]), obj);
+       }
 #endif
 
-       gc_handles [idx] = (gpointer)-1;
-       gc_handle_types [idx] = (guint8)-1;
-       LeaveCriticalSection (&handle_section);
+       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 << 2) | handles->type;
 }
 
-gpointer
-ves_icall_System_GCHandle_GetAddrOfPinnedObject (guint32 handle)
+guint32
+mono_gchandle_new (MonoObject *obj, gboolean pinned)
 {
-       MonoObject *obj;
-       int type = handle & 0x3;
+       return alloc_handle (&gc_handles [pinned? HANDLE_PINNED: HANDLE_NORMAL], obj);
+}
 
-       MONO_ARCH_SAVE_REGS;
+guint32
+mono_gchandle_new_weakref (MonoObject *obj, gboolean track_resurrection)
+{
+       return alloc_handle (&gc_handles [track_resurrection? HANDLE_WEAK_TRACK: HANDLE_WEAK], obj);
+}
 
-       if (gc_handles) {
-               EnterCriticalSection (&handle_section);
-               obj = gc_handles [handle >> 2];
-               g_assert (gc_handle_types [handle >> 2] == type);
-               LeaveCriticalSection (&handle_section);
-               if ((type == HANDLE_WEAK) || (type == HANDLE_WEAK_TRACK)) {
+/* This will return NULL for a collected object if using a weakref handle */
+MonoObject*
+mono_gchandle_get_target (guint32 gchandle)
+{
+       guint slot = gchandle >> 2;
+       HandleData *handles = &gc_handles [gchandle & 3];
+       MonoObject *obj = NULL;
+       lock_handles (handles);
+       if (slot < handles->size) {
+               obj = handles->entries [slot];
+               if (handles->type <= HANDLE_WEAK_TRACK) {
                        obj = REVEAL_POINTER (obj);
                        if (obj == (MonoObject *) -1)
-                               return NULL;
+                               obj = NULL;
                }
-               return obj;
+       } else {
+               /* print a warning? */
        }
-       return NULL;
+       unlock_handles (handles);
+       /*g_print ("get target of entry %d of type %d: %p\n", slot, handles->type, obj);*/
+       return obj;
+}
+
+static void
+mono_gchandle_set_target (guint32 gchandle, MonoObject *obj)
+{
+       guint slot = gchandle >> 2;
+       HandleData *handles = &gc_handles [gchandle & 3];
+       lock_handles (handles);
+       if (slot < handles->size) {
+#ifdef HAVE_BOEHM_GC
+               if (handles->type <= HANDLE_WEAK_TRACK) {
+                       GC_unregister_disappearing_link (&handles->entries [slot]);
+                       GC_GENERAL_REGISTER_DISAPPEARING_LINK (&(handles->entries [slot]), obj);
+                       handles->entries [slot] = (void*)HIDE_POINTER (obj);
+               } else {
+                       handles->entries [slot] = obj;
+               }
+#else
+               handles->entries [slot] = obj;
+#endif
+       } else {
+               /* print a warning? */
+       }
+       /*g_print ("changed entry %d of type %d to object %p (in slot: %p)\n", slot, gchandle & 3, obj, handles->entries [slot]);*/
+       unlock_handles (handles);
+}
+
+void
+mono_gchandle_free (guint32 gchandle)
+{
+       guint slot = gchandle >> 2;
+       HandleData *handles = &gc_handles [gchandle & 3];
+       lock_handles (handles);
+       if (slot < handles->size) {
+#ifdef HAVE_BOEHM_GC
+               if (handles->type <= HANDLE_WEAK_TRACK)
+                       GC_unregister_disappearing_link (&handles->entries [slot]);
+#endif
+               handles->entries [slot] = NULL;
+               handles->bitmap [slot / 32] &= ~(1 << (slot % 32));
+       } else {
+               /* print a warning? */
+       }
+       /*g_print ("freed entry %d of type %d\n", slot, gchandle & 3);*/
+       unlock_handles (handles);
 }
 
 #if HAVE_BOEHM_GC
@@ -475,7 +622,7 @@ finalize_domain_objects (DomainFinalizationReq *req)
        int i;
        GPtrArray *objs;
        MonoDomain *domain = req->domain;
-
+       
        while (g_hash_table_size (domain->finalizable_objects_hash) > 0) {
                /* 
                 * Since the domain is unloading, nobody is allowed to put
@@ -485,7 +632,7 @@ finalize_domain_objects (DomainFinalizationReq *req)
                objs = g_ptr_array_new ();
                g_hash_table_foreach (domain->finalizable_objects_hash, 
                                                          collect_objects, objs);
-               //printf ("FINALIZING %d OBJECTS.\n", objs->len);
+               /* printf ("FINALIZING %d OBJECTS.\n", objs->len); */
 
                for (i = 0; i < objs->len; ++i) {
                        MonoObject *o = (MonoObject*)g_ptr_array_index (objs, i);
@@ -496,24 +643,27 @@ finalize_domain_objects (DomainFinalizationReq *req)
                g_ptr_array_free (objs, TRUE);
        }
 
-       //printf ("DONE.\n");
+       /* Process finalizers which are already in the queue */
+       GC_invoke_finalizers ();
+
+       /* printf ("DONE.\n"); */
        SetEvent (req->done_event);
 
-       /* FIXME: How to delete the event ? */
+       /* The event is closed in mono_domain_finalize if we get here */
        g_free (req);
 }
 
 static guint32 finalizer_thread (gpointer unused)
 {
-       guint32 stack_start;
-       
-       mono_thread_new_init (GetCurrentThreadId (), &stack_start, NULL);
-       
+       gc_thread = mono_thread_current ();
+
+       SetEvent (thread_started_event);
+
        while(!finished) {
                /* Wait to be notified that there's at least one
                 * finaliser to run
                 */
-               WaitForSingleObject (finalizer_event, INFINITE);
+               WaitForSingleObjectEx (finalizer_event, INFINITE, TRUE);
 
                if (domains_to_finalize) {
                        EnterCriticalSection (&finalizer_mutex);
@@ -548,7 +698,6 @@ static guint32 finalizer_thread (gpointer unused)
        }
 
        SetEvent (shutdown_event);
-       
        return(0);
 }
 
@@ -588,6 +737,12 @@ static GCThreadFunctions mono_gc_thread_vtable = {
 };
 #endif /* WITH_INCLUDED_LIBGC */
 
+static void
+mono_gc_warning (char *msg, GC_word arg)
+{
+       mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_GC, msg, (unsigned long)arg);
+}
+
 void mono_gc_init (void)
 {
        InitializeCriticalSection (&handle_section);
@@ -598,10 +753,18 @@ void mono_gc_init (void)
 #ifdef WITH_INCLUDED_LIBGC
        gc_thread_vtable = &mono_gc_thread_vtable;
 #endif
+       
+       MONO_GC_REGISTER_ROOT (gc_handles [HANDLE_NORMAL].entries);
+       MONO_GC_REGISTER_ROOT (gc_handles [HANDLE_PINNED].entries);
+       GC_no_dls = TRUE;
+
+       GC_oom_fn = mono_gc_out_of_memory;
+
+       GC_set_warn_proc (mono_gc_warning);
 
 #ifdef ENABLE_FINALIZER_THREAD
 
-       if (getenv ("GC_DONT_GC")) {
+       if (g_getenv ("GC_DONT_GC")) {
                gc_disabled = TRUE;
                return;
        }
@@ -609,21 +772,20 @@ void 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);
-       if (finalizer_event == NULL || pending_done_event == NULL || shutdown_event == NULL) {
+       thread_started_event = CreateEvent (NULL, TRUE, FALSE, NULL);
+       if (finalizer_event == NULL || pending_done_event == NULL || shutdown_event == NULL || thread_started_event == NULL) {
                g_assert_not_reached ();
        }
 
        GC_finalize_on_demand = 1;
        GC_finalizer_notifier = finalize_notify;
-       
-       /* Don't use mono_thread_create here, because we don't want
-        * the runtime to wait for this thread to exit when it's
-        * cleaning up.
+
+       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 ()
         */
-       gc_thread = CreateThread (NULL, mono_threads_get_default_stacksize (), finalizer_thread, NULL, 0, NULL);
-       if (gc_thread == NULL) {
-               g_assert_not_reached ();
-       }
+       WaitForSingleObjectEx (thread_started_event, INFINITE, FALSE);
 #endif
 }
 
@@ -634,17 +796,19 @@ void mono_gc_cleanup (void)
 #endif
 
 #ifdef ENABLE_FINALIZER_THREAD
-       ResetEvent (shutdown_event);
-       finished = TRUE;
        if (!gc_disabled) {
-               finalize_notify ();
-               /* Finishing the finalizer thread, so wait a little bit... */
-               /* MS seems to wait for about 2 seconds */
-               /* 
-                * FIXME: This is not thread safe. If the finalizer thread keeps
-                * running, and the runtime is shut down, it will lead to a crash.
-                */
-               WaitForSingleObject (shutdown_event, 2000);
+               ResetEvent (shutdown_event);
+               finished = TRUE;
+               if (mono_thread_current () != gc_thread) {
+                       finalize_notify ();
+                       /* Finishing the finalizer thread, so wait a little bit... */
+                       /* MS seems to wait for about 2 seconds */
+                       if (WaitForSingleObjectEx (shutdown_event, 2000000, FALSE) == WAIT_TIMEOUT) {
+                               mono_thread_stop (gc_thread);
+                       }
+               }
+               gc_thread = NULL;
+               GC_finalizer_notifier = NULL;
        }
 
 #endif
@@ -664,3 +828,10 @@ void mono_gc_cleanup (void)
 
 #endif
 
+gboolean
+mono_gc_is_finalizer_thread (MonoThread *thread)
+{
+       return thread == gc_thread;
+}
+
+