2006-05-31 Zoltan Varga <vargaz@gmail.com>
[mono.git] / mono / metadata / threads.c
index 344bd732544055beeda0c5af55a6c24571c9a21c..773701d5f23cfd7ff06e765d1e24dab812885f2b 100644 (file)
@@ -31,6 +31,7 @@
 #include <mono/metadata/marshal.h>
 #include <mono/io-layer/io-layer.h>
 #include <mono/metadata/object-internals.h>
+#include <mono/metadata/mono-debug-debugger.h>
 #include <mono/utils/mono-compiler.h>
 
 #include <mono/os/gc_wrapper.h>
 /*#define LIBGC_DEBUG(a) do { a; } while (0)*/
 #define LIBGC_DEBUG(a)
 
+/* Provide this for systems with glib < 2.6 */
+#ifndef G_GSIZE_FORMAT
+#   if GLIB_SIZEOF_LONG == 8
+#       define G_GSIZE_FORMAT "lu"
+#   else
+#       define G_GSIZE_FORMAT "u"
+#   endif
+#endif
+
 struct StartInfo 
 {
        guint32 (*func)(void *);
@@ -66,8 +76,13 @@ typedef struct {
        int offset;
 } StaticDataInfo;
 
-/* Number of cached culture objects in the MonoThread->culture_info array */
+/* Number of cached culture objects in the MonoThread->cached_culture_info array
+ * (per-type): we use the first NUM entries for CultureInfo and the last for
+ * UICultureInfo. So the size of the array is really NUM_CACHED_CULTURES * 2.
+ */
 #define NUM_CACHED_CULTURES 4
+#define CULTURES_START_IDX 0
+#define UICULTURES_START_IDX NUM_CACHED_CULTURES
 
 /*
  * The "os_handle" field of the WaitHandle class.
@@ -118,10 +133,7 @@ static MonoThreadStartCB mono_thread_start_cb = NULL;
 static MonoThreadAttachCB mono_thread_attach_cb = NULL;
 
 /* function called at thread cleanup */
-static MonoThreadCleanupFunc mono_thread_cleanup = NULL;
-
-/* function called when a new thread has been created */
-static MonoThreadCallbacks *mono_thread_callbacks = NULL;
+static MonoThreadCleanupFunc mono_thread_cleanup_fn = NULL;
 
 /* The default stack size for each thread */
 static guint32 default_stacksize = 0;
@@ -211,7 +223,7 @@ static void handle_remove(gsize tid)
 static void thread_cleanup (MonoThread *thread)
 {
        g_assert (thread != NULL);
-       
+
        mono_release_type_locks (thread);
 
        if (!mono_monitor_enter (thread->synch_lock))
@@ -228,11 +240,10 @@ static void thread_cleanup (MonoThread *thread)
        if (thread->serialized_culture_info)
                g_free (thread->serialized_culture_info);
 
-       mono_gc_free_fixed (thread->culture_info);
-       mono_gc_free_fixed (thread->ui_culture_info);
+       thread->cached_culture_info = NULL;
 
-       if (mono_thread_cleanup)
-               mono_thread_cleanup (thread);
+       if (mono_thread_cleanup_fn)
+               mono_thread_cleanup_fn (thread);
 }
 
 static guint32 WINAPI start_wrapper(void *data)
@@ -240,12 +251,12 @@ static guint32 WINAPI start_wrapper(void *data)
        struct StartInfo *start_info=(struct StartInfo *)data;
        guint32 (*start_func)(void *);
        void *start_arg;
-       guint32 tid;
+       gsize tid;
        MonoThread *thread=start_info->obj;
        MonoObject *start_delegate = start_info->delegate;
 
        THREAD_DEBUG (g_message ("%s: (%"G_GSIZE_FORMAT") Start wrapper", __func__, GetCurrentThreadId ()));
-       
+
        /* We can be sure start_info->obj->tid and
         * start_info->obj->handle have been set, because the thread
         * was created suspended, and these values were set before the
@@ -334,9 +345,6 @@ void mono_thread_new_init (gsize tid, gpointer stack_start, gpointer func)
        if (mono_thread_start_cb) {
                mono_thread_start_cb (tid, stack_start, func);
        }
-
-       if (mono_thread_callbacks)
-               (* mono_thread_callbacks->thread_created) (tid, stack_start, func);
 }
 
 void mono_threads_set_default_stacksize (guint32 stacksize)
@@ -355,7 +363,7 @@ void mono_thread_create (MonoDomain *domain, gpointer func, gpointer arg)
        HANDLE thread_handle;
        struct StartInfo *start_info;
        gsize tid;
-       
+
        thread=(MonoThread *)mono_object_new (domain,
                                              mono_defaults.thread_class);
 
@@ -380,7 +388,7 @@ void mono_thread_create (MonoDomain *domain, gpointer func, gpointer arg)
        thread->handle=thread_handle;
        thread->tid=tid;
 
-       thread->synch_lock=mono_object_new (domain, mono_defaults.object_class);
+       MONO_OBJECT_SETREF (thread, synch_lock, mono_object_new (domain, mono_defaults.object_class));
                                                  
        handle_store(thread);
 
@@ -402,7 +410,7 @@ mono_thread_attach (MonoDomain *domain)
        }
 
        if (!mono_gc_register_thread (&domain)) {
-               g_error ("Thread %p calling into managed code is not registered with the GC. On UNIX, this can be fixed by #include-ing <gc.h> before <pthread.h> in the file containing the thread creation code.", GetCurrentThread ());
+               g_error ("Thread %"G_GSIZE_FORMAT" calling into managed code is not registered with the GC. On UNIX, this can be fixed by #include-ing <gc.h> before <pthread.h> in the file containing the thread creation code.", GetCurrentThreadId ());
        }
 
        thread = (MonoThread *)mono_object_new (domain,
@@ -413,18 +421,17 @@ mono_thread_attach (MonoDomain *domain)
 
        tid=GetCurrentThreadId ();
 
-#ifdef PLATFORM_WIN32
        /* 
         * The handle returned by GetCurrentThread () is a pseudo handle, so it can't be used to
         * refer to the thread from other threads for things like aborting.
         */
        DuplicateHandle (GetCurrentProcess (), thread_handle, GetCurrentProcess (), &thread_handle, 
                                         THREAD_ALL_ACCESS, TRUE, 0);
-#endif
 
        thread->handle=thread_handle;
        thread->tid=tid;
-       thread->synch_lock=mono_object_new (domain, mono_defaults.object_class);
+       thread->stack_ptr = &tid;
+       MONO_OBJECT_SETREF (thread, synch_lock, mono_object_new (domain, mono_defaults.object_class));
 
        THREAD_DEBUG (g_message ("%s: Attached thread ID %"G_GSIZE_FORMAT" (handle %p)", __func__, tid, thread_handle));
 
@@ -454,10 +461,10 @@ mono_thread_detach (MonoThread *thread)
        
        thread_cleanup (thread);
 
-       /* Need to CloseHandle this thread, because we took a reference in
-        * mono_thread_attach ()
+       /* Don't need to CloseHandle this thread, even though we took a
+        * reference in mono_thread_attach (), because the GC will do it
+        * when the Thread object is finalised.
         */
-       CloseHandle(thread->handle);
 }
 
 void
@@ -503,7 +510,7 @@ HANDLE ves_icall_System_Threading_Thread_Thread_internal(MonoThread *this,
                /* This is freed in start_wrapper */
                start_info = g_new0 (struct StartInfo, 1);
                start_info->func = start_func;
-               start_info->start_arg = this->start_obj;
+               start_info->start_arg = this->start_obj; /* FIXME: GC object stored in unmanaged memory */
                start_info->delegate = start;
                start_info->obj = this;
                start_info->domain = mono_domain_get ();
@@ -565,14 +572,8 @@ static void mono_thread_start (MonoThread *thread)
         */
        handle_store (thread);
 
-       if (mono_thread_callbacks)
-               (* mono_thread_callbacks->start_resume) (thread->tid);
-
        ResumeThread (thread->handle);
 
-       if (mono_thread_callbacks)
-               (* mono_thread_callbacks->end_resume) (thread->tid);
-
        if(thread->start_notify!=NULL) {
                /* Wait for the thread to set up its TLS data etc, so
                 * theres no potential race condition if someone tries
@@ -653,18 +654,16 @@ ves_icall_System_Threading_Thread_SetName_internal (MonoThread *this_obj, MonoSt
        mono_monitor_exit (this_obj->synch_lock);
 }
 
-MonoObject*
-ves_icall_System_Threading_Thread_GetCachedCurrentCulture (MonoThread *this)
+static MonoObject*
+lookup_cached_culture (MonoThread *this, MonoDomain *domain, int start_idx)
 {
        MonoObject *res;
-       MonoDomain *domain;
        int i;
 
-       /* No need to lock here */
-       if (this->culture_info) {
+       if (this->cached_culture_info) {
                domain = mono_domain_get ();
-               for (i = 0; i < NUM_CACHED_CULTURES; ++i) {
-                       res = this->culture_info [i];
+               for (i = start_idx; i < start_idx + NUM_CACHED_CULTURES; ++i) {
+                       res = mono_array_get (this->cached_culture_info, MonoObject*, i);
                        if (res && res->vtable->domain == domain)
                                return res;
                }
@@ -673,6 +672,12 @@ ves_icall_System_Threading_Thread_GetCachedCurrentCulture (MonoThread *this)
        return NULL;
 }
 
+MonoObject*
+ves_icall_System_Threading_Thread_GetCachedCurrentCulture (MonoThread *this)
+{
+       return lookup_cached_culture (this, mono_domain_get (), CULTURES_START_IDX);
+}
+
 MonoArray*
 ves_icall_System_Threading_Thread_GetSerializedCurrentCulture (MonoThread *this)
 {
@@ -682,40 +687,55 @@ ves_icall_System_Threading_Thread_GetSerializedCurrentCulture (MonoThread *this)
        if (this->serialized_culture_info) {
                res = mono_array_new (mono_domain_get (), mono_defaults.byte_class, this->serialized_culture_info_len);
                memcpy (mono_array_addr (res, guint8, 0), this->serialized_culture_info, this->serialized_culture_info_len);
-       }
-       else
+       } else {
                res = NULL;
+       }
        mono_monitor_exit (this->synch_lock);
 
        return res;
 }
 
-void
-ves_icall_System_Threading_Thread_SetCachedCurrentCulture (MonoThread *this, MonoObject *culture)
+static void
+cache_culture (MonoThread *this, MonoObject *culture, int start_idx)
 {
        int i;
        MonoDomain *domain = mono_domain_get ();
+       MonoObject *obj;
+       int free_slot = -1;
+       int same_domain_slot = -1;
 
        mono_monitor_enter (this->synch_lock);
-       if (!this->culture_info) {
-               this->culture_info = mono_gc_alloc_fixed (sizeof (MonoObject*) * NUM_CACHED_CULTURES, NULL);
-       }
-
-       for (i = 0; i < NUM_CACHED_CULTURES; ++i) {
-               if (this->culture_info [i]) {
-                       if (this->culture_info [i]->vtable->domain == domain)
-                               /* Replace */
-                               break;
+       if (!this->cached_culture_info)
+               this->cached_culture_info = mono_array_new (mono_object_domain (this), mono_defaults.object_class, NUM_CACHED_CULTURES * 2);
+
+       for (i = start_idx; i < start_idx + NUM_CACHED_CULTURES; ++i) {
+               obj = mono_array_get (this->cached_culture_info, MonoObject*, i);
+               /* Free entry */
+               if (!obj) {
+                       free_slot = i;
+                       /* we continue, because there may be a slot used with the same domain */
+                       continue;
                }
-               else
-                       /* Free entry */
+               /* Replace */
+               if (obj->vtable->domain == domain) {
+                       same_domain_slot = i;
                        break;
+               }
        }
-       if (i < NUM_CACHED_CULTURES)
-               this->culture_info [i] = culture;
+       if (same_domain_slot >= 0)
+               mono_array_setref (this->cached_culture_info, same_domain_slot, culture);
+       else if (free_slot >= 0)
+               mono_array_setref (this->cached_culture_info, free_slot, culture);
+       /* we may want to replace an existing entry here, even when no suitable slot is found */
        mono_monitor_exit (this->synch_lock);
 }
 
+void
+ves_icall_System_Threading_Thread_SetCachedCurrentCulture (MonoThread *this, MonoObject *culture)
+{
+       cache_culture (this, culture, CULTURES_START_IDX);
+}
+
 void
 ves_icall_System_Threading_Thread_SetSerializedCurrentCulture (MonoThread *this, MonoArray *arr)
 {
@@ -732,21 +752,7 @@ ves_icall_System_Threading_Thread_SetSerializedCurrentCulture (MonoThread *this,
 MonoObject*
 ves_icall_System_Threading_Thread_GetCachedCurrentUICulture (MonoThread *this)
 {
-       MonoObject *res;
-       MonoDomain *domain;
-       int i;
-
-       /* No need to lock here */
-       if (this->ui_culture_info) {
-               domain = mono_domain_get ();
-               for (i = 0; i < NUM_CACHED_CULTURES; ++i) {
-                       res = this->ui_culture_info [i];
-                       if (res && res->vtable->domain == domain)
-                               return res;
-               }
-       }
-
-       return NULL;
+       return lookup_cached_culture (this, mono_domain_get (), UICULTURES_START_IDX);
 }
 
 MonoArray*
@@ -758,9 +764,9 @@ ves_icall_System_Threading_Thread_GetSerializedCurrentUICulture (MonoThread *thi
        if (this->serialized_ui_culture_info) {
                res = mono_array_new (mono_domain_get (), mono_defaults.byte_class, this->serialized_ui_culture_info_len);
                memcpy (mono_array_addr (res, guint8, 0), this->serialized_ui_culture_info, this->serialized_ui_culture_info_len);
-       }
-       else
+       } else {
                res = NULL;
+       }
        mono_monitor_exit (this->synch_lock);
 
        return res;
@@ -769,27 +775,7 @@ ves_icall_System_Threading_Thread_GetSerializedCurrentUICulture (MonoThread *thi
 void
 ves_icall_System_Threading_Thread_SetCachedCurrentUICulture (MonoThread *this, MonoObject *culture)
 {
-       int i;
-       MonoDomain *domain = mono_domain_get ();
-
-       mono_monitor_enter (this->synch_lock);
-       if (!this->ui_culture_info) {
-               this->ui_culture_info = mono_gc_alloc_fixed (sizeof (MonoObject*) * NUM_CACHED_CULTURES, NULL);
-       }
-
-       for (i = 0; i < NUM_CACHED_CULTURES; ++i) {
-               if (this->ui_culture_info [i]) {
-                       if (this->ui_culture_info [i]->vtable->domain == domain)
-                               /* Replace */
-                               break;
-               }
-               else
-                       /* Free entry */
-                       break;
-       }
-       if (i < NUM_CACHED_CULTURES)
-               this->ui_culture_info [i] = culture;
-       mono_monitor_exit (this->synch_lock);
+       cache_culture (this, culture, UICULTURES_START_IDX);
 }
 
 void
@@ -1382,7 +1368,7 @@ ves_icall_System_Threading_Interlocked_Add_Int (gint32 *location, gint32 value)
        *location = orig + value;
        mono_interlocked_unlock ();
 
-       return orig;
+       return orig + value;
 #endif
 }
 
@@ -1401,7 +1387,7 @@ ves_icall_System_Threading_Interlocked_Add_Long (gint64 *location, gint64 value)
        *location = orig + value;
        mono_interlocked_unlock ();
 
-       return orig;
+       return orig + value;
 #endif
 }
 
@@ -1554,7 +1540,7 @@ ves_icall_System_Threading_Thread_Abort (MonoThread *thread, MonoObject *state)
        }
 
        thread->state |= ThreadState_AbortRequested;
-       thread->abort_state = state;
+       MONO_OBJECT_SETREF (thread, abort_state, state);
        thread->abort_exc = NULL;
 
        mono_monitor_exit (thread->synch_lock);
@@ -1802,15 +1788,38 @@ void mono_thread_init (MonoThreadStartCB start_cb,
        GetCurrentProcess ();
 }
 
-void
-mono_threads_install_cleanup (MonoThreadCleanupFunc func)
+void mono_thread_cleanup (void)
 {
-       mono_thread_cleanup = func;
+#if !defined(PLATFORM_WIN32) && !defined(RUN_IN_SUBTHREAD)
+       /* The main thread must abandon any held mutexes (particularly
+        * important for named mutexes as they are shared across
+        * processes, see bug 74680.)  This will happen when the
+        * thread exits, but if it's not running in a subthread it
+        * won't exit in time.
+        */
+       /* Using non-w32 API is a nasty kludge, but I couldn't find
+        * anything in the documentation that would let me do this
+        * here yet still be safe to call on windows.
+        */
+       _wapi_thread_signal_self (mono_environment_exitcode_get ());
+#endif
+
+#if 0
+       /* This stuff needs more testing, it seems one of these
+        * critical sections can be locked when mono_thread_cleanup is
+        * called.
+        */
+       DeleteCriticalSection (&threads_mutex);
+       DeleteCriticalSection (&interlocked_mutex);
+       DeleteCriticalSection (&contexts_mutex);
+       CloseHandle (background_change_event);
+#endif
 }
 
-void mono_install_thread_callbacks (MonoThreadCallbacks *callbacks)
+void
+mono_threads_install_cleanup (MonoThreadCleanupFunc func)
 {
-       mono_thread_callbacks = callbacks;
+       mono_thread_cleanup_fn = func;
 }
 
 G_GNUC_UNUSED
@@ -1926,27 +1935,38 @@ static void build_wait_tids (gpointer key, gpointer value, gpointer user)
                /* Ignore background threads, we abort them later */
                mono_monitor_enter (thread->synch_lock);
                if (thread->state & ThreadState_Background) {
+                       THREAD_DEBUG (g_message ("%s: ignoring background thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
                        mono_monitor_exit (thread->synch_lock);
                        return; /* just leave, ignore */
                }
                mono_monitor_exit (thread->synch_lock);
                
-               if (mono_gc_is_finalizer_thread (thread))
+               if (mono_gc_is_finalizer_thread (thread)) {
+                       THREAD_DEBUG (g_message ("%s: ignoring finalizer thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
                        return;
+               }
 
-               if (thread == mono_thread_current ())
+               if (thread == mono_thread_current ()) {
+                       THREAD_DEBUG (g_message ("%s: ignoring current thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
                        return;
+               }
 
-               if (thread == mono_thread_get_main ())
+               if (thread == mono_thread_get_main ()) {
+                       THREAD_DEBUG (g_message ("%s: ignoring main thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
                        return;
+               }
 
                handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
-               if (handle == NULL)
+               if (handle == NULL) {
+                       THREAD_DEBUG (g_message ("%s: ignoring unopenable thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
                        return;
+               }
                
                wait->handles[wait->num]=handle;
                wait->threads[wait->num]=thread;
                wait->num++;
+
+               THREAD_DEBUG (g_message ("%s: adding thread %"G_GSIZE_FORMAT, __func__, (gsize)thread->tid));
        } else {
                /* Just ignore the rest, we can't do anything with
                 * them yet
@@ -2045,20 +2065,6 @@ void mono_thread_manage (void)
                        wait_for_tids (wait, INFINITE);
                }
        } while (wait->num > 0);
-
-#if !defined(PLATFORM_WIN32) && !defined(RUN_IN_SUBTHREAD)
-       /* The main thread must abandon any held mutexes (particularly
-        * important for named mutexes as they are shared across
-        * processes, see bug 74680.)  This will happen when the
-        * thread exits, but if it's not running in a subthread it
-        * won't exit in time.
-        */
-       /* Using non-w32 API is a nasty kludge, but I couldn't find
-        * anything in the documentation that would let me do this
-        * here yet still be safe to call on windows.
-        */
-       _wapi_thread_abandon_mutexes (GetCurrentThread ());
-#endif
        
        /* 
         * give the subthreads a chance to really quit (this is mainly needed
@@ -2352,17 +2358,13 @@ clear_cached_culture (gpointer key, gpointer value, gpointer user_data)
        int i;
 
        /* No locking needed here */
+       /* FIXME: why no locking? writes to the cache are protected with synch_lock above */
 
-       if (thread->culture_info) {
-               for (i = 0; i < NUM_CACHED_CULTURES; ++i) {
-                       if (thread->culture_info [i] && thread->culture_info [i]->vtable->domain == domain)
-                               thread->culture_info [i] = NULL;
-               }
-       }
-       if (thread->ui_culture_info) {
-               for (i = 0; i < NUM_CACHED_CULTURES; ++i) {
-                       if (thread->ui_culture_info [i] && thread->ui_culture_info [i]->vtable->domain == domain)
-                               thread->ui_culture_info [i] = NULL;
+       if (thread->cached_culture_info) {
+               for (i = 0; i < NUM_CACHED_CULTURES * 2; ++i) {
+                       MonoObject *obj = mono_array_get (thread->cached_culture_info, MonoObject*, i);
+                       if (obj && obj->vtable->domain == domain)
+                               mono_array_set (thread->cached_culture_info, MonoObject*, i, NULL);
                }
        }
 }
@@ -2643,58 +2645,6 @@ mono_thread_free_local_slot_values (int slot, MonoBoolean thread_local)
        }
 }
 
-static void gc_stop_world (gpointer key, gpointer value, gpointer user)
-{
-       MonoThread *thread=(MonoThread *)value;
-
-       LIBGC_DEBUG (g_message ("%s: %"G_GSIZE_FORMAT" - %"G_GSIZE_FORMAT, __func__, (gsize)user, (gsize)thread->tid));
-
-       if(thread->tid == (gsize)user)
-               return;
-
-       SuspendThread (thread->handle);
-}
-
-void mono_gc_stop_world (void)
-{
-       gsize self = GetCurrentThreadId ();
-
-       LIBGC_DEBUG (g_message ("%s: %"G_GSIZE_FORMAT" - %p", __func__, self, threads));
-
-       mono_threads_lock ();
-
-       if (threads != NULL)
-               mono_g_hash_table_foreach (threads, gc_stop_world, (gpointer)self);
-       
-       mono_threads_unlock ();
-}
-
-static void gc_start_world (gpointer key, gpointer value, gpointer user)
-{
-       MonoThread *thread=(MonoThread *)value;
-       
-       LIBGC_DEBUG (g_message ("%s: %"G_GSIZE_FORMAT" - %"G_GSIZE_FORMAT, __func__, (gsize)user, (gsize)thread->tid));
-
-       if(thread->tid == (gsize)user)
-               return;
-
-       ResumeThread (thread->handle);
-}
-
-void mono_gc_start_world (void)
-{
-       gsize self = GetCurrentThreadId ();
-
-       LIBGC_DEBUG (g_message ("%s: %"G_GSIZE_FORMAT" - %p", __func__, self, threads));
-
-       mono_threads_lock ();
-
-       if (threads != NULL)
-               mono_g_hash_table_foreach (threads, gc_start_world, (gpointer)self);
-       
-       mono_threads_unlock ();
-}
-
 #ifdef __MINGW32__
 static CALLBACK void dummy_apc (ULONG_PTR param)
 {
@@ -2725,7 +2675,7 @@ static MonoException* mono_thread_execute_interruption (MonoThread *thread)
 
        if ((thread->state & ThreadState_AbortRequested) != 0) {
                if (thread->abort_exc == NULL)
-                       thread->abort_exc = mono_get_exception_thread_abort ();
+                       MONO_OBJECT_SETREF (thread, abort_exc, mono_get_exception_thread_abort ());
                mono_monitor_exit (thread->synch_lock);
                return thread->abort_exc;
        }
@@ -2860,17 +2810,3 @@ gint32* mono_thread_interruption_request_flag ()
 {
        return &thread_interruption_requested;
 }
-
-static void debugger_create_all_threads (gpointer key, gpointer value, gpointer user)
-{
-       MonoThread *thread = (MonoThread *)value;
-       (* mono_thread_callbacks->thread_created) (thread->tid, thread->stack_ptr, NULL);
-}
-
-void
-mono_debugger_create_all_threads (void)
-{
-       mono_threads_lock ();
-       mono_g_hash_table_foreach (threads, debugger_create_all_threads, NULL);
-       mono_threads_unlock ();
-}