almost all required function implemented - first integration with jdwp - nothing...
[cacao.git] / src / threads / native / threads.c
index 5c130cc701e6b8934967019ac38ed0f6fbeb3fe3..08a0c420fc4626dacf53f4a3803a93ceb6ea783f 100644 (file)
@@ -1,6 +1,37 @@
-#include "global.h"
+/* src/threads/native/threads.c - native threads support
+
+   Copyright (C) 1996-2005 R. Grafl, A. Krall, C. Kruegel, C. Oates,
+   R. Obermaisser, M. Platter, M. Probst, S. Ring, E. Steiner,
+   C. Thalinger, D. Thuernbeck, P. Tomsich, C. Ullrich, J. Wenninger,
+   Institut f. Computersprachen - TU Wien
+
+   This file is part of CACAO.
+
+   This program is free software; you can redistribute it and/or
+   modify it under the terms of the GNU General Public License as
+   published by the Free Software Foundation; either version 2, or (at
+   your option) any later version.
+
+   This program is distributed in the hope that it will be useful, but
+   WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+   General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program; if not, write to the Free Software
+   Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
+   02111-1307, USA.
+
+   Contact: cacao@complang.tuwien.ac.at
+
+   Authors: Stefan Ring
+
+   Changes: Christian Thalinger
+
+   $Id: threads.c 3570 2005-11-04 16:58:36Z motse $
+
+*/
 
-#if defined(NATIVE_THREADS)
 
 #include <stdlib.h>
 #include <string.h>
 #include <time.h>
 #include <errno.h>
 
+#include <pthread.h>
+#include <semaphore.h>
+
 #include "config.h"
-#include "thread.h"
-#include "codegen.h"
-#include "locks.h"
-#include "tables.h"
-#include "native.h"
-#include "loader.h"
-#include "builtin.h"
-#include "asmpart.h"
-#include "exceptions.h"
-#include "toolbox/logging.h"
-#include "toolbox/memory.h"
-#include "toolbox/avl.h"
-#include "mm/boehm.h"
+#include "vm/types.h"
 
-#include "nat/java_lang_Object.h"
-#include "nat/java_lang_Throwable.h"
-#include "nat/java_lang_Thread.h"
-#include "nat/java_lang_ThreadGroup.h"
-#include "nat/java_lang_VMThread.h"
+#ifndef USE_MD_THREAD_STUFF
+#include "machine-instr.h"
+#else
+#include "threads/native/generic-primitives.h"
+#endif
 
-#include <pthread.h>
-#include <semaphore.h>
+#include "cacao/cacao.h"
+#include "mm/boehm.h"
+#include "mm/memory.h"
+#include "native/native.h"
+#include "native/include/java_lang_Object.h"
+#include "native/include/java_lang_Throwable.h"
+#include "native/include/java_lang_Thread.h"
+#include "native/include/java_lang_ThreadGroup.h"
+#include "native/include/java_lang_VMThread.h"
+#include "threads/native/threads.h"
+#include "toolbox/avl.h"
+#include "toolbox/logging.h"
+#include "vm/builtin.h"
+#include "vm/exceptions.h"
+#include "vm/global.h"
+#include "vm/loader.h"
+#include "vm/options.h"
+#include "vm/stringlocal.h"
+#include "vm/tables.h"
+#include "vm/jit/asmpart.h"
 
 #if !defined(__DARWIN__)
 #if defined(__LINUX__)
 #elif defined(__MIPS__)
 #define GC_IRIX_THREADS
 #endif
-#include "../mm/boehm-gc/include/gc.h"
+#include "boehm-gc/include/gc.h"
+#endif
+
+#ifdef USE_MD_THREAD_STUFF
+pthread_mutex_t _atomic_add_lock = PTHREAD_MUTEX_INITIALIZER;
+pthread_mutex_t _cas_lock = PTHREAD_MUTEX_INITIALIZER;
+pthread_mutex_t _mb_lock = PTHREAD_MUTEX_INITIALIZER;
 #endif
 
 #ifdef MUTEXSIM
@@ -110,10 +156,9 @@ static void setPriority(pthread_t tid, int priority)
        pthread_setschedparam(tid, policy, &schedp);
 }
 
-#include "machine-instr.h"
 
 static struct avl_table *criticaltree;
-static threadobject *mainthreadobj;
+threadobject *mainthreadobj;
 
 #ifndef HAVE___THREAD
 pthread_key_t tkey_threadinfo;
@@ -270,20 +315,26 @@ static void cast_darwinstop()
                        kern_return_t r;
 
                        r = thread_suspend(thread);
-                       if (r != KERN_SUCCESS)
-                               panic("thread_suspend failed");
+                       if (r != KERN_SUCCESS) {
+                               log_text("thread_suspend failed");
+                               assert(0);
+                       }
 
                        r = thread_get_state(thread, flavor,
                                (natural_t*)&thread_state, &thread_state_count);
-                       if (r != KERN_SUCCESS)
-                               panic("thread_get_state failed");
+                       if (r != KERN_SUCCESS) {
+                               log_text("thread_get_state failed");
+                               assert(0);
+                       }
 
                        thread_restartcriticalsection(&thread_state);
 
                        r = thread_set_state(thread, flavor,
                                (natural_t*)&thread_state, thread_state_count);
-                       if (r != KERN_SUCCESS)
-                               panic("thread_set_state failed");
+                       if (r != KERN_SUCCESS) {
+                               log_text("thread_set_state failed");
+                               assert(0);
+                       }
                }
                tobj = tobj->info.next;
        } while (tobj != mainthreadobj);
@@ -298,9 +349,14 @@ static void cast_darwinresume()
                nativethread *info = &tobj->info;
                if (info != infoself)
                {
+                       mach_port_t thread = info->mach_thread;
+                       kern_return_t r;
+
                        r = thread_resume(thread);
-                       if (r != KERN_SUCCESS)
-                               panic("thread_resume failed");
+                       if (r != KERN_SUCCESS) {
+                               log_text("thread_resume failed");
+                               assert(0);
+                       }
                }
                tobj = tobj->info.next;
        } while (tobj != mainthreadobj);
@@ -356,7 +412,7 @@ static void sigsuspend_handler(ucontext_t *ctx)
 
        /* Do as Boehm does. On IRIX a condition variable is used for wake-up
           (not POSIX async-safe). */
-#if defined(__MIPS__)
+#if defined(__IRIX__)
        pthread_mutex_lock(&suspend_ack_lock);
        sem_post(&suspend_ack);
        pthread_cond_wait(&suspend_cond, &suspend_ack_lock);
@@ -390,15 +446,31 @@ static void setthreadobject(threadobject *thread)
 #endif
 }
 
+
+/* thread_setself **************************************************************
+
+   XXX
+
+*******************************************************************************/
+
+void *thread_getself(void)
+{
+       return pthread_getspecific(tkey_threadinfo);
+}
+
+
 static monitorLockRecord *dummyLR;
 
 static void initPools();
 
-/*
- * Initialize threads.
- */
-void
-initThreadsEarly()
+
+/* thread_preinit **************************************************************
+
+   Do some early initialization of stuff required.
+
+*******************************************************************************/
+
+void threads_preinit(void)
 {
 #ifndef MUTEXSIM
        pthread_mutexattr_t mutexattr;
@@ -415,12 +487,11 @@ initThreadsEarly()
        pthread_mutex_init(&threadlistlock, NULL);
        pthread_mutex_init(&stopworldlock, NULL);
 
-       /* Allocate something so the garbage collector's signal handlers are  */
-       /* installed. */
+       /* Allocate something so the garbage collector's signal handlers
+          are installed. */
        heap_allocate(1, false, NULL);
 
        mainthreadobj = NEW(threadobject);
-       memset(mainthreadobj, 0, sizeof(threadobject));
        mainthreadobj->info.tid = pthread_self();
 #if !defined(HAVE___THREAD)
        pthread_key_create(&tkey_threadinfo, NULL);
@@ -432,9 +503,9 @@ initThreadsEarly()
        thread_addstaticcritical();
        sem_init(&suspend_ack, 0, 0);
 
-       /* Every newly created object's monitorPtr points here so we save a check
-        * against NULL */
-       dummyLR = mem_alloc(sizeof(monitorLockRecord));
+       /* Every newly created object's monitorPtr points here so we save
+          a check against NULL */
+       dummyLR = NEW(monitorLockRecord);
        dummyLR->o = NULL;
        dummyLR->ownerThread = NULL;
        dummyLR->waiting = false;
@@ -444,130 +515,191 @@ static pthread_attr_t threadattr;
 
 static void freeLockRecordPools(lockRecordPool *);
 
-void
-initThreads(u1 *stackbottom)
+
+/* threads_init ****************************************************************
+
+   Initializes the threads required by the JVM: main, finalizer.
+
+*******************************************************************************/
+
+bool threads_init(u1 *stackbottom)
 {
-       classinfo *threadclass;
-       classinfo *threadgroupclass;
-       java_lang_String *threadname;
-       java_lang_Thread *mainthread;
+       java_lang_String      *threadname;
+       java_lang_Thread      *mainthread;
        java_lang_ThreadGroup *threadgroup;
-       threadobject *tempthread = mainthreadobj;
-       methodinfo *method;
-
-       threadclass = class_new(utf_new_char("java/lang/VMThread"));
-       class_load(threadclass);
-       class_link(threadclass);
+       threadobject          *tempthread;
+       methodinfo            *method;
 
-       if (!threadclass)
-               throw_exception_exit();
+       tempthread = mainthreadobj;
 
        freeLockRecordPools(mainthreadobj->ee.lrpool);
-       /* This is kinda tricky, we grow the java.lang.Thread object so we can keep
-        * the execution environment there. No Thread object must have been created
-        * at an earlier time */
-       threadclass->instancesize = sizeof(threadobject);
 
-       /* Create a VMThread */
-       mainthreadobj = (threadobject *) builtin_new(threadclass);
+       /* This is kinda tricky, we grow the java.lang.Thread object so we
+          can keep the execution environment there. No Thread object must
+          have been created at an earlier time. */
+
+       class_java_lang_VMThread->instancesize = sizeof(threadobject);
+
+       /* create a VMThread */
+
+       mainthreadobj = (threadobject *) builtin_new(class_java_lang_VMThread);
 
        if (!mainthreadobj)
-               throw_exception_exit();
+               return false;
 
        FREE(tempthread, threadobject);
+
        initThread(&mainthreadobj->o);
 
        setthreadobject(mainthreadobj);
 
        initLocks();
+
        mainthreadobj->info.next = mainthreadobj;
        mainthreadobj->info.prev = mainthreadobj;
 
+#if defined(ENABLE_INTRP)
+       /* create interpreter stack */
+
+       if (opt_intrp) {
+               MSET(intrp_main_stack, 0, u1, opt_stacksize);
+               mainthreadobj->info._global_sp = intrp_main_stack + opt_stacksize;
+       }
+#endif
+
        threadname = javastring_new(utf_new_char("main"));
 
-       /* Allocate and init ThreadGroup */
-       threadgroupclass = class_new(utf_new_char("java/lang/ThreadGroup"));
-       threadgroup =
-               (java_lang_ThreadGroup *) native_new_and_init(threadgroupclass);
+       /* allocate and init ThreadGroup */
+
+       threadgroup = (java_lang_ThreadGroup *)
+               native_new_and_init(class_java_lang_ThreadGroup);
 
        if (!threadgroup)
                throw_exception_exit();
 
-       /* Create a Thread */
-       threadclass = class_new(utf_new_char("java/lang/Thread"));
-       mainthread = (java_lang_Thread*) builtin_new(threadclass);
-       mainthreadobj->o.thread = mainthread;
+       /* create a Thread */
+
+       mainthread = (java_lang_Thread *) builtin_new(class_java_lang_Thread);
 
        if (!mainthread)
                throw_exception_exit();
 
-       /* Call Thread constructor */
-       method = class_resolveclassmethod(threadclass,
-                                                                         utf_new_char("<init>"),
+       mainthreadobj->o.thread = mainthread;
+
+       /* call Thread.<init>(Ljava/lang/VMThread;Ljava/lang/String;IZ)V */
+
+       method = class_resolveclassmethod(class_java_lang_Thread,
+                                                                         utf_init,
                                                                          utf_new_char("(Ljava/lang/VMThread;Ljava/lang/String;IZ)V"),
-                                                                         threadclass,
+                                                                         class_java_lang_Thread,
                                                                          true);
 
        if (!method)
-               throw_exception_exit();
+               return false;
 
        asm_calljavafunction(method, mainthread, mainthreadobj, threadname, (void*) 5);
        if (*exceptionptr)
-               throw_exception_exit();
+               return false;
 
        mainthread->group = threadgroup;
        /* XXX This is a hack because the fourth argument was omitted */
        mainthread->daemon = false;
 
-       /* Add mainthread to ThreadGroup */
-       method = class_resolveclassmethod(threadgroupclass,
+       /* add mainthread to ThreadGroup */
+
+       method = class_resolveclassmethod(class_java_lang_ThreadGroup,
                                                                          utf_new_char("addThread"),
                                                                          utf_new_char("(Ljava/lang/Thread;)V"),
-                                                                         threadgroupclass,
+                                                                         class_java_lang_ThreadGroup,
                                                                          true);
 
        if (!method)
-               throw_exception_exit();
+               return false;
 
        asm_calljavafunction(method, threadgroup, mainthread, NULL, NULL);
-       if (*exceptionptr)
-               throw_exception_exit();
 
-       /* TODO InheritableThreadLocal */
+       if (*exceptionptr)
+               return false;
 
        setPriority(pthread_self(), 5);
 
        pthread_attr_init(&threadattr);
        pthread_attr_setdetachstate(&threadattr, PTHREAD_CREATE_DETACHED);
+
+       /* everything's ok */
+
+       return true;
 }
 
+
 void initThread(java_lang_VMThread *t)
 {
        threadobject *thread = (threadobject*) t;
        nativethread *info = &thread->info;
        info->tid = pthread_self();
+       /* TODO destroy all those things */
        pthread_mutex_init(&info->joinMutex, NULL);
        pthread_cond_init(&info->joinCond, NULL);
 
-       thread->interrupted = 0;
-       thread->waiting = NULL;
+       pthread_mutex_init(&thread->waitLock, NULL);
+       pthread_cond_init(&thread->waitCond, NULL);
+       thread->interrupted = false;
+       thread->signaled = false;
+       thread->isSleeping = false;
 }
 
 static void initThreadLocks(threadobject *);
 
+
 typedef struct {
        threadobject *thread;
-       sem_t *psem;
+       functionptr   function;
+       sem_t        *psem;
+       sem_t        *psem_first;
 } startupinfo;
 
-static void *threadstartup(void *t)
+
+/* threads_startup *************************************************************
+
+   Thread startup function called by pthread_create.
+
+******************************************************************************/
+
+static void *threads_startup_thread(void *t)
 {
-       startupinfo *startup = t;
-       threadobject *thread = startup->thread;
-       sem_t *psem = startup->psem;
-       nativethread *info = &thread->info;
+       startupinfo  *startup;
+       threadobject *thread;
+       sem_t        *psem;
+       nativethread *info;
        threadobject *tnext;
-       methodinfo *method;
+       methodinfo   *method;
+       functionptr   function;
+
+#if defined(ENABLE_INTRP)
+       u1 *intrp_thread_stack;
+
+       /* create interpreter stack */
+
+       if (opt_intrp) {
+               intrp_thread_stack = (u1 *) alloca(opt_stacksize);
+               MSET(intrp_thread_stack, 0, u1, opt_stacksize);
+       }
+#endif
+
+       /* get passed startupinfo structure and the values in there */
+
+       startup = t;
+
+       thread   = startup->thread;
+       function = startup->function;
+       psem     = startup->psem;
+
+       info = &thread->info;
+
+       /* Seems like we've encountered a situation where info->tid was not set by
+        * pthread_create. We alleviate this problem by waiting for pthread_create
+        * to return. */
+       sem_wait(startup->psem_first);
 
        t = NULL;
 #if defined(__DARWIN__)
@@ -575,11 +707,15 @@ static void *threadstartup(void *t)
 #endif
        setthreadobject(thread);
 
+       /* insert the thread into the threadlist */
+
        pthread_mutex_lock(&threadlistlock);
+
        info->prev = mainthreadobj;
        info->next = tnext = mainthreadobj->info.next;
        mainthreadobj->info.next = thread;
        tnext->info.prev = thread;
+
        pthread_mutex_unlock(&threadlistlock);
 
        initThreadLocks(thread);
@@ -589,57 +725,98 @@ static void *threadstartup(void *t)
 
        setPriority(info->tid, thread->o.thread->priority);
 
-       /* Find the run()V method and call it */
-       method = class_resolveclassmethod(thread->o.header.vftbl->class,
-                                                                         utf_new_char("run"),
-                                                                         utf_new_char("()V"),
-                                                                         thread->o.header.vftbl->class,
-                                                                         true);
+#if defined(ENABLE_INTRP)
+       /* set interpreter stack */
+
+       if (opt_intrp)
+               THREADINFO->_global_sp = (void *) (intrp_thread_stack + opt_stacksize);
+#endif
+
+       /* find and run the Thread.run()V method if no other function was passed */
+
+       if (function == NULL) {
+               method = class_resolveclassmethod(thread->o.header.vftbl->class,
+                                                                                 utf_run,
+                                                                                 utf_void__void,
+                                                                                 thread->o.header.vftbl->class,
+                                                                                 true);
+
+               if (!method)
+                       throw_exception();
 
-       /* if method != NULL, we had not exception */
-       if (method) {
                asm_calljavafunction(method, thread, NULL, NULL, NULL);
 
        } else {
-               throw_exception();
+               /* call passed function, e.g. finalizer_thread */
+
+               (function)();
        }
 
-       /* Allow lock record pools to be used by other threads. They cannot be
-        * deleted so we'd better not waste them. */
+       /* Allow lock record pools to be used by other threads. They
+          cannot be deleted so we'd better not waste them. */
+
        freeLockRecordPools(thread->ee.lrpool);
 
+       /* remove thread from thread list, do this inside a lock */
+
        pthread_mutex_lock(&threadlistlock);
        info->next->info.prev = info->prev;
        info->prev->info.next = info->next;
        pthread_mutex_unlock(&threadlistlock);
 
+       /* reset thread id (lock on joinMutex? TWISTI) */
+
        pthread_mutex_lock(&info->joinMutex);
        info->tid = 0;
        pthread_mutex_unlock(&info->joinMutex);
+
        pthread_cond_broadcast(&info->joinCond);
 
        return NULL;
 }
 
-void startThread(thread *t)
+
+/* threads_start_thread ********************************************************
+
+   Start a thread in the JVM.
+
+******************************************************************************/
+
+void threads_start_thread(thread *t, functionptr function)
 {
-       nativethread *info = &((threadobject*) t->vmThread)->info;
-       sem_t sem;
-       startupinfo startup;
+       nativethread *info;
+       sem_t         sem;
+       sem_t         sem_first;
+       startupinfo   startup;
+
+       info = &((threadobject *) t->vmThread)->info;
+
+       /* fill startupinfo structure passed by pthread_create to XXX */
 
-       startup.thread = (threadobject*) t->vmThread;
-       startup.psem = &sem;
+       startup.thread     = (threadobject*) t->vmThread;
+       startup.function   = function;       /* maybe we don't call Thread.run()V */
+       startup.psem       = &sem;
+       startup.psem_first = &sem_first;
 
        sem_init(&sem, 0, 0);
+       sem_init(&sem_first, 0, 0);
        
-       if (pthread_create(&info->tid, &threadattr, threadstartup, &startup))
-               panic("pthread_create failed");
+       if (pthread_create(&info->tid, &threadattr, threads_startup_thread,
+                                          &startup)) {
+               log_text("pthread_create failed");
+               assert(0);
+       }
+
+       sem_post(&sem_first);
+
+       /* wait here until the thread has entered itself into the thread list */
 
-       /* Wait here until the thread has entered itself into the thread list */
        sem_wait(&sem);
        sem_destroy(&sem);
+       sem_destroy(&sem_first);
 }
 
+
 /* At the end of the program, we wait for all running non-daemon threads to die
  */
 
@@ -662,7 +839,7 @@ void joinAllThreads()
                nativethread *info = &thread->info;
                pthread_mutex_lock(&info->joinMutex);
                pthread_mutex_unlock(&threadlistlock);
-               if (info->tid)
+               while (info->tid)
                        pthread_cond_wait(&info->joinCond, &info->joinMutex);
                pthread_mutex_unlock(&info->joinMutex);
                pthread_mutex_lock(&threadlistlock);
@@ -677,13 +854,11 @@ static void initLockRecord(monitorLockRecord *r, threadobject *t)
        r->queuers = 0;
        r->o = NULL;
        r->waiter = NULL;
-       r->incharge = &dummyLR;
+       r->incharge = (monitorLockRecord *) &dummyLR;
        r->waiting = false;
        sem_init(&r->queueSem, 0, 0);
        pthread_mutex_init(&r->resolveLock, NULL);
        pthread_cond_init(&r->resolveWait, NULL);
-       pthread_mutex_init(&r->waitLock, NULL);
-       pthread_cond_init(&r->waitCond, NULL);
 }
 
 /* No lock record must ever be destroyed because there may still be references
@@ -694,8 +869,6 @@ static void destroyLockRecord(monitorLockRecord *r)
        sem_destroy(&r->queueSem);
        pthread_mutex_destroy(&r->resolveLock);
        pthread_cond_destroy(&r->resolveWait);
-       pthread_mutex_destroy(&r->waitLock);
-       pthread_cond_destroy(&r->waitCond);
 }
 */
 
@@ -727,8 +900,8 @@ static lockRecordPool *allocNewLockRecordPool(threadobject *thread, int size)
 
 #define INITIALLOCKRECORDS 8
 
-static pthread_mutex_t pool_lock;
-static lockRecordPool *global_pool;
+pthread_mutex_t pool_lock;
+lockRecordPool *global_pool;
 
 static void initPools()
 {
@@ -794,12 +967,30 @@ void initObjectLock(java_objectheader *o)
        o->monitorPtr = dummyLR;
 }
 
+
+/* get_dummyLR *****************************************************************
+
+   Returns the global dummy monitor lock record. The pointer is
+   required in the code generator to set up a virtual
+   java_objectheader for code patch locking.
+
+*******************************************************************************/
+
+monitorLockRecord *get_dummyLR(void)
+{
+       return dummyLR;
+}
+
+
 static void queueOnLockRecord(monitorLockRecord *lr, java_objectheader *o)
 {
        atomic_add(&lr->queuers, 1);
+
        MEMORY_BARRIER_AFTER_ATOMIC();
-       if (lr->o == o)
+
+       while (lr->o == o)
                sem_wait(&lr->queueSem);
+
        atomic_add(&lr->queuers, -1);
 }
 
@@ -864,12 +1055,21 @@ monitorLockRecord *monitorEnter(threadobject *t, java_objectheader *o)
 
 static void wakeWaiters(monitorLockRecord *lr)
 {
+       monitorLockRecord *tmplr;
+       s4 q;
+
+       /* assign lock record to a temporary variable */
+
+       tmplr = lr;
+
        do {
-               int q = lr->queuers;
+               q = tmplr->queuers;
+
                while (q--)
-                       sem_post(&lr->queueSem);
-               lr = lr->waiter;
-       } while (lr);
+                       sem_post(&tmplr->queueSem);
+
+               tmplr = tmplr->waiter;
+       } while (tmplr != NULL && tmplr != lr);
 }
 
 #define GRAB_LR(lr,t) \
@@ -878,8 +1078,8 @@ static void wakeWaiters(monitorLockRecord *lr)
        }
 
 #define CHECK_MONITORSTATE(lr,t,mo,a) \
-    if (lr->o != mo || lr->ownerThread != t) { \
-               *exceptionptr = new_exception(string_java_lang_IllegalMonitorStateException); \
+    if (lr == NULL || lr->o != mo || lr->ownerThread != t) { \
+               *exceptionptr = new_illegalmonitorstateexception(); \
                a; \
        }
 
@@ -920,22 +1120,54 @@ static void removeFromWaiters(monitorLockRecord *lr, monitorLockRecord *wlr)
        } while (lr);
 }
 
-bool waitWithTimeout(threadobject *t, monitorLockRecord *lr, struct timespec *wakeupTime)
+static inline bool timespec_less(const struct timespec *tv1, const struct timespec *tv2)
+{
+       return tv1->tv_sec < tv2->tv_sec || (tv1->tv_sec == tv2->tv_sec && tv1->tv_nsec < tv2->tv_nsec);
+}
+
+static bool timeIsEarlier(const struct timespec *tv)
+{
+       struct timeval tvnow;
+       struct timespec tsnow;
+       gettimeofday(&tvnow, NULL);
+       tsnow.tv_sec = tvnow.tv_sec;
+       tsnow.tv_nsec = tvnow.tv_usec * 1000;
+       return timespec_less(&tsnow, tv);
+}
+
+
+/* waitWithTimeout *************************************************************
+
+   XXX
+
+*******************************************************************************/
+
+static bool waitWithTimeout(threadobject *t, monitorLockRecord *lr, struct timespec *wakeupTime)
 {
        bool wasinterrupted;
 
-       pthread_mutex_lock(&lr->waitLock);
-       t->waiting = lr;
+       pthread_mutex_lock(&t->waitLock);
+
+       t->isSleeping = true;
+
        if (wakeupTime->tv_sec || wakeupTime->tv_nsec)
-               pthread_cond_timedwait(&lr->waitCond, &lr->waitLock, wakeupTime);
+               while (!t->interrupted && !t->signaled && timeIsEarlier(wakeupTime))
+                       pthread_cond_timedwait(&t->waitCond, &t->waitLock, wakeupTime);
        else
-               pthread_cond_wait(&lr->waitCond, &lr->waitLock);
-       wasinterrupted = t->waiting == NULL;
-       t->waiting = NULL;
-       pthread_mutex_unlock(&lr->waitLock);
+               while (!t->interrupted && !t->signaled)
+                       pthread_cond_wait(&t->waitCond, &t->waitLock);
+
+       wasinterrupted = t->interrupted;
+       t->interrupted = false;
+       t->signaled = false;
+       t->isSleeping = false;
+
+       pthread_mutex_unlock(&t->waitLock);
+
        return wasinterrupted;
 }
 
+
 static void calcAbsoluteTime(struct timespec *tm, s8 millis, s4 nanos)
 {
        if (millis || nanos) {
@@ -987,10 +1219,16 @@ static void notifyOneOrAll(threadobject *t, java_objectheader *o, bool one)
        GRAB_LR(lr, t);
        CHECK_MONITORSTATE(lr, t, o, return);
        do {
+               threadobject *wthread;
                monitorLockRecord *wlr = lr->waiter;
                if (!wlr)
                        break;
-               pthread_cond_signal(&wlr->waitCond);
+               wthread = wlr->ownerThread;
+               pthread_mutex_lock(&wthread->waitLock);
+               if (wthread->isSleeping)
+                       pthread_cond_signal(&wthread->waitCond);
+               wthread->signaled = true;
+               pthread_mutex_unlock(&wthread->waitLock);
                lr = wlr;
        } while (!one);
 }
@@ -999,32 +1237,27 @@ bool threadHoldsLock(threadobject *t, java_objectheader *o)
 {
        monitorLockRecord *lr = o->monitorPtr;
        GRAB_LR(lr, t);
-       return lr->o == o && lr->ownerThread == t;
+       /* The reason why we have to check against NULL is that
+        * dummyLR->incharge == NULL */
+       return lr && lr->o == o && lr->ownerThread == t;
 }
 
 void interruptThread(java_lang_VMThread *thread)
 {
        threadobject *t = (threadobject*) thread;
 
-       monitorLockRecord *lr = t->waiting;
-       if (lr) {
-               pthread_mutex_lock(&lr->waitLock);
-               if (t->waiting == lr) {
-                       t->waiting = NULL;
-                       pthread_cond_signal(&lr->waitCond);
-               }
-               pthread_mutex_unlock(&lr->waitLock);
-               return;
-       }
-       
-       t->interrupted = 1;
+       t->interrupted = true;
+       pthread_mutex_lock(&t->waitLock);
+       if (t->isSleeping)
+               pthread_cond_signal(&t->waitCond);
+       pthread_mutex_unlock(&t->waitLock);
 }
 
 bool interruptedThread()
 {
        threadobject *t = (threadobject*) THREADOBJECT;
-       long intr = t->interrupted;
-       t->interrupted = 0;
+       bool intr = t->interrupted;
+       t->interrupted = false;
        return intr;
 }
 
@@ -1079,8 +1312,70 @@ void broadcast_cond_for_object(java_objectheader *o)
        notifyOneOrAll(t, o, false);
 }
 
+
+/* threads_dump ****************************************************************
+
+   Dumps info for all threads running in the JVM. This function is
+   called when SIGQUIT (<ctrl>-\) is sent to CACAO.
+
+*******************************************************************************/
+
+void threads_dump(void)
+{
+       threadobject       *tobj;
+       java_lang_VMThread *vmt;
+       nativethread       *nt;
+       ExecEnvironment    *ee;
+       java_lang_Thread   *t;
+       utf                *name;
+
+       tobj = mainthreadobj;
+
+       printf("Full thread dump CACAO "VERSION":\n");
+
+       /* iterate over all started threads */
+
+       do {
+               /* get thread objects */
+
+               vmt = &tobj->o;
+               nt  = &tobj->info;
+               ee  = &tobj->ee;
+               t   = vmt->thread;
+
+               /* the thread may be currently in initalization, don't print it */
+
+               if (t) {
+                       /* get thread name */
+
+                       name = javastring_toutf(t->name, false);
+
+                       printf("\n\"");
+                       utf_display(name);
+                       printf("\" ");
+
+                       if (t->daemon)
+                               printf("daemon ");
+
+#if SIZEOF_VOID_P == 8
+                       printf("prio=%d tid=0x%016lx\n", t->priority, nt->tid);
+#else
+                       printf("prio=%d tid=0x%08lx\n", t->priority, nt->tid);
 #endif
 
+                       /* send SIGUSR1 to thread to print stacktrace */
+
+                       pthread_kill(nt->tid, SIGUSR1);
+
+                       /* sleep this thread a bit, so the signal can reach the thread */
+
+                       sleepThread(10, 0);
+               }
+
+               tobj = tobj->info.next;
+       } while (tobj && (tobj != mainthreadobj));
+}
+
 
 /*
  * These are local overrides for various environment variables in Emacs.