1 /* src/threads/thread.cpp - machine independent thread functions
3 Copyright (C) 1996-2011
4 CACAOVM - Verein zur Foerderung der freien virtuellen Maschine CACAO
6 This file is part of CACAO.
8 This program is free software; you can redistribute it and/or
9 modify it under the terms of the GNU General Public License as
10 published by the Free Software Foundation; either version 2, or (at
11 your option) any later version.
13 This program is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with this program; if not, write to the Free Software
20 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
34 #include "mm/memory.hpp"
36 #if defined(ENABLE_GC_BOEHM)
37 /* We need to include Boehm's gc.h here for GC_register_my_thread and
39 # include "mm/boehm-gc/include/gc.h"
42 #include "native/llni.h"
43 #include "native/native.hpp"
45 #include "threads/lock.hpp"
46 #include "threads/threadlist.hpp"
47 #include "threads/thread.hpp"
49 #include "vm/jit/builtin.hpp"
50 #include "vm/class.hpp"
51 #include "vm/exceptions.hpp"
52 #include "vm/finalizer.hpp"
53 #include "vm/globals.hpp"
54 #include "vm/javaobjects.hpp"
55 #include "vm/method.hpp"
56 #include "vm/options.h"
57 #include "vm/string.hpp"
61 #if defined(ENABLE_STATISTICS)
62 # include "vm/statistics.h"
65 #include "vm/jit/stacktrace.hpp"
68 /* global variables ***********************************************************/
70 static methodinfo *thread_method_init;
71 static java_handle_t *threadgroup_system;
72 static java_handle_t *threadgroup_main;
74 #if defined(__LINUX__)
75 /* XXX Remove for exact-GC. */
76 bool threads_pthreads_implementation_nptl;
80 /* static functions ***********************************************************/
82 static void thread_create_initial_thread(void);
83 static threadobject *thread_new(int32_t flags);
86 /* threads_preinit *************************************************************
88 Do some early initialization of stuff required.
90 *******************************************************************************/
92 void threads_preinit(void)
94 threadobject *mainthread;
95 #if defined(__LINUX__) && defined(_CS_GNU_LIBPTHREAD_VERSION)
100 TRACESUBSYSTEMINITIALIZATION("threads_preinit");
102 #if defined(__LINUX__)
103 /* XXX Remove for exact-GC. */
105 /* On Linux we need to check the pthread implementation. */
107 /* _CS_GNU_LIBPTHREAD_VERSION (GNU C library only; since glibc 2.3.2) */
108 /* If the glibc is a pre-2.3.2 version, we fall back to
111 # if defined(_CS_GNU_LIBPTHREAD_VERSION)
112 len = confstr(_CS_GNU_LIBPTHREAD_VERSION, NULL, (size_t) 0);
114 /* Some systems return as length 0 (maybe cross-compilation
115 related). In this case we also fall back to linuxthreads. */
118 pathbuf = MNEW(char, len);
120 (void) confstr(_CS_GNU_LIBPTHREAD_VERSION, pathbuf, len);
122 if (strstr(pathbuf, "NPTL") != NULL)
123 threads_pthreads_implementation_nptl = true;
125 threads_pthreads_implementation_nptl = false;
128 threads_pthreads_implementation_nptl = false;
130 threads_pthreads_implementation_nptl = false;
134 /* Initialize the threads implementation (sets the thinlock on the
137 threads_impl_preinit();
139 /* Create internal thread data-structure for the main thread. */
141 mainthread = thread_new(THREAD_FLAG_JAVA);
143 /* Add the thread to the thread list. */
145 ThreadList::add_to_active_thread_list(mainthread);
147 /* The main thread should always have index 1. */
149 if (mainthread->index != 1)
150 vm_abort("threads_preinit: main thread index not 1: %d != 1",
153 /* Thread is already running. */
155 mainthread->state = THREAD_STATE_RUNNABLE;
157 /* Store the internal thread data-structure in the TSD. */
159 thread_set_current(mainthread);
163 /* threads_init ****************************************************************
165 Initialize the main thread.
167 *******************************************************************************/
169 void threads_init(void)
171 TRACESUBSYSTEMINITIALIZATION("threads_init");
173 /* Create the system and main thread groups. */
175 ThreadRuntime::thread_create_initial_threadgroups(&threadgroup_main, &threadgroup_system);
177 /* Cache the java.lang.Thread initialization method. */
179 thread_method_init = ThreadRuntime::get_thread_init_method();
181 if (thread_method_init == NULL)
182 vm_abort("threads_init: failed to resolve thread init method");
184 thread_create_initial_thread();
188 /* thread_create_object ********************************************************
190 Create a Java thread object for the given thread data-structure,
191 initializes it and adds the thread to the threadgroup.
196 name .... thread name
197 group ... threadgroup
201 *******************************************************************************/
203 static bool thread_create_object(threadobject *t, java_handle_t *name, java_handle_t *group)
205 /* Create a java.lang.Thread Java object. */
207 java_handle_t* h = builtin_new(class_java_lang_Thread);
212 java_lang_Thread jlt(h);
214 // Set the Java object in the thread data-structure. This
215 // indicates that the thread is attached to the VM.
216 t->object = LLNI_DIRECT(jlt.get_handle());
218 return ThreadRuntime::invoke_thread_initializer(jlt, t, thread_method_init, name, group);
222 /* thread_create_initial_thread ***********************************************
224 Create the initial thread: main
226 *******************************************************************************/
228 static void thread_create_initial_thread(void)
233 /* Get the main-thread (NOTE: The main thread is always the first
234 thread in the list). */
236 t = ThreadList::get_main_thread();
238 /* The thread name. */
240 name = javastring_new(utf_main);
242 #if defined(ENABLE_INTRP)
243 /* create interpreter stack */
246 MSET(intrp_main_stack, 0, u1, opt_stacksize);
247 mainthread->_global_sp = (Cell*) (intrp_main_stack + opt_stacksize);
251 /* Create the Java thread object. */
253 if (!thread_create_object(t, name, threadgroup_main))
254 vm_abort("thread_create_initial_thread: failed to create Java object");
256 /* Initialize the implementation specific bits. */
260 DEBUGTHREADS("starting (main)", t);
264 /* thread_new ******************************************************************
266 Allocates and initializes an internal thread data-structure and
267 adds it to the threads list.
269 *******************************************************************************/
271 static threadobject *thread_new(int32_t flags)
276 /* Lock the thread lists */
280 index = ThreadList::get_free_thread_index();
282 /* Allocate a thread data structure. */
284 /* First, try to get one from the free-list. */
286 t = ThreadList::get_free_thread();
288 /* Unlock the thread lists. */
290 ThreadList::unlock();
293 /* Equivalent of MZERO on the else path */
295 threads_impl_thread_clear(t);
298 #if defined(ENABLE_GC_BOEHM)
299 t = GCNEW_UNCOLLECTABLE(threadobject, 1);
301 t = NEW(threadobject);
304 #if defined(ENABLE_STATISTICS)
306 size_threadobject += sizeof(threadobject);
311 MZERO(t, threadobject, 1);
313 // Initialize the mutex and the condition.
314 t->flc_lock = new Mutex();
315 t->flc_cond = new Condition();
317 t->waitmutex = new Mutex();
318 t->waitcond = new Condition();
320 t->suspendmutex = new Mutex();
321 t->suspendcond = new Condition();
323 #if defined(ENABLE_TLH)
327 #if defined(ENABLE_GC_CACAO)
328 /* Register reference to java.lang.Thread with the GC. */
329 /* FIXME is it ok to do this only once? */
331 gc_reference_register(&(t->object), GC_REFTYPE_THREADOBJECT);
332 gc_reference_register(&(t->_exceptionptr), GC_REFTYPE_THREADOBJECT);
335 t->_dumpmemory = new DumpMemory();
338 /* Pre-compute the thinlock-word. */
343 t->thinlock = Lockword::pre_compute_thinlock(t->index);
345 t->state = THREAD_STATE_NEW;
347 #if defined(ENABLE_GC_CACAO)
348 t->flags |= THREAD_FLAG_IN_NATIVE;
351 /* Initialize the implementation-specific bits. */
353 threads_impl_thread_reuse(t);
359 /* thread_free *****************************************************************
361 Remove the thread from the threads-list and free the internal
362 thread data structure. The thread index is added to the
363 thread-index free-list.
366 t ... thread data structure
368 *******************************************************************************/
370 void thread_free(threadobject *t)
372 /* Set the reference to the Java object to NULL. */
376 ThreadList::deactivate_thread(t);
380 /* threads_thread_start_internal ***********************************************
382 Start an internal thread in the JVM. No Java thread objects exists
386 name.......UTF-8 name of the thread
387 f..........function pointer to C function to start
389 *******************************************************************************/
391 static void thread_cleanup_finalizer(java_handle_t *h, void *data)
393 threadobject *t = reinterpret_cast<threadobject*>(data);
394 ThreadList::release_thread(t, false);
397 bool threads_thread_start_internal(utf *name, functionptr f)
401 /* Create internal thread data-structure. */
403 t = thread_new(THREAD_FLAG_INTERNAL | THREAD_FLAG_DAEMON);
405 /* Add the thread to the thread list. */
407 ThreadList::add_to_active_thread_list(t);
409 /* Create the Java thread object. */
411 if (!thread_create_object(t, javastring_new(name), threadgroup_system)) {
412 ThreadList::release_thread(t, true);
416 Finalizer::attach_custom_finalizer(LLNI_WRAP(t->object), thread_cleanup_finalizer, t);
418 /* Start the thread. */
420 threads_impl_thread_start(t, f);
422 /* everything's ok */
428 /* threads_thread_start ********************************************************
430 Start a Java thread in the JVM. Only the java thread object exists
434 object.....the java thread object java.lang.Thread
436 *******************************************************************************/
438 void threads_thread_start(java_handle_t *object)
440 java_lang_Thread jlt(object);
442 /* Create internal thread data-structure. */
444 u4 flags = THREAD_FLAG_JAVA;
445 #if defined(ENABLE_JAVASE)
446 /* Is this a daemon thread? */
448 if (jlt.get_daemon())
449 flags |= THREAD_FLAG_DAEMON;
452 threadobject* t = thread_new(flags);
454 /* Link the two objects together. */
456 t->object = LLNI_DIRECT(object);
458 /* Add the thread to the thread list. */
460 ThreadList::add_to_active_thread_list(t);
462 Atomic::write_memory_barrier();
464 ThreadRuntime::setup_thread_vmdata(jlt, t);
466 Finalizer::attach_custom_finalizer(LLNI_WRAP(t->object), thread_cleanup_finalizer, t);
468 /* Start the thread. Don't pass a function pointer (NULL) since
469 we want Thread.run()V here. */
471 threads_impl_thread_start(t, NULL);
476 * Attaches the current thread to the VM.
478 * @param vm_aargs Attach arguments.
479 * @param isdaemon true if the attached thread should be a daemon
482 * @return true on success, false otherwise.
484 bool thread_attach_current_thread(JavaVMAttachArgs *vm_aargs, bool isdaemon)
490 java_handle_t *group;
492 /* If the current thread has already been attached, this operation
495 result = thread_current_is_attached();
500 /* Create internal thread data structure. */
502 u4 flags = THREAD_FLAG_JAVA;
504 flags |= THREAD_FLAG_DAEMON;
506 t = thread_new(flags);
508 /* Store the internal thread data-structure in the TSD. */
510 thread_set_current(t);
512 /* The thread is flagged and (non-)daemon thread, we can leave the
515 /* Add the thread to the thread list. */
517 ThreadList::add_to_active_thread_list(t);
519 DEBUGTHREADS("attaching", t);
521 /* Get the thread name. */
523 if (vm_aargs != NULL) {
524 u = utf_new_char(vm_aargs->name);
530 name = javastring_new(u);
532 #if defined(ENABLE_JAVASE)
533 /* Get the threadgroup. */
535 if (vm_aargs != NULL)
536 group = (java_handle_t *) vm_aargs->group;
540 /* If no threadgroup was given, use the main threadgroup. */
543 group = threadgroup_main;
546 #if defined(ENABLE_INTRP)
547 /* create interpreter stack */
550 MSET(intrp_main_stack, 0, u1, opt_stacksize);
551 thread->_global_sp = (Cell *) (intrp_main_stack + opt_stacksize);
555 /* Create the Java thread object. */
557 if (!thread_create_object(t, name, group)) {
558 ThreadList::release_thread(t, true);
562 /* The thread is completely initialized. */
564 thread_set_state_runnable(t);
571 * Attaches the current external thread to the VM. This function is
572 * called by JNI's AttachCurrentThread.
574 * @param vm_aargs Attach arguments.
575 * @param isdaemon true if the attached thread should be a daemon
578 * @return true on success, false otherwise.
580 bool thread_attach_current_external_thread(JavaVMAttachArgs *vm_aargs, bool isdaemon)
584 #if defined(ENABLE_GC_BOEHM)
585 struct GC_stack_base sb;
587 /* Register the thread with Boehm-GC. This must happen before the
588 thread allocates any memory from the GC heap.*/
590 result = GC_get_stack_base(&sb);
592 if (result != GC_SUCCESS)
593 vm_abort("threads_attach_current_thread: GC_get_stack_base failed");
595 GC_register_my_thread(&sb);
598 result = thread_attach_current_thread(vm_aargs, isdaemon);
600 if (result == false) {
601 #if defined(ENABLE_GC_BOEHM)
602 /* Unregister the thread. */
604 GC_unregister_my_thread();
615 * Detaches the current external thread from the VM. This function is
616 * called by JNI's DetachCurrentThread.
618 * @return true on success, false otherwise.
620 bool thread_detach_current_external_thread(void)
624 result = thread_detach_current_thread();
629 #if defined(ENABLE_GC_BOEHM)
630 /* Unregister the thread with Boehm-GC. This must happen after
631 the thread allocates any memory from the GC heap. */
633 /* Don't detach the main thread. This is a workaround for
634 OpenJDK's java launcher. */
635 if (thread_get_current()->index != 1)
636 GC_unregister_my_thread();
643 /* thread_fprint_name **********************************************************
645 Print the name of the given thread to the given stream.
648 t ........ thread data-structure
649 stream ... stream to print to
651 *******************************************************************************/
653 void thread_fprint_name(threadobject *t, FILE *stream)
655 if (LLNI_WRAP(t->object) == NULL)
658 java_lang_Thread jlt(LLNI_WRAP(t->object));
660 ThreadRuntime::print_thread_name(jlt, stream);
664 /* thread_print_info ***********************************************************
666 Print information of the passed thread.
669 t ... thread data-structure.
671 *******************************************************************************/
673 void thread_print_info(threadobject *t)
675 java_lang_Thread jlt(LLNI_WRAP(t->object));
677 /* Print as much as we can when we are in state NEW. */
679 if (jlt.get_handle() != NULL) {
680 /* Print thread name. */
683 thread_fprint_name(t, stdout);
689 if (thread_is_daemon(t))
692 if (jlt.get_handle() != NULL) {
693 printf(" prio=%d", jlt.get_priority());
696 #if SIZEOF_VOID_P == 8
697 printf(" t=0x%016lx tid=0x%016lx (%ld)",
698 (ptrint) t, (ptrint) t->tid, (ptrint) t->tid);
700 printf(" t=0x%08x tid=0x%08x (%d)",
701 (ptrint) t, (ptrint) t->tid, (ptrint) t->tid);
704 printf(" index=%d", t->index);
706 /* Print thread state. */
708 int state = cacaothread_get_state(t);
711 case THREAD_STATE_NEW:
714 case THREAD_STATE_RUNNABLE:
717 case THREAD_STATE_BLOCKED:
720 case THREAD_STATE_WAITING:
723 case THREAD_STATE_TIMED_WAITING:
724 printf(" waiting on condition");
726 case THREAD_STATE_PARKED:
729 case THREAD_STATE_TIMED_PARKED:
730 printf(" timed parked");
732 case THREAD_STATE_TERMINATED:
733 printf(" terminated");
736 vm_abort("thread_print_info: unknown thread state %d", state);
741 /* threads_get_current_tid *****************************************************
743 Return the tid of the current thread.
748 *******************************************************************************/
750 intptr_t threads_get_current_tid(void)
752 threadobject *thread;
754 thread = THREADOBJECT;
756 /* this may happen during bootstrap */
761 return (intptr_t) thread->tid;
766 * Set the current state of the given thread. This method should only
767 * be called while holding the threadlist-lock and after checking that
768 * the new state is valid. It is best to not call this method directly
769 * but call the specific setter methods below.
771 static inline void thread_set_state(threadobject *t, int state)
773 // Set the state of our internal threadobject.
776 ThreadRuntime::set_javathread_state(t, state);
780 /* thread_set_state_runnable ***************************************************
782 Set the current state of the given thread to THREAD_STATE_RUNNABLE.
784 NOTE: If the thread has already terminated, don't set the state.
785 This is important for threads_detach_thread.
787 *******************************************************************************/
789 void thread_set_state_runnable(threadobject *t)
791 if (t->state != THREAD_STATE_TERMINATED) {
792 thread_set_state(t, THREAD_STATE_RUNNABLE);
794 DEBUGTHREADS("is RUNNABLE", t);
799 /* thread_set_state_waiting ****************************************************
801 Set the current state of the given thread to THREAD_STATE_WAITING.
803 NOTE: If the thread has already terminated, don't set the state.
804 This is important for threads_detach_thread.
806 *******************************************************************************/
808 void thread_set_state_waiting(threadobject *t)
810 if (t->state != THREAD_STATE_TERMINATED) {
811 thread_set_state(t, THREAD_STATE_WAITING);
813 DEBUGTHREADS("is WAITING", t);
818 /* thread_set_state_timed_waiting **********************************************
820 Set the current state of the given thread to
821 THREAD_STATE_TIMED_WAITING.
823 NOTE: If the thread has already terminated, don't set the state.
824 This is important for threads_detach_thread.
826 *******************************************************************************/
828 void thread_set_state_timed_waiting(threadobject *t)
830 if (t->state != THREAD_STATE_TERMINATED) {
831 thread_set_state(t, THREAD_STATE_TIMED_WAITING);
833 DEBUGTHREADS("is TIMED_WAITING", t);
838 /* thread_set_state_parked *****************************************************
840 Set the current state of the given thread to THREAD_STATE_PARKED.
842 NOTE: If the thread has already terminated, don't set the state.
843 This is important for threads_detach_thread.
845 *******************************************************************************/
847 void thread_set_state_parked(threadobject *t)
849 if (t->state != THREAD_STATE_TERMINATED) {
850 thread_set_state(t, THREAD_STATE_PARKED);
852 DEBUGTHREADS("is PARKED", t);
857 /* thread_set_state_timed_parked ***********************************************
859 Set the current state of the given thread to THREAD_STATE_TIMED_PARKED.
861 NOTE: If the thread has already terminated, don't set the state.
862 This is important for threads_detach_thread.
864 *******************************************************************************/
866 void thread_set_state_timed_parked(threadobject *t)
868 if (t->state != THREAD_STATE_TERMINATED) {
869 thread_set_state(t, THREAD_STATE_TIMED_PARKED);
871 DEBUGTHREADS("is TIMED_PARKED", t);
876 /* thread_set_state_terminated *************************************************
878 Set the current state of the given thread to
879 THREAD_STATE_TERMINATED.
881 *******************************************************************************/
883 void thread_set_state_terminated(threadobject *t)
885 /* Set the state inside a lock. */
887 thread_set_state(t, THREAD_STATE_TERMINATED);
889 DEBUGTHREADS("is TERMINATED", t);
893 /* thread_get_thread **********************************************************
895 Return the thread data structure of the given Java thread object.
898 h ... java.lang.{VM}Thread object
904 Usage of this function without the thread list lock held is
905 almost certainly a bug.
907 *******************************************************************************/
909 threadobject *thread_get_thread(java_handle_t *h)
911 return ThreadRuntime::get_threadobject_from_thread(h);
915 /* threads_thread_is_alive *****************************************************
917 Returns if the give thread is alive.
919 *******************************************************************************/
921 bool threads_thread_is_alive(threadobject *t)
925 state = cacaothread_get_state(t);
928 case THREAD_STATE_NEW:
929 case THREAD_STATE_TERMINATED:
932 case THREAD_STATE_RUNNABLE:
933 case THREAD_STATE_BLOCKED:
934 case THREAD_STATE_WAITING:
935 case THREAD_STATE_TIMED_WAITING:
936 case THREAD_STATE_PARKED:
937 case THREAD_STATE_TIMED_PARKED:
941 vm_abort("threads_thread_is_alive: unknown thread state %d", state);
944 /* keep compiler happy */
949 /* thread_is_interrupted *******************************************************
951 Check if the given thread has been interrupted.
954 t ... the thread to check
957 true, if the given thread had been interrupted
959 *******************************************************************************/
961 bool thread_is_interrupted(threadobject *t)
963 /* We need the mutex because classpath will call this function when
964 a blocking system call is interrupted. The mutex ensures that it will
965 see the correct value for the interrupted flag. */
967 t->waitmutex->lock();
968 bool interrupted = t->interrupted;
969 t->waitmutex->unlock();
975 /* thread_set_interrupted ******************************************************
977 Set the interrupted flag to the given value.
980 interrupted ... value to set
982 *******************************************************************************/
984 void thread_set_interrupted(threadobject *t, bool interrupted)
986 t->waitmutex->lock();
987 t->interrupted = interrupted;
988 t->waitmutex->unlock();
991 /* thread_handle_set_priority **************************************************
993 Calls threads_set_thread_priority for the threadobject associated
994 with the thread indicated by handle th, while holding the thread
997 *******************************************************************************/
999 void thread_handle_set_priority(java_handle_t *th, int priority)
1001 threadobject *t = thread_get_thread(th);
1002 /* For GNU classpath, this should not happen, because both
1003 setPriority() and start() are synchronized. */
1005 threads_set_thread_priority(t->tid, priority);
1008 /* thread_handle_is_interrupted ************************************************
1010 Calls thread_is_interrupted for the threadobject associated with
1011 the thread indicated by handle th, while holding the thread list
1014 *******************************************************************************/
1016 bool thread_handle_is_interrupted(java_handle_t *th)
1018 threadobject *t = thread_get_thread(th);
1019 return t ? thread_is_interrupted(t) : false;
1022 /* thread_handle_interrupt *****************************************************
1024 Calls threads_thread_interrupt for the threadobject associated with
1025 the thread indicated by handle th, while holding the thread list
1028 *******************************************************************************/
1030 void thread_handle_interrupt(java_handle_t *th)
1032 threadobject *t = thread_get_thread(th);
1033 /* For GNU classpath, this should not happen, because both
1034 interrupt() and start() are synchronized. */
1036 threads_thread_interrupt(t);
1039 /* thread_handle_get_state *****************************************************
1041 Calls cacaothread_get_state for the threadobject associated with
1042 the thread indicated by handle th, while holding the thread list
1045 *******************************************************************************/
1047 int thread_handle_get_state(java_handle_t *th)
1049 threadobject *t = thread_get_thread(th);
1050 return t ? cacaothread_get_state(t) : THREAD_STATE_NEW;
1055 * These are local overrides for various environment variables in Emacs.
1056 * Please do not remove this and leave it at the end of the file, where
1057 * Emacs will automagically detect them.
1058 * ---------------------------------------------------------------------
1061 * indent-tabs-mode: t
1065 * vim:noexpandtab:sw=4:ts=4: