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 java_handle_t *h = LLNI_WRAP(t->object);
373 java_lang_Thread jlt(h);
374 ThreadRuntime::clear_heap_reference(jlt);
376 /* Set the reference to the Java object to NULL. */
380 ThreadList::deactivate_thread(t);
384 /* threads_thread_start_internal ***********************************************
386 Start an internal thread in the JVM. No Java thread objects exists
390 name.......UTF-8 name of the thread
391 f..........function pointer to C function to start
393 *******************************************************************************/
395 static void thread_cleanup_finalizer(java_handle_t *h, void *data)
397 threadobject *t = reinterpret_cast<threadobject*>(data);
398 ThreadList::release_thread(t, false);
401 bool threads_thread_start_internal(utf *name, functionptr f)
405 /* Create internal thread data-structure. */
407 t = thread_new(THREAD_FLAG_INTERNAL | THREAD_FLAG_DAEMON);
409 /* Add the thread to the thread list. */
411 ThreadList::add_to_active_thread_list(t);
413 /* Create the Java thread object. */
415 if (!thread_create_object(t, javastring_new(name), threadgroup_system)) {
416 ThreadList::release_thread(t, true);
420 Finalizer::attach_custom_finalizer(LLNI_WRAP(t->object), thread_cleanup_finalizer, t);
422 /* Start the thread. */
424 threads_impl_thread_start(t, f);
426 /* everything's ok */
432 /* threads_thread_start ********************************************************
434 Start a Java thread in the JVM. Only the java thread object exists
438 object.....the java thread object java.lang.Thread
440 *******************************************************************************/
442 void threads_thread_start(java_handle_t *object)
444 java_lang_Thread jlt(object);
446 /* Create internal thread data-structure. */
448 u4 flags = THREAD_FLAG_JAVA;
449 #if defined(ENABLE_JAVASE)
450 /* Is this a daemon thread? */
452 if (jlt.get_daemon())
453 flags |= THREAD_FLAG_DAEMON;
456 threadobject* t = thread_new(flags);
458 /* Link the two objects together. */
460 t->object = LLNI_DIRECT(object);
462 /* Add the thread to the thread list. */
464 ThreadList::add_to_active_thread_list(t);
466 Atomic::write_memory_barrier();
468 ThreadRuntime::setup_thread_vmdata(jlt, t);
470 Finalizer::attach_custom_finalizer(LLNI_WRAP(t->object), thread_cleanup_finalizer, t);
472 thread_set_state_runnable(t);
474 /* Start the thread. Don't pass a function pointer (NULL) since
475 we want Thread.run()V here. */
477 threads_impl_thread_start(t, NULL);
482 * Attaches the current thread to the VM.
484 * @param vm_aargs Attach arguments.
485 * @param isdaemon true if the attached thread should be a daemon
488 * @return true on success, false otherwise.
490 bool thread_attach_current_thread(JavaVMAttachArgs *vm_aargs, bool isdaemon)
496 java_handle_t *group;
498 /* If the current thread has already been attached, this operation
501 result = thread_current_is_attached();
506 /* Create internal thread data structure. */
508 u4 flags = THREAD_FLAG_JAVA;
510 flags |= THREAD_FLAG_DAEMON;
512 t = thread_new(flags);
514 /* Store the internal thread data-structure in the TSD. */
516 thread_set_current(t);
518 /* The thread is flagged and (non-)daemon thread, we can leave the
521 /* Add the thread to the thread list. */
523 ThreadList::add_to_active_thread_list(t);
525 DEBUGTHREADS("attaching", t);
527 /* Get the thread name. */
529 if (vm_aargs != NULL) {
530 u = utf_new_char(vm_aargs->name);
536 name = javastring_new(u);
538 #if defined(ENABLE_JAVASE)
539 /* Get the threadgroup. */
541 if (vm_aargs != NULL)
542 group = (java_handle_t *) vm_aargs->group;
546 /* If no threadgroup was given, use the main threadgroup. */
549 group = threadgroup_main;
552 #if defined(ENABLE_INTRP)
553 /* create interpreter stack */
556 MSET(intrp_main_stack, 0, u1, opt_stacksize);
557 thread->_global_sp = (Cell *) (intrp_main_stack + opt_stacksize);
561 /* Create the Java thread object. */
563 if (!thread_create_object(t, name, group)) {
564 ThreadList::release_thread(t, true);
568 /* The thread is completely initialized. */
570 thread_set_state_runnable(t);
577 * Attaches the current external thread to the VM. This function is
578 * called by JNI's AttachCurrentThread.
580 * @param vm_aargs Attach arguments.
581 * @param isdaemon true if the attached thread should be a daemon
584 * @return true on success, false otherwise.
586 bool thread_attach_current_external_thread(JavaVMAttachArgs *vm_aargs, bool isdaemon)
590 #if defined(ENABLE_GC_BOEHM)
591 struct GC_stack_base sb;
593 /* Register the thread with Boehm-GC. This must happen before the
594 thread allocates any memory from the GC heap.*/
596 result = GC_get_stack_base(&sb);
598 if (result != GC_SUCCESS)
599 vm_abort("threads_attach_current_thread: GC_get_stack_base failed");
601 GC_register_my_thread(&sb);
604 result = thread_attach_current_thread(vm_aargs, isdaemon);
606 if (result == false) {
607 #if defined(ENABLE_GC_BOEHM)
608 /* Unregister the thread. */
610 GC_unregister_my_thread();
621 * Detaches the current external thread from the VM. This function is
622 * called by JNI's DetachCurrentThread.
624 * @return true on success, false otherwise.
626 bool thread_detach_current_external_thread(void)
630 result = thread_detach_current_thread();
635 #if defined(ENABLE_GC_BOEHM)
636 /* Unregister the thread with Boehm-GC. This must happen after
637 the thread allocates any memory from the GC heap. */
639 /* Don't detach the main thread. This is a workaround for
640 OpenJDK's java launcher. */
641 if (thread_get_current()->index != 1)
642 GC_unregister_my_thread();
649 /* thread_fprint_name **********************************************************
651 Print the name of the given thread to the given stream.
654 t ........ thread data-structure
655 stream ... stream to print to
657 *******************************************************************************/
659 void thread_fprint_name(threadobject *t, FILE *stream)
661 if (LLNI_WRAP(t->object) == NULL)
664 java_lang_Thread jlt(LLNI_WRAP(t->object));
666 ThreadRuntime::print_thread_name(jlt, stream);
670 /* thread_print_info ***********************************************************
672 Print information of the passed thread.
675 t ... thread data-structure.
677 *******************************************************************************/
679 void thread_print_info(threadobject *t)
681 java_lang_Thread jlt(LLNI_WRAP(t->object));
683 /* Print as much as we can when we are in state NEW. */
685 if (jlt.get_handle() != NULL) {
686 /* Print thread name. */
689 thread_fprint_name(t, stdout);
695 if (thread_is_daemon(t))
698 if (jlt.get_handle() != NULL) {
699 printf(" prio=%d", jlt.get_priority());
702 #if SIZEOF_VOID_P == 8
703 printf(" t=0x%016lx tid=0x%016lx (%ld)",
704 (ptrint) t, (ptrint) t->tid, (ptrint) t->tid);
706 printf(" t=0x%08x tid=0x%08x (%d)",
707 (ptrint) t, (ptrint) t->tid, (ptrint) t->tid);
710 printf(" index=%d", t->index);
712 /* Print thread state. */
714 int state = cacaothread_get_state(t);
717 case THREAD_STATE_NEW:
720 case THREAD_STATE_RUNNABLE:
723 case THREAD_STATE_BLOCKED:
726 case THREAD_STATE_WAITING:
729 case THREAD_STATE_TIMED_WAITING:
730 printf(" waiting on condition");
732 case THREAD_STATE_PARKED:
735 case THREAD_STATE_TIMED_PARKED:
736 printf(" timed parked");
738 case THREAD_STATE_TERMINATED:
739 printf(" terminated");
742 vm_abort("thread_print_info: unknown thread state %d", state);
747 /* threads_get_current_tid *****************************************************
749 Return the tid of the current thread.
754 *******************************************************************************/
756 intptr_t threads_get_current_tid(void)
758 threadobject *thread;
760 thread = THREADOBJECT;
762 /* this may happen during bootstrap */
767 return (intptr_t) thread->tid;
772 * Set the current state of the given thread. This method should only
773 * be called while holding the threadlist-lock and after checking that
774 * the new state is valid. It is best to not call this method directly
775 * but call the specific setter methods below.
777 static inline void thread_set_state(threadobject *t, int state)
779 // Set the state of our internal threadobject.
782 ThreadRuntime::set_javathread_state(t, state);
786 /* thread_set_state_runnable ***************************************************
788 Set the current state of the given thread to THREAD_STATE_RUNNABLE.
790 NOTE: If the thread has already terminated, don't set the state.
791 This is important for threads_detach_thread.
793 *******************************************************************************/
795 void thread_set_state_runnable(threadobject *t)
797 if (t->state != THREAD_STATE_TERMINATED) {
798 thread_set_state(t, THREAD_STATE_RUNNABLE);
800 DEBUGTHREADS("is RUNNABLE", t);
805 /* thread_set_state_waiting ****************************************************
807 Set the current state of the given thread to THREAD_STATE_WAITING.
809 NOTE: If the thread has already terminated, don't set the state.
810 This is important for threads_detach_thread.
812 *******************************************************************************/
814 void thread_set_state_waiting(threadobject *t)
816 if (t->state != THREAD_STATE_TERMINATED) {
817 thread_set_state(t, THREAD_STATE_WAITING);
819 DEBUGTHREADS("is WAITING", t);
824 /* thread_set_state_timed_waiting **********************************************
826 Set the current state of the given thread to
827 THREAD_STATE_TIMED_WAITING.
829 NOTE: If the thread has already terminated, don't set the state.
830 This is important for threads_detach_thread.
832 *******************************************************************************/
834 void thread_set_state_timed_waiting(threadobject *t)
836 if (t->state != THREAD_STATE_TERMINATED) {
837 thread_set_state(t, THREAD_STATE_TIMED_WAITING);
839 DEBUGTHREADS("is TIMED_WAITING", t);
844 /* thread_set_state_parked *****************************************************
846 Set the current state of the given thread to THREAD_STATE_PARKED.
848 NOTE: If the thread has already terminated, don't set the state.
849 This is important for threads_detach_thread.
851 *******************************************************************************/
853 void thread_set_state_parked(threadobject *t)
855 if (t->state != THREAD_STATE_TERMINATED) {
856 thread_set_state(t, THREAD_STATE_PARKED);
858 DEBUGTHREADS("is PARKED", t);
863 /* thread_set_state_timed_parked ***********************************************
865 Set the current state of the given thread to THREAD_STATE_TIMED_PARKED.
867 NOTE: If the thread has already terminated, don't set the state.
868 This is important for threads_detach_thread.
870 *******************************************************************************/
872 void thread_set_state_timed_parked(threadobject *t)
874 if (t->state != THREAD_STATE_TERMINATED) {
875 thread_set_state(t, THREAD_STATE_TIMED_PARKED);
877 DEBUGTHREADS("is TIMED_PARKED", t);
882 /* thread_set_state_terminated *************************************************
884 Set the current state of the given thread to
885 THREAD_STATE_TERMINATED.
887 *******************************************************************************/
889 void thread_set_state_terminated(threadobject *t)
891 /* Set the state inside a lock. */
893 thread_set_state(t, THREAD_STATE_TERMINATED);
895 DEBUGTHREADS("is TERMINATED", t);
899 /* thread_get_thread **********************************************************
901 Return the thread data structure of the given Java thread object.
904 h ... java.lang.{VM}Thread object
910 Usage of this function without the thread list lock held is
911 almost certainly a bug.
913 *******************************************************************************/
915 threadobject *thread_get_thread(java_handle_t *h)
917 return ThreadRuntime::get_threadobject_from_thread(h);
921 /* threads_thread_is_alive *****************************************************
923 Returns if the give thread is alive.
925 *******************************************************************************/
927 bool threads_thread_is_alive(threadobject *t)
931 state = cacaothread_get_state(t);
934 case THREAD_STATE_NEW:
935 case THREAD_STATE_TERMINATED:
938 case THREAD_STATE_RUNNABLE:
939 case THREAD_STATE_BLOCKED:
940 case THREAD_STATE_WAITING:
941 case THREAD_STATE_TIMED_WAITING:
942 case THREAD_STATE_PARKED:
943 case THREAD_STATE_TIMED_PARKED:
947 vm_abort("threads_thread_is_alive: unknown thread state %d", state);
950 /* keep compiler happy */
955 /* thread_is_interrupted *******************************************************
957 Check if the given thread has been interrupted.
960 t ... the thread to check
963 true, if the given thread had been interrupted
965 *******************************************************************************/
967 bool thread_is_interrupted(threadobject *t)
969 /* We need the mutex because classpath will call this function when
970 a blocking system call is interrupted. The mutex ensures that it will
971 see the correct value for the interrupted flag. */
973 t->waitmutex->lock();
974 bool interrupted = t->interrupted;
975 t->waitmutex->unlock();
981 /* thread_set_interrupted ******************************************************
983 Set the interrupted flag to the given value.
986 interrupted ... value to set
988 *******************************************************************************/
990 void thread_set_interrupted(threadobject *t, bool interrupted)
992 t->waitmutex->lock();
993 t->interrupted = interrupted;
994 t->waitmutex->unlock();
997 /* thread_handle_set_priority **************************************************
999 Calls threads_set_thread_priority for the threadobject associated
1000 with the thread indicated by handle th, while holding the thread
1003 *******************************************************************************/
1005 void thread_handle_set_priority(java_handle_t *th, int priority)
1007 threadobject *t = thread_get_thread(th);
1008 /* For GNU classpath, this should not happen, because both
1009 setPriority() and start() are synchronized. */
1011 threads_set_thread_priority(t->tid, priority);
1014 /* thread_handle_is_interrupted ************************************************
1016 Calls thread_is_interrupted for the threadobject associated with
1017 the thread indicated by handle th, while holding the thread list
1020 *******************************************************************************/
1022 bool thread_handle_is_interrupted(java_handle_t *th)
1024 threadobject *t = thread_get_thread(th);
1025 return t ? thread_is_interrupted(t) : false;
1028 /* thread_handle_interrupt *****************************************************
1030 Calls threads_thread_interrupt for the threadobject associated with
1031 the thread indicated by handle th, while holding the thread list
1034 *******************************************************************************/
1036 void thread_handle_interrupt(java_handle_t *th)
1038 threadobject *t = thread_get_thread(th);
1039 /* For GNU classpath, this should not happen, because both
1040 interrupt() and start() are synchronized. */
1042 threads_thread_interrupt(t);
1045 /* thread_handle_get_state *****************************************************
1047 Calls cacaothread_get_state for the threadobject associated with
1048 the thread indicated by handle th, while holding the thread list
1051 *******************************************************************************/
1053 int thread_handle_get_state(java_handle_t *th)
1055 threadobject *t = thread_get_thread(th);
1056 return t ? cacaothread_get_state(t) : THREAD_STATE_NEW;
1061 * These are local overrides for various environment variables in Emacs.
1062 * Please do not remove this and leave it at the end of the file, where
1063 * Emacs will automagically detect them.
1064 * ---------------------------------------------------------------------
1067 * indent-tabs-mode: t
1071 * vim:noexpandtab:sw=4:ts=4: