2009-06-04 Zoltan Varga <vargaz@gmail.com>
[mono.git] / mono / metadata / gc.c
index 998b07b29e9ad7be08bc936088d5b213e8d3c9c4..43b09a5eb37a4288f3eb9bb82ddb0730db5add3d 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/metadata/gc-internal.h>
 #include <mono/metadata/marshal.h> /* for mono_delegate_free_ftnptr () */
+#include <mono/metadata/attach.h>
+#if HAVE_SEMAPHORE_H
+#include <semaphore.h>
+/* we do this only for known working systems (OSX for example
+ * has the header and functions, but they don't work at all): in other cases
+ * we fall back to the io-layer slightly slower and signal-unsafe Event.
+ */
+#if defined (__linux__) || (defined(__APPLE__) && defined(__arm__))
+#define USE_POSIX_SEM 1
+#endif
+#endif
+
+#ifndef PLATFORM_WIN32
+#include <pthread.h>
+#endif
 
 typedef struct DomainFinalizationReq {
        MonoDomain *domain;
@@ -51,10 +69,11 @@ static MonoThread *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
@@ -67,30 +86,63 @@ add_thread_to_finalize (MonoThread *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);
 
@@ -110,11 +162,14 @@ run_finalize (void *obj, void *data)
                }
        }
 
+       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
@@ -129,20 +184,41 @@ run_finalize (void *obj, void *data)
 
        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)
+       if (mono_marshal_free_ccw (o) && !finalizer) {
+               mono_domain_set_internal (caller_domain);
                return;
+       }
+#endif
 
-       mono_runtime_invoke (finalizer, o, NULL, &exc);
+       /* 
+        * 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
@@ -155,7 +231,7 @@ mono_gc_finalize_threadpool_threads (void)
                thread->threadpool_thread = FALSE;
                mono_object_register_finalizer ((MonoObject*)thread);
 
-               run_finalize (thread, NULL);
+               mono_gc_run_finalize (thread, NULL);
 
                threads_to_finalize = mono_mlist_next (threads_to_finalize);
        }
@@ -201,14 +277,14 @@ object_register_finalizer (MonoObject *obj, void (*callback)(void *, void*))
                 */
                return;
 
-       mono_domain_lock (domain);
+       mono_domain_finalizers_lock (domain);
 
        if (callback)
                g_hash_table_insert (domain->finalizable_objects_hash, obj, obj);
        else
                g_hash_table_remove (domain->finalizable_objects_hash, obj);
 
-       mono_domain_unlock (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)
@@ -228,13 +304,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.
@@ -285,6 +361,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); */
@@ -338,7 +417,7 @@ ves_icall_System_GC_ReRegisterForFinalize (MonoObject *obj)
 {
        MONO_ARCH_SAVE_REGS;
 
-       object_register_finalizer (obj, run_finalize);
+       object_register_finalizer (obj, mono_gc_run_finalize);
 }
 
 void
@@ -391,8 +470,6 @@ typedef enum {
        HANDLE_PINNED
 } HandleType;
 
-static void mono_gchandle_set_target (guint32 gchandle, MonoObject *obj);
-
 static HandleType mono_gchandle_get_type (guint32 gchandle);
 
 MonoObject *
@@ -493,7 +570,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);
@@ -556,7 +633,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);
@@ -577,9 +654,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);
@@ -605,7 +683,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);
 }
 
 /**
@@ -630,7 +708,14 @@ 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
@@ -681,15 +766,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;
                }
@@ -698,6 +786,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
 }
 
 /**
@@ -751,6 +844,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) {
@@ -763,6 +861,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);
 }
@@ -806,6 +905,9 @@ mono_gchandle_free_domain (MonoDomain *domain)
 
 #ifndef HAVE_NULL_GC
 
+#if USE_POSIX_SEM
+static sem_t finalizer_sem;
+#endif
 static HANDLE finalizer_event;
 static volatile gboolean finished=FALSE;
 
@@ -816,9 +918,15 @@ mono_gc_finalize_notify (void)
        g_message (G_GNUC_PRETTY_FUNCTION ": prodding finalizer");
 #endif
 
+#if USE_POSIX_SEM
+       sem_post (&finalizer_sem);
+#else
        SetEvent (finalizer_event);
+#endif
 }
 
+#ifdef HAVE_BOEHM_GC
+
 static void
 collect_objects (gpointer key, gpointer value, gpointer user_data)
 {
@@ -826,6 +934,8 @@ collect_objects (gpointer key, gpointer value, gpointer user_data)
        g_ptr_array_add (arr, key);
 }
 
+#endif
+
 /*
  * finalize_domain_objects:
  *
@@ -852,7 +962,7 @@ finalize_domain_objects (DomainFinalizationReq *req)
                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);
@@ -864,7 +974,7 @@ finalize_domain_objects (DomainFinalizationReq *req)
        while ((count = mono_gc_finalizers_for_domain (domain, to_finalize, NUM_FOBJECTS))) {
                int i;
                for (i = 0; i < count; ++i) {
-                       run_finalize (to_finalize [i], 0);
+                       mono_gc_run_finalize (to_finalize [i], 0);
                }
        }
 #endif
@@ -882,16 +992,20 @@ finalize_domain_objects (DomainFinalizationReq *req)
 static guint32
 finalizer_thread (gpointer unused)
 {
-       gc_thread = mono_thread_current ();
-
-       SetEvent (thread_started_event);
-
        while (!finished) {
                /* Wait to be notified that there's at least one
                 * finaliser to run
                 */
+#if USE_POSIX_SEM
+               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 ();
@@ -939,26 +1053,14 @@ 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);
-
-       /*
-        * Waiting for a new thread would result in a deadlock when the runtime is
-        * initialized from _CorDllMain that is called while the OS loader lock is
-        * held by LoadLibrary. Avoiding waiting for the finalizer thread being
-        * created should not cause any issues on Windows.
-        */
-#ifndef PLATFORM_WIN32
-       /*
-        * Wait until the finalizer thread sets gc_thread since its value is needed
-        * by mono_thread_attach ()
-        */
-       WaitForSingleObjectEx (thread_started_event, INFINITE, FALSE);
+#if USE_POSIX_SEM
+       sem_init (&finalizer_sem, 0, 0);
 #endif
+
+       gc_thread = mono_thread_create_internal (mono_domain_get (), finalizer_thread, NULL, FALSE);
 }
 
 void
@@ -976,7 +1078,32 @@ mono_gc_cleanup (void)
                        /* 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) {
+                               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_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;