1 /* src/threads/native/threads.c - native threads support
3 Copyright (C) 1996-2005, 2006 R. Grafl, A. Krall, C. Kruegel,
4 C. Oates, R. Obermaisser, M. Platter, M. Probst, S. Ring,
5 E. Steiner, C. Thalinger, D. Thuernbeck, P. Tomsich, C. Ullrich,
6 J. Wenninger, 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., 51 Franklin Street, Fifth Floor, Boston, MA
25 Contact: cacao@cacaojvm.org
29 Changes: Christian Thalinger
31 $Id: threads.c 4357 2006-01-22 23:33:38Z twisti $
39 #include <sys/types.h>
47 #include <semaphore.h>
54 #ifndef USE_MD_THREAD_STUFF
55 #include "machine-instr.h"
57 #include "threads/native/generic-primitives.h"
60 #include "cacao/cacao.h"
62 #include "mm/memory.h"
63 #include "native/native.h"
64 #include "native/include/java_lang_Object.h"
65 #include "native/include/java_lang_Throwable.h"
66 #include "native/include/java_lang_Thread.h"
67 #include "native/include/java_lang_ThreadGroup.h"
68 #include "native/include/java_lang_VMThread.h"
69 #include "threads/native/threads.h"
70 #include "toolbox/avl.h"
71 #include "toolbox/logging.h"
72 #include "vm/builtin.h"
73 #include "vm/exceptions.h"
74 #include "vm/global.h"
75 #include "vm/loader.h"
76 #include "vm/options.h"
77 #include "vm/stringlocal.h"
78 #include "vm/jit/asmpart.h"
80 #if !defined(__DARWIN__)
81 #if defined(__LINUX__)
82 #define GC_LINUX_THREADS
83 #elif defined(__MIPS__)
84 #define GC_IRIX_THREADS
86 #include "boehm-gc/include/gc.h"
89 #ifdef USE_MD_THREAD_STUFF
90 pthread_mutex_t _atomic_add_lock = PTHREAD_MUTEX_INITIALIZER;
91 pthread_mutex_t _cas_lock = PTHREAD_MUTEX_INITIALIZER;
92 pthread_mutex_t _mb_lock = PTHREAD_MUTEX_INITIALIZER;
97 /* We need this for older MacOSX (10.1.x) */
100 pthread_mutex_t mutex;
103 } pthread_mutex_rec_t;
105 static void pthread_mutex_init_rec(pthread_mutex_rec_t *m)
107 pthread_mutex_init(&m->mutex, NULL);
111 static void pthread_mutex_destroy_rec(pthread_mutex_rec_t *m)
113 pthread_mutex_destroy(&m->mutex);
116 static void pthread_mutex_lock_rec(pthread_mutex_rec_t *m)
121 pthread_mutex_lock(&m->mutex);
122 m->owner = pthread_self();
126 if (m->owner != pthread_self())
127 pthread_mutex_lock(&m->mutex);
136 static void pthread_mutex_unlock_rec(pthread_mutex_rec_t *m)
139 pthread_mutex_unlock(&m->mutex);
144 #define pthread_mutex_lock_rec pthread_mutex_lock
145 #define pthread_mutex_unlock_rec pthread_mutex_unlock
146 #define pthread_mutex_rec_t pthread_mutex_t
148 #endif /* MUTEXSIM */
150 static void setPriority(pthread_t tid, int priority)
152 struct sched_param schedp;
155 pthread_getschedparam(tid, &policy, &schedp);
156 schedp.sched_priority = priority;
157 pthread_setschedparam(tid, policy, &schedp);
161 static avl_tree *criticaltree;
162 threadobject *mainthreadobj;
164 #ifndef HAVE___THREAD
165 pthread_key_t tkey_threadinfo;
167 __thread threadobject *threadobj;
170 static pthread_mutex_rec_t compiler_mutex;
171 static pthread_mutex_rec_t tablelock;
175 pthread_mutex_lock_rec(&compiler_mutex);
178 void compiler_unlock()
180 pthread_mutex_unlock_rec(&compiler_mutex);
185 pthread_mutex_lock_rec(&tablelock);
190 pthread_mutex_unlock_rec(&tablelock);
194 static s4 criticalcompare(const void *pa, const void *pb)
196 const threadcritnode *na = pa;
197 const threadcritnode *nb = pb;
199 if (na->mcodebegin < nb->mcodebegin)
201 if (na->mcodebegin > nb->mcodebegin)
207 static const threadcritnode *findcritical(u1 *mcodeptr)
210 const threadcritnode *m;
212 n = criticaltree->root;
219 const threadcritnode *d = n->data;
221 if (mcodeptr == d->mcodebegin)
224 if (mcodeptr < d->mcodebegin) {
241 void thread_registercritical(threadcritnode *n)
243 avl_insert(criticaltree, n);
246 u1 *thread_checkcritical(u1 *mcodeptr)
248 const threadcritnode *n = findcritical(mcodeptr);
249 return (n && mcodeptr < n->mcodeend && mcodeptr > n->mcodebegin) ? n->mcoderestart : NULL;
252 static void thread_addstaticcritical()
254 /* XXX TWISTI: this is just a quick hack */
255 #if defined(ENABLE_JIT)
256 threadcritnode *n = &asm_criticalsections;
258 while (n->mcodebegin)
259 thread_registercritical(n++);
263 static pthread_mutex_t threadlistlock;
265 static pthread_mutex_t stopworldlock;
266 volatile int stopworldwhere;
268 static sem_t suspend_ack;
269 #if defined(__MIPS__)
270 static pthread_mutex_t suspend_ack_lock = PTHREAD_MUTEX_INITIALIZER;
271 static pthread_cond_t suspend_cond = PTHREAD_COND_INITIALIZER;
275 * where - 1 from within GC
278 void lock_stopworld(int where)
280 pthread_mutex_lock(&stopworldlock);
281 stopworldwhere = where;
284 void unlock_stopworld()
287 pthread_mutex_unlock(&stopworldlock);
290 #if !defined(__DARWIN__)
291 /* Caller must hold threadlistlock */
292 static int cast_sendsignals(int sig, int count)
295 threadobject *tobj = mainthreadobj;
296 nativethread *infoself = THREADINFO;
301 tobj = tobj->info.next;
302 } while (tobj != mainthreadobj);
305 nativethread *info = &tobj->info;
306 if (info != infoself)
307 pthread_kill(info->tid, sig);
308 tobj = tobj->info.next;
309 } while (tobj != mainthreadobj);
316 static void cast_darwinstop()
318 threadobject *tobj = mainthreadobj;
319 nativethread *infoself = THREADINFO;
322 nativethread *info = &tobj->info;
323 if (info != infoself)
325 thread_state_flavor_t flavor = PPC_THREAD_STATE;
326 mach_msg_type_number_t thread_state_count = PPC_THREAD_STATE_COUNT;
327 ppc_thread_state_t thread_state;
328 mach_port_t thread = info->mach_thread;
331 r = thread_suspend(thread);
332 if (r != KERN_SUCCESS) {
333 log_text("thread_suspend failed");
337 r = thread_get_state(thread, flavor,
338 (natural_t*)&thread_state, &thread_state_count);
339 if (r != KERN_SUCCESS) {
340 log_text("thread_get_state failed");
344 thread_restartcriticalsection(&thread_state);
346 r = thread_set_state(thread, flavor,
347 (natural_t*)&thread_state, thread_state_count);
348 if (r != KERN_SUCCESS) {
349 log_text("thread_set_state failed");
353 tobj = tobj->info.next;
354 } while (tobj != mainthreadobj);
357 static void cast_darwinresume()
359 threadobject *tobj = mainthreadobj;
360 nativethread *infoself = THREADINFO;
363 nativethread *info = &tobj->info;
364 if (info != infoself)
366 mach_port_t thread = info->mach_thread;
369 r = thread_resume(thread);
370 if (r != KERN_SUCCESS) {
371 log_text("thread_resume failed");
375 tobj = tobj->info.next;
376 } while (tobj != mainthreadobj);
381 #if defined(__MIPS__)
382 static void cast_irixresume()
384 pthread_mutex_lock(&suspend_ack_lock);
385 pthread_cond_broadcast(&suspend_cond);
386 pthread_mutex_unlock(&suspend_ack_lock);
390 void cast_stopworld()
394 pthread_mutex_lock(&threadlistlock);
395 #if defined(__DARWIN__)
398 count = cast_sendsignals(GC_signum1(), 0);
399 for (i=0; i<count; i++)
400 sem_wait(&suspend_ack);
402 pthread_mutex_unlock(&threadlistlock);
405 void cast_startworld()
407 pthread_mutex_lock(&threadlistlock);
408 #if defined(__DARWIN__)
410 #elif defined(__MIPS__)
413 cast_sendsignals(GC_signum2(), -1);
415 pthread_mutex_unlock(&threadlistlock);
419 #if !defined(__DARWIN__)
420 static void sigsuspend_handler(ucontext_t *ctx)
425 /* XXX TWISTI: this is just a quick hack */
426 #if defined(ENABLE_JIT)
427 thread_restartcriticalsection(ctx);
430 /* Do as Boehm does. On IRIX a condition variable is used for wake-up
431 (not POSIX async-safe). */
432 #if defined(__IRIX__)
433 pthread_mutex_lock(&suspend_ack_lock);
434 sem_post(&suspend_ack);
435 pthread_cond_wait(&suspend_cond, &suspend_ack_lock);
436 pthread_mutex_unlock(&suspend_ack_lock);
438 sem_post(&suspend_ack);
442 sigdelset(&sigs, sig);
447 int cacao_suspendhandler(ucontext_t *ctx)
449 if (stopworldwhere != 2)
452 sigsuspend_handler(ctx);
457 static void setthreadobject(threadobject *thread)
459 #if !defined(HAVE___THREAD)
460 pthread_setspecific(tkey_threadinfo, thread);
467 /* thread_setself **************************************************************
471 *******************************************************************************/
473 void *thread_getself(void)
475 return pthread_getspecific(tkey_threadinfo);
479 static monitorLockRecord *dummyLR;
481 static void initPools();
484 /* thread_preinit **************************************************************
486 Do some early initialization of stuff required.
488 *******************************************************************************/
490 void threads_preinit(void)
493 pthread_mutexattr_t mutexattr;
494 pthread_mutexattr_init(&mutexattr);
495 pthread_mutexattr_settype(&mutexattr, PTHREAD_MUTEX_RECURSIVE);
496 pthread_mutex_init(&compiler_mutex, &mutexattr);
497 pthread_mutex_init(&tablelock, &mutexattr);
498 pthread_mutexattr_destroy(&mutexattr);
500 pthread_mutex_init_rec(&compiler_mutex);
501 pthread_mutex_init_rec(&tablelock);
504 pthread_mutex_init(&threadlistlock, NULL);
505 pthread_mutex_init(&stopworldlock, NULL);
507 /* Allocate something so the garbage collector's signal handlers
509 heap_allocate(1, false, NULL);
511 mainthreadobj = NEW(threadobject);
512 mainthreadobj->info.tid = pthread_self();
513 #if !defined(HAVE___THREAD)
514 pthread_key_create(&tkey_threadinfo, NULL);
516 setthreadobject(mainthreadobj);
519 /* Every newly created object's monitorPtr points here so we save
520 a check against NULL */
522 dummyLR = NEW(monitorLockRecord);
524 dummyLR->ownerThread = NULL;
525 dummyLR->waiting = false;
527 /* we need a working dummyLR before initializing the critical
530 criticaltree = avl_create(&criticalcompare);
532 thread_addstaticcritical();
533 sem_init(&suspend_ack, 0, 0);
537 static pthread_attr_t threadattr;
539 static void freeLockRecordPools(lockRecordPool *);
542 /* threads_init ****************************************************************
544 Initializes the threads required by the JVM: main, finalizer.
546 *******************************************************************************/
548 bool threads_init(u1 *stackbottom)
550 java_lang_String *threadname;
551 java_lang_Thread *mainthread;
552 java_lang_ThreadGroup *threadgroup;
553 threadobject *tempthread;
556 tempthread = mainthreadobj;
558 freeLockRecordPools(mainthreadobj->ee.lrpool);
560 /* This is kinda tricky, we grow the java.lang.Thread object so we
561 can keep the execution environment there. No Thread object must
562 have been created at an earlier time. */
564 class_java_lang_VMThread->instancesize = sizeof(threadobject);
566 /* create a VMThread */
568 mainthreadobj = (threadobject *) builtin_new(class_java_lang_VMThread);
573 FREE(tempthread, threadobject);
575 initThread(&mainthreadobj->o);
577 setthreadobject(mainthreadobj);
581 mainthreadobj->info.next = mainthreadobj;
582 mainthreadobj->info.prev = mainthreadobj;
584 #if defined(ENABLE_INTRP)
585 /* create interpreter stack */
588 MSET(intrp_main_stack, 0, u1, opt_stacksize);
589 mainthreadobj->info._global_sp = intrp_main_stack + opt_stacksize;
593 threadname = javastring_new(utf_new_char("main"));
595 /* allocate and init ThreadGroup */
597 threadgroup = (java_lang_ThreadGroup *)
598 native_new_and_init(class_java_lang_ThreadGroup);
601 throw_exception_exit();
603 /* create a Thread */
605 mainthread = (java_lang_Thread *) builtin_new(class_java_lang_Thread);
608 throw_exception_exit();
610 mainthreadobj->o.thread = mainthread;
612 /* call Thread.<init>(Ljava/lang/VMThread;Ljava/lang/String;IZ)V */
614 method = class_resolveclassmethod(class_java_lang_Thread,
616 utf_new_char("(Ljava/lang/VMThread;Ljava/lang/String;IZ)V"),
617 class_java_lang_Thread,
623 ASM_CALLJAVAFUNCTION(method, mainthread, mainthreadobj, threadname,
629 mainthread->group = threadgroup;
630 /* XXX This is a hack because the fourth argument was omitted */
631 mainthread->daemon = false;
633 /* add mainthread to ThreadGroup */
635 method = class_resolveclassmethod(class_java_lang_ThreadGroup,
636 utf_new_char("addThread"),
637 utf_new_char("(Ljava/lang/Thread;)V"),
638 class_java_lang_ThreadGroup,
644 ASM_CALLJAVAFUNCTION(method, threadgroup, mainthread, NULL, NULL);
649 setPriority(pthread_self(), 5);
651 pthread_attr_init(&threadattr);
652 pthread_attr_setdetachstate(&threadattr, PTHREAD_CREATE_DETACHED);
654 /* everything's ok */
660 void initThread(java_lang_VMThread *t)
662 threadobject *thread = (threadobject*) t;
663 nativethread *info = &thread->info;
664 info->tid = pthread_self();
665 /* TODO destroy all those things */
666 pthread_mutex_init(&info->joinMutex, NULL);
667 pthread_cond_init(&info->joinCond, NULL);
669 pthread_mutex_init(&thread->waitLock, NULL);
670 pthread_cond_init(&thread->waitCond, NULL);
671 thread->interrupted = false;
672 thread->signaled = false;
673 thread->isSleeping = false;
676 static void initThreadLocks(threadobject *);
680 threadobject *thread;
681 functionptr function;
687 /* threads_startup *************************************************************
689 Thread startup function called by pthread_create.
691 ******************************************************************************/
693 static void *threads_startup_thread(void *t)
695 startupinfo *startup;
696 threadobject *thread;
701 functionptr function;
703 #if defined(ENABLE_INTRP)
704 u1 *intrp_thread_stack;
706 /* create interpreter stack */
709 intrp_thread_stack = (u1 *) alloca(opt_stacksize);
710 MSET(intrp_thread_stack, 0, u1, opt_stacksize);
714 /* get passed startupinfo structure and the values in there */
718 thread = startup->thread;
719 function = startup->function;
720 psem = startup->psem;
722 info = &thread->info;
724 /* Seems like we've encountered a situation where info->tid was not set by
725 * pthread_create. We alleviate this problem by waiting for pthread_create
727 sem_wait(startup->psem_first);
730 #if defined(__DARWIN__)
731 info->mach_thread = mach_thread_self();
733 setthreadobject(thread);
735 /* insert the thread into the threadlist */
737 pthread_mutex_lock(&threadlistlock);
739 info->prev = mainthreadobj;
740 info->next = tnext = mainthreadobj->info.next;
741 mainthreadobj->info.next = thread;
742 tnext->info.prev = thread;
744 pthread_mutex_unlock(&threadlistlock);
746 initThreadLocks(thread);
751 setPriority(info->tid, thread->o.thread->priority);
753 #if defined(ENABLE_INTRP)
754 /* set interpreter stack */
757 THREADINFO->_global_sp = (void *) (intrp_thread_stack + opt_stacksize);
760 /* find and run the Thread.run()V method if no other function was passed */
762 if (function == NULL) {
763 method = class_resolveclassmethod(thread->o.header.vftbl->class,
766 thread->o.header.vftbl->class,
772 ASM_CALLJAVAFUNCTION(method, thread, NULL, NULL, NULL);
775 /* call passed function, e.g. finalizer_thread */
780 /* Allow lock record pools to be used by other threads. They
781 cannot be deleted so we'd better not waste them. */
783 freeLockRecordPools(thread->ee.lrpool);
785 /* remove thread from thread list, do this inside a lock */
787 pthread_mutex_lock(&threadlistlock);
788 info->next->info.prev = info->prev;
789 info->prev->info.next = info->next;
790 pthread_mutex_unlock(&threadlistlock);
792 /* reset thread id (lock on joinMutex? TWISTI) */
794 pthread_mutex_lock(&info->joinMutex);
796 pthread_mutex_unlock(&info->joinMutex);
798 pthread_cond_broadcast(&info->joinCond);
804 /* threads_start_thread ********************************************************
806 Start a thread in the JVM.
808 ******************************************************************************/
810 void threads_start_thread(thread *t, functionptr function)
817 info = &((threadobject *) t->vmThread)->info;
819 /* fill startupinfo structure passed by pthread_create to XXX */
821 startup.thread = (threadobject*) t->vmThread;
822 startup.function = function; /* maybe we don't call Thread.run()V */
824 startup.psem_first = &sem_first;
826 sem_init(&sem, 0, 0);
827 sem_init(&sem_first, 0, 0);
829 if (pthread_create(&info->tid, &threadattr, threads_startup_thread,
831 log_text("pthread_create failed");
835 sem_post(&sem_first);
837 /* wait here until the thread has entered itself into the thread list */
841 sem_destroy(&sem_first);
845 /* At the end of the program, we wait for all running non-daemon threads to die
848 static threadobject *findNonDaemon(threadobject *thread)
850 while (thread != mainthreadobj) {
851 if (!thread->o.thread->daemon)
853 thread = thread->info.prev;
859 void joinAllThreads()
861 threadobject *thread;
862 pthread_mutex_lock(&threadlistlock);
863 while ((thread = findNonDaemon(mainthreadobj->info.prev)) != NULL) {
864 nativethread *info = &thread->info;
865 pthread_mutex_lock(&info->joinMutex);
866 pthread_mutex_unlock(&threadlistlock);
868 pthread_cond_wait(&info->joinCond, &info->joinMutex);
869 pthread_mutex_unlock(&info->joinMutex);
870 pthread_mutex_lock(&threadlistlock);
872 pthread_mutex_unlock(&threadlistlock);
875 static void initLockRecord(monitorLockRecord *r, threadobject *t)
882 r->incharge = (monitorLockRecord *) &dummyLR;
884 sem_init(&r->queueSem, 0, 0);
885 pthread_mutex_init(&r->resolveLock, NULL);
886 pthread_cond_init(&r->resolveWait, NULL);
889 /* No lock record must ever be destroyed because there may still be references
892 static void destroyLockRecord(monitorLockRecord *r)
894 sem_destroy(&r->queueSem);
895 pthread_mutex_destroy(&r->resolveLock);
896 pthread_cond_destroy(&r->resolveWait);
902 initThreadLocks(mainthreadobj);
905 static void initThreadLocks(threadobject *thread)
907 thread->ee.firstLR = NULL;
908 thread->ee.lrpool = NULL;
909 thread->ee.numlr = 0;
912 static lockRecordPool *allocNewLockRecordPool(threadobject *thread, int size)
914 lockRecordPool *p = mem_alloc(sizeof(lockRecordPoolHeader) + sizeof(monitorLockRecord) * size);
917 p->header.size = size;
918 for (i=0; i<size; i++) {
919 initLockRecord(&p->lr[i], thread);
920 p->lr[i].nextFree = &p->lr[i+1];
922 p->lr[i-1].nextFree = NULL;
926 #define INITIALLOCKRECORDS 8
928 pthread_mutex_t pool_lock;
929 lockRecordPool *global_pool;
931 static void initPools()
933 pthread_mutex_init(&pool_lock, NULL);
936 static lockRecordPool *allocLockRecordPool(threadobject *t, int size)
938 pthread_mutex_lock(&pool_lock);
941 lockRecordPool *pool = global_pool;
942 global_pool = pool->header.next;
943 pthread_mutex_unlock(&pool_lock);
945 for (i=0; i < pool->header.size; i++)
946 pool->lr[i].ownerThread = t;
950 pthread_mutex_unlock(&pool_lock);
952 return allocNewLockRecordPool(t, size);
955 static void freeLockRecordPools(lockRecordPool *pool)
957 lockRecordPoolHeader *last;
958 pthread_mutex_lock(&pool_lock);
959 last = &pool->header;
961 last = &last->next->header;
962 last->next = global_pool;
964 pthread_mutex_unlock(&pool_lock);
967 static monitorLockRecord *allocLockRecordSimple(threadobject *t)
969 monitorLockRecord *r = t->ee.firstLR;
972 int poolsize = t->ee.numlr ? t->ee.numlr * 2 : INITIALLOCKRECORDS;
973 lockRecordPool *pool = allocLockRecordPool(t, poolsize);
974 pool->header.next = t->ee.lrpool;
977 t->ee.numlr += pool->header.size;
980 t->ee.firstLR = r->nextFree;
984 static inline void recycleLockRecord(threadobject *t, monitorLockRecord *r)
986 r->nextFree = t->ee.firstLR;
990 void initObjectLock(java_objectheader *o)
992 o->monitorPtr = dummyLR;
996 /* get_dummyLR *****************************************************************
998 Returns the global dummy monitor lock record. The pointer is
999 required in the code generator to set up a virtual
1000 java_objectheader for code patch locking.
1002 *******************************************************************************/
1004 monitorLockRecord *get_dummyLR(void)
1010 static void queueOnLockRecord(monitorLockRecord *lr, java_objectheader *o)
1012 atomic_add(&lr->queuers, 1);
1014 MEMORY_BARRIER_AFTER_ATOMIC();
1017 sem_wait(&lr->queueSem);
1019 atomic_add(&lr->queuers, -1);
1022 static void freeLockRecord(monitorLockRecord *lr)
1029 sem_post(&lr->queueSem);
1032 static inline void handleWaiter(monitorLockRecord *mlr, monitorLockRecord *lr)
1038 monitorLockRecord *monitorEnter(threadobject *t, java_objectheader *o)
1041 monitorLockRecord *lr = o->monitorPtr;
1043 monitorLockRecord *nlr, *mlr = allocLockRecordSimple(t);
1047 nlr = o->monitorPtr;
1049 handleWaiter(mlr, lr);
1053 if (lr->ownerThread != t)
1055 MEMORY_BARRIER_BEFORE_ATOMIC();
1056 nlr = (void*) compare_and_swap((long*) &o->monitorPtr, (long) lr, (long) mlr);
1059 if (mlr == lr || lr->o != o) {
1060 handleWaiter(mlr, lr);
1064 queueOnLockRecord(lr, o);
1065 handleWaiter(mlr, lr);
1068 freeLockRecord(mlr);
1069 recycleLockRecord(t, mlr);
1070 queueOnLockRecord(nlr, o);
1072 if (lr->ownerThread == t) {
1076 queueOnLockRecord(lr, o);
1081 static void wakeWaiters(monitorLockRecord *lr)
1083 monitorLockRecord *tmplr;
1086 /* assign lock record to a temporary variable */
1094 sem_post(&tmplr->queueSem);
1096 tmplr = tmplr->waiter;
1097 } while (tmplr != NULL && tmplr != lr);
1100 #define GRAB_LR(lr,t) \
1101 if (lr->ownerThread != t) { \
1102 lr = lr->incharge; \
1105 #define CHECK_MONITORSTATE(lr,t,mo,a) \
1106 if (lr == NULL || lr->o != mo || lr->ownerThread != t) { \
1107 *exceptionptr = new_illegalmonitorstateexception(); \
1111 bool monitorExit(threadobject *t, java_objectheader *o)
1113 monitorLockRecord *lr = o->monitorPtr;
1115 CHECK_MONITORSTATE(lr, t, o, return false);
1116 if (lr->lockCount > 1) {
1121 monitorLockRecord *wlr = lr->waiter;
1122 if (o->monitorPtr != lr ||
1123 (void*) compare_and_swap((long*) &o->monitorPtr, (long) lr, (long) wlr) != lr)
1125 monitorLockRecord *nlr = o->monitorPtr;
1127 STORE_ORDER_BARRIER();
1133 recycleLockRecord(t, lr);
1137 static void removeFromWaiters(monitorLockRecord *lr, monitorLockRecord *wlr)
1140 if (lr->waiter == wlr) {
1141 lr->waiter = wlr->waiter;
1148 static inline bool timespec_less(const struct timespec *tv1, const struct timespec *tv2)
1150 return tv1->tv_sec < tv2->tv_sec || (tv1->tv_sec == tv2->tv_sec && tv1->tv_nsec < tv2->tv_nsec);
1153 static bool timeIsEarlier(const struct timespec *tv)
1155 struct timeval tvnow;
1156 struct timespec tsnow;
1157 gettimeofday(&tvnow, NULL);
1158 tsnow.tv_sec = tvnow.tv_sec;
1159 tsnow.tv_nsec = tvnow.tv_usec * 1000;
1160 return timespec_less(&tsnow, tv);
1164 /* waitWithTimeout *************************************************************
1168 *******************************************************************************/
1170 static bool waitWithTimeout(threadobject *t, monitorLockRecord *lr, struct timespec *wakeupTime)
1172 bool wasinterrupted;
1174 pthread_mutex_lock(&t->waitLock);
1176 t->isSleeping = true;
1178 if (wakeupTime->tv_sec || wakeupTime->tv_nsec)
1179 while (!t->interrupted && !t->signaled && timeIsEarlier(wakeupTime))
1180 pthread_cond_timedwait(&t->waitCond, &t->waitLock, wakeupTime);
1182 while (!t->interrupted && !t->signaled)
1183 pthread_cond_wait(&t->waitCond, &t->waitLock);
1185 wasinterrupted = t->interrupted;
1186 t->interrupted = false;
1187 t->signaled = false;
1188 t->isSleeping = false;
1190 pthread_mutex_unlock(&t->waitLock);
1192 return wasinterrupted;
1196 static void calcAbsoluteTime(struct timespec *tm, s8 millis, s4 nanos)
1198 if (millis || nanos) {
1201 gettimeofday(&tv, NULL);
1202 tv.tv_sec += millis / 1000;
1204 nsec = tv.tv_usec * 1000 + (s4) millis * 1000000 + nanos;
1205 tm->tv_sec = tv.tv_sec + nsec / 1000000000;
1206 tm->tv_nsec = nsec % 1000000000;
1213 void monitorWait(threadobject *t, java_objectheader *o, s8 millis, s4 nanos)
1215 bool wasinterrupted;
1216 struct timespec wakeupTime;
1217 monitorLockRecord *mlr, *lr = o->monitorPtr;
1219 CHECK_MONITORSTATE(lr, t, o, return);
1221 calcAbsoluteTime(&wakeupTime, millis, nanos);
1224 wakeWaiters(lr->waiter);
1226 STORE_ORDER_BARRIER();
1228 wasinterrupted = waitWithTimeout(t, lr, &wakeupTime);
1229 mlr = monitorEnter(t, o);
1230 removeFromWaiters(mlr, lr);
1231 mlr->lockCount = lr->lockCount;
1233 lr->waiting = false;
1235 recycleLockRecord(t, lr);
1238 *exceptionptr = new_exception(string_java_lang_InterruptedException);
1241 static void notifyOneOrAll(threadobject *t, java_objectheader *o, bool one)
1243 monitorLockRecord *lr = o->monitorPtr;
1245 CHECK_MONITORSTATE(lr, t, o, return);
1247 threadobject *wthread;
1248 monitorLockRecord *wlr = lr->waiter;
1251 wthread = wlr->ownerThread;
1252 pthread_mutex_lock(&wthread->waitLock);
1253 if (wthread->isSleeping)
1254 pthread_cond_signal(&wthread->waitCond);
1255 wthread->signaled = true;
1256 pthread_mutex_unlock(&wthread->waitLock);
1261 bool threadHoldsLock(threadobject *t, java_objectheader *o)
1263 monitorLockRecord *lr = o->monitorPtr;
1265 /* The reason why we have to check against NULL is that
1266 * dummyLR->incharge == NULL */
1267 return lr && lr->o == o && lr->ownerThread == t;
1270 void interruptThread(java_lang_VMThread *thread)
1272 threadobject *t = (threadobject*) thread;
1274 t->interrupted = true;
1275 pthread_mutex_lock(&t->waitLock);
1277 pthread_cond_signal(&t->waitCond);
1278 pthread_mutex_unlock(&t->waitLock);
1281 bool interruptedThread()
1283 threadobject *t = (threadobject*) THREADOBJECT;
1284 bool intr = t->interrupted;
1285 t->interrupted = false;
1289 bool isInterruptedThread(java_lang_VMThread *thread)
1291 threadobject *t = (threadobject*) thread;
1292 return t->interrupted;
1295 void sleepThread(s8 millis, s4 nanos)
1297 bool wasinterrupted;
1298 threadobject *t = (threadobject*) THREADOBJECT;
1299 monitorLockRecord *lr;
1300 struct timespec wakeupTime;
1301 calcAbsoluteTime(&wakeupTime, millis, nanos);
1303 lr = allocLockRecordSimple(t);
1304 wasinterrupted = waitWithTimeout(t, lr, &wakeupTime);
1305 recycleLockRecord(t, lr);
1308 *exceptionptr = new_exception(string_java_lang_InterruptedException);
1316 void setPriorityThread(thread *t, s4 priority)
1318 nativethread *info = &((threadobject*) t->vmThread)->info;
1319 setPriority(info->tid, priority);
1322 void wait_cond_for_object(java_objectheader *o, s8 time, s4 nanos)
1324 threadobject *t = (threadobject*) THREADOBJECT;
1325 monitorWait(t, o, time, nanos);
1328 void signal_cond_for_object(java_objectheader *o)
1330 threadobject *t = (threadobject*) THREADOBJECT;
1331 notifyOneOrAll(t, o, true);
1334 void broadcast_cond_for_object(java_objectheader *o)
1336 threadobject *t = (threadobject*) THREADOBJECT;
1337 notifyOneOrAll(t, o, false);
1341 /* threads_dump ****************************************************************
1343 Dumps info for all threads running in the JVM. This function is
1344 called when SIGQUIT (<ctrl>-\) is sent to CACAO.
1346 *******************************************************************************/
1348 void threads_dump(void)
1351 java_lang_VMThread *vmt;
1353 ExecEnvironment *ee;
1354 java_lang_Thread *t;
1357 tobj = mainthreadobj;
1359 printf("Full thread dump CACAO "VERSION":\n");
1361 /* iterate over all started threads */
1364 /* get thread objects */
1371 /* the thread may be currently in initalization, don't print it */
1374 /* get thread name */
1376 name = javastring_toutf(t->name, false);
1385 #if SIZEOF_VOID_P == 8
1386 printf("prio=%d tid=0x%016lx\n", t->priority, nt->tid);
1388 printf("prio=%d tid=0x%08lx\n", t->priority, nt->tid);
1391 /* send SIGUSR1 to thread to print stacktrace */
1393 pthread_kill(nt->tid, SIGUSR1);
1395 /* sleep this thread a bit, so the signal can reach the thread */
1400 tobj = tobj->info.next;
1401 } while (tobj && (tobj != mainthreadobj));
1406 * These are local overrides for various environment variables in Emacs.
1407 * Please do not remove this and leave it at the end of the file, where
1408 * Emacs will automagically detect them.
1409 * ---------------------------------------------------------------------
1412 * indent-tabs-mode: t