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 3830 2005-12-01 23:07:33Z 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 struct avl_table *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);
191 static int criticalcompare(const void *pa, const void *pb, void *param)
193 const threadcritnode *na = pa;
194 const threadcritnode *nb = pb;
196 if (na->mcodebegin < nb->mcodebegin)
198 if (na->mcodebegin > nb->mcodebegin)
203 static const threadcritnode *findcritical(u1 *mcodeptr)
205 struct avl_node *n = criticaltree->avl_root;
206 const threadcritnode *m = NULL;
211 const threadcritnode *d = n->avl_data;
212 if (mcodeptr == d->mcodebegin)
214 if (mcodeptr < d->mcodebegin) {
220 if (n->avl_link[1]) {
229 void thread_registercritical(threadcritnode *n)
231 avl_insert(criticaltree, n);
234 u1 *thread_checkcritical(u1 *mcodeptr)
236 const threadcritnode *n = findcritical(mcodeptr);
237 return (n && mcodeptr < n->mcodeend && mcodeptr > n->mcodebegin) ? n->mcoderestart : NULL;
240 static void thread_addstaticcritical()
242 threadcritnode *n = &asm_criticalsections;
244 while (n->mcodebegin)
245 thread_registercritical(n++);
248 static pthread_mutex_t threadlistlock;
250 static pthread_mutex_t stopworldlock;
251 volatile int stopworldwhere;
253 static sem_t suspend_ack;
254 #if defined(__MIPS__)
255 static pthread_mutex_t suspend_ack_lock = PTHREAD_MUTEX_INITIALIZER;
256 static pthread_cond_t suspend_cond = PTHREAD_COND_INITIALIZER;
260 * where - 1 from within GC
263 void lock_stopworld(int where)
265 pthread_mutex_lock(&stopworldlock);
266 stopworldwhere = where;
269 void unlock_stopworld()
272 pthread_mutex_unlock(&stopworldlock);
275 #if !defined(__DARWIN__)
276 /* Caller must hold threadlistlock */
277 static int cast_sendsignals(int sig, int count)
280 threadobject *tobj = mainthreadobj;
281 nativethread *infoself = THREADINFO;
286 tobj = tobj->info.next;
287 } while (tobj != mainthreadobj);
290 nativethread *info = &tobj->info;
291 if (info != infoself)
292 pthread_kill(info->tid, sig);
293 tobj = tobj->info.next;
294 } while (tobj != mainthreadobj);
301 static void cast_darwinstop()
303 threadobject *tobj = mainthreadobj;
304 nativethread *infoself = THREADINFO;
307 nativethread *info = &tobj->info;
308 if (info != infoself)
310 thread_state_flavor_t flavor = PPC_THREAD_STATE;
311 mach_msg_type_number_t thread_state_count = PPC_THREAD_STATE_COUNT;
312 ppc_thread_state_t thread_state;
313 mach_port_t thread = info->mach_thread;
316 r = thread_suspend(thread);
317 if (r != KERN_SUCCESS) {
318 log_text("thread_suspend failed");
322 r = thread_get_state(thread, flavor,
323 (natural_t*)&thread_state, &thread_state_count);
324 if (r != KERN_SUCCESS) {
325 log_text("thread_get_state failed");
329 thread_restartcriticalsection(&thread_state);
331 r = thread_set_state(thread, flavor,
332 (natural_t*)&thread_state, thread_state_count);
333 if (r != KERN_SUCCESS) {
334 log_text("thread_set_state failed");
338 tobj = tobj->info.next;
339 } while (tobj != mainthreadobj);
342 static void cast_darwinresume()
344 threadobject *tobj = mainthreadobj;
345 nativethread *infoself = THREADINFO;
348 nativethread *info = &tobj->info;
349 if (info != infoself)
351 mach_port_t thread = info->mach_thread;
354 r = thread_resume(thread);
355 if (r != KERN_SUCCESS) {
356 log_text("thread_resume failed");
360 tobj = tobj->info.next;
361 } while (tobj != mainthreadobj);
366 #if defined(__MIPS__)
367 static void cast_irixresume()
369 pthread_mutex_lock(&suspend_ack_lock);
370 pthread_cond_broadcast(&suspend_cond);
371 pthread_mutex_unlock(&suspend_ack_lock);
375 void cast_stopworld()
379 pthread_mutex_lock(&threadlistlock);
380 #if defined(__DARWIN__)
383 count = cast_sendsignals(GC_signum1(), 0);
384 for (i=0; i<count; i++)
385 sem_wait(&suspend_ack);
387 pthread_mutex_unlock(&threadlistlock);
390 void cast_startworld()
392 pthread_mutex_lock(&threadlistlock);
393 #if defined(__DARWIN__)
395 #elif defined(__MIPS__)
398 cast_sendsignals(GC_signum2(), -1);
400 pthread_mutex_unlock(&threadlistlock);
404 #if !defined(__DARWIN__)
405 static void sigsuspend_handler(ucontext_t *ctx)
410 thread_restartcriticalsection(ctx);
412 /* Do as Boehm does. On IRIX a condition variable is used for wake-up
413 (not POSIX async-safe). */
414 #if defined(__IRIX__)
415 pthread_mutex_lock(&suspend_ack_lock);
416 sem_post(&suspend_ack);
417 pthread_cond_wait(&suspend_cond, &suspend_ack_lock);
418 pthread_mutex_unlock(&suspend_ack_lock);
420 sem_post(&suspend_ack);
424 sigdelset(&sigs, sig);
429 int cacao_suspendhandler(ucontext_t *ctx)
431 if (stopworldwhere != 2)
434 sigsuspend_handler(ctx);
439 static void setthreadobject(threadobject *thread)
441 #if !defined(HAVE___THREAD)
442 pthread_setspecific(tkey_threadinfo, thread);
449 /* thread_setself **************************************************************
453 *******************************************************************************/
455 void *thread_getself(void)
457 return pthread_getspecific(tkey_threadinfo);
461 static monitorLockRecord *dummyLR;
463 static void initPools();
466 /* thread_preinit **************************************************************
468 Do some early initialization of stuff required.
470 *******************************************************************************/
472 void threads_preinit(void)
475 pthread_mutexattr_t mutexattr;
476 pthread_mutexattr_init(&mutexattr);
477 pthread_mutexattr_settype(&mutexattr, PTHREAD_MUTEX_RECURSIVE);
478 pthread_mutex_init(&compiler_mutex, &mutexattr);
479 pthread_mutex_init(&tablelock, &mutexattr);
480 pthread_mutexattr_destroy(&mutexattr);
482 pthread_mutex_init_rec(&compiler_mutex);
483 pthread_mutex_init_rec(&tablelock);
486 pthread_mutex_init(&threadlistlock, NULL);
487 pthread_mutex_init(&stopworldlock, NULL);
489 /* Allocate something so the garbage collector's signal handlers
491 heap_allocate(1, false, NULL);
493 mainthreadobj = NEW(threadobject);
494 mainthreadobj->info.tid = pthread_self();
495 #if !defined(HAVE___THREAD)
496 pthread_key_create(&tkey_threadinfo, NULL);
498 setthreadobject(mainthreadobj);
501 criticaltree = avl_create(criticalcompare, NULL, NULL);
502 thread_addstaticcritical();
503 sem_init(&suspend_ack, 0, 0);
505 /* Every newly created object's monitorPtr points here so we save
506 a check against NULL */
507 dummyLR = NEW(monitorLockRecord);
509 dummyLR->ownerThread = NULL;
510 dummyLR->waiting = false;
513 static pthread_attr_t threadattr;
515 static void freeLockRecordPools(lockRecordPool *);
518 /* threads_init ****************************************************************
520 Initializes the threads required by the JVM: main, finalizer.
522 *******************************************************************************/
524 bool threads_init(u1 *stackbottom)
526 java_lang_String *threadname;
527 java_lang_Thread *mainthread;
528 java_lang_ThreadGroup *threadgroup;
529 threadobject *tempthread;
532 tempthread = mainthreadobj;
534 freeLockRecordPools(mainthreadobj->ee.lrpool);
536 /* This is kinda tricky, we grow the java.lang.Thread object so we
537 can keep the execution environment there. No Thread object must
538 have been created at an earlier time. */
540 class_java_lang_VMThread->instancesize = sizeof(threadobject);
542 /* create a VMThread */
544 mainthreadobj = (threadobject *) builtin_new(class_java_lang_VMThread);
549 FREE(tempthread, threadobject);
551 initThread(&mainthreadobj->o);
553 setthreadobject(mainthreadobj);
557 mainthreadobj->info.next = mainthreadobj;
558 mainthreadobj->info.prev = mainthreadobj;
560 #if defined(ENABLE_INTRP)
561 /* create interpreter stack */
564 MSET(intrp_main_stack, 0, u1, opt_stacksize);
565 mainthreadobj->info._global_sp = intrp_main_stack + opt_stacksize;
569 threadname = javastring_new(utf_new_char("main"));
571 /* allocate and init ThreadGroup */
573 threadgroup = (java_lang_ThreadGroup *)
574 native_new_and_init(class_java_lang_ThreadGroup);
577 throw_exception_exit();
579 /* create a Thread */
581 mainthread = (java_lang_Thread *) builtin_new(class_java_lang_Thread);
584 throw_exception_exit();
586 mainthreadobj->o.thread = mainthread;
588 /* call Thread.<init>(Ljava/lang/VMThread;Ljava/lang/String;IZ)V */
590 method = class_resolveclassmethod(class_java_lang_Thread,
592 utf_new_char("(Ljava/lang/VMThread;Ljava/lang/String;IZ)V"),
593 class_java_lang_Thread,
599 asm_calljavafunction(method, mainthread, mainthreadobj, threadname, (void*) 5);
603 mainthread->group = threadgroup;
604 /* XXX This is a hack because the fourth argument was omitted */
605 mainthread->daemon = false;
607 /* add mainthread to ThreadGroup */
609 method = class_resolveclassmethod(class_java_lang_ThreadGroup,
610 utf_new_char("addThread"),
611 utf_new_char("(Ljava/lang/Thread;)V"),
612 class_java_lang_ThreadGroup,
618 asm_calljavafunction(method, threadgroup, mainthread, NULL, NULL);
623 setPriority(pthread_self(), 5);
625 pthread_attr_init(&threadattr);
626 pthread_attr_setdetachstate(&threadattr, PTHREAD_CREATE_DETACHED);
628 /* everything's ok */
634 void initThread(java_lang_VMThread *t)
636 threadobject *thread = (threadobject*) t;
637 nativethread *info = &thread->info;
638 info->tid = pthread_self();
639 /* TODO destroy all those things */
640 pthread_mutex_init(&info->joinMutex, NULL);
641 pthread_cond_init(&info->joinCond, NULL);
643 pthread_mutex_init(&thread->waitLock, NULL);
644 pthread_cond_init(&thread->waitCond, NULL);
645 thread->interrupted = false;
646 thread->signaled = false;
647 thread->isSleeping = false;
650 static void initThreadLocks(threadobject *);
654 threadobject *thread;
655 functionptr function;
661 /* threads_startup *************************************************************
663 Thread startup function called by pthread_create.
665 ******************************************************************************/
667 static void *threads_startup_thread(void *t)
669 startupinfo *startup;
670 threadobject *thread;
675 functionptr function;
677 #if defined(ENABLE_INTRP)
678 u1 *intrp_thread_stack;
680 /* create interpreter stack */
683 intrp_thread_stack = (u1 *) alloca(opt_stacksize);
684 MSET(intrp_thread_stack, 0, u1, opt_stacksize);
688 /* get passed startupinfo structure and the values in there */
692 thread = startup->thread;
693 function = startup->function;
694 psem = startup->psem;
696 info = &thread->info;
698 /* Seems like we've encountered a situation where info->tid was not set by
699 * pthread_create. We alleviate this problem by waiting for pthread_create
701 sem_wait(startup->psem_first);
704 #if defined(__DARWIN__)
705 info->mach_thread = mach_thread_self();
707 setthreadobject(thread);
709 /* insert the thread into the threadlist */
711 pthread_mutex_lock(&threadlistlock);
713 info->prev = mainthreadobj;
714 info->next = tnext = mainthreadobj->info.next;
715 mainthreadobj->info.next = thread;
716 tnext->info.prev = thread;
718 pthread_mutex_unlock(&threadlistlock);
720 initThreadLocks(thread);
725 setPriority(info->tid, thread->o.thread->priority);
727 #if defined(ENABLE_INTRP)
728 /* set interpreter stack */
731 THREADINFO->_global_sp = (void *) (intrp_thread_stack + opt_stacksize);
734 /* find and run the Thread.run()V method if no other function was passed */
736 if (function == NULL) {
737 method = class_resolveclassmethod(thread->o.header.vftbl->class,
740 thread->o.header.vftbl->class,
746 asm_calljavafunction(method, thread, NULL, NULL, NULL);
749 /* call passed function, e.g. finalizer_thread */
754 /* Allow lock record pools to be used by other threads. They
755 cannot be deleted so we'd better not waste them. */
757 freeLockRecordPools(thread->ee.lrpool);
759 /* remove thread from thread list, do this inside a lock */
761 pthread_mutex_lock(&threadlistlock);
762 info->next->info.prev = info->prev;
763 info->prev->info.next = info->next;
764 pthread_mutex_unlock(&threadlistlock);
766 /* reset thread id (lock on joinMutex? TWISTI) */
768 pthread_mutex_lock(&info->joinMutex);
770 pthread_mutex_unlock(&info->joinMutex);
772 pthread_cond_broadcast(&info->joinCond);
778 /* threads_start_thread ********************************************************
780 Start a thread in the JVM.
782 ******************************************************************************/
784 void threads_start_thread(thread *t, functionptr function)
791 info = &((threadobject *) t->vmThread)->info;
793 /* fill startupinfo structure passed by pthread_create to XXX */
795 startup.thread = (threadobject*) t->vmThread;
796 startup.function = function; /* maybe we don't call Thread.run()V */
798 startup.psem_first = &sem_first;
800 sem_init(&sem, 0, 0);
801 sem_init(&sem_first, 0, 0);
803 if (pthread_create(&info->tid, &threadattr, threads_startup_thread,
805 log_text("pthread_create failed");
809 sem_post(&sem_first);
811 /* wait here until the thread has entered itself into the thread list */
815 sem_destroy(&sem_first);
819 /* At the end of the program, we wait for all running non-daemon threads to die
822 static threadobject *findNonDaemon(threadobject *thread)
824 while (thread != mainthreadobj) {
825 if (!thread->o.thread->daemon)
827 thread = thread->info.prev;
833 void joinAllThreads()
835 threadobject *thread;
836 pthread_mutex_lock(&threadlistlock);
837 while ((thread = findNonDaemon(mainthreadobj->info.prev)) != NULL) {
838 nativethread *info = &thread->info;
839 pthread_mutex_lock(&info->joinMutex);
840 pthread_mutex_unlock(&threadlistlock);
842 pthread_cond_wait(&info->joinCond, &info->joinMutex);
843 pthread_mutex_unlock(&info->joinMutex);
844 pthread_mutex_lock(&threadlistlock);
846 pthread_mutex_unlock(&threadlistlock);
849 static void initLockRecord(monitorLockRecord *r, threadobject *t)
856 r->incharge = (monitorLockRecord *) &dummyLR;
858 sem_init(&r->queueSem, 0, 0);
859 pthread_mutex_init(&r->resolveLock, NULL);
860 pthread_cond_init(&r->resolveWait, NULL);
863 /* No lock record must ever be destroyed because there may still be references
866 static void destroyLockRecord(monitorLockRecord *r)
868 sem_destroy(&r->queueSem);
869 pthread_mutex_destroy(&r->resolveLock);
870 pthread_cond_destroy(&r->resolveWait);
876 initThreadLocks(mainthreadobj);
879 static void initThreadLocks(threadobject *thread)
881 thread->ee.firstLR = NULL;
882 thread->ee.lrpool = NULL;
883 thread->ee.numlr = 0;
886 static lockRecordPool *allocNewLockRecordPool(threadobject *thread, int size)
888 lockRecordPool *p = mem_alloc(sizeof(lockRecordPoolHeader) + sizeof(monitorLockRecord) * size);
891 p->header.size = size;
892 for (i=0; i<size; i++) {
893 initLockRecord(&p->lr[i], thread);
894 p->lr[i].nextFree = &p->lr[i+1];
896 p->lr[i-1].nextFree = NULL;
900 #define INITIALLOCKRECORDS 8
902 pthread_mutex_t pool_lock;
903 lockRecordPool *global_pool;
905 static void initPools()
907 pthread_mutex_init(&pool_lock, NULL);
910 static lockRecordPool *allocLockRecordPool(threadobject *t, int size)
912 pthread_mutex_lock(&pool_lock);
915 lockRecordPool *pool = global_pool;
916 global_pool = pool->header.next;
917 pthread_mutex_unlock(&pool_lock);
919 for (i=0; i < pool->header.size; i++)
920 pool->lr[i].ownerThread = t;
924 pthread_mutex_unlock(&pool_lock);
926 return allocNewLockRecordPool(t, size);
929 static void freeLockRecordPools(lockRecordPool *pool)
931 lockRecordPoolHeader *last;
932 pthread_mutex_lock(&pool_lock);
933 last = &pool->header;
935 last = &last->next->header;
936 last->next = global_pool;
938 pthread_mutex_unlock(&pool_lock);
941 static monitorLockRecord *allocLockRecordSimple(threadobject *t)
943 monitorLockRecord *r = t->ee.firstLR;
946 int poolsize = t->ee.numlr ? t->ee.numlr * 2 : INITIALLOCKRECORDS;
947 lockRecordPool *pool = allocLockRecordPool(t, poolsize);
948 pool->header.next = t->ee.lrpool;
951 t->ee.numlr += pool->header.size;
954 t->ee.firstLR = r->nextFree;
958 static inline void recycleLockRecord(threadobject *t, monitorLockRecord *r)
960 r->nextFree = t->ee.firstLR;
964 void initObjectLock(java_objectheader *o)
966 o->monitorPtr = dummyLR;
970 /* get_dummyLR *****************************************************************
972 Returns the global dummy monitor lock record. The pointer is
973 required in the code generator to set up a virtual
974 java_objectheader for code patch locking.
976 *******************************************************************************/
978 monitorLockRecord *get_dummyLR(void)
984 static void queueOnLockRecord(monitorLockRecord *lr, java_objectheader *o)
986 atomic_add(&lr->queuers, 1);
988 MEMORY_BARRIER_AFTER_ATOMIC();
991 sem_wait(&lr->queueSem);
993 atomic_add(&lr->queuers, -1);
996 static void freeLockRecord(monitorLockRecord *lr)
1003 sem_post(&lr->queueSem);
1006 static inline void handleWaiter(monitorLockRecord *mlr, monitorLockRecord *lr)
1012 monitorLockRecord *monitorEnter(threadobject *t, java_objectheader *o)
1015 monitorLockRecord *lr = o->monitorPtr;
1017 monitorLockRecord *nlr, *mlr = allocLockRecordSimple(t);
1021 nlr = o->monitorPtr;
1023 handleWaiter(mlr, lr);
1027 if (lr->ownerThread != t)
1029 MEMORY_BARRIER_BEFORE_ATOMIC();
1030 nlr = (void*) compare_and_swap((long*) &o->monitorPtr, (long) lr, (long) mlr);
1033 if (mlr == lr || lr->o != o) {
1034 handleWaiter(mlr, lr);
1038 queueOnLockRecord(lr, o);
1039 handleWaiter(mlr, lr);
1042 freeLockRecord(mlr);
1043 recycleLockRecord(t, mlr);
1044 queueOnLockRecord(nlr, o);
1046 if (lr->ownerThread == t) {
1050 queueOnLockRecord(lr, o);
1055 static void wakeWaiters(monitorLockRecord *lr)
1057 monitorLockRecord *tmplr;
1060 /* assign lock record to a temporary variable */
1068 sem_post(&tmplr->queueSem);
1070 tmplr = tmplr->waiter;
1071 } while (tmplr != NULL && tmplr != lr);
1074 #define GRAB_LR(lr,t) \
1075 if (lr->ownerThread != t) { \
1076 lr = lr->incharge; \
1079 #define CHECK_MONITORSTATE(lr,t,mo,a) \
1080 if (lr == NULL || lr->o != mo || lr->ownerThread != t) { \
1081 *exceptionptr = new_illegalmonitorstateexception(); \
1085 bool monitorExit(threadobject *t, java_objectheader *o)
1087 monitorLockRecord *lr = o->monitorPtr;
1089 CHECK_MONITORSTATE(lr, t, o, return false);
1090 if (lr->lockCount > 1) {
1095 monitorLockRecord *wlr = lr->waiter;
1096 if (o->monitorPtr != lr ||
1097 (void*) compare_and_swap((long*) &o->monitorPtr, (long) lr, (long) wlr) != lr)
1099 monitorLockRecord *nlr = o->monitorPtr;
1101 STORE_ORDER_BARRIER();
1107 recycleLockRecord(t, lr);
1111 static void removeFromWaiters(monitorLockRecord *lr, monitorLockRecord *wlr)
1114 if (lr->waiter == wlr) {
1115 lr->waiter = wlr->waiter;
1122 static inline bool timespec_less(const struct timespec *tv1, const struct timespec *tv2)
1124 return tv1->tv_sec < tv2->tv_sec || (tv1->tv_sec == tv2->tv_sec && tv1->tv_nsec < tv2->tv_nsec);
1127 static bool timeIsEarlier(const struct timespec *tv)
1129 struct timeval tvnow;
1130 struct timespec tsnow;
1131 gettimeofday(&tvnow, NULL);
1132 tsnow.tv_sec = tvnow.tv_sec;
1133 tsnow.tv_nsec = tvnow.tv_usec * 1000;
1134 return timespec_less(&tsnow, tv);
1138 /* waitWithTimeout *************************************************************
1142 *******************************************************************************/
1144 static bool waitWithTimeout(threadobject *t, monitorLockRecord *lr, struct timespec *wakeupTime)
1146 bool wasinterrupted;
1148 pthread_mutex_lock(&t->waitLock);
1150 t->isSleeping = true;
1152 if (wakeupTime->tv_sec || wakeupTime->tv_nsec)
1153 while (!t->interrupted && !t->signaled && timeIsEarlier(wakeupTime))
1154 pthread_cond_timedwait(&t->waitCond, &t->waitLock, wakeupTime);
1156 while (!t->interrupted && !t->signaled)
1157 pthread_cond_wait(&t->waitCond, &t->waitLock);
1159 wasinterrupted = t->interrupted;
1160 t->interrupted = false;
1161 t->signaled = false;
1162 t->isSleeping = false;
1164 pthread_mutex_unlock(&t->waitLock);
1166 return wasinterrupted;
1170 static void calcAbsoluteTime(struct timespec *tm, s8 millis, s4 nanos)
1172 if (millis || nanos) {
1175 gettimeofday(&tv, NULL);
1176 tv.tv_sec += millis / 1000;
1178 nsec = tv.tv_usec * 1000 + (s4) millis * 1000000 + nanos;
1179 tm->tv_sec = tv.tv_sec + nsec / 1000000000;
1180 tm->tv_nsec = nsec % 1000000000;
1187 void monitorWait(threadobject *t, java_objectheader *o, s8 millis, s4 nanos)
1189 bool wasinterrupted;
1190 struct timespec wakeupTime;
1191 monitorLockRecord *mlr, *lr = o->monitorPtr;
1193 CHECK_MONITORSTATE(lr, t, o, return);
1195 calcAbsoluteTime(&wakeupTime, millis, nanos);
1198 wakeWaiters(lr->waiter);
1200 STORE_ORDER_BARRIER();
1202 wasinterrupted = waitWithTimeout(t, lr, &wakeupTime);
1203 mlr = monitorEnter(t, o);
1204 removeFromWaiters(mlr, lr);
1205 mlr->lockCount = lr->lockCount;
1207 lr->waiting = false;
1209 recycleLockRecord(t, lr);
1212 *exceptionptr = new_exception(string_java_lang_InterruptedException);
1215 static void notifyOneOrAll(threadobject *t, java_objectheader *o, bool one)
1217 monitorLockRecord *lr = o->monitorPtr;
1219 CHECK_MONITORSTATE(lr, t, o, return);
1221 threadobject *wthread;
1222 monitorLockRecord *wlr = lr->waiter;
1225 wthread = wlr->ownerThread;
1226 pthread_mutex_lock(&wthread->waitLock);
1227 if (wthread->isSleeping)
1228 pthread_cond_signal(&wthread->waitCond);
1229 wthread->signaled = true;
1230 pthread_mutex_unlock(&wthread->waitLock);
1235 bool threadHoldsLock(threadobject *t, java_objectheader *o)
1237 monitorLockRecord *lr = o->monitorPtr;
1239 /* The reason why we have to check against NULL is that
1240 * dummyLR->incharge == NULL */
1241 return lr && lr->o == o && lr->ownerThread == t;
1244 void interruptThread(java_lang_VMThread *thread)
1246 threadobject *t = (threadobject*) thread;
1248 t->interrupted = true;
1249 pthread_mutex_lock(&t->waitLock);
1251 pthread_cond_signal(&t->waitCond);
1252 pthread_mutex_unlock(&t->waitLock);
1255 bool interruptedThread()
1257 threadobject *t = (threadobject*) THREADOBJECT;
1258 bool intr = t->interrupted;
1259 t->interrupted = false;
1263 bool isInterruptedThread(java_lang_VMThread *thread)
1265 threadobject *t = (threadobject*) thread;
1266 return t->interrupted;
1269 void sleepThread(s8 millis, s4 nanos)
1271 bool wasinterrupted;
1272 threadobject *t = (threadobject*) THREADOBJECT;
1273 monitorLockRecord *lr;
1274 struct timespec wakeupTime;
1275 calcAbsoluteTime(&wakeupTime, millis, nanos);
1277 lr = allocLockRecordSimple(t);
1278 wasinterrupted = waitWithTimeout(t, lr, &wakeupTime);
1279 recycleLockRecord(t, lr);
1282 *exceptionptr = new_exception(string_java_lang_InterruptedException);
1290 void setPriorityThread(thread *t, s4 priority)
1292 nativethread *info = &((threadobject*) t->vmThread)->info;
1293 setPriority(info->tid, priority);
1296 void wait_cond_for_object(java_objectheader *o, s8 time, s4 nanos)
1298 threadobject *t = (threadobject*) THREADOBJECT;
1299 monitorWait(t, o, time, nanos);
1302 void signal_cond_for_object(java_objectheader *o)
1304 threadobject *t = (threadobject*) THREADOBJECT;
1305 notifyOneOrAll(t, o, true);
1308 void broadcast_cond_for_object(java_objectheader *o)
1310 threadobject *t = (threadobject*) THREADOBJECT;
1311 notifyOneOrAll(t, o, false);
1315 /* threads_dump ****************************************************************
1317 Dumps info for all threads running in the JVM. This function is
1318 called when SIGQUIT (<ctrl>-\) is sent to CACAO.
1320 *******************************************************************************/
1322 void threads_dump(void)
1325 java_lang_VMThread *vmt;
1327 ExecEnvironment *ee;
1328 java_lang_Thread *t;
1331 tobj = mainthreadobj;
1333 printf("Full thread dump CACAO "VERSION":\n");
1335 /* iterate over all started threads */
1338 /* get thread objects */
1345 /* the thread may be currently in initalization, don't print it */
1348 /* get thread name */
1350 name = javastring_toutf(t->name, false);
1359 #if SIZEOF_VOID_P == 8
1360 printf("prio=%d tid=0x%016lx\n", t->priority, nt->tid);
1362 printf("prio=%d tid=0x%08lx\n", t->priority, nt->tid);
1365 /* send SIGUSR1 to thread to print stacktrace */
1367 pthread_kill(nt->tid, SIGUSR1);
1369 /* sleep this thread a bit, so the signal can reach the thread */
1374 tobj = tobj->info.next;
1375 } while (tobj && (tobj != mainthreadobj));
1380 * These are local overrides for various environment variables in Emacs.
1381 * Please do not remove this and leave it at the end of the file, where
1382 * Emacs will automagically detect them.
1383 * ---------------------------------------------------------------------
1386 * indent-tabs-mode: t