This commit was manufactured by cvs2svn to create branch 'mono-1-0'.
[mono.git] / mono / metadata / threads.c
index 9b9b4179b295fd178a3d9a21ca54d21c6814a29a..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>
@@ -24,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>
@@ -97,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.
  */
@@ -150,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);
@@ -229,12 +243,9 @@ static guint32 start_wrapper(void *data)
        mono_thread_push_appdomain_ref (mono_domain_get ());
 
        thread_adjust_static_data (thread);
-#ifndef PLATFORM_WIN32
 #ifdef DEBUG
        g_message (G_GNUC_PRETTY_FUNCTION "start_wrapper for %d\n", thread->tid);
 #endif
-       pthread_cleanup_push ((void (*) (void *)) mono_thread_detach, thread);
-#endif
 
        start_func (this);
 #ifdef PLATFORM_WIN32
@@ -259,8 +270,6 @@ static guint32 start_wrapper(void *data)
        TlsSetValue (current_object_key, NULL);
        
        thread_cleanup (thread);
-#else
-       pthread_cleanup_pop (1);
 #endif
 
        return(0);
@@ -301,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
         */
@@ -316,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);
@@ -401,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
@@ -500,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;
        }
@@ -514,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
@@ -578,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;
        }
@@ -586,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");
@@ -659,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 ());
@@ -710,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);
@@ -749,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 ());
@@ -767,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 ) { 
@@ -928,47 +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_error ("Thread.Abort is not yet implemented under Windows");  
-       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
@@ -1037,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);
@@ -1094,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
@@ -1106,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
@@ -1133,6 +1307,7 @@ 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;
 
                /* Ignore background threads, we abort them later */
@@ -1145,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 {
@@ -1158,15 +1337,34 @@ static void build_wait_tids (gpointer key, gpointer value, gpointer user)
 static gboolean
 remove_and_abort_threads (gpointer key, gpointer value, gpointer user)
 {
-       guint32 self = GPOINTER_TO_UINT (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_print ("Aborting id: %d\n", thread->tid);
+                       g_message (G_GNUC_PRETTY_FUNCTION ": Thread id %d already aborting", thread->tid);
 #endif
-               ves_icall_System_Threading_Thread_Abort (thread, (MonoDomain *) thread->obj.vtable->domain);
+                       return(TRUE);
+               }
+               
+#ifdef THREAD_DEBUG
+               g_print (G_GNUC_PRETTY_FUNCTION ": Aborting id: %d\n", thread->tid);
+#endif
+               mono_thread_stop (thread);
                return TRUE;
        }
 
@@ -1210,7 +1408,7 @@ void mono_thread_manage (void)
                }
        } while(wait->num>0);
        
-       g_free (wait);
+       mono_thread_pool_cleanup ();
 
        EnterCriticalSection(&threads_mutex);
 
@@ -1218,10 +1416,17 @@ void mono_thread_manage (void)
         * Remove everything but the finalizer thread and self.
         * Also abort all the background threads
         * */
-       mono_g_hash_table_foreach_remove (threads, remove_and_abort_threads,
-                                         GUINT_TO_POINTER (GetCurrentThreadId ()));
+       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)
@@ -1264,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);
@@ -1277,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);
@@ -1310,10 +1515,14 @@ abort_appdomain_thread (gpointer key, gpointer value, gpointer user_data)
 
        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);
+               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 {
@@ -1522,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
@@ -1531,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;
 }
@@ -1539,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;
@@ -1554,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);
@@ -1628,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)