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
32 $Id: threads.c 5704 2006-10-05 20:30:12Z edwin $
39 /* XXX cleanup these includes */
44 #include <sys/types.h>
57 #if !defined(USE_FAKE_ATOMIC_INSTRUCTIONS)
58 # include "machine-instr.h"
60 # include "threads/native/generic-primitives.h"
64 #include "mm/memory.h"
65 #include "native/native.h"
66 #include "native/include/java_lang_Object.h"
67 #include "native/include/java_lang_Throwable.h"
68 #include "native/include/java_lang_Thread.h"
69 #include "native/include/java_lang_ThreadGroup.h"
70 #include "native/include/java_lang_VMThread.h"
71 #include "threads/native/threads.h"
72 #include "toolbox/avl.h"
73 #include "toolbox/logging.h"
74 #include "vm/builtin.h"
75 #include "vm/exceptions.h"
76 #include "vm/global.h"
77 #include "vm/loader.h"
78 #include "vm/options.h"
79 #include "vm/stringlocal.h"
81 #include "vm/jit/asmpart.h"
83 #if !defined(__DARWIN__)
84 # if defined(__LINUX__)
85 # define GC_LINUX_THREADS
86 # elif defined(__MIPS__)
87 # define GC_IRIX_THREADS
89 # include <semaphore.h>
90 # include "boehm-gc/include/gc.h"
93 #if defined(ENABLE_JVMTI)
94 #include "native/jvmti/cacaodbg.h"
97 #if defined(__DARWIN__)
98 /* Darwin has no working semaphore implementation. This one is taken
102 This is a very simple semaphore implementation for darwin. It
103 is implemented in terms of pthreads calls so it isn't async signal
104 safe. This isn't a problem because signals aren't used to
105 suspend threads on darwin.
108 static int sem_init(sem_t *sem, int pshared, int value)
115 if (pthread_mutex_init(&sem->mutex, NULL) < 0)
118 if (pthread_cond_init(&sem->cond, NULL) < 0)
124 static int sem_post(sem_t *sem)
126 if (pthread_mutex_lock(&sem->mutex) < 0)
131 if (pthread_cond_signal(&sem->cond) < 0) {
132 pthread_mutex_unlock(&sem->mutex);
136 if (pthread_mutex_unlock(&sem->mutex) < 0)
142 static int sem_wait(sem_t *sem)
144 if (pthread_mutex_lock(&sem->mutex) < 0)
147 while (sem->value == 0) {
148 pthread_cond_wait(&sem->cond, &sem->mutex);
153 if (pthread_mutex_unlock(&sem->mutex) < 0)
159 static int sem_destroy(sem_t *sem)
161 if (pthread_cond_destroy(&sem->cond) < 0)
164 if (pthread_mutex_destroy(&sem->mutex) < 0)
169 #endif /* defined(__DARWIN__) */
172 /* internally used constants **************************************************/
174 /* CAUTION: Do not change these values. Boehm GC code depends on them. */
175 #define STOPWORLD_FROM_GC 1
176 #define STOPWORLD_FROM_CLASS_NUMBERING 2
178 #define THREADS_INITIAL_TABLE_SIZE 8
181 /* startupinfo *****************************************************************
183 Struct used to pass info from threads_start_thread to
184 threads_startup_thread.
186 ******************************************************************************/
189 threadobject *thread; /* threadobject for this thread */
190 functionptr function; /* function to run in the new thread */
191 sem_t *psem; /* signals when thread has been entered */
192 /* in the thread list */
193 sem_t *psem_first; /* signals when pthread_create has returned */
197 /* prototypes *****************************************************************/
199 static void threads_table_init(void);
200 static s4 threads_table_add(threadobject *thread);
201 static void threads_table_remove(threadobject *thread);
202 static void threads_calc_absolute_time(struct timespec *tm, s8 millis, s4 nanos);
205 static void threads_table_dump(FILE *file);
208 /******************************************************************************/
209 /* GLOBAL VARIABLES */
210 /******************************************************************************/
212 /* the main thread */
213 threadobject *mainthreadobj;
215 static methodinfo *method_thread_init;
216 static methodinfo *method_threadgroup_add;
218 /* the thread object of the current thread */
219 /* This is either a thread-local variable defined with __thread, or */
220 /* a thread-specific value stored with key threads_current_threadobject_key. */
221 #if defined(HAVE___THREAD)
222 __thread threadobject *threads_current_threadobject;
224 pthread_key_t threads_current_threadobject_key;
227 /* global threads table */
228 static threads_table_t threads_table;
230 /* global compiler mutex */
231 static pthread_mutex_rec_t compiler_mutex;
233 /* global mutex for changing the thread list */
234 static pthread_mutex_t threadlistlock;
236 /* global mutex for stop-the-world */
237 static pthread_mutex_t stopworldlock;
239 /* this is one of the STOPWORLD_FROM_ constants, telling why the world is */
241 static volatile int stopworldwhere;
243 /* semaphore used for acknowleding thread suspension */
244 static sem_t suspend_ack;
245 #if defined(__MIPS__)
246 static pthread_mutex_t suspend_ack_lock = PTHREAD_MUTEX_INITIALIZER;
247 static pthread_cond_t suspend_cond = PTHREAD_COND_INITIALIZER;
250 static pthread_attr_t threadattr;
252 /* mutexes used by the fake atomic instructions */
253 #if defined(USE_FAKE_ATOMIC_INSTRUCTIONS)
254 pthread_mutex_t _atomic_add_lock = PTHREAD_MUTEX_INITIALIZER;
255 pthread_mutex_t _cas_lock = PTHREAD_MUTEX_INITIALIZER;
256 pthread_mutex_t _mb_lock = PTHREAD_MUTEX_INITIALIZER;
260 /******************************************************************************/
261 /* Recursive Mutex Implementation for Darwin */
262 /******************************************************************************/
264 #if defined(MUTEXSIM)
266 /* We need this for older MacOSX (10.1.x) */
268 void pthread_mutex_init_rec(pthread_mutex_rec_t *m)
270 pthread_mutex_init(&m->mutex, NULL);
274 void pthread_mutex_destroy_rec(pthread_mutex_rec_t *m)
276 pthread_mutex_destroy(&m->mutex);
279 void pthread_mutex_lock_rec(pthread_mutex_rec_t *m)
284 pthread_mutex_lock(&m->mutex);
285 m->owner = pthread_self();
290 if (m->owner != pthread_self()) {
291 pthread_mutex_lock(&m->mutex);
301 void pthread_mutex_unlock_rec(pthread_mutex_rec_t *m)
304 pthread_mutex_unlock(&m->mutex);
307 #endif /* defined(MUTEXSIM) */
310 /* threads_sem_init ************************************************************
312 Initialize a semaphore. Checks against errors and interruptions.
315 sem..............the semaphore to initialize
316 shared...........true if this semaphore will be shared between processes
317 value............the initial value for the semaphore
319 *******************************************************************************/
321 void threads_sem_init(sem_t *sem, bool shared, int value)
328 r = sem_init(sem, shared, value);
331 } while (errno == EINTR);
333 vm_abort("sem_init failed: %s", strerror(errno));
337 /* threads_sem_wait ************************************************************
339 Wait for a semaphore, non-interruptible.
341 IMPORTANT: Always use this function instead of `sem_wait` directly, as
342 `sem_wait` may be interrupted by signals!
345 sem..............the semaphore to wait on
347 *******************************************************************************/
349 void threads_sem_wait(sem_t *sem)
359 } while (errno == EINTR);
361 vm_abort("sem_wait failed: %s", strerror(errno));
365 /* threads_sem_post ************************************************************
367 Increase the count of a semaphore. Checks for errors.
370 sem..............the semaphore to increase the count of
372 *******************************************************************************/
374 void threads_sem_post(sem_t *sem)
380 /* unlike sem_wait, sem_post is not interruptible */
386 vm_abort("sem_post failed: %s", strerror(errno));
390 /* threads_set_thread_priority *************************************************
392 Set the priority of the given thread.
395 tid..........thread id
396 priority.....priority to set
398 ******************************************************************************/
400 static void threads_set_thread_priority(pthread_t tid, int priority)
402 struct sched_param schedp;
405 pthread_getschedparam(tid, &policy, &schedp);
406 schedp.sched_priority = priority;
407 pthread_setschedparam(tid, policy, &schedp);
411 /* compiler_lock ***************************************************************
413 Enter the compiler lock.
415 ******************************************************************************/
417 void compiler_lock(void)
419 pthread_mutex_lock_rec(&compiler_mutex);
423 /* compiler_unlock *************************************************************
425 Release the compiler lock.
427 ******************************************************************************/
429 void compiler_unlock(void)
431 pthread_mutex_unlock_rec(&compiler_mutex);
435 /* lock_stopworld **************************************************************
437 Enter the stopworld lock, specifying why the world shall be stopped.
440 where........ STOPWORLD_FROM_GC (1) from within GC
441 STOPWORLD_FROM_CLASS_NUMBERING (2) class numbering
443 ******************************************************************************/
445 void lock_stopworld(int where)
447 pthread_mutex_lock(&stopworldlock);
448 stopworldwhere = where;
452 /* unlock_stopworld ************************************************************
454 Release the stopworld lock.
456 ******************************************************************************/
458 void unlock_stopworld(void)
461 pthread_mutex_unlock(&stopworldlock);
464 #if !defined(__DARWIN__)
465 /* Caller must hold threadlistlock */
466 static int threads_cast_sendsignals(int sig, int count)
469 threadobject *tobj = mainthreadobj;
470 threadobject *self = THREADOBJECT;
476 } while (tobj != mainthreadobj);
479 assert(tobj == mainthreadobj);
483 pthread_kill(tobj->tid, sig);
485 } while (tobj != mainthreadobj);
492 static void threads_cast_darwinstop(void)
494 threadobject *tobj = mainthreadobj;
495 threadobject *self = THREADOBJECT;
500 thread_state_flavor_t flavor = MACHINE_THREAD_STATE;
501 mach_msg_type_number_t thread_state_count = MACHINE_THREAD_STATE_COUNT;
502 #if defined(__I386__)
503 i386_thread_state_t thread_state;
505 ppc_thread_state_t thread_state;
507 mach_port_t thread = tobj->mach_thread;
510 r = thread_suspend(thread);
511 if (r != KERN_SUCCESS) {
512 log_text("thread_suspend failed");
516 r = thread_get_state(thread, flavor,
517 (natural_t*)&thread_state, &thread_state_count);
518 if (r != KERN_SUCCESS) {
519 log_text("thread_get_state failed");
523 thread_restartcriticalsection(&thread_state);
525 r = thread_set_state(thread, flavor,
526 (natural_t*)&thread_state, thread_state_count);
527 if (r != KERN_SUCCESS) {
528 log_text("thread_set_state failed");
533 } while (tobj != mainthreadobj);
536 static void threads_cast_darwinresume(void)
538 threadobject *tobj = mainthreadobj;
539 threadobject *self = THREADOBJECT;
544 mach_port_t thread = tobj->mach_thread;
547 r = thread_resume(thread);
548 if (r != KERN_SUCCESS) {
549 log_text("thread_resume failed");
554 } while (tobj != mainthreadobj);
559 #if defined(__MIPS__)
560 static void threads_cast_irixresume(void)
562 pthread_mutex_lock(&suspend_ack_lock);
563 pthread_cond_broadcast(&suspend_cond);
564 pthread_mutex_unlock(&suspend_ack_lock);
568 void threads_cast_stopworld(void)
571 lock_stopworld(STOPWORLD_FROM_CLASS_NUMBERING);
572 pthread_mutex_lock(&threadlistlock);
573 #if defined(__DARWIN__)
574 threads_cast_darwinstop();
575 #elif defined(__CYGWIN__)
579 count = threads_cast_sendsignals(GC_signum1(), 0);
580 for (i=0; i<count; i++)
581 threads_sem_wait(&suspend_ack);
583 pthread_mutex_unlock(&threadlistlock);
586 void threads_cast_startworld(void)
588 pthread_mutex_lock(&threadlistlock);
589 #if defined(__DARWIN__)
590 threads_cast_darwinresume();
591 #elif defined(__MIPS__)
592 threads_cast_irixresume();
593 #elif defined(__CYGWIN__)
597 threads_cast_sendsignals(GC_signum2(), -1);
599 pthread_mutex_unlock(&threadlistlock);
603 #if !defined(__DARWIN__)
604 static void threads_sigsuspend_handler(ucontext_t *ctx)
609 /* XXX TWISTI: this is just a quick hack */
610 #if defined(ENABLE_JIT)
611 thread_restartcriticalsection(ctx);
614 /* Do as Boehm does. On IRIX a condition variable is used for wake-up
615 (not POSIX async-safe). */
616 #if defined(__IRIX__)
617 pthread_mutex_lock(&suspend_ack_lock);
618 threads_sem_post(&suspend_ack);
619 pthread_cond_wait(&suspend_cond, &suspend_ack_lock);
620 pthread_mutex_unlock(&suspend_ack_lock);
621 #elif defined(__CYGWIN__)
625 threads_sem_post(&suspend_ack);
629 sigdelset(&sigs, sig);
634 /* This function is called from Boehm GC code. */
636 int cacao_suspendhandler(ucontext_t *ctx)
638 if (stopworldwhere != STOPWORLD_FROM_CLASS_NUMBERING)
641 threads_sigsuspend_handler(ctx);
646 /* threads_set_current_threadobject ********************************************
648 Set the current thread object.
651 thread.......the thread object to set
653 *******************************************************************************/
655 static void threads_set_current_threadobject(threadobject *thread)
657 #if !defined(HAVE___THREAD)
658 pthread_setspecific(threads_current_threadobject_key, thread);
660 threads_current_threadobject = thread;
665 /* threads_get_current_threadobject ********************************************
667 Return the threadobject of the current thread.
670 the current threadobject * (an instance of java.lang.VMThread)
672 *******************************************************************************/
674 threadobject *threads_get_current_threadobject(void)
680 /* threads_preinit *************************************************************
682 Do some early initialization of stuff required.
684 *******************************************************************************/
686 void threads_preinit(void)
689 pthread_mutexattr_t mutexattr;
690 pthread_mutexattr_init(&mutexattr);
691 pthread_mutexattr_settype(&mutexattr, PTHREAD_MUTEX_RECURSIVE);
692 pthread_mutex_init(&compiler_mutex, &mutexattr);
693 pthread_mutexattr_destroy(&mutexattr);
695 pthread_mutex_init_rec(&compiler_mutex);
698 pthread_mutex_init(&threadlistlock, NULL);
699 pthread_mutex_init(&stopworldlock, NULL);
701 /* Allocate something so the garbage collector's signal handlers
703 heap_allocate(1, false, NULL);
705 mainthreadobj = NEW(threadobject);
706 mainthreadobj->tid = pthread_self();
707 mainthreadobj->index = 1;
708 mainthreadobj->thinlock = lock_pre_compute_thinlock(mainthreadobj->index);
710 #if !defined(HAVE___THREAD)
711 pthread_key_create(&threads_current_threadobject_key, NULL);
713 threads_set_current_threadobject(mainthreadobj);
715 threads_sem_init(&suspend_ack, 0, 0);
717 /* initialize the threads table */
719 threads_table_init();
721 /* initialize subsystems */
729 /* threads_init ****************************************************************
731 Initializes the threads required by the JVM: main, finalizer.
733 *******************************************************************************/
735 bool threads_init(void)
737 java_lang_String *threadname;
738 java_lang_Thread *mainthread;
739 java_lang_ThreadGroup *threadgroup;
740 threadobject *tempthread;
742 tempthread = mainthreadobj;
744 /* XXX We have to find a new way to free lock records */
745 /* with the new locking algorithm. */
746 /* lock_record_free_pools(mainthreadobj->ee.lockrecordpools); */
748 /* This is kinda tricky, we grow the java.lang.Thread object so we
749 can keep the execution environment there. No Thread object must
750 have been created at an earlier time. */
752 class_java_lang_VMThread->instancesize = sizeof(threadobject);
754 /* get methods we need in this file */
757 class_resolveclassmethod(class_java_lang_Thread,
759 utf_new_char("(Ljava/lang/VMThread;Ljava/lang/String;IZ)V"),
760 class_java_lang_Thread,
763 if (method_thread_init == NULL)
766 method_threadgroup_add =
767 class_resolveclassmethod(class_java_lang_ThreadGroup,
768 utf_new_char("addThread"),
769 utf_new_char("(Ljava/lang/Thread;)V"),
770 class_java_lang_ThreadGroup,
773 if (method_threadgroup_add == NULL)
776 /* create a VMThread */
778 mainthreadobj = (threadobject *) builtin_new(class_java_lang_VMThread);
780 if (mainthreadobj == NULL)
783 FREE(tempthread, threadobject);
785 threads_init_threadobject(&mainthreadobj->o);
787 threads_set_current_threadobject(mainthreadobj);
789 lock_init_execution_env(mainthreadobj);
791 mainthreadobj->next = mainthreadobj;
792 mainthreadobj->prev = mainthreadobj;
794 threads_table_add(mainthreadobj);
796 /* mark main thread as Java thread */
798 mainthreadobj->flags = THREAD_FLAG_JAVA;
800 #if defined(ENABLE_INTRP)
801 /* create interpreter stack */
804 MSET(intrp_main_stack, 0, u1, opt_stacksize);
805 mainthreadobj->_global_sp = intrp_main_stack + opt_stacksize;
809 threadname = javastring_new(utf_new_char("main"));
811 /* allocate and init ThreadGroup */
813 threadgroup = (java_lang_ThreadGroup *)
814 native_new_and_init(class_java_lang_ThreadGroup);
817 throw_exception_exit();
819 /* create a Thread */
821 mainthread = (java_lang_Thread *) builtin_new(class_java_lang_Thread);
823 if (mainthread == NULL)
824 throw_exception_exit();
826 mainthreadobj->o.thread = mainthread;
828 /* call Thread.<init>(Ljava/lang/VMThread;Ljava/lang/String;IZ)V */
830 (void) vm_call_method(method_thread_init, (java_objectheader *) mainthread,
831 mainthreadobj, threadname, NORM_PRIORITY, false);
836 mainthread->group = threadgroup;
838 /* add mainthread to ThreadGroup */
840 (void) vm_call_method(method_threadgroup_add,
841 (java_objectheader *) threadgroup,
847 threads_set_thread_priority(pthread_self(), NORM_PRIORITY);
849 /* initialize the thread attribute object */
851 if (pthread_attr_init(&threadattr)) {
852 log_println("pthread_attr_init failed: %s", strerror(errno));
856 pthread_attr_setdetachstate(&threadattr, PTHREAD_CREATE_DETACHED);
858 /* everything's ok */
864 /* threads_table_init *********************************************************
866 Initialize the global threads table.
868 ******************************************************************************/
870 static void threads_table_init(void)
875 size = THREADS_INITIAL_TABLE_SIZE;
877 threads_table.size = size;
878 threads_table.table = MNEW(threads_table_entry_t, size);
880 /* link the entries in a freelist */
882 for (i=0; i<size; ++i) {
883 threads_table.table[i].nextfree = i+1;
886 /* terminate the freelist */
888 threads_table.table[size-1].nextfree = 0; /* index 0 is never free */
892 /* threads_table_add **********************************************************
894 Add a thread to the global threads table. The index is entered in the
895 threadobject. The thinlock value for the thread is pre-computed.
898 thread............the thread to add
901 The table index for the newly added thread. This value has also been
902 entered in the threadobject.
905 The caller must hold the threadlistlock!
907 ******************************************************************************/
909 static s4 threads_table_add(threadobject *thread)
916 /* table[0] serves as the head of the freelist */
918 index = threads_table.table[0].nextfree;
920 /* if we got a free index, use it */
924 threads_table.table[0].nextfree = threads_table.table[index].nextfree;
925 threads_table.table[index].thread = thread;
926 thread->index = index;
927 thread->thinlock = lock_pre_compute_thinlock(index);
931 /* we must grow the table */
933 oldsize = threads_table.size;
934 newsize = oldsize * 2;
936 threads_table.table = MREALLOC(threads_table.table, threads_table_entry_t,
938 threads_table.size = newsize;
940 /* link the new entries to a free list */
942 for (i=oldsize; i<newsize; ++i) {
943 threads_table.table[i].nextfree = i+1;
946 /* terminate the freelist */
948 threads_table.table[newsize-1].nextfree = 0; /* index 0 is never free */
950 /* use the first of the new entries */
957 /* threads_table_remove *******************************************************
959 Remove a thread from the global threads table.
962 thread............the thread to remove
965 The caller must hold the threadlistlock!
967 ******************************************************************************/
969 static void threads_table_remove(threadobject *thread)
973 index = thread->index;
975 /* put the index into the freelist */
977 threads_table.table[index] = threads_table.table[0];
978 threads_table.table[0].nextfree = index;
980 /* delete the index in the threadobject to discover bugs */
986 /* threads_init_threadobject **************************************************
988 Initialize implementation fields of a java.lang.VMThread.
991 t............the java.lang.VMThread
993 ******************************************************************************/
995 void threads_init_threadobject(java_lang_VMThread *t)
997 threadobject *thread = (threadobject*) t;
999 thread->tid = pthread_self();
1003 /* TODO destroy all those things */
1004 pthread_mutex_init(&(thread->joinmutex), NULL);
1005 pthread_cond_init(&(thread->joincond), NULL);
1007 pthread_mutex_init(&(thread->waitmutex), NULL);
1008 pthread_cond_init(&(thread->waitcond), NULL);
1010 thread->interrupted = false;
1011 thread->signaled = false;
1012 thread->sleeping = false;
1016 /* threads_startup_thread ******************************************************
1018 Thread startup function called by pthread_create.
1020 Thread which have a startup.function != NULL are marked as internal
1021 threads. All other threads are threated as normal Java threads.
1023 NOTE: This function is not called directly by pthread_create. The Boehm GC
1024 inserts its own GC_start_routine in between, which then calls
1028 t............the argument passed to pthread_create, ie. a pointer to
1029 a startupinfo struct. CAUTION: When the `psem` semaphore
1030 is posted, the startupinfo struct becomes invalid! (It
1031 is allocated on the stack of threads_start_thread.)
1033 ******************************************************************************/
1035 static void *threads_startup_thread(void *t)
1037 startupinfo *startup;
1038 threadobject *thread;
1040 threadobject *tnext;
1042 functionptr function;
1044 #if defined(ENABLE_INTRP)
1045 u1 *intrp_thread_stack;
1047 /* create interpreter stack */
1050 intrp_thread_stack = GCMNEW(u1, opt_stacksize);
1051 MSET(intrp_thread_stack, 0, u1, opt_stacksize);
1054 intrp_thread_stack = NULL;
1057 /* get passed startupinfo structure and the values in there */
1060 t = NULL; /* make sure it's not used wrongly */
1062 thread = startup->thread;
1063 function = startup->function;
1064 psem = startup->psem;
1066 /* Seems like we've encountered a situation where thread->tid was not set by
1067 * pthread_create. We alleviate this problem by waiting for pthread_create
1069 threads_sem_wait(startup->psem_first);
1071 /* set the thread object */
1073 #if defined(__DARWIN__)
1074 thread->mach_thread = mach_thread_self();
1076 threads_set_current_threadobject(thread);
1078 /* insert the thread into the threadlist and the threads table */
1080 pthread_mutex_lock(&threadlistlock);
1082 thread->prev = mainthreadobj;
1083 thread->next = tnext = mainthreadobj->next;
1084 mainthreadobj->next = thread;
1085 tnext->prev = thread;
1087 threads_table_add(thread);
1089 pthread_mutex_unlock(&threadlistlock);
1091 /* init data structures of this thread */
1093 lock_init_execution_env(thread);
1095 /* tell threads_startup_thread that we registered ourselves */
1096 /* CAUTION: *startup becomes invalid with this! */
1099 threads_sem_post(psem);
1101 /* set our priority */
1103 threads_set_thread_priority(thread->tid, thread->o.thread->priority);
1105 #if defined(ENABLE_INTRP)
1106 /* set interpreter stack */
1109 thread->_global_sp = (void *) (intrp_thread_stack + opt_stacksize);
1112 #if defined(ENABLE_JVMTI)
1113 /* fire thread start event */
1116 jvmti_ThreadStartEnd(JVMTI_EVENT_THREAD_START);
1119 /* find and run the Thread.run()V method if no other function was passed */
1121 if (function == NULL) {
1122 /* this is a normal Java thread */
1124 thread->flags |= THREAD_FLAG_JAVA;
1126 method = class_resolveclassmethod(thread->o.header.vftbl->class,
1129 thread->o.header.vftbl->class,
1135 /* increase total started thread count */
1137 _Jv_jvm->total_started_thread_count++;
1139 (void) vm_call_method(method, (java_objectheader *) thread);
1142 /* this is an internal thread */
1144 thread->flags |= THREAD_FLAG_INTERNAL;
1146 /* increase total started thread count */
1148 _Jv_jvm->total_started_thread_count++;
1150 /* call passed function, e.g. finalizer_thread */
1155 #if defined(ENABLE_JVMTI)
1156 /* fire thread end event */
1159 jvmti_ThreadStartEnd(JVMTI_EVENT_THREAD_END);
1162 threads_detach_thread(thread);
1168 /* threads_start_thread ********************************************************
1170 Start a thread in the JVM.
1173 t............the java.lang.Thread object
1174 function.....function to run in the new thread. NULL means that the
1175 "run" method of the object `t` should be called
1177 ******************************************************************************/
1179 void threads_start_thread(java_lang_Thread *t, functionptr function)
1183 pthread_attr_t attr;
1184 startupinfo startup;
1185 threadobject *thread;
1187 thread = (threadobject *) t->vmThread;
1189 /* fill startupinfo structure passed by pthread_create to
1190 * threads_startup_thread */
1192 startup.thread = thread;
1193 startup.function = function; /* maybe we don't call Thread.run()V */
1194 startup.psem = &sem;
1195 startup.psem_first = &sem_first;
1197 threads_sem_init(&sem, 0, 0);
1198 threads_sem_init(&sem_first, 0, 0);
1200 /* initialize thread attribute object */
1202 if (pthread_attr_init(&attr))
1203 vm_abort("pthread_attr_init failed: %s", strerror(errno));
1205 /* initialize thread stacksize */
1207 if (pthread_attr_setstacksize(&attr, opt_stacksize))
1208 vm_abort("pthread_attr_setstacksize failed: %s", strerror(errno));
1210 /* create the thread */
1212 if (pthread_create(&thread->tid, &attr, threads_startup_thread, &startup))
1213 vm_abort("pthread_create failed: %s", strerror(errno));
1215 /* signal that pthread_create has returned, so thread->tid is valid */
1217 threads_sem_post(&sem_first);
1219 /* wait here until the thread has entered itself into the thread list */
1221 threads_sem_wait(&sem);
1226 sem_destroy(&sem_first);
1230 /* threads_attach_current_thread ***********************************************
1232 Attaches the current thread to the VM. Used in JNI.
1234 *******************************************************************************/
1236 bool threads_attach_current_thread(JavaVMAttachArgs *vm_aargs, bool isdaemon)
1238 threadobject *thread;
1239 java_lang_Thread *t;
1241 java_lang_String *s;
1242 java_lang_ThreadGroup *group;
1243 java_objectheader *o;
1245 /* create a java.lang.VMThread object */
1247 thread = (threadobject *) builtin_new(class_java_lang_VMThread);
1252 threads_init_threadobject(&thread->o);
1253 threads_set_current_threadobject(thread);
1254 lock_init_execution_env(thread);
1256 /* insert the thread into the threadlist and the threads table */
1258 pthread_mutex_lock(&threadlistlock);
1260 thread->prev = mainthreadobj;
1261 thread->next = mainthreadobj->next;
1262 mainthreadobj->next = thread;
1263 thread->next->prev = thread;
1265 threads_table_add(thread);
1267 pthread_mutex_unlock(&threadlistlock);
1269 /* mark main thread as Java thread */
1271 thread->flags = THREAD_FLAG_JAVA;
1273 #if defined(ENABLE_INTRP)
1274 /* create interpreter stack */
1277 MSET(intrp_main_stack, 0, u1, opt_stacksize);
1278 thread->_global_sp = intrp_main_stack + opt_stacksize;
1282 /* create a java.lang.Thread object */
1284 t = (java_lang_Thread *) builtin_new(class_java_lang_Thread);
1289 thread->o.thread = t;
1291 if (vm_aargs != NULL) {
1292 u = utf_new_char(vm_aargs->name);
1293 group = (java_lang_ThreadGroup *) vm_aargs->group;
1297 group = mainthreadobj->o.thread->group;
1300 s = javastring_new(u);
1302 o = (java_objectheader *) t;
1304 (void) vm_call_method(method_thread_init, o, thread, s, NORM_PRIORITY,
1310 /* store the thread group in the object */
1314 o = (java_objectheader *) group;
1316 (void) vm_call_method(method_threadgroup_add, o, t);
1325 /* threads_detach_thread *******************************************************
1327 Detaches the passed thread from the VM. Used in JNI.
1329 *******************************************************************************/
1331 bool threads_detach_thread(threadobject *thread)
1333 java_lang_Thread *t;
1334 java_lang_ThreadGroup *group;
1336 java_objectheader *o;
1338 /* Allow lock record pools to be used by other threads. They
1339 cannot be deleted so we'd better not waste them. */
1341 /* XXX We have to find a new way to free lock records */
1342 /* with the new locking algorithm. */
1343 /* lock_record_free_pools(thread->ee.lockrecordpools); */
1345 /* XXX implement uncaught exception stuff (like JamVM does) */
1347 /* remove thread from the thread group */
1349 t = thread->o.thread;
1352 /* XXX TWISTI: should all threads be in a ThreadGroup? */
1354 if (group != NULL) {
1355 m = class_resolveclassmethod(group->header.vftbl->class,
1357 utf_java_lang_Thread__V,
1358 class_java_lang_ThreadGroup,
1364 o = (java_objectheader *) group;
1366 (void) vm_call_method(m, o, t);
1372 /* remove thread from thread list and threads table, do this
1375 pthread_mutex_lock(&threadlistlock);
1377 thread->next->prev = thread->prev;
1378 thread->prev->next = thread->next;
1380 threads_table_remove(thread);
1382 pthread_mutex_unlock(&threadlistlock);
1384 /* reset thread id (lock on joinmutex? TWISTI) */
1386 pthread_mutex_lock(&thread->joinmutex);
1388 pthread_mutex_unlock(&thread->joinmutex);
1390 /* tell everyone that a thread has finished */
1392 pthread_cond_broadcast(&thread->joincond);
1398 /* threads_find_non_daemon_thread **********************************************
1400 Helper function used by threads_join_all_threads for finding
1401 non-daemon threads that are still running.
1403 *******************************************************************************/
1405 /* At the end of the program, we wait for all running non-daemon
1408 static threadobject *threads_find_non_daemon_thread(threadobject *thread)
1410 while (thread != mainthreadobj) {
1411 if (!thread->o.thread->daemon)
1413 thread = thread->prev;
1420 /* threads_join_all_threads ****************************************************
1422 Join all non-daemon threads.
1424 *******************************************************************************/
1426 void threads_join_all_threads(void)
1428 threadobject *thread;
1430 pthread_mutex_lock(&threadlistlock);
1432 while ((thread = threads_find_non_daemon_thread(mainthreadobj->prev)) != NULL) {
1434 pthread_mutex_lock(&thread->joinmutex);
1436 pthread_mutex_unlock(&threadlistlock);
1439 pthread_cond_wait(&thread->joincond, &thread->joinmutex);
1441 pthread_mutex_unlock(&thread->joinmutex);
1443 pthread_mutex_lock(&threadlistlock);
1446 pthread_mutex_unlock(&threadlistlock);
1450 /* threads_timespec_earlier ****************************************************
1452 Return true if timespec tv1 is earlier than timespec tv2.
1455 tv1..........first timespec
1456 tv2..........second timespec
1459 true, if the first timespec is earlier
1461 *******************************************************************************/
1463 static inline bool threads_timespec_earlier(const struct timespec *tv1,
1464 const struct timespec *tv2)
1466 return (tv1->tv_sec < tv2->tv_sec)
1468 (tv1->tv_sec == tv2->tv_sec && tv1->tv_nsec < tv2->tv_nsec);
1472 /* threads_current_time_is_earlier_than ****************************************
1474 Check if the current time is earlier than the given timespec.
1477 tv...........the timespec to compare against
1480 true, if the current time is earlier
1482 *******************************************************************************/
1484 static bool threads_current_time_is_earlier_than(const struct timespec *tv)
1486 struct timeval tvnow;
1487 struct timespec tsnow;
1489 /* get current time */
1491 if (gettimeofday(&tvnow, NULL) != 0)
1492 vm_abort("gettimeofday failed: %s\n", strerror(errno));
1494 /* convert it to a timespec */
1496 tsnow.tv_sec = tvnow.tv_sec;
1497 tsnow.tv_nsec = tvnow.tv_usec * 1000;
1499 /* compare current time with the given timespec */
1501 return threads_timespec_earlier(&tsnow, tv);
1505 /* threads_wait_with_timeout ***************************************************
1507 Wait until the given point in time on a monitor until either
1508 we are notified, we are interrupted, or the time is up.
1511 t............the current thread
1512 wakeupTime...absolute (latest) wakeup time
1513 If both tv_sec and tv_nsec are zero, this function
1514 waits for an unlimited amount of time.
1517 true.........if the wait has been interrupted,
1518 false........if the wait was ended by notification or timeout
1520 *******************************************************************************/
1522 static bool threads_wait_with_timeout(threadobject *t,
1523 struct timespec *wakeupTime)
1525 bool wasinterrupted;
1527 /* acquire the waitmutex */
1529 pthread_mutex_lock(&t->waitmutex);
1531 /* mark us as sleeping */
1535 /* wait on waitcond */
1537 if (wakeupTime->tv_sec || wakeupTime->tv_nsec) {
1539 while (!t->interrupted && !t->signaled
1540 && threads_current_time_is_earlier_than(wakeupTime))
1542 pthread_cond_timedwait(&t->waitcond, &t->waitmutex, wakeupTime);
1547 while (!t->interrupted && !t->signaled)
1548 pthread_cond_wait(&t->waitcond, &t->waitmutex);
1551 /* check if we were interrupted */
1553 wasinterrupted = t->interrupted;
1555 /* reset all flags */
1557 t->interrupted = false;
1558 t->signaled = false;
1559 t->sleeping = false;
1561 /* release the waitmutex */
1563 pthread_mutex_unlock(&t->waitmutex);
1565 return wasinterrupted;
1569 /* threads_wait_with_timeout_relative ******************************************
1571 Wait for the given maximum amount of time on a monitor until either
1572 we are notified, we are interrupted, or the time is up.
1575 t............the current thread
1576 millis.......milliseconds to wait
1577 nanos........nanoseconds to wait
1580 true.........if the wait has been interrupted,
1581 false........if the wait was ended by notification or timeout
1583 *******************************************************************************/
1585 bool threads_wait_with_timeout_relative(threadobject *t,
1589 struct timespec wakeupTime;
1591 /* calculate the the (latest) wakeup time */
1593 threads_calc_absolute_time(&wakeupTime, millis, nanos);
1597 return threads_wait_with_timeout(t, &wakeupTime);
1601 /* threads_calc_absolute_time **************************************************
1603 Calculate the absolute point in time a given number of ms and ns from now.
1606 millis............milliseconds from now
1607 nanos.............nanoseconds from now
1610 *tm...............receives the timespec of the absolute point in time
1612 *******************************************************************************/
1614 static void threads_calc_absolute_time(struct timespec *tm, s8 millis, s4 nanos)
1616 if ((millis != 0x7fffffffffffffffLLU) && (millis || nanos)) {
1619 gettimeofday(&tv, NULL);
1620 tv.tv_sec += millis / 1000;
1622 nsec = tv.tv_usec * 1000 + (s4) millis * 1000000 + nanos;
1623 tm->tv_sec = tv.tv_sec + nsec / 1000000000;
1624 tm->tv_nsec = nsec % 1000000000;
1633 /* threads_interrupt_thread ****************************************************
1635 Interrupt the given thread.
1637 The thread gets the "waitcond" signal and
1638 its interrupted flag is set to true.
1641 thread............the thread to interrupt
1643 *******************************************************************************/
1645 void threads_interrupt_thread(java_lang_VMThread *thread)
1647 threadobject *t = (threadobject*) thread;
1649 /* signal the thread a "waitcond" and tell it that it has been */
1652 pthread_mutex_lock(&t->waitmutex);
1654 pthread_cond_signal(&t->waitcond);
1655 t->interrupted = true;
1656 pthread_mutex_unlock(&t->waitmutex);
1660 /* threads_check_if_interrupted_and_reset **************************************
1662 Check if the current thread has been interrupted and reset the
1666 true, if the current thread had been interrupted
1668 *******************************************************************************/
1670 bool threads_check_if_interrupted_and_reset(void)
1675 t = (threadobject*) THREADOBJECT;
1677 intr = t->interrupted;
1679 t->interrupted = false;
1685 /* threads_thread_has_been_interrupted *********************************************************
1687 Check if the given thread has been interrupted
1690 t............the thread to check
1693 true, if the given thread had been interrupted
1695 *******************************************************************************/
1697 bool threads_thread_has_been_interrupted(java_lang_VMThread *thread)
1701 t = (threadobject*) thread;
1703 return t->interrupted;
1707 /* threads_sleep ***************************************************************
1709 Sleep the current thread for the specified amount of time.
1711 *******************************************************************************/
1713 void threads_sleep(s8 millis, s4 nanos)
1716 struct timespec wakeupTime;
1717 bool wasinterrupted;
1719 t = (threadobject *) THREADOBJECT;
1721 threads_calc_absolute_time(&wakeupTime, millis, nanos);
1723 wasinterrupted = threads_wait_with_timeout(t, &wakeupTime);
1726 *exceptionptr = new_exception(string_java_lang_InterruptedException);
1730 /* threads_yield *****************************************************************
1732 Yield to the scheduler.
1734 *******************************************************************************/
1736 void threads_yield(void)
1742 /* threads_java_lang_Thread_set_priority ***********************************************************
1744 Set the priority for the given java.lang.Thread.
1747 t............the java.lang.Thread
1748 priority.....the priority
1750 *******************************************************************************/
1752 void threads_java_lang_Thread_set_priority(java_lang_Thread *t, s4 priority)
1754 threadobject *thread;
1756 thread = (threadobject*) t->vmThread;
1758 threads_set_thread_priority(thread->tid, priority);
1762 /* threads_dump ****************************************************************
1764 Dumps info for all threads running in the JVM. This function is
1765 called when SIGQUIT (<ctrl>-\) is sent to CACAO.
1767 *******************************************************************************/
1769 void threads_dump(void)
1772 java_lang_VMThread *vmt;
1773 java_lang_Thread *t;
1776 tobj = mainthreadobj;
1778 printf("Full thread dump CACAO "VERSION":\n");
1780 /* iterate over all started threads */
1783 /* get thread objects */
1788 /* the thread may be currently in initalization, don't print it */
1791 /* get thread name */
1793 name = javastring_toutf(t->name, false);
1796 utf_display_printable_ascii(name);
1802 #if SIZEOF_VOID_P == 8
1803 printf("prio=%d tid=0x%016lx\n", t->priority, tobj->tid);
1805 printf("prio=%d tid=0x%08lx\n", t->priority, tobj->tid);
1808 /* send SIGUSR1 to thread to print stacktrace */
1810 pthread_kill(tobj->tid, SIGUSR1);
1812 /* sleep this thread a bit, so the signal can reach the thread */
1814 threads_sleep(10, 0);
1818 } while (tobj && (tobj != mainthreadobj));
1822 /* threads_table_dump *********************************************************
1824 Dump the threads table for debugging purposes.
1827 file..............stream to write to
1829 ******************************************************************************/
1831 #if !defined(NDEBUG)
1832 static void threads_table_dump(FILE *file)
1838 pthread_mutex_lock(&threadlistlock);
1840 size = threads_table.size;
1842 fprintf(file, "======== THREADS TABLE (size %d) ========\n", size);
1844 for (i=0; i<size; ++i) {
1845 index = threads_table.table[i].nextfree;
1847 fprintf(file, "%4d: ", i);
1850 fprintf(file, "free, nextfree = %d\n", index);
1853 fprintf(file, "thread %p\n", (void*) threads_table.table[i].thread);
1857 fprintf(file, "======== END OF THREADS TABLE ========\n");
1859 pthread_mutex_unlock(&threadlistlock);
1864 * These are local overrides for various environment variables in Emacs.
1865 * Please do not remove this and leave it at the end of the file, where
1866 * Emacs will automagically detect them.
1867 * ---------------------------------------------------------------------
1870 * indent-tabs-mode: t
1874 * vim:noexpandtab:sw=4:ts=4: