2004-01-19 Zoltan Varga <vargaz@freemail.hu>
[mono.git] / mono / metadata / gc.c
index a7b71520df8076cc08e117abd8e410d96fbdaa5a..6815f0027d9f320417a709789f82b66336764b3a 100644 (file)
@@ -10,7 +10,7 @@
 #include <glib.h>
 #include <string.h>
 
-#include <mono/metadata/gc.h>
+#include <mono/metadata/gc-internal.h>
 #include <mono/metadata/threads.h>
 #include <mono/metadata/tabledefs.h>
 #include <mono/metadata/exception.h>
 #define REVEAL_POINTER(v)       (v)
 #endif
 
+typedef struct DomainFinalizationReq {
+       MonoDomain *domain;
+       HANDLE done_event;
+} DomainFinalizationReq;
+
+#ifdef PLATFORM_WINCE /* FIXME: add accessors to gc.dll API */
+extern void (*__imp_GC_finalizer_notifier)(void);
+#define GC_finalizer_notifier __imp_GC_finalizer_notifier
+extern int __imp_GC_finalize_on_demand;
+#define GC_finalize_on_demand __imp_GC_finalize_on_demand
+#endif
+
 static int finalize_slot = -1;
 
+static gboolean gc_disabled = FALSE;
+
+static CRITICAL_SECTION finalizer_mutex;
+
+static GSList *domains_to_finalize= NULL;
+
+static HANDLE gc_thread;
+
 static void object_register_finalizer (MonoObject *obj, void (*callback)(void *, void*));
 
+#if HAVE_BOEHM_GC
+static void finalize_notify (void);
+static HANDLE pending_done_event;
+static HANDLE shutdown_event;
+#endif
+
 /* 
  * 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...
@@ -34,7 +60,7 @@ static void
 run_finalize (void *obj, void *data)
 {
        MonoObject *exc = NULL;
-       MonoObject *o;
+       MonoObject *o, *o2;
        o = (MonoObject*)((char*)obj + GPOINTER_TO_UINT (data));
 
        if (finalize_slot < 0) {
@@ -48,11 +74,25 @@ run_finalize (void *obj, void *data)
                        }
                }
        }
+
+       mono_domain_lock (o->vtable->domain);
+
+       o2 = g_hash_table_lookup (o->vtable->domain->finalizable_objects_hash, o);
+
+       mono_domain_unlock (o->vtable->domain);
+
+       if (!o2)
+               /* Already finalized somehow */
+               return;
+
        /* make sure the finalizer is not called again if the object is resurrected */
        object_register_finalizer (obj, NULL);
        /* 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);*/
-       mono_domain_set (mono_object_domain (o));
+       /* 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_runtime_invoke (o->vtable->klass->vtable [finalize_slot], o, NULL, &exc);
 
        if (exc) {
@@ -74,7 +114,28 @@ object_register_finalizer (MonoObject *obj, void (*callback)(void *, void*))
 #if HAVE_BOEHM_GC
        guint offset = 0;
 
+#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))
+               /*
+                * 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);
+
+       if (callback)
+               g_hash_table_insert (obj->vtable->domain->finalizable_objects_hash, obj,
+                                                        obj);
+       else
+               g_hash_table_remove (obj->vtable->domain->finalizable_objects_hash, obj);
+
+       mono_domain_unlock (obj->vtable->domain);
+
        GC_REGISTER_FINALIZER_NO_ORDER ((char*)obj - offset, callback, GUINT_TO_POINTER (offset), NULL, NULL);
 #endif
 }
@@ -82,90 +143,62 @@ object_register_finalizer (MonoObject *obj, void (*callback)(void *, void*))
 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);*/
+       /* 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);
 }
 
-/* 
- * to speedup, at class init time, check if a class or struct
- * have fields that need to be finalized and set a flag.
+/*
+ * mono_domain_finalize:
+ *
+ *  Request finalization of all finalizable objects inside @domain. Wait
+ * @timeout msecs for the finalization to complete.
+ * Returns: TRUE if succeeded, FALSE if there was a timeout
  */
-static void
-finalize_fields (MonoClass *class, char *data, gboolean instance, GHashTable *todo) {
-       int i;
-       MonoClassField *field;
-       MonoObject *obj;
 
-       /*if (!instance)
-               g_print ("Finalize statics on on %s\n", class->name);*/
-       if (instance && class->valuetype)
-               data -= sizeof (MonoObject);
-       do {
-               for (i = 0; i < class->field.count; ++i) {
-                       field = &class->fields [i];
-                       if (instance) {
-                               if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
-                                       continue;
-                       } else {
-                               if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC))
-                                       continue;
-                       }
-                       switch (field->type->type) {
-                       case MONO_TYPE_OBJECT:
-                       case MONO_TYPE_CLASS:
-                               obj = *((MonoObject**)(data + field->offset));
-                               if (obj) {
-                                       if (mono_object_class (obj)->has_finalize) {
-                                               /* disable the registered finalizer */
-                                               object_register_finalizer (obj, NULL);
-                                               run_finalize (obj, NULL);
-                                       } else {
-                                               /* 
-                                                * if the type doesn't have a finalizer, we finalize 
-                                                * the fields ourselves just like we do for structs.
-                                                * Disabled for now: how do we handle loops?
-                                                */
-                                               /*finalize_fields (mono_object_class (obj), obj, TRUE, todo);*/
-                                       }
-                               }
-                               break;
-                       case MONO_TYPE_VALUETYPE: {
-                               MonoClass *fclass = mono_class_from_mono_type (field->type);
-                               if (fclass->enumtype)
-                                       continue;
-                               /*finalize_fields (fclass, data + field->offset, TRUE, todo);*/
-                               break;
-                       }
-                       case MONO_TYPE_ARRAY:
-                       case MONO_TYPE_SZARRAY:
-                               /* FIXME: foreach item... */
-                               break;
-                       }
-               }
-               if (!instance)
-                       return;
-               class = class->parent;
-       } while (class);
-}
+gboolean
+mono_domain_finalize (MonoDomain *domain, guint32 timeout) 
+{
+       DomainFinalizationReq *req;
+       guint32 res;
+       HANDLE done_event;
+
+       /* 
+        * 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;
 
-static void
-finalize_static_data (MonoClass *class, MonoVTable *vtable, GHashTable *todo) {
+       GC_gcollect ();
 
-       if (class->enumtype || !vtable->data)
-               return;
-       finalize_fields (class, vtable->data, FALSE, todo);
-}
+       done_event = CreateEvent (NULL, TRUE, FALSE, NULL);
 
-void
-mono_domain_finalize (MonoDomain *domain) {
+       req = g_new0 (DomainFinalizationReq, 1);
+       req->domain = domain;
+       req->done_event = done_event;
+       
+       EnterCriticalSection (&finalizer_mutex);
 
-       GHashTable *todo = g_hash_table_new (NULL, NULL);
-#if HAVE_BOEHM_GC
-       GC_gcollect ();
+       domains_to_finalize = g_slist_append (domains_to_finalize, req);
+
+       LeaveCriticalSection (&finalizer_mutex);
+
+       /* Tell the finalizer thread to finalize this appdomain */
+       finalize_notify ();
+
+       res = WaitForSingleObject (done_event, timeout);
+
+       //printf ("WAIT RES: %d.\n", res);
+       if (res == WAIT_TIMEOUT)
+               return FALSE;
+       else
+               return TRUE;
+#else
+       /* We don't support domain finalization without a GC */
+       return FALSE;
 #endif
-       mono_g_hash_table_foreach (domain->class_vtable_hash, (GHFunc)finalize_static_data, todo);
-       /* FIXME: finalize objects in todo... */
-       g_hash_table_destroy (todo);
 }
 
 void
@@ -186,7 +219,7 @@ ves_icall_System_GC_GetTotalMemory (MonoBoolean forceCollection)
 #if HAVE_BOEHM_GC
        if (forceCollection)
                GC_gcollect ();
-       return GC_get_heap_size ();
+       return GC_get_heap_size () - GC_get_free_bytes ();
 #else
        return 0;
 #endif
@@ -222,9 +255,26 @@ void
 ves_icall_System_GC_WaitForPendingFinalizers (void)
 {
        MONO_ARCH_SAVE_REGS;
+       
+#if HAVE_BOEHM_GC
+       if (!GC_should_invoke_finalizers ())
+               return;
+
+       if (GetCurrentThread () == gc_thread)
+               /* Avoid deadlocks */
+               return;
+
+       ResetEvent (pending_done_event);
+       finalize_notify ();
+       /* g_print ("Waiting for pending finalizers....\n"); */
+       WaitForSingleObject (pending_done_event, INFINITE);
+       /* g_print ("Done pending....\n"); */
+#else
+#endif
 }
 
-/*static CRITICAL_SECTION handle_section;*/
+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;
@@ -257,15 +307,17 @@ ves_icall_System_GCHandle_GetTarget (guint32 handle)
 
        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 obj;
        }
        return NULL;
 }
@@ -274,10 +326,13 @@ guint32
 ves_icall_System_GCHandle_GetTargetHandle (MonoObject *obj, guint32 handle, gint32 type)
 {
        gpointer val = obj;
-       guint32 h, idx = next_handle++;
+       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;
@@ -313,7 +368,7 @@ ves_icall_System_GCHandle_GetTargetHandle (MonoObject *obj, guint32 handle, gint
                gc_handles = new_array;
                gc_handle_types = new_type_array;
 #else
-               g_error ("No GCHandle support built-in");
+               mono_raise_exception (mono_get_exception_execution_engine ("No GCHandle support built-in"));
 #endif
        }
 
@@ -331,7 +386,7 @@ ves_icall_System_GCHandle_GetTargetHandle (MonoObject *obj, guint32 handle, gint
                if (gc_handles [idx] != (gpointer)-1)
                        GC_GENERAL_REGISTER_DISAPPEARING_LINK (&(gc_handles [idx]), obj);
 #else
-               g_error ("No weakref support");
+               mono_raise_exception (mono_get_exception_execution_engine ("No weakref support"));
 #endif
                break;
        default:
@@ -339,6 +394,7 @@ ves_icall_System_GCHandle_GetTargetHandle (MonoObject *obj, guint32 handle, gint
                gc_handle_types [idx] = type;
                break;
        }
+       LeaveCriticalSection (&handle_section);
        return h;
 }
 
@@ -350,6 +406,8 @@ ves_icall_System_GCHandle_FreeHandle (guint32 handle)
 
        MONO_ARCH_SAVE_REGS;
 
+       EnterCriticalSection (&handle_section);
+
 #ifdef HAVE_BOEHM_GC
        g_assert (type == gc_handle_types [idx]);
        if ((type == HANDLE_WEAK) || (type == HANDLE_WEAK_TRACK)) {
@@ -357,11 +415,13 @@ ves_icall_System_GCHandle_FreeHandle (guint32 handle)
                        GC_unregister_disappearing_link (&(gc_handles [idx]));
        }
 #else
-       g_error ("No GCHandle support");
+       LeaveCriticalSection (&handle_section);
+       mono_raise_exception (mono_get_exception_execution_engine ("No GCHandle support"));
 #endif
 
        gc_handles [idx] = (gpointer)-1;
        gc_handle_types [idx] = (guint8)-1;
+       LeaveCriticalSection (&handle_section);
 }
 
 gpointer
@@ -373,8 +433,10 @@ ves_icall_System_GCHandle_GetAddrOfPinnedObject (guint32 handle)
        MONO_ARCH_SAVE_REGS;
 
        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)) {
                        obj = REVEAL_POINTER (obj);
                        if (obj == (MonoObject *) -1)
@@ -399,11 +461,57 @@ static void finalize_notify (void)
        SetEvent (finalizer_event);
 }
 
+static void
+collect_objects (gpointer key, gpointer value, gpointer user_data)
+{
+       GPtrArray *arr = (GPtrArray*)user_data;
+       g_ptr_array_add (arr, key);
+}
+
+/*
+ * finalize_domain_objects:
+ *
+ *  Run the finalizers of all finalizable objects in req->domain.
+ */
+static void
+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
+                * 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);
+               //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);
+               }
+
+               g_ptr_array_free (objs, TRUE);
+       }
+
+       //printf ("DONE.\n");
+       SetEvent (req->done_event);
+
+       /* FIXME: How to delete the event ? */
+       g_free (req);
+}
+
 static guint32 finalizer_thread (gpointer unused)
 {
        guint32 stack_start;
        
-       mono_new_thread_init (NULL, &stack_start);
+       mono_thread_new_init (GetCurrentThreadId (), &stack_start, NULL);
        
        while(!finished) {
                /* Wait to be notified that there's at least one
@@ -411,25 +519,101 @@ static guint32 finalizer_thread (gpointer unused)
                 */
                WaitForSingleObject (finalizer_event, INFINITE);
 
+               if (domains_to_finalize) {
+                       EnterCriticalSection (&finalizer_mutex);
+                       if (domains_to_finalize) {
+                               DomainFinalizationReq *req = domains_to_finalize->data;
+                               domains_to_finalize = g_slist_remove (domains_to_finalize, req);
+                               LeaveCriticalSection (&finalizer_mutex);
+
+                               finalize_domain_objects (req);
+                       }
+                       else
+                               LeaveCriticalSection (&finalizer_mutex);
+               }                               
+
 #ifdef DEBUG
                g_message (G_GNUC_PRETTY_FUNCTION ": invoking finalizers");
 #endif
 
-               GC_invoke_finalizers ();
+               /* If finished == TRUE, mono_gc_cleanup has been called (from mono_runtime_cleanup),
+                * before the domain is unloaded.
+                *
+                * There is a bug in GC_invoke_finalizer () in versions <= 6.2alpha4:
+                * the 'mem_freed' variable is not initialized when there are no
+                * objects to finalize, which leads to strange behavior later on.
+                * The check is necessary to work around that bug.
+                */
+               if (GC_should_invoke_finalizers ()) {
+                       GC_invoke_finalizers ();
+               }
+
+               SetEvent (pending_done_event);
        }
+
+       SetEvent (shutdown_event);
        
        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 WITH_INCLUDED_LIBGC
+/* from threads.c */
+extern void mono_gc_stop_world (void);
+extern void mono_gc_start_world (void);
+extern void mono_gc_push_all_stacks (void);
+
+static void mono_gc_lock (void)
+{
+       EnterCriticalSection (&allocator_section);
+}
+
+static void mono_gc_unlock (void)
+{
+       LeaveCriticalSection (&allocator_section);
+}
+
+static GCThreadFunctions mono_gc_thread_vtable = {
+       NULL,
+
+       mono_gc_lock,
+       mono_gc_unlock,
+
+       mono_gc_stop_world,
+       NULL,
+       mono_gc_push_all_stacks,
+       mono_gc_start_world
+};
+#endif /* WITH_INCLUDED_LIBGC */
+
 void mono_gc_init (void)
 {
-       HANDLE gc_thread;
+       InitializeCriticalSection (&handle_section);
+       InitializeCriticalSection (&allocator_section);
+
+       InitializeCriticalSection (&finalizer_mutex);
+
+#ifdef WITH_INCLUDED_LIBGC
+       gc_thread_vtable = &mono_gc_thread_vtable;
+#endif
+
+#ifdef ENABLE_FINALIZER_THREAD
 
-       if (getenv ("GC_DONT_GC"))
+       if (getenv ("GC_DONT_GC")) {
+               gc_disabled = TRUE;
                return;
+       }
        
        finalizer_event = CreateEvent (NULL, FALSE, FALSE, NULL);
-       if (finalizer_event == 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) {
                g_assert_not_reached ();
        }
 
@@ -440,10 +624,11 @@ void mono_gc_init (void)
         * the runtime to wait for this thread to exit when it's
         * cleaning up.
         */
-       gc_thread = CreateThread (NULL, 0, finalizer_thread, NULL, 0, NULL);
+       gc_thread = CreateThread (NULL, mono_threads_get_default_stacksize (), finalizer_thread, NULL, 0, NULL);
        if (gc_thread == NULL) {
                g_assert_not_reached ();
        }
+#endif
 }
 
 void mono_gc_cleanup (void)
@@ -452,8 +637,21 @@ void mono_gc_cleanup (void)
        g_message (G_GNUC_PRETTY_FUNCTION ": cleaning up finalizer");
 #endif
 
-       finished = TRUE;
-       finalize_notify ();
+#ifdef ENABLE_FINALIZER_THREAD
+       if (!gc_disabled) {
+               ResetEvent (shutdown_event);
+               finished = TRUE;
+               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);
+       }
+
+#endif
 }
 
 #else
@@ -461,6 +659,7 @@ void mono_gc_cleanup (void)
 /* no Boehm GC support. */
 void mono_gc_init (void)
 {
+       InitializeCriticalSection (&handle_section);
 }
 
 void mono_gc_cleanup (void)