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 #if defined(ENABLE_GC_BOEHM)
421 Finalizer::attach_custom_finalizer(LLNI_WRAP(t->object), thread_cleanup_finalizer, t);
424 /* Start the thread. */
426 threads_impl_thread_start(t, f);
428 /* everything's ok */
434 /* threads_thread_start ********************************************************
436 Start a Java thread in the JVM. Only the java thread object exists
440 object.....the java thread object java.lang.Thread
442 *******************************************************************************/
444 void threads_thread_start(java_handle_t *object)
446 java_lang_Thread jlt(object);
448 /* Create internal thread data-structure. */
450 u4 flags = THREAD_FLAG_JAVA;
451 #if defined(ENABLE_JAVASE)
452 /* Is this a daemon thread? */
454 if (jlt.get_daemon())
455 flags |= THREAD_FLAG_DAEMON;
458 threadobject* t = thread_new(flags);
460 /* Link the two objects together. */
462 t->object = LLNI_DIRECT(object);
464 /* Add the thread to the thread list. */
466 ThreadList::add_to_active_thread_list(t);
468 Atomic::write_memory_barrier();
470 ThreadRuntime::setup_thread_vmdata(jlt, t);
472 #if defined(ENABLE_GC_BOEHM)
473 Finalizer::attach_custom_finalizer(LLNI_WRAP(t->object), thread_cleanup_finalizer, t);
476 thread_set_state_runnable(t);
478 /* Start the thread. Don't pass a function pointer (NULL) since
479 we want Thread.run()V here. */
481 threads_impl_thread_start(t, NULL);
486 * Attaches the current thread to the VM.
488 * @param vm_aargs Attach arguments.
489 * @param isdaemon true if the attached thread should be a daemon
492 * @return true on success, false otherwise.
494 bool thread_attach_current_thread(JavaVMAttachArgs *vm_aargs, bool isdaemon)
500 java_handle_t *group;
502 /* If the current thread has already been attached, this operation
505 result = thread_current_is_attached();
510 /* Create internal thread data structure. */
512 u4 flags = THREAD_FLAG_JAVA;
514 flags |= THREAD_FLAG_DAEMON;
516 t = thread_new(flags);
518 /* Store the internal thread data-structure in the TSD. */
520 thread_set_current(t);
522 /* The thread is flagged and (non-)daemon thread, we can leave the
525 /* Add the thread to the thread list. */
527 ThreadList::add_to_active_thread_list(t);
529 DEBUGTHREADS("attaching", t);
531 /* Get the thread name. */
533 if (vm_aargs != NULL) {
534 u = utf_new_char(vm_aargs->name);
540 name = javastring_new(u);
542 #if defined(ENABLE_JAVASE)
543 /* Get the threadgroup. */
545 if (vm_aargs != NULL)
546 group = (java_handle_t *) vm_aargs->group;
550 /* If no threadgroup was given, use the main threadgroup. */
553 group = threadgroup_main;
556 #if defined(ENABLE_INTRP)
557 /* create interpreter stack */
560 MSET(intrp_main_stack, 0, u1, opt_stacksize);
561 thread->_global_sp = (Cell *) (intrp_main_stack + opt_stacksize);
565 /* Create the Java thread object. */
567 if (!thread_create_object(t, name, group)) {
568 ThreadList::release_thread(t, true);
572 /* The thread is completely initialized. */
574 thread_set_state_runnable(t);
581 * Attaches the current external thread to the VM. This function is
582 * called by JNI's AttachCurrentThread.
584 * @param vm_aargs Attach arguments.
585 * @param isdaemon true if the attached thread should be a daemon
588 * @return true on success, false otherwise.
590 bool thread_attach_current_external_thread(JavaVMAttachArgs *vm_aargs, bool isdaemon)
594 #if defined(ENABLE_GC_BOEHM)
595 struct GC_stack_base sb;
597 /* Register the thread with Boehm-GC. This must happen before the
598 thread allocates any memory from the GC heap.*/
600 result = GC_get_stack_base(&sb);
602 if (result != GC_SUCCESS)
603 vm_abort("threads_attach_current_thread: GC_get_stack_base failed");
605 GC_register_my_thread(&sb);
608 result = thread_attach_current_thread(vm_aargs, isdaemon);
610 if (result == false) {
611 #if defined(ENABLE_GC_BOEHM)
612 /* Unregister the thread. */
614 GC_unregister_my_thread();
625 * Detaches the current external thread from the VM. This function is
626 * called by JNI's DetachCurrentThread.
628 * @return true on success, false otherwise.
630 bool thread_detach_current_external_thread(void)
634 result = thread_detach_current_thread();
639 #if defined(ENABLE_GC_BOEHM)
640 /* Unregister the thread with Boehm-GC. This must happen after
641 the thread allocates any memory from the GC heap. */
643 /* Don't detach the main thread. This is a workaround for
644 OpenJDK's java launcher. */
645 if (thread_get_current()->index != 1)
646 GC_unregister_my_thread();
653 /* thread_fprint_name **********************************************************
655 Print the name of the given thread to the given stream.
658 t ........ thread data-structure
659 stream ... stream to print to
661 *******************************************************************************/
663 void thread_fprint_name(threadobject *t, FILE *stream)
665 if (LLNI_WRAP(t->object) == NULL)
668 java_lang_Thread jlt(LLNI_WRAP(t->object));
670 ThreadRuntime::print_thread_name(jlt, stream);
674 /* thread_print_info ***********************************************************
676 Print information of the passed thread.
679 t ... thread data-structure.
681 *******************************************************************************/
683 void thread_print_info(threadobject *t)
685 java_lang_Thread jlt(LLNI_WRAP(t->object));
687 /* Print as much as we can when we are in state NEW. */
689 if (jlt.get_handle() != NULL) {
690 /* Print thread name. */
693 thread_fprint_name(t, stdout);
699 if (thread_is_daemon(t))
702 if (jlt.get_handle() != NULL) {
703 printf(" prio=%d", jlt.get_priority());
706 #if SIZEOF_VOID_P == 8
707 printf(" t=0x%016lx tid=0x%016lx (%ld)",
708 (ptrint) t, (ptrint) t->tid, (ptrint) t->tid);
710 printf(" t=0x%08x tid=0x%08x (%d)",
711 (ptrint) t, (ptrint) t->tid, (ptrint) t->tid);
714 printf(" index=%d", t->index);
716 /* Print thread state. */
718 int state = cacaothread_get_state(t);
721 case THREAD_STATE_NEW:
724 case THREAD_STATE_RUNNABLE:
727 case THREAD_STATE_BLOCKED:
730 case THREAD_STATE_WAITING:
733 case THREAD_STATE_TIMED_WAITING:
734 printf(" waiting on condition");
736 case THREAD_STATE_PARKED:
739 case THREAD_STATE_TIMED_PARKED:
740 printf(" timed parked");
742 case THREAD_STATE_TERMINATED:
743 printf(" terminated");
746 vm_abort("thread_print_info: unknown thread state %d", state);
751 /* threads_get_current_tid *****************************************************
753 Return the tid of the current thread.
758 *******************************************************************************/
760 intptr_t threads_get_current_tid(void)
762 threadobject *thread;
764 thread = THREADOBJECT;
766 /* this may happen during bootstrap */
771 return (intptr_t) thread->tid;
776 * Set the current state of the given thread. This method should only
777 * be called while holding the threadlist-lock and after checking that
778 * the new state is valid. It is best to not call this method directly
779 * but call the specific setter methods below.
781 static inline void thread_set_state(threadobject *t, int state)
783 // Set the state of our internal threadobject.
786 ThreadRuntime::set_javathread_state(t, state);
790 /* thread_set_state_runnable ***************************************************
792 Set the current state of the given thread to THREAD_STATE_RUNNABLE.
794 NOTE: If the thread has already terminated, don't set the state.
795 This is important for threads_detach_thread.
797 *******************************************************************************/
799 void thread_set_state_runnable(threadobject *t)
801 if (t->state != THREAD_STATE_TERMINATED) {
802 thread_set_state(t, THREAD_STATE_RUNNABLE);
804 DEBUGTHREADS("is RUNNABLE", t);
809 /* thread_set_state_waiting ****************************************************
811 Set the current state of the given thread to THREAD_STATE_WAITING.
813 NOTE: If the thread has already terminated, don't set the state.
814 This is important for threads_detach_thread.
816 *******************************************************************************/
818 void thread_set_state_waiting(threadobject *t)
820 if (t->state != THREAD_STATE_TERMINATED) {
821 thread_set_state(t, THREAD_STATE_WAITING);
823 DEBUGTHREADS("is WAITING", t);
828 /* thread_set_state_timed_waiting **********************************************
830 Set the current state of the given thread to
831 THREAD_STATE_TIMED_WAITING.
833 NOTE: If the thread has already terminated, don't set the state.
834 This is important for threads_detach_thread.
836 *******************************************************************************/
838 void thread_set_state_timed_waiting(threadobject *t)
840 if (t->state != THREAD_STATE_TERMINATED) {
841 thread_set_state(t, THREAD_STATE_TIMED_WAITING);
843 DEBUGTHREADS("is TIMED_WAITING", t);
848 /* thread_set_state_parked *****************************************************
850 Set the current state of the given thread to THREAD_STATE_PARKED.
852 NOTE: If the thread has already terminated, don't set the state.
853 This is important for threads_detach_thread.
855 *******************************************************************************/
857 void thread_set_state_parked(threadobject *t)
859 if (t->state != THREAD_STATE_TERMINATED) {
860 thread_set_state(t, THREAD_STATE_PARKED);
862 DEBUGTHREADS("is PARKED", t);
867 /* thread_set_state_timed_parked ***********************************************
869 Set the current state of the given thread to THREAD_STATE_TIMED_PARKED.
871 NOTE: If the thread has already terminated, don't set the state.
872 This is important for threads_detach_thread.
874 *******************************************************************************/
876 void thread_set_state_timed_parked(threadobject *t)
878 if (t->state != THREAD_STATE_TERMINATED) {
879 thread_set_state(t, THREAD_STATE_TIMED_PARKED);
881 DEBUGTHREADS("is TIMED_PARKED", t);
886 /* thread_set_state_terminated *************************************************
888 Set the current state of the given thread to
889 THREAD_STATE_TERMINATED.
891 *******************************************************************************/
893 void thread_set_state_terminated(threadobject *t)
895 /* Set the state inside a lock. */
897 thread_set_state(t, THREAD_STATE_TERMINATED);
899 DEBUGTHREADS("is TERMINATED", t);
903 /* thread_get_thread **********************************************************
905 Return the thread data structure of the given Java thread object.
908 h ... java.lang.{VM}Thread object
914 Usage of this function without the thread list lock held is
915 almost certainly a bug.
917 *******************************************************************************/
919 threadobject *thread_get_thread(java_handle_t *h)
921 return ThreadRuntime::get_threadobject_from_thread(h);
925 /* threads_thread_is_alive *****************************************************
927 Returns if the give thread is alive.
929 *******************************************************************************/
931 bool threads_thread_is_alive(threadobject *t)
935 state = cacaothread_get_state(t);
938 case THREAD_STATE_NEW:
939 case THREAD_STATE_TERMINATED:
942 case THREAD_STATE_RUNNABLE:
943 case THREAD_STATE_BLOCKED:
944 case THREAD_STATE_WAITING:
945 case THREAD_STATE_TIMED_WAITING:
946 case THREAD_STATE_PARKED:
947 case THREAD_STATE_TIMED_PARKED:
951 vm_abort("threads_thread_is_alive: unknown thread state %d", state);
954 /* keep compiler happy */
959 /* thread_is_interrupted *******************************************************
961 Check if the given thread has been interrupted.
964 t ... the thread to check
967 true, if the given thread had been interrupted
969 *******************************************************************************/
971 bool thread_is_interrupted(threadobject *t)
973 /* We need the mutex because classpath will call this function when
974 a blocking system call is interrupted. The mutex ensures that it will
975 see the correct value for the interrupted flag. */
977 t->waitmutex->lock();
978 bool interrupted = t->interrupted;
979 t->waitmutex->unlock();
985 /* thread_set_interrupted ******************************************************
987 Set the interrupted flag to the given value.
990 interrupted ... value to set
992 *******************************************************************************/
994 void thread_set_interrupted(threadobject *t, bool interrupted)
996 t->waitmutex->lock();
997 t->interrupted = interrupted;
998 t->waitmutex->unlock();
1001 /* thread_handle_set_priority **************************************************
1003 Calls threads_set_thread_priority for the threadobject associated
1004 with the thread indicated by handle th, while holding the thread
1007 *******************************************************************************/
1009 void thread_handle_set_priority(java_handle_t *th, int priority)
1011 threadobject *t = thread_get_thread(th);
1012 /* For GNU classpath, this should not happen, because both
1013 setPriority() and start() are synchronized. */
1015 threads_set_thread_priority(t->tid, priority);
1018 /* thread_handle_is_interrupted ************************************************
1020 Calls thread_is_interrupted for the threadobject associated with
1021 the thread indicated by handle th, while holding the thread list
1024 *******************************************************************************/
1026 bool thread_handle_is_interrupted(java_handle_t *th)
1028 threadobject *t = thread_get_thread(th);
1029 return t ? thread_is_interrupted(t) : false;
1032 /* thread_handle_interrupt *****************************************************
1034 Calls threads_thread_interrupt for the threadobject associated with
1035 the thread indicated by handle th, while holding the thread list
1038 *******************************************************************************/
1040 void thread_handle_interrupt(java_handle_t *th)
1042 threadobject *t = thread_get_thread(th);
1043 /* For GNU classpath, this should not happen, because both
1044 interrupt() and start() are synchronized. */
1046 threads_thread_interrupt(t);
1049 /* thread_handle_get_state *****************************************************
1051 Calls cacaothread_get_state for the threadobject associated with
1052 the thread indicated by handle th, while holding the thread list
1055 *******************************************************************************/
1057 int thread_handle_get_state(java_handle_t *th)
1059 threadobject *t = thread_get_thread(th);
1060 return t ? cacaothread_get_state(t) : THREAD_STATE_NEW;
1065 * These are local overrides for various environment variables in Emacs.
1066 * Please do not remove this and leave it at the end of the file, where
1067 * Emacs will automagically detect them.
1068 * ---------------------------------------------------------------------
1071 * indent-tabs-mode: t
1075 * vim:noexpandtab:sw=4:ts=4: