1 /* src/threads/native/threads.c - native threads support
3 Copyright (C) 1996-2005 R. Grafl, A. Krall, C. Kruegel, C. Oates,
4 R. Obermaisser, M. Platter, M. Probst, S. Ring, E. Steiner,
5 C. Thalinger, D. Thuernbeck, P. Tomsich, C. Ullrich, J. Wenninger,
6 Institut f. Computersprachen - TU Wien
8 This file is part of CACAO.
10 This program is free software; you can redistribute it and/or
11 modify it under the terms of the GNU General Public License as
12 published by the Free Software Foundation; either version 2, or (at
13 your option) any later version.
15 This program is distributed in the hope that it will be useful, but
16 WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 General Public License for more details.
20 You should have received a copy of the GNU General Public License
21 along with this program; if not, write to the Free Software
22 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
25 Contact: cacao@complang.tuwien.ac.at
29 Changes: Christian Thalinger
31 $Id: threads.c 4087 2006-01-03 23:46:48Z twisti $
39 #include <sys/types.h>
47 #include <semaphore.h>
52 #ifndef USE_MD_THREAD_STUFF
53 #include "machine-instr.h"
55 #include "threads/native/generic-primitives.h"
58 #include "cacao/cacao.h"
60 #include "mm/memory.h"
61 #include "native/native.h"
62 #include "native/include/java_lang_Object.h"
63 #include "native/include/java_lang_Throwable.h"
64 #include "native/include/java_lang_Thread.h"
65 #include "native/include/java_lang_ThreadGroup.h"
66 #include "native/include/java_lang_VMThread.h"
67 #include "threads/native/threads.h"
68 #include "toolbox/avl.h"
69 #include "toolbox/logging.h"
70 #include "vm/builtin.h"
71 #include "vm/exceptions.h"
72 #include "vm/global.h"
73 #include "vm/loader.h"
74 #include "vm/options.h"
75 #include "vm/stringlocal.h"
76 #include "vm/jit/asmpart.h"
78 #if !defined(__DARWIN__)
79 #if defined(__LINUX__)
80 #define GC_LINUX_THREADS
81 #elif defined(__MIPS__)
82 #define GC_IRIX_THREADS
84 #include "boehm-gc/include/gc.h"
87 #ifdef USE_MD_THREAD_STUFF
88 pthread_mutex_t _atomic_add_lock = PTHREAD_MUTEX_INITIALIZER;
89 pthread_mutex_t _cas_lock = PTHREAD_MUTEX_INITIALIZER;
90 pthread_mutex_t _mb_lock = PTHREAD_MUTEX_INITIALIZER;
95 /* We need this for older MacOSX (10.1.x) */
98 pthread_mutex_t mutex;
101 } pthread_mutex_rec_t;
103 static void pthread_mutex_init_rec(pthread_mutex_rec_t *m)
105 pthread_mutex_init(&m->mutex, NULL);
109 static void pthread_mutex_destroy_rec(pthread_mutex_rec_t *m)
111 pthread_mutex_destroy(&m->mutex);
114 static void pthread_mutex_lock_rec(pthread_mutex_rec_t *m)
119 pthread_mutex_lock(&m->mutex);
120 m->owner = pthread_self();
124 if (m->owner != pthread_self())
125 pthread_mutex_lock(&m->mutex);
134 static void pthread_mutex_unlock_rec(pthread_mutex_rec_t *m)
137 pthread_mutex_unlock(&m->mutex);
142 #define pthread_mutex_lock_rec pthread_mutex_lock
143 #define pthread_mutex_unlock_rec pthread_mutex_unlock
144 #define pthread_mutex_rec_t pthread_mutex_t
146 #endif /* MUTEXSIM */
148 static void setPriority(pthread_t tid, int priority)
150 struct sched_param schedp;
153 pthread_getschedparam(tid, &policy, &schedp);
154 schedp.sched_priority = priority;
155 pthread_setschedparam(tid, policy, &schedp);
159 static avl_tree *criticaltree;
160 threadobject *mainthreadobj;
162 #ifndef HAVE___THREAD
163 pthread_key_t tkey_threadinfo;
165 __thread threadobject *threadobj;
168 static pthread_mutex_rec_t compiler_mutex;
169 static pthread_mutex_rec_t tablelock;
173 pthread_mutex_lock_rec(&compiler_mutex);
176 void compiler_unlock()
178 pthread_mutex_unlock_rec(&compiler_mutex);
183 pthread_mutex_lock_rec(&tablelock);
188 pthread_mutex_unlock_rec(&tablelock);
192 static s4 criticalcompare(const void *pa, const void *pb)
194 const threadcritnode *na = pa;
195 const threadcritnode *nb = pb;
197 if (na->mcodebegin < nb->mcodebegin)
199 if (na->mcodebegin > nb->mcodebegin)
205 static const threadcritnode *findcritical(u1 *mcodeptr)
208 const threadcritnode *m;
210 n = criticaltree->root;
217 const threadcritnode *d = n->data;
219 if (mcodeptr == d->mcodebegin)
222 if (mcodeptr < d->mcodebegin) {
239 void thread_registercritical(threadcritnode *n)
241 avl_insert(criticaltree, n);
244 u1 *thread_checkcritical(u1 *mcodeptr)
246 const threadcritnode *n = findcritical(mcodeptr);
247 return (n && mcodeptr < n->mcodeend && mcodeptr > n->mcodebegin) ? n->mcoderestart : NULL;
250 static void thread_addstaticcritical()
252 threadcritnode *n = &asm_criticalsections;
254 while (n->mcodebegin)
255 thread_registercritical(n++);
258 static pthread_mutex_t threadlistlock;
260 static pthread_mutex_t stopworldlock;
261 volatile int stopworldwhere;
263 static sem_t suspend_ack;
264 #if defined(__MIPS__)
265 static pthread_mutex_t suspend_ack_lock = PTHREAD_MUTEX_INITIALIZER;
266 static pthread_cond_t suspend_cond = PTHREAD_COND_INITIALIZER;
270 * where - 1 from within GC
273 void lock_stopworld(int where)
275 pthread_mutex_lock(&stopworldlock);
276 stopworldwhere = where;
279 void unlock_stopworld()
282 pthread_mutex_unlock(&stopworldlock);
285 #if !defined(__DARWIN__)
286 /* Caller must hold threadlistlock */
287 static int cast_sendsignals(int sig, int count)
290 threadobject *tobj = mainthreadobj;
291 nativethread *infoself = THREADINFO;
296 tobj = tobj->info.next;
297 } while (tobj != mainthreadobj);
300 nativethread *info = &tobj->info;
301 if (info != infoself)
302 pthread_kill(info->tid, sig);
303 tobj = tobj->info.next;
304 } while (tobj != mainthreadobj);
311 static void cast_darwinstop()
313 threadobject *tobj = mainthreadobj;
314 nativethread *infoself = THREADINFO;
317 nativethread *info = &tobj->info;
318 if (info != infoself)
320 thread_state_flavor_t flavor = PPC_THREAD_STATE;
321 mach_msg_type_number_t thread_state_count = PPC_THREAD_STATE_COUNT;
322 ppc_thread_state_t thread_state;
323 mach_port_t thread = info->mach_thread;
326 r = thread_suspend(thread);
327 if (r != KERN_SUCCESS) {
328 log_text("thread_suspend failed");
332 r = thread_get_state(thread, flavor,
333 (natural_t*)&thread_state, &thread_state_count);
334 if (r != KERN_SUCCESS) {
335 log_text("thread_get_state failed");
339 thread_restartcriticalsection(&thread_state);
341 r = thread_set_state(thread, flavor,
342 (natural_t*)&thread_state, thread_state_count);
343 if (r != KERN_SUCCESS) {
344 log_text("thread_set_state failed");
348 tobj = tobj->info.next;
349 } while (tobj != mainthreadobj);
352 static void cast_darwinresume()
354 threadobject *tobj = mainthreadobj;
355 nativethread *infoself = THREADINFO;
358 nativethread *info = &tobj->info;
359 if (info != infoself)
361 mach_port_t thread = info->mach_thread;
364 r = thread_resume(thread);
365 if (r != KERN_SUCCESS) {
366 log_text("thread_resume failed");
370 tobj = tobj->info.next;
371 } while (tobj != mainthreadobj);
376 #if defined(__MIPS__)
377 static void cast_irixresume()
379 pthread_mutex_lock(&suspend_ack_lock);
380 pthread_cond_broadcast(&suspend_cond);
381 pthread_mutex_unlock(&suspend_ack_lock);
385 void cast_stopworld()
389 pthread_mutex_lock(&threadlistlock);
390 #if defined(__DARWIN__)
393 count = cast_sendsignals(GC_signum1(), 0);
394 for (i=0; i<count; i++)
395 sem_wait(&suspend_ack);
397 pthread_mutex_unlock(&threadlistlock);
400 void cast_startworld()
402 pthread_mutex_lock(&threadlistlock);
403 #if defined(__DARWIN__)
405 #elif defined(__MIPS__)
408 cast_sendsignals(GC_signum2(), -1);
410 pthread_mutex_unlock(&threadlistlock);
414 #if !defined(__DARWIN__)
415 static void sigsuspend_handler(ucontext_t *ctx)
420 thread_restartcriticalsection(ctx);
422 /* Do as Boehm does. On IRIX a condition variable is used for wake-up
423 (not POSIX async-safe). */
424 #if defined(__IRIX__)
425 pthread_mutex_lock(&suspend_ack_lock);
426 sem_post(&suspend_ack);
427 pthread_cond_wait(&suspend_cond, &suspend_ack_lock);
428 pthread_mutex_unlock(&suspend_ack_lock);
430 sem_post(&suspend_ack);
434 sigdelset(&sigs, sig);
439 int cacao_suspendhandler(ucontext_t *ctx)
441 if (stopworldwhere != 2)
444 sigsuspend_handler(ctx);
449 static void setthreadobject(threadobject *thread)
451 #if !defined(HAVE___THREAD)
452 pthread_setspecific(tkey_threadinfo, thread);
459 /* thread_setself **************************************************************
463 *******************************************************************************/
465 void *thread_getself(void)
467 return pthread_getspecific(tkey_threadinfo);
471 static monitorLockRecord *dummyLR;
473 static void initPools();
476 /* thread_preinit **************************************************************
478 Do some early initialization of stuff required.
480 *******************************************************************************/
482 void threads_preinit(void)
485 pthread_mutexattr_t mutexattr;
486 pthread_mutexattr_init(&mutexattr);
487 pthread_mutexattr_settype(&mutexattr, PTHREAD_MUTEX_RECURSIVE);
488 pthread_mutex_init(&compiler_mutex, &mutexattr);
489 pthread_mutex_init(&tablelock, &mutexattr);
490 pthread_mutexattr_destroy(&mutexattr);
492 pthread_mutex_init_rec(&compiler_mutex);
493 pthread_mutex_init_rec(&tablelock);
496 pthread_mutex_init(&threadlistlock, NULL);
497 pthread_mutex_init(&stopworldlock, NULL);
499 /* Allocate something so the garbage collector's signal handlers
501 heap_allocate(1, false, NULL);
503 mainthreadobj = NEW(threadobject);
504 mainthreadobj->info.tid = pthread_self();
505 #if !defined(HAVE___THREAD)
506 pthread_key_create(&tkey_threadinfo, NULL);
508 setthreadobject(mainthreadobj);
511 /* Every newly created object's monitorPtr points here so we save
512 a check against NULL */
514 dummyLR = NEW(monitorLockRecord);
516 dummyLR->ownerThread = NULL;
517 dummyLR->waiting = false;
519 /* we need a working dummyLR before initializing the critical
522 criticaltree = avl_create(&criticalcompare);
524 thread_addstaticcritical();
525 sem_init(&suspend_ack, 0, 0);
529 static pthread_attr_t threadattr;
531 static void freeLockRecordPools(lockRecordPool *);
534 /* threads_init ****************************************************************
536 Initializes the threads required by the JVM: main, finalizer.
538 *******************************************************************************/
540 bool threads_init(u1 *stackbottom)
542 java_lang_String *threadname;
543 java_lang_Thread *mainthread;
544 java_lang_ThreadGroup *threadgroup;
545 threadobject *tempthread;
548 tempthread = mainthreadobj;
550 freeLockRecordPools(mainthreadobj->ee.lrpool);
552 /* This is kinda tricky, we grow the java.lang.Thread object so we
553 can keep the execution environment there. No Thread object must
554 have been created at an earlier time. */
556 class_java_lang_VMThread->instancesize = sizeof(threadobject);
558 /* create a VMThread */
560 mainthreadobj = (threadobject *) builtin_new(class_java_lang_VMThread);
565 FREE(tempthread, threadobject);
567 initThread(&mainthreadobj->o);
569 setthreadobject(mainthreadobj);
573 mainthreadobj->info.next = mainthreadobj;
574 mainthreadobj->info.prev = mainthreadobj;
576 #if defined(ENABLE_INTRP)
577 /* create interpreter stack */
580 MSET(intrp_main_stack, 0, u1, opt_stacksize);
581 mainthreadobj->info._global_sp = intrp_main_stack + opt_stacksize;
585 threadname = javastring_new(utf_new_char("main"));
587 /* allocate and init ThreadGroup */
589 threadgroup = (java_lang_ThreadGroup *)
590 native_new_and_init(class_java_lang_ThreadGroup);
593 throw_exception_exit();
595 /* create a Thread */
597 mainthread = (java_lang_Thread *) builtin_new(class_java_lang_Thread);
600 throw_exception_exit();
602 mainthreadobj->o.thread = mainthread;
604 /* call Thread.<init>(Ljava/lang/VMThread;Ljava/lang/String;IZ)V */
606 method = class_resolveclassmethod(class_java_lang_Thread,
608 utf_new_char("(Ljava/lang/VMThread;Ljava/lang/String;IZ)V"),
609 class_java_lang_Thread,
615 asm_calljavafunction(method, mainthread, mainthreadobj, threadname, (void*) 5);
619 mainthread->group = threadgroup;
620 /* XXX This is a hack because the fourth argument was omitted */
621 mainthread->daemon = false;
623 /* add mainthread to ThreadGroup */
625 method = class_resolveclassmethod(class_java_lang_ThreadGroup,
626 utf_new_char("addThread"),
627 utf_new_char("(Ljava/lang/Thread;)V"),
628 class_java_lang_ThreadGroup,
634 asm_calljavafunction(method, threadgroup, mainthread, NULL, NULL);
639 setPriority(pthread_self(), 5);
641 pthread_attr_init(&threadattr);
642 pthread_attr_setdetachstate(&threadattr, PTHREAD_CREATE_DETACHED);
644 /* everything's ok */
650 void initThread(java_lang_VMThread *t)
652 threadobject *thread = (threadobject*) t;
653 nativethread *info = &thread->info;
654 info->tid = pthread_self();
655 /* TODO destroy all those things */
656 pthread_mutex_init(&info->joinMutex, NULL);
657 pthread_cond_init(&info->joinCond, NULL);
659 pthread_mutex_init(&thread->waitLock, NULL);
660 pthread_cond_init(&thread->waitCond, NULL);
661 thread->interrupted = false;
662 thread->signaled = false;
663 thread->isSleeping = false;
666 static void initThreadLocks(threadobject *);
670 threadobject *thread;
671 functionptr function;
677 /* threads_startup *************************************************************
679 Thread startup function called by pthread_create.
681 ******************************************************************************/
683 static void *threads_startup_thread(void *t)
685 startupinfo *startup;
686 threadobject *thread;
691 functionptr function;
693 #if defined(ENABLE_INTRP)
694 u1 *intrp_thread_stack;
696 /* create interpreter stack */
699 intrp_thread_stack = (u1 *) alloca(opt_stacksize);
700 MSET(intrp_thread_stack, 0, u1, opt_stacksize);
704 /* get passed startupinfo structure and the values in there */
708 thread = startup->thread;
709 function = startup->function;
710 psem = startup->psem;
712 info = &thread->info;
714 /* Seems like we've encountered a situation where info->tid was not set by
715 * pthread_create. We alleviate this problem by waiting for pthread_create
717 sem_wait(startup->psem_first);
720 #if defined(__DARWIN__)
721 info->mach_thread = mach_thread_self();
723 setthreadobject(thread);
725 /* insert the thread into the threadlist */
727 pthread_mutex_lock(&threadlistlock);
729 info->prev = mainthreadobj;
730 info->next = tnext = mainthreadobj->info.next;
731 mainthreadobj->info.next = thread;
732 tnext->info.prev = thread;
734 pthread_mutex_unlock(&threadlistlock);
736 initThreadLocks(thread);
741 setPriority(info->tid, thread->o.thread->priority);
743 #if defined(ENABLE_INTRP)
744 /* set interpreter stack */
747 THREADINFO->_global_sp = (void *) (intrp_thread_stack + opt_stacksize);
750 /* find and run the Thread.run()V method if no other function was passed */
752 if (function == NULL) {
753 method = class_resolveclassmethod(thread->o.header.vftbl->class,
756 thread->o.header.vftbl->class,
762 asm_calljavafunction(method, thread, NULL, NULL, NULL);
765 /* call passed function, e.g. finalizer_thread */
770 /* Allow lock record pools to be used by other threads. They
771 cannot be deleted so we'd better not waste them. */
773 freeLockRecordPools(thread->ee.lrpool);
775 /* remove thread from thread list, do this inside a lock */
777 pthread_mutex_lock(&threadlistlock);
778 info->next->info.prev = info->prev;
779 info->prev->info.next = info->next;
780 pthread_mutex_unlock(&threadlistlock);
782 /* reset thread id (lock on joinMutex? TWISTI) */
784 pthread_mutex_lock(&info->joinMutex);
786 pthread_mutex_unlock(&info->joinMutex);
788 pthread_cond_broadcast(&info->joinCond);
794 /* threads_start_thread ********************************************************
796 Start a thread in the JVM.
798 ******************************************************************************/
800 void threads_start_thread(thread *t, functionptr function)
807 info = &((threadobject *) t->vmThread)->info;
809 /* fill startupinfo structure passed by pthread_create to XXX */
811 startup.thread = (threadobject*) t->vmThread;
812 startup.function = function; /* maybe we don't call Thread.run()V */
814 startup.psem_first = &sem_first;
816 sem_init(&sem, 0, 0);
817 sem_init(&sem_first, 0, 0);
819 if (pthread_create(&info->tid, &threadattr, threads_startup_thread,
821 log_text("pthread_create failed");
825 sem_post(&sem_first);
827 /* wait here until the thread has entered itself into the thread list */
831 sem_destroy(&sem_first);
835 /* At the end of the program, we wait for all running non-daemon threads to die
838 static threadobject *findNonDaemon(threadobject *thread)
840 while (thread != mainthreadobj) {
841 if (!thread->o.thread->daemon)
843 thread = thread->info.prev;
849 void joinAllThreads()
851 threadobject *thread;
852 pthread_mutex_lock(&threadlistlock);
853 while ((thread = findNonDaemon(mainthreadobj->info.prev)) != NULL) {
854 nativethread *info = &thread->info;
855 pthread_mutex_lock(&info->joinMutex);
856 pthread_mutex_unlock(&threadlistlock);
858 pthread_cond_wait(&info->joinCond, &info->joinMutex);
859 pthread_mutex_unlock(&info->joinMutex);
860 pthread_mutex_lock(&threadlistlock);
862 pthread_mutex_unlock(&threadlistlock);
865 static void initLockRecord(monitorLockRecord *r, threadobject *t)
872 r->incharge = (monitorLockRecord *) &dummyLR;
874 sem_init(&r->queueSem, 0, 0);
875 pthread_mutex_init(&r->resolveLock, NULL);
876 pthread_cond_init(&r->resolveWait, NULL);
879 /* No lock record must ever be destroyed because there may still be references
882 static void destroyLockRecord(monitorLockRecord *r)
884 sem_destroy(&r->queueSem);
885 pthread_mutex_destroy(&r->resolveLock);
886 pthread_cond_destroy(&r->resolveWait);
892 initThreadLocks(mainthreadobj);
895 static void initThreadLocks(threadobject *thread)
897 thread->ee.firstLR = NULL;
898 thread->ee.lrpool = NULL;
899 thread->ee.numlr = 0;
902 static lockRecordPool *allocNewLockRecordPool(threadobject *thread, int size)
904 lockRecordPool *p = mem_alloc(sizeof(lockRecordPoolHeader) + sizeof(monitorLockRecord) * size);
907 p->header.size = size;
908 for (i=0; i<size; i++) {
909 initLockRecord(&p->lr[i], thread);
910 p->lr[i].nextFree = &p->lr[i+1];
912 p->lr[i-1].nextFree = NULL;
916 #define INITIALLOCKRECORDS 8
918 pthread_mutex_t pool_lock;
919 lockRecordPool *global_pool;
921 static void initPools()
923 pthread_mutex_init(&pool_lock, NULL);
926 static lockRecordPool *allocLockRecordPool(threadobject *t, int size)
928 pthread_mutex_lock(&pool_lock);
931 lockRecordPool *pool = global_pool;
932 global_pool = pool->header.next;
933 pthread_mutex_unlock(&pool_lock);
935 for (i=0; i < pool->header.size; i++)
936 pool->lr[i].ownerThread = t;
940 pthread_mutex_unlock(&pool_lock);
942 return allocNewLockRecordPool(t, size);
945 static void freeLockRecordPools(lockRecordPool *pool)
947 lockRecordPoolHeader *last;
948 pthread_mutex_lock(&pool_lock);
949 last = &pool->header;
951 last = &last->next->header;
952 last->next = global_pool;
954 pthread_mutex_unlock(&pool_lock);
957 static monitorLockRecord *allocLockRecordSimple(threadobject *t)
959 monitorLockRecord *r = t->ee.firstLR;
962 int poolsize = t->ee.numlr ? t->ee.numlr * 2 : INITIALLOCKRECORDS;
963 lockRecordPool *pool = allocLockRecordPool(t, poolsize);
964 pool->header.next = t->ee.lrpool;
967 t->ee.numlr += pool->header.size;
970 t->ee.firstLR = r->nextFree;
974 static inline void recycleLockRecord(threadobject *t, monitorLockRecord *r)
976 r->nextFree = t->ee.firstLR;
980 void initObjectLock(java_objectheader *o)
982 o->monitorPtr = dummyLR;
986 /* get_dummyLR *****************************************************************
988 Returns the global dummy monitor lock record. The pointer is
989 required in the code generator to set up a virtual
990 java_objectheader for code patch locking.
992 *******************************************************************************/
994 monitorLockRecord *get_dummyLR(void)
1000 static void queueOnLockRecord(monitorLockRecord *lr, java_objectheader *o)
1002 atomic_add(&lr->queuers, 1);
1004 MEMORY_BARRIER_AFTER_ATOMIC();
1007 sem_wait(&lr->queueSem);
1009 atomic_add(&lr->queuers, -1);
1012 static void freeLockRecord(monitorLockRecord *lr)
1019 sem_post(&lr->queueSem);
1022 static inline void handleWaiter(monitorLockRecord *mlr, monitorLockRecord *lr)
1028 monitorLockRecord *monitorEnter(threadobject *t, java_objectheader *o)
1031 monitorLockRecord *lr = o->monitorPtr;
1033 monitorLockRecord *nlr, *mlr = allocLockRecordSimple(t);
1037 nlr = o->monitorPtr;
1039 handleWaiter(mlr, lr);
1043 if (lr->ownerThread != t)
1045 MEMORY_BARRIER_BEFORE_ATOMIC();
1046 nlr = (void*) compare_and_swap((long*) &o->monitorPtr, (long) lr, (long) mlr);
1049 if (mlr == lr || lr->o != o) {
1050 handleWaiter(mlr, lr);
1054 queueOnLockRecord(lr, o);
1055 handleWaiter(mlr, lr);
1058 freeLockRecord(mlr);
1059 recycleLockRecord(t, mlr);
1060 queueOnLockRecord(nlr, o);
1062 if (lr->ownerThread == t) {
1066 queueOnLockRecord(lr, o);
1071 static void wakeWaiters(monitorLockRecord *lr)
1073 monitorLockRecord *tmplr;
1076 /* assign lock record to a temporary variable */
1084 sem_post(&tmplr->queueSem);
1086 tmplr = tmplr->waiter;
1087 } while (tmplr != NULL && tmplr != lr);
1090 #define GRAB_LR(lr,t) \
1091 if (lr->ownerThread != t) { \
1092 lr = lr->incharge; \
1095 #define CHECK_MONITORSTATE(lr,t,mo,a) \
1096 if (lr == NULL || lr->o != mo || lr->ownerThread != t) { \
1097 *exceptionptr = new_illegalmonitorstateexception(); \
1101 bool monitorExit(threadobject *t, java_objectheader *o)
1103 monitorLockRecord *lr = o->monitorPtr;
1105 CHECK_MONITORSTATE(lr, t, o, return false);
1106 if (lr->lockCount > 1) {
1111 monitorLockRecord *wlr = lr->waiter;
1112 if (o->monitorPtr != lr ||
1113 (void*) compare_and_swap((long*) &o->monitorPtr, (long) lr, (long) wlr) != lr)
1115 monitorLockRecord *nlr = o->monitorPtr;
1117 STORE_ORDER_BARRIER();
1123 recycleLockRecord(t, lr);
1127 static void removeFromWaiters(monitorLockRecord *lr, monitorLockRecord *wlr)
1130 if (lr->waiter == wlr) {
1131 lr->waiter = wlr->waiter;
1138 static inline bool timespec_less(const struct timespec *tv1, const struct timespec *tv2)
1140 return tv1->tv_sec < tv2->tv_sec || (tv1->tv_sec == tv2->tv_sec && tv1->tv_nsec < tv2->tv_nsec);
1143 static bool timeIsEarlier(const struct timespec *tv)
1145 struct timeval tvnow;
1146 struct timespec tsnow;
1147 gettimeofday(&tvnow, NULL);
1148 tsnow.tv_sec = tvnow.tv_sec;
1149 tsnow.tv_nsec = tvnow.tv_usec * 1000;
1150 return timespec_less(&tsnow, tv);
1154 /* waitWithTimeout *************************************************************
1158 *******************************************************************************/
1160 static bool waitWithTimeout(threadobject *t, monitorLockRecord *lr, struct timespec *wakeupTime)
1162 bool wasinterrupted;
1164 pthread_mutex_lock(&t->waitLock);
1166 t->isSleeping = true;
1168 if (wakeupTime->tv_sec || wakeupTime->tv_nsec)
1169 while (!t->interrupted && !t->signaled && timeIsEarlier(wakeupTime))
1170 pthread_cond_timedwait(&t->waitCond, &t->waitLock, wakeupTime);
1172 while (!t->interrupted && !t->signaled)
1173 pthread_cond_wait(&t->waitCond, &t->waitLock);
1175 wasinterrupted = t->interrupted;
1176 t->interrupted = false;
1177 t->signaled = false;
1178 t->isSleeping = false;
1180 pthread_mutex_unlock(&t->waitLock);
1182 return wasinterrupted;
1186 static void calcAbsoluteTime(struct timespec *tm, s8 millis, s4 nanos)
1188 if (millis || nanos) {
1191 gettimeofday(&tv, NULL);
1192 tv.tv_sec += millis / 1000;
1194 nsec = tv.tv_usec * 1000 + (s4) millis * 1000000 + nanos;
1195 tm->tv_sec = tv.tv_sec + nsec / 1000000000;
1196 tm->tv_nsec = nsec % 1000000000;
1203 void monitorWait(threadobject *t, java_objectheader *o, s8 millis, s4 nanos)
1205 bool wasinterrupted;
1206 struct timespec wakeupTime;
1207 monitorLockRecord *mlr, *lr = o->monitorPtr;
1209 CHECK_MONITORSTATE(lr, t, o, return);
1211 calcAbsoluteTime(&wakeupTime, millis, nanos);
1214 wakeWaiters(lr->waiter);
1216 STORE_ORDER_BARRIER();
1218 wasinterrupted = waitWithTimeout(t, lr, &wakeupTime);
1219 mlr = monitorEnter(t, o);
1220 removeFromWaiters(mlr, lr);
1221 mlr->lockCount = lr->lockCount;
1223 lr->waiting = false;
1225 recycleLockRecord(t, lr);
1228 *exceptionptr = new_exception(string_java_lang_InterruptedException);
1231 static void notifyOneOrAll(threadobject *t, java_objectheader *o, bool one)
1233 monitorLockRecord *lr = o->monitorPtr;
1235 CHECK_MONITORSTATE(lr, t, o, return);
1237 threadobject *wthread;
1238 monitorLockRecord *wlr = lr->waiter;
1241 wthread = wlr->ownerThread;
1242 pthread_mutex_lock(&wthread->waitLock);
1243 if (wthread->isSleeping)
1244 pthread_cond_signal(&wthread->waitCond);
1245 wthread->signaled = true;
1246 pthread_mutex_unlock(&wthread->waitLock);
1251 bool threadHoldsLock(threadobject *t, java_objectheader *o)
1253 monitorLockRecord *lr = o->monitorPtr;
1255 /* The reason why we have to check against NULL is that
1256 * dummyLR->incharge == NULL */
1257 return lr && lr->o == o && lr->ownerThread == t;
1260 void interruptThread(java_lang_VMThread *thread)
1262 threadobject *t = (threadobject*) thread;
1264 t->interrupted = true;
1265 pthread_mutex_lock(&t->waitLock);
1267 pthread_cond_signal(&t->waitCond);
1268 pthread_mutex_unlock(&t->waitLock);
1271 bool interruptedThread()
1273 threadobject *t = (threadobject*) THREADOBJECT;
1274 bool intr = t->interrupted;
1275 t->interrupted = false;
1279 bool isInterruptedThread(java_lang_VMThread *thread)
1281 threadobject *t = (threadobject*) thread;
1282 return t->interrupted;
1285 void sleepThread(s8 millis, s4 nanos)
1287 bool wasinterrupted;
1288 threadobject *t = (threadobject*) THREADOBJECT;
1289 monitorLockRecord *lr;
1290 struct timespec wakeupTime;
1291 calcAbsoluteTime(&wakeupTime, millis, nanos);
1293 lr = allocLockRecordSimple(t);
1294 wasinterrupted = waitWithTimeout(t, lr, &wakeupTime);
1295 recycleLockRecord(t, lr);
1298 *exceptionptr = new_exception(string_java_lang_InterruptedException);
1306 void setPriorityThread(thread *t, s4 priority)
1308 nativethread *info = &((threadobject*) t->vmThread)->info;
1309 setPriority(info->tid, priority);
1312 void wait_cond_for_object(java_objectheader *o, s8 time, s4 nanos)
1314 threadobject *t = (threadobject*) THREADOBJECT;
1315 monitorWait(t, o, time, nanos);
1318 void signal_cond_for_object(java_objectheader *o)
1320 threadobject *t = (threadobject*) THREADOBJECT;
1321 notifyOneOrAll(t, o, true);
1324 void broadcast_cond_for_object(java_objectheader *o)
1326 threadobject *t = (threadobject*) THREADOBJECT;
1327 notifyOneOrAll(t, o, false);
1331 /* threads_dump ****************************************************************
1333 Dumps info for all threads running in the JVM. This function is
1334 called when SIGQUIT (<ctrl>-\) is sent to CACAO.
1336 *******************************************************************************/
1338 void threads_dump(void)
1341 java_lang_VMThread *vmt;
1343 ExecEnvironment *ee;
1344 java_lang_Thread *t;
1347 tobj = mainthreadobj;
1349 printf("Full thread dump CACAO "VERSION":\n");
1351 /* iterate over all started threads */
1354 /* get thread objects */
1361 /* the thread may be currently in initalization, don't print it */
1364 /* get thread name */
1366 name = javastring_toutf(t->name, false);
1375 #if SIZEOF_VOID_P == 8
1376 printf("prio=%d tid=0x%016lx\n", t->priority, nt->tid);
1378 printf("prio=%d tid=0x%08lx\n", t->priority, nt->tid);
1381 /* send SIGUSR1 to thread to print stacktrace */
1383 pthread_kill(nt->tid, SIGUSR1);
1385 /* sleep this thread a bit, so the signal can reach the thread */
1390 tobj = tobj->info.next;
1391 } while (tobj && (tobj != mainthreadobj));
1396 * These are local overrides for various environment variables in Emacs.
1397 * Please do not remove this and leave it at the end of the file, where
1398 * Emacs will automagically detect them.
1399 * ---------------------------------------------------------------------
1402 * indent-tabs-mode: t