This commit was manufactured by cvs2svn to create branch 'mono-1-0'.
[mono.git] / mono / metadata / threads.c
index da46f665153b403cb165919c158dd8aff6cfb367..2159aad9ac4eadecc5bd4bc445bb85bdfdebf3ef 100644 (file)
  */
 
 #include <config.h>
+#ifdef PLATFORM_WIN32
+#define _WIN32_WINNT 0x0500
+#endif
+
 #include <glib.h>
 #include <signal.h>
+#include <string.h>
 
 #include <mono/metadata/object.h>
-#include <mono/metadata/appdomain.h>
+#include <mono/metadata/domain-internals.h>
 #include <mono/metadata/profiler-private.h>
 #include <mono/metadata/threads.h>
 #include <mono/metadata/threadpool.h>
@@ -23,6 +28,7 @@
 #include <mono/metadata/environment.h>
 #include <mono/metadata/monitor.h>
 #include <mono/metadata/gc-internal.h>
+#include <mono/metadata/marshal.h>
 #include <mono/io-layer/io-layer.h>
 
 #include <mono/os/gc_wrapper.h>
@@ -96,6 +102,13 @@ static guint32 mono_alloc_static_data_slot (StaticDataInfo *static_data, guint32
 /* Spin lock for InterlockedXXX 64 bit functions */
 static CRITICAL_SECTION interlocked_mutex;
 
+/* Controls access to interruption flag */
+static CRITICAL_SECTION interruption_mutex;
+
+/* global count of thread interruptions requested */
+static gint32 thread_interruption_requested = 0;
+
+
 /* handle_store() and handle_remove() manage the array of threads that
  * still need to be waited for when the main thread exits.
  */
@@ -149,9 +162,11 @@ static void handle_remove(guint32 tid)
 
 static void thread_cleanup (MonoThread *thread)
 {
-       mono_monitor_try_enter ((MonoObject *)thread, INFINITE);
+       if (!mono_monitor_enter (thread->synch_lock))
+               return;
+
        thread->state |= ThreadState_Stopped;
-       mono_monitor_exit ((MonoObject *)thread);
+       mono_monitor_exit (thread->synch_lock);
 
        mono_profiler_thread_end (thread->tid);
        handle_remove (thread->tid);
@@ -228,9 +243,12 @@ static guint32 start_wrapper(void *data)
        mono_thread_push_appdomain_ref (mono_domain_get ());
 
        thread_adjust_static_data (thread);
+#ifdef DEBUG
+       g_message (G_GNUC_PRETTY_FUNCTION "start_wrapper for %d\n", thread->tid);
+#endif
 
        start_func (this);
-
+#ifdef PLATFORM_WIN32
        /* If the thread calls ExitThread at all, this remaining code
         * will not be executed, but the main thread will eventually
         * call thread_cleanup() on this thread's behalf.
@@ -252,7 +270,8 @@ static guint32 start_wrapper(void *data)
        TlsSetValue (current_object_key, NULL);
        
        thread_cleanup (thread);
-       
+#endif
+
        return(0);
 }
 
@@ -291,7 +310,7 @@ void mono_thread_create (MonoDomain *domain, gpointer func, gpointer arg)
        start_info->obj = thread;
        start_info->domain = domain;
        start_info->this = arg;
-               
+       
        /* Create suspended, so we can do some housekeeping before the thread
         * starts
         */
@@ -306,6 +325,8 @@ 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);
+                                                 
        handle_store(thread);
 
        ResumeThread (thread_handle);
@@ -360,25 +381,16 @@ mono_thread_attach (MonoDomain *domain)
 }
 
 void
-ves_icall_System_Threading_ThreadPool_GetAvailableThreads (int *workerThreads, int *completionPortThreads)
-{
-       int busy;
-
-       MONO_ARCH_SAVE_REGS;
-
-       busy = (int) InterlockedCompareExchange (&busy_worker_threads, 0, -1);
-       *workerThreads = mono_max_worker_threads - busy;
-       *completionPortThreads = 0;
-}
-
-void
-ves_icall_System_Threading_ThreadPool_GetMaxThreads (int *workerThreads, int *completionPortThreads)
+mono_thread_detach (MonoThread *thread)
 {
+       g_return_if_fail (thread != NULL);
 
-       MONO_ARCH_SAVE_REGS;
-
-       *workerThreads = mono_max_worker_threads;
-       *completionPortThreads = 0;
+#ifdef DEBUG
+       g_message (G_GNUC_PRETTY_FUNCTION "mono_thread_detach for %d\n", thread->tid);
+#endif
+       TlsSetValue (current_object_key, NULL);
+       
+       thread_cleanup (thread);
 }
 
 HANDLE ves_icall_System_Threading_Thread_Thread_internal(MonoThread *this,
@@ -400,6 +412,7 @@ HANDLE ves_icall_System_Threading_Thread_Thread_internal(MonoThread *this,
 #endif
        
        im = mono_get_delegate_invoke (start->vtable->klass);
+       im = mono_marshal_get_delegate_invoke (im);
        if (mono_thread_callbacks)
                start_func = (* mono_thread_callbacks->thread_start_compile_func) (im);
        else
@@ -499,7 +512,7 @@ void ves_icall_System_Threading_Thread_Start_internal(MonoThread *this,
                          GetCurrentThreadId (), this, this->tid);
 #endif
 
-               WaitForSingleObject (this->start_notify, INFINITE);
+               WaitForSingleObjectEx (this->start_notify, INFINITE, FALSE);
                CloseHandle (this->start_notify);
                this->start_notify=NULL;
        }
@@ -513,13 +526,23 @@ void ves_icall_System_Threading_Thread_Start_internal(MonoThread *this,
 
 void ves_icall_System_Threading_Thread_Sleep_internal(gint32 ms)
 {
+       MonoThread *thread = mono_thread_current ();
+       
        MONO_ARCH_SAVE_REGS;
 
 #ifdef THREAD_DEBUG
        g_message(G_GNUC_PRETTY_FUNCTION ": Sleeping for %d ms", ms);
 #endif
 
-       Sleep(ms);
+       mono_monitor_enter (thread->synch_lock);
+       thread->state |= ThreadState_WaitSleepJoin;
+       mono_monitor_exit (thread->synch_lock);
+       
+       SleepEx(ms,TRUE);
+       
+       mono_monitor_enter (thread->synch_lock);
+       thread->state &= ~ThreadState_WaitSleepJoin;
+       mono_monitor_exit (thread->synch_lock);
 }
 
 gint32
@@ -577,6 +600,10 @@ gboolean ves_icall_System_Threading_Thread_Join_internal(MonoThread *this,
        
        MONO_ARCH_SAVE_REGS;
 
+       mono_monitor_enter (this->synch_lock);
+       this->state |= ThreadState_WaitSleepJoin;
+       mono_monitor_exit (this->synch_lock);
+
        if(ms== -1) {
                ms=INFINITE;
        }
@@ -585,7 +612,12 @@ gboolean ves_icall_System_Threading_Thread_Join_internal(MonoThread *this,
                   thread, ms);
 #endif
        
-       ret=WaitForSingleObject(thread, ms);
+       ret=WaitForSingleObjectEx (thread, ms, TRUE);
+
+       mono_monitor_enter (this->synch_lock);
+       this->state &= ~ThreadState_WaitSleepJoin;
+       mono_monitor_exit (this->synch_lock);
+       
        if(ret==WAIT_OBJECT_0) {
 #ifdef THREAD_DEBUG
                g_message (G_GNUC_PRETTY_FUNCTION ": join successful");
@@ -658,17 +690,22 @@ gboolean ves_icall_System_Threading_WaitHandle_WaitAll_internal(MonoArray *mono_
                ms=INFINITE;
        }
        
-       ret=WaitForMultipleObjects(numhandles, handles, TRUE, ms);
+       ret=WaitForMultipleObjectsEx(numhandles, handles, TRUE, ms, TRUE);
 
        g_free(handles);
-       
+
        if(ret==WAIT_FAILED) {
 #ifdef THREAD_WAIT_DEBUG
                g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Wait failed",
                          GetCurrentThreadId ());
 #endif
                return(FALSE);
-       } else if(ret==WAIT_TIMEOUT) {
+       } else if(ret==WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION) {
+               /* Do we want to try again if we get
+                * WAIT_IO_COMPLETION? The documentation for
+                * WaitHandle doesn't give any clues.  (We'd have to
+                * fiddle with the timeout if we retry.)
+                */
 #ifdef THREAD_WAIT_DEBUG
                g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Wait timed out",
                          GetCurrentThreadId ());
@@ -709,10 +746,10 @@ gint32 ves_icall_System_Threading_WaitHandle_WaitAny_internal(MonoArray *mono_ha
                ms=INFINITE;
        }
 
-       ret=WaitForMultipleObjects(numhandles, handles, FALSE, ms);
+       ret=WaitForMultipleObjectsEx(numhandles, handles, FALSE, ms, TRUE);
 
        g_free(handles);
-       
+
 #ifdef THREAD_WAIT_DEBUG
        g_message(G_GNUC_PRETTY_FUNCTION ": (%d) returning %d",
                  GetCurrentThreadId (), ret);
@@ -748,14 +785,20 @@ gboolean ves_icall_System_Threading_WaitHandle_WaitOne_internal(MonoObject *this
                ms=INFINITE;
        }
        
-       ret=WaitForSingleObject(handle, ms);
+       ret=WaitForSingleObjectEx (handle, ms, TRUE);
+
        if(ret==WAIT_FAILED) {
 #ifdef THREAD_WAIT_DEBUG
                g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Wait failed",
                          GetCurrentThreadId ());
 #endif
                return(FALSE);
-       } else if(ret==WAIT_TIMEOUT) {
+       } else if(ret==WAIT_TIMEOUT || ret == WAIT_IO_COMPLETION) {
+               /* Do we want to try again if we get
+                * WAIT_IO_COMPLETION? The documentation for
+                * WaitHandle doesn't give any clues.  (We'd have to
+                * fiddle with the timeout if we retry.)
+                */
 #ifdef THREAD_WAIT_DEBUG
                g_message(G_GNUC_PRETTY_FUNCTION ": (%d) Wait timed out",
                          GetCurrentThreadId ());
@@ -766,12 +809,25 @@ gboolean ves_icall_System_Threading_WaitHandle_WaitOne_internal(MonoObject *this
        return(TRUE);
 }
 
-HANDLE ves_icall_System_Threading_Mutex_CreateMutex_internal (MonoBoolean owned, MonoString *name)
+HANDLE ves_icall_System_Threading_Mutex_CreateMutex_internal (MonoBoolean owned, MonoString *name, MonoBoolean *created)
 { 
+       HANDLE mutex;
+       
        MONO_ARCH_SAVE_REGS;
    
-       return(CreateMutex (NULL, owned,
-                           name==NULL?NULL:mono_string_chars (name)));
+       *created = TRUE;
+       
+       if (name == NULL) {
+               mutex = CreateMutex (NULL, owned, NULL);
+       } else {
+               mutex = CreateMutex (NULL, owned, mono_string_chars (name));
+               
+               if (GetLastError () == ERROR_ALREADY_EXISTS) {
+                       *created = FALSE;
+               }
+       }
+
+       return(mutex);
 }                                                                   
 
 void ves_icall_System_Threading_Mutex_ReleaseMutex_internal (HANDLE handle ) { 
@@ -927,46 +983,163 @@ mono_thread_get_abort_signal (void)
 #endif /* __MINGW32__ */
 }
 
+#ifdef __MINGW32__
+static guint32 interruption_request_apc (gpointer param)
+{
+       MonoException* exc = mono_thread_request_interruption (FALSE);
+       if (exc) mono_raise_exception (exc);
+       return 0;
+}
+#endif /* __MINGW32__ */
+
+/*
+ * signal_thread_state_change
+ *
+ * Tells the thread that his state has changed and it has to enter the new
+ * state as soon as possible.
+ */
+static void signal_thread_state_change (MonoThread *thread)
+{
+#ifdef __MINGW32__
+       QueueUserAPC (interruption_request_apc, thread->handle, NULL);
+#else
+       /* fixme: store the state somewhere */
+#ifdef PTHREAD_POINTER_ID
+       pthread_kill (GUINT_TO_POINTER(thread->tid), mono_thread_get_abort_signal ());
+#else
+       pthread_kill (thread->tid, mono_thread_get_abort_signal ());
+#endif
+#endif /* __MINGW32__ */
+}
+
 void
 ves_icall_System_Threading_Thread_Abort (MonoThread *thread, MonoObject *state)
 {
        MONO_ARCH_SAVE_REGS;
 
+       mono_monitor_enter (thread->synch_lock);
+
+       if ((thread->state & ThreadState_AbortRequested) != 0 || 
+               (thread->state & ThreadState_StopRequested) != 0) 
+       {
+               mono_monitor_exit (thread->synch_lock);
+               return;
+       }
+
+       thread->state |= ThreadState_AbortRequested;
        thread->abort_state = state;
        thread->abort_exc = NULL;
 
+       mono_monitor_exit (thread->synch_lock);
+
 #ifdef THREAD_DEBUG
        g_message (G_GNUC_PRETTY_FUNCTION
                   ": (%d) Abort requested for %p (%d)", GetCurrentThreadId (),
                   thread, thread->tid);
 #endif
        
-#ifdef __MINGW32__
-       g_assert_not_reached ();
-#else
-       /* fixme: store the state somewhere */
-#ifdef PTHREAD_POINTER_ID
-       pthread_kill (GUINT_TO_POINTER(thread->tid), mono_thread_get_abort_signal ());
-#else
-       pthread_kill (thread->tid, mono_thread_get_abort_signal ());
-#endif
-#endif /* __MINGW32__ */
+       /* Make sure the thread is awake */
+       ves_icall_System_Threading_Thread_Resume (thread);
+       
+       signal_thread_state_change (thread);
 }
 
 void
 ves_icall_System_Threading_Thread_ResetAbort (void)
 {
        MonoThread *thread = mono_thread_current ();
-       
-       MONO_ARCH_SAVE_REGS;
 
+       MONO_ARCH_SAVE_REGS;
+       
+       mono_monitor_enter (thread->synch_lock);
+       
+       thread->state &= ~ThreadState_AbortRequested;
+       
        if (!thread->abort_exc) {
                const char *msg = "Unable to reset abort because no abort was requested";
+               mono_monitor_exit (thread->synch_lock);
                mono_raise_exception (mono_get_exception_thread_state (msg));
        } else {
                thread->abort_exc = NULL;
                thread->abort_state = NULL;
        }
+       
+       mono_monitor_exit (thread->synch_lock);
+}
+
+void
+ves_icall_System_Threading_Thread_Suspend (MonoThread *thread)
+{
+       MONO_ARCH_SAVE_REGS;
+
+       mono_monitor_enter (thread->synch_lock);
+
+       if ((thread->state & ThreadState_Suspended) != 0 || 
+               (thread->state & ThreadState_SuspendRequested) != 0 ||
+               (thread->state & ThreadState_StopRequested) != 0) 
+       {
+               mono_monitor_exit (thread->synch_lock);
+               return;
+       }
+       
+       thread->state |= ThreadState_SuspendRequested;
+       mono_monitor_exit (thread->synch_lock);
+
+       signal_thread_state_change (thread);
+}
+
+void
+ves_icall_System_Threading_Thread_Resume (MonoThread *thread)
+{
+       MONO_ARCH_SAVE_REGS;
+
+       mono_monitor_enter (thread->synch_lock);
+
+       if ((thread->state & ThreadState_SuspendRequested) != 0) {
+               thread->state &= ~ThreadState_SuspendRequested;
+               mono_monitor_exit (thread->synch_lock);
+               return;
+       }
+               
+       if ((thread->state & ThreadState_Suspended) == 0) 
+       {
+               mono_monitor_exit (thread->synch_lock);
+               return;
+       }
+       
+       thread->resume_event = CreateEvent (NULL, TRUE, FALSE, NULL);
+       
+       /* Awake the thread */
+       SetEvent (thread->suspend_event);
+
+       mono_monitor_exit (thread->synch_lock);
+
+       /* Wait for the thread to awake */
+       WaitForSingleObject (thread->resume_event, INFINITE);
+       CloseHandle (thread->resume_event);
+       thread->resume_event = NULL;
+}
+
+void mono_thread_stop (MonoThread *thread)
+{
+       mono_monitor_enter (thread->synch_lock);
+
+       if ((thread->state & ThreadState_StopRequested) != 0 ||
+               (thread->state & ThreadState_Stopped) != 0)
+       {
+               mono_monitor_exit (thread->synch_lock);
+               return;
+       }
+       
+       /* Make sure the thread is awake */
+       ves_icall_System_Threading_Thread_Resume (thread);
+       
+       thread->state |= ThreadState_StopRequested;
+       thread->state &= ~ThreadState_AbortRequested;
+       
+       mono_monitor_exit (thread->synch_lock);
+       
+       signal_thread_state_change (thread);
 }
 
 gint8
@@ -1035,6 +1208,7 @@ void mono_thread_init (MonoThreadStartCB start_cb,
        InitializeCriticalSection(&threads_mutex);
        InitializeCriticalSection(&interlocked_mutex);
        InitializeCriticalSection(&contexts_mutex);
+       InitializeCriticalSection(&interruption_mutex);
        
        mono_init_static_data_info (&thread_static_info);
        mono_init_static_data_info (&context_static_info);
@@ -1092,7 +1266,8 @@ static void wait_for_tids (struct wait_data *wait, guint32 timeout)
                  ": %d threads to wait for in this batch", wait->num);
 #endif
 
-       ret=WaitForMultipleObjects(wait->num, wait->handles, TRUE, timeout);
+       ret=WaitForMultipleObjectsEx(wait->num, wait->handles, TRUE, timeout, FALSE);
+
        if(ret==WAIT_FAILED) {
                /* See the comment in build_wait_tids() */
 #ifdef THREAD_DEBUG
@@ -1104,6 +1279,7 @@ static void wait_for_tids (struct wait_data *wait, guint32 timeout)
 
        for(i=0; i<wait->num; i++) {
                guint32 tid=wait->threads[i]->tid;
+               CloseHandle (wait->handles[i]);
                
                if(mono_g_hash_table_lookup (threads, GUINT_TO_POINTER(tid))!=NULL) {
                        /* This thread must have been killed, because
@@ -1131,10 +1307,10 @@ static void build_wait_tids (gpointer key, gpointer value, gpointer user)
        struct wait_data *wait=(struct wait_data *)user;
 
        if(wait->num<MAXIMUM_WAIT_OBJECTS) {
+               HANDLE handle;
                MonoThread *thread=(MonoThread *)value;
 
-               /* BUG: For now we just ignore background threads, we should abort them
-               */
+               /* Ignore background threads, we abort them later */
                if (thread->state & ThreadState_Background)
                        return; /* just leave, ignore */
                
@@ -1144,7 +1320,11 @@ static void build_wait_tids (gpointer key, gpointer value, gpointer user)
                if (thread == mono_thread_current ())
                        return;
 
-               wait->handles[wait->num]=thread->handle;
+               handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
+               if (handle == NULL)
+                       return;
+               
+               wait->handles[wait->num]=handle;
                wait->threads[wait->num]=thread;
                wait->num++;
        } else {
@@ -1154,6 +1334,43 @@ static void build_wait_tids (gpointer key, gpointer value, gpointer user)
        }
 }
 
+static gboolean
+remove_and_abort_threads (gpointer key, gpointer value, gpointer user)
+{
+       struct wait_data *wait=(struct wait_data *)user;
+       guint32 self = GetCurrentThreadId ();
+       MonoThread *thread = (MonoThread *) value;
+       HANDLE handle;
+
+       /* The finalizer thread is not a background thread */
+       if (thread->tid != self && thread->state & ThreadState_Background) {
+       
+               handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
+               if (handle == NULL)
+                       return FALSE;
+               
+               wait->handles[wait->num]=thread->handle;
+               wait->threads[wait->num]=thread;
+               wait->num++;
+       
+               if(thread->state & ThreadState_AbortRequested ||
+                  thread->state & ThreadState_Aborted) {
+#ifdef THREAD_DEBUG
+                       g_message (G_GNUC_PRETTY_FUNCTION ": Thread id %d already aborting", thread->tid);
+#endif
+                       return(TRUE);
+               }
+               
+#ifdef THREAD_DEBUG
+               g_print (G_GNUC_PRETTY_FUNCTION ": Aborting id: %d\n", thread->tid);
+#endif
+               mono_thread_stop (thread);
+               return TRUE;
+       }
+
+       return (thread->tid != self && !mono_gc_is_finalizer_thread (thread)); 
+}
+
 void mono_thread_manage (void)
 {
        struct wait_data *wait=g_new0 (struct wait_data, 1);
@@ -1163,12 +1380,15 @@ void mono_thread_manage (void)
        g_message(G_GNUC_PRETTY_FUNCTION ": Joining each running thread...");
 #endif
        
+       EnterCriticalSection (&threads_mutex);
        if(threads==NULL) {
 #ifdef THREAD_DEBUG
                g_message(G_GNUC_PRETTY_FUNCTION ": No threads");
 #endif
+               LeaveCriticalSection (&threads_mutex);
                return;
        }
+       LeaveCriticalSection (&threads_mutex);
        
        do {
                EnterCriticalSection (&threads_mutex);
@@ -1178,10 +1398,9 @@ void mono_thread_manage (void)
                          mono_g_hash_table_size (threads));
                mono_g_hash_table_foreach (threads, print_tids, NULL);
 #endif
-
+       
                wait->num=0;
                mono_g_hash_table_foreach (threads, build_wait_tids, wait);
-       
                LeaveCriticalSection (&threads_mutex);
                if(wait->num>0) {
                        /* Something to wait for */
@@ -1189,14 +1408,25 @@ void mono_thread_manage (void)
                }
        } while(wait->num>0);
        
-       g_free (wait);
+       mono_thread_pool_cleanup ();
 
        EnterCriticalSection(&threads_mutex);
 
-       mono_g_hash_table_destroy(threads);
-       threads=NULL;
+       /* 
+        * Remove everything but the finalizer thread and self.
+        * Also abort all the background threads
+        * */
+       wait->num = 0;
+       mono_g_hash_table_foreach_remove (threads, remove_and_abort_threads, wait);
 
        LeaveCriticalSection(&threads_mutex);
+
+       if(wait->num>0) {
+               /* Something to wait for */
+               wait_for_tids (wait, INFINITE);
+       }
+
+       g_free (wait);
 }
 
 static void terminate_thread (gpointer key, gpointer value, gpointer user)
@@ -1239,7 +1469,7 @@ mono_thread_push_appdomain_ref (MonoDomain *domain)
        MonoThread *thread = mono_thread_current ();
 
        if (thread) {
-               //printf ("PUSH REF: %p -> %s.\n", thread, domain->friendly_name);
+               /* printf ("PUSH REF: %p -> %s.\n", thread, domain->friendly_name); */
                EnterCriticalSection (&threads_mutex);
                thread->appdomain_refs = g_slist_prepend (thread->appdomain_refs, domain);
                LeaveCriticalSection (&threads_mutex);
@@ -1252,9 +1482,9 @@ mono_thread_pop_appdomain_ref (void)
        MonoThread *thread = mono_thread_current ();
 
        if (thread) {
-               //printf ("POP REF: %p -> %s.\n", thread, ((MonoDomain*)(thread->appdomain_refs->data))->friendly_name);
+               /* printf ("POP REF: %p -> %s.\n", thread, ((MonoDomain*)(thread->appdomain_refs->data))->friendly_name); */
                EnterCriticalSection (&threads_mutex);
-               // FIXME: How can the list be empty ?
+               /* FIXME: How can the list be empty ? */
                if (thread->appdomain_refs)
                        thread->appdomain_refs = g_slist_remove (thread->appdomain_refs, thread->appdomain_refs->data);
                LeaveCriticalSection (&threads_mutex);
@@ -1284,11 +1514,15 @@ abort_appdomain_thread (gpointer key, gpointer value, gpointer user_data)
        MonoDomain *domain = data->domain;
 
        if (mono_thread_has_appdomain_ref (thread, domain)) {
-               //printf ("ABORTING THREAD %p BECAUSE IT REFERENCES DOMAIN %s.\n", thread, domain->friendly_name);
-               ves_icall_System_Threading_Thread_Abort (thread, (MonoObject*)domain->domain);
+               /* printf ("ABORTING THREAD %p BECAUSE IT REFERENCES DOMAIN %s.\n", thread, domain->friendly_name); */
+               HANDLE handle = OpenThread (THREAD_ALL_ACCESS, TRUE, thread->tid);
+               if (handle == NULL)
+                       return;
+
+               ves_icall_System_Threading_Thread_Abort (thread, NULL);
 
                if(data->wait.num<MAXIMUM_WAIT_OBJECTS) {
-                       data->wait.handles [data->wait.num] = thread->handle;
+                       data->wait.handles [data->wait.num] = handle;
                        data->wait.threads [data->wait.num] = thread;
                        data->wait.num++;
                } else {
@@ -1310,7 +1544,7 @@ mono_threads_abort_appdomain_threads (MonoDomain *domain, int timeout)
        abort_appdomain_data user_data;
        guint32 start_time;
 
-       //printf ("ABORT BEGIN.\n");
+       /* printf ("ABORT BEGIN.\n"); */
 
        start_time = GetTickCount ();
        do {
@@ -1333,7 +1567,7 @@ mono_threads_abort_appdomain_threads (MonoDomain *domain, int timeout)
        }
        while (user_data.wait.num > 0);
 
-       //printf ("ABORT DONE.\n");
+       /* printf ("ABORT DONE.\n"); */
 
        return TRUE;
 }
@@ -1497,7 +1731,9 @@ mono_alloc_special_static_data (guint32 static_type, guint32 size, guint32 align
        {
                EnterCriticalSection (&threads_mutex);
                offset = mono_alloc_static_data_slot (&thread_static_info, size, align);
-               mono_g_hash_table_foreach (threads, alloc_thread_static_data_helper, GUINT_TO_POINTER (offset));
+               /* This can be called during startup */
+               if (threads != NULL)
+                       mono_g_hash_table_foreach (threads, alloc_thread_static_data_helper, GUINT_TO_POINTER (offset));
                LeaveCriticalSection (&threads_mutex);
        }
        else
@@ -1506,7 +1742,7 @@ mono_alloc_special_static_data (guint32 static_type, guint32 size, guint32 align
                EnterCriticalSection (&contexts_mutex);
                offset = mono_alloc_static_data_slot (&context_static_info, size, align);
                LeaveCriticalSection (&contexts_mutex);
-               offset |= 0x80000000;   // Set the high bit to indicate context static data
+               offset |= 0x80000000;   /* Set the high bit to indicate context static data */
        }
        return offset;
 }
@@ -1514,7 +1750,7 @@ mono_alloc_special_static_data (guint32 static_type, guint32 size, guint32 align
 gpointer
 mono_get_special_static_data (guint32 offset)
 {
-       // The high bit means either thread (0) or static (1) data.
+       /* The high bit means either thread (0) or static (1) data. */
 
        guint32 static_type = (offset & 0x80000000);
        int idx;
@@ -1529,8 +1765,9 @@ mono_get_special_static_data (guint32 offset)
        }
        else
        {
-               // Allocate static data block under demand, since we don't have a list
+               /* Allocate static data block under demand, since we don't have a list
                // of contexts
+               */
                MonoAppContext *context = mono_context_get ();
                if (!context->static_data || !context->static_data [idx]) {
                        EnterCriticalSection (&contexts_mutex);
@@ -1603,6 +1840,154 @@ void mono_gc_start_world (void)
        LeaveCriticalSection (&threads_mutex);
 }
 
+
+static guint32 dummy_apc (gpointer param)
+{
+       return 0;
+}
+
+/*
+ * mono_thread_execute_interruption
+ * 
+ * Performs the operation that the requested thread state requires (abort,
+ * suspend or stop)
+ */
+static MonoException* mono_thread_execute_interruption (MonoThread *thread)
+{
+       mono_monitor_enter (thread->synch_lock);
+       
+       if (thread->interruption_requested) {
+               /* this will consume pending APC calls */
+               WaitForSingleObjectEx (GetCurrentThread(), 0, TRUE);
+               EnterCriticalSection (&interruption_mutex);
+               thread_interruption_requested--;
+               LeaveCriticalSection (&interruption_mutex);
+               thread->interruption_requested = FALSE;
+       }
+
+       if ((thread->state & ThreadState_AbortRequested) != 0) {
+               thread->abort_exc = mono_get_exception_thread_abort ();
+               mono_monitor_exit (thread->synch_lock);
+               return thread->abort_exc;
+       }
+       else if ((thread->state & ThreadState_SuspendRequested) != 0) {
+               thread->state &= ~ThreadState_SuspendRequested;
+               thread->state |= ThreadState_Suspended;
+               thread->suspend_event = CreateEvent (NULL, TRUE, FALSE, NULL);
+               mono_monitor_exit (thread->synch_lock);
+               
+               WaitForSingleObject (thread->suspend_event, INFINITE);
+               
+               mono_monitor_enter (thread->synch_lock);
+               CloseHandle (thread->suspend_event);
+               thread->suspend_event = NULL;
+               thread->state &= ~ThreadState_Suspended;
+       
+               /* The thread that requested the resume will have replaced this event
+            * and will be waiting for it
+                */
+               SetEvent (thread->resume_event);
+               mono_monitor_exit (thread->synch_lock);
+               return NULL;
+       }
+       else if ((thread->state & ThreadState_StopRequested) != 0) {
+               /* FIXME: do this through the JIT? */
+               mono_monitor_exit (thread->synch_lock);
+               ExitThread (-1);
+               return NULL;
+       }
+       
+       mono_monitor_exit (thread->synch_lock);
+       return NULL;
+}
+
+/*
+ * mono_thread_request_interruption
+ *
+ * A signal handler can call this method to request the interruption of a
+ * thread. The result of the interruption will depend on the current state of
+ * the thread. If the result is an exception that needs to be throw, it is 
+ * provided as return value.
+ */
+MonoException* mono_thread_request_interruption (gboolean running_managed)
+{
+       MonoThread *thread = mono_thread_current ();
+
+       /* The thread may already be stopping */
+       if (thread == NULL) 
+               return NULL;
+       
+       mono_monitor_enter (thread->synch_lock);
+       
+       if (thread->interruption_requested) {
+               mono_monitor_exit (thread->synch_lock);
+               return NULL;
+       }
+
+       if (!running_managed) {
+               /* Can't stop while in unmanaged code. Increase the global interruption
+                  request count. When exiting the unmanaged method the count will be
+                  checked and the thread will be interrupted. */
+               
+               EnterCriticalSection (&interruption_mutex);
+               thread_interruption_requested++;
+               LeaveCriticalSection (&interruption_mutex);
+               
+               thread->interruption_requested = TRUE;
+               mono_monitor_exit (thread->synch_lock);
+               
+               /* this will awake the thread if it is in WaitForSingleObject 
+              or similar */
+               QueueUserAPC (dummy_apc, thread->handle, NULL);
+               
+               return NULL;
+       }
+       else {
+               mono_monitor_exit (thread->synch_lock);
+               return mono_thread_execute_interruption (thread);
+       }
+}
+
+gboolean mono_thread_interruption_requested ()
+{
+       if (thread_interruption_requested) {
+               MonoThread *thread = mono_thread_current ();
+               /* The thread may already be stopping */
+               if (thread != NULL) 
+                       return (thread->interruption_requested);
+       }
+       return FALSE;
+}
+
+/*
+ * Performs the interruption of the current thread, if one has been requested.
+ */
+void mono_thread_interruption_checkpoint ()
+{
+       MonoThread *thread = mono_thread_current ();
+       
+       /* The thread may already be stopping */
+       if (thread == NULL) 
+               return;
+       
+       if (thread->interruption_requested) {
+               MonoException* exc = mono_thread_execute_interruption (thread);
+               if (exc) mono_raise_exception (exc);
+       }
+}
+
+/*
+ * Returns the address of a flag that will be non-zero if an interruption has
+ * been requested for a thread. The thread to interrupt may not be the current
+ * thread, so an additional call to mono_thread_interruption_requested() or
+ * mono_thread_interruption_checkpoint() is allways needed if the flag is not
+ * zero.
+ */
+gint32* mono_thread_interruption_request_flag ()
+{
+       return &thread_interruption_requested;
+}
+
 #ifdef WITH_INCLUDED_LIBGC
 
 static void gc_push_all_stacks (gpointer key, gpointer value, gpointer user)