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 /* Start the thread. Don't pass a function pointer (NULL) since
473 we want Thread.run()V here. */
475 threads_impl_thread_start(t, NULL);
480 * Attaches the current thread to the VM.
482 * @param vm_aargs Attach arguments.
483 * @param isdaemon true if the attached thread should be a daemon
486 * @return true on success, false otherwise.
488 bool thread_attach_current_thread(JavaVMAttachArgs *vm_aargs, bool isdaemon)
494 java_handle_t *group;
496 /* If the current thread has already been attached, this operation
499 result = thread_current_is_attached();
504 /* Create internal thread data structure. */
506 u4 flags = THREAD_FLAG_JAVA;
508 flags |= THREAD_FLAG_DAEMON;
510 t = thread_new(flags);
512 /* Store the internal thread data-structure in the TSD. */
514 thread_set_current(t);
516 /* The thread is flagged and (non-)daemon thread, we can leave the
519 /* Add the thread to the thread list. */
521 ThreadList::add_to_active_thread_list(t);
523 DEBUGTHREADS("attaching", t);
525 /* Get the thread name. */
527 if (vm_aargs != NULL) {
528 u = utf_new_char(vm_aargs->name);
534 name = javastring_new(u);
536 #if defined(ENABLE_JAVASE)
537 /* Get the threadgroup. */
539 if (vm_aargs != NULL)
540 group = (java_handle_t *) vm_aargs->group;
544 /* If no threadgroup was given, use the main threadgroup. */
547 group = threadgroup_main;
550 #if defined(ENABLE_INTRP)
551 /* create interpreter stack */
554 MSET(intrp_main_stack, 0, u1, opt_stacksize);
555 thread->_global_sp = (Cell *) (intrp_main_stack + opt_stacksize);
559 /* Create the Java thread object. */
561 if (!thread_create_object(t, name, group)) {
562 ThreadList::release_thread(t, true);
566 /* The thread is completely initialized. */
568 thread_set_state_runnable(t);
575 * Attaches the current external thread to the VM. This function is
576 * called by JNI's AttachCurrentThread.
578 * @param vm_aargs Attach arguments.
579 * @param isdaemon true if the attached thread should be a daemon
582 * @return true on success, false otherwise.
584 bool thread_attach_current_external_thread(JavaVMAttachArgs *vm_aargs, bool isdaemon)
588 #if defined(ENABLE_GC_BOEHM)
589 struct GC_stack_base sb;
591 /* Register the thread with Boehm-GC. This must happen before the
592 thread allocates any memory from the GC heap.*/
594 result = GC_get_stack_base(&sb);
596 if (result != GC_SUCCESS)
597 vm_abort("threads_attach_current_thread: GC_get_stack_base failed");
599 GC_register_my_thread(&sb);
602 result = thread_attach_current_thread(vm_aargs, isdaemon);
604 if (result == false) {
605 #if defined(ENABLE_GC_BOEHM)
606 /* Unregister the thread. */
608 GC_unregister_my_thread();
619 * Detaches the current external thread from the VM. This function is
620 * called by JNI's DetachCurrentThread.
622 * @return true on success, false otherwise.
624 bool thread_detach_current_external_thread(void)
628 result = thread_detach_current_thread();
633 #if defined(ENABLE_GC_BOEHM)
634 /* Unregister the thread with Boehm-GC. This must happen after
635 the thread allocates any memory from the GC heap. */
637 /* Don't detach the main thread. This is a workaround for
638 OpenJDK's java launcher. */
639 if (thread_get_current()->index != 1)
640 GC_unregister_my_thread();
647 /* thread_fprint_name **********************************************************
649 Print the name of the given thread to the given stream.
652 t ........ thread data-structure
653 stream ... stream to print to
655 *******************************************************************************/
657 void thread_fprint_name(threadobject *t, FILE *stream)
659 if (LLNI_WRAP(t->object) == NULL)
662 java_lang_Thread jlt(LLNI_WRAP(t->object));
664 ThreadRuntime::print_thread_name(jlt, stream);
668 /* thread_print_info ***********************************************************
670 Print information of the passed thread.
673 t ... thread data-structure.
675 *******************************************************************************/
677 void thread_print_info(threadobject *t)
679 java_lang_Thread jlt(LLNI_WRAP(t->object));
681 /* Print as much as we can when we are in state NEW. */
683 if (jlt.get_handle() != NULL) {
684 /* Print thread name. */
687 thread_fprint_name(t, stdout);
693 if (thread_is_daemon(t))
696 if (jlt.get_handle() != NULL) {
697 printf(" prio=%d", jlt.get_priority());
700 #if SIZEOF_VOID_P == 8
701 printf(" t=0x%016lx tid=0x%016lx (%ld)",
702 (ptrint) t, (ptrint) t->tid, (ptrint) t->tid);
704 printf(" t=0x%08x tid=0x%08x (%d)",
705 (ptrint) t, (ptrint) t->tid, (ptrint) t->tid);
708 printf(" index=%d", t->index);
710 /* Print thread state. */
712 int state = cacaothread_get_state(t);
715 case THREAD_STATE_NEW:
718 case THREAD_STATE_RUNNABLE:
721 case THREAD_STATE_BLOCKED:
724 case THREAD_STATE_WAITING:
727 case THREAD_STATE_TIMED_WAITING:
728 printf(" waiting on condition");
730 case THREAD_STATE_PARKED:
733 case THREAD_STATE_TIMED_PARKED:
734 printf(" timed parked");
736 case THREAD_STATE_TERMINATED:
737 printf(" terminated");
740 vm_abort("thread_print_info: unknown thread state %d", state);
745 /* threads_get_current_tid *****************************************************
747 Return the tid of the current thread.
752 *******************************************************************************/
754 intptr_t threads_get_current_tid(void)
756 threadobject *thread;
758 thread = THREADOBJECT;
760 /* this may happen during bootstrap */
765 return (intptr_t) thread->tid;
770 * Set the current state of the given thread. This method should only
771 * be called while holding the threadlist-lock and after checking that
772 * the new state is valid. It is best to not call this method directly
773 * but call the specific setter methods below.
775 static inline void thread_set_state(threadobject *t, int state)
777 // Set the state of our internal threadobject.
780 ThreadRuntime::set_javathread_state(t, state);
784 /* thread_set_state_runnable ***************************************************
786 Set the current state of the given thread to THREAD_STATE_RUNNABLE.
788 NOTE: If the thread has already terminated, don't set the state.
789 This is important for threads_detach_thread.
791 *******************************************************************************/
793 void thread_set_state_runnable(threadobject *t)
795 if (t->state != THREAD_STATE_TERMINATED) {
796 thread_set_state(t, THREAD_STATE_RUNNABLE);
798 DEBUGTHREADS("is RUNNABLE", t);
803 /* thread_set_state_waiting ****************************************************
805 Set the current state of the given thread to THREAD_STATE_WAITING.
807 NOTE: If the thread has already terminated, don't set the state.
808 This is important for threads_detach_thread.
810 *******************************************************************************/
812 void thread_set_state_waiting(threadobject *t)
814 if (t->state != THREAD_STATE_TERMINATED) {
815 thread_set_state(t, THREAD_STATE_WAITING);
817 DEBUGTHREADS("is WAITING", t);
822 /* thread_set_state_timed_waiting **********************************************
824 Set the current state of the given thread to
825 THREAD_STATE_TIMED_WAITING.
827 NOTE: If the thread has already terminated, don't set the state.
828 This is important for threads_detach_thread.
830 *******************************************************************************/
832 void thread_set_state_timed_waiting(threadobject *t)
834 if (t->state != THREAD_STATE_TERMINATED) {
835 thread_set_state(t, THREAD_STATE_TIMED_WAITING);
837 DEBUGTHREADS("is TIMED_WAITING", t);
842 /* thread_set_state_parked *****************************************************
844 Set the current state of the given thread to THREAD_STATE_PARKED.
846 NOTE: If the thread has already terminated, don't set the state.
847 This is important for threads_detach_thread.
849 *******************************************************************************/
851 void thread_set_state_parked(threadobject *t)
853 if (t->state != THREAD_STATE_TERMINATED) {
854 thread_set_state(t, THREAD_STATE_PARKED);
856 DEBUGTHREADS("is PARKED", t);
861 /* thread_set_state_timed_parked ***********************************************
863 Set the current state of the given thread to THREAD_STATE_TIMED_PARKED.
865 NOTE: If the thread has already terminated, don't set the state.
866 This is important for threads_detach_thread.
868 *******************************************************************************/
870 void thread_set_state_timed_parked(threadobject *t)
872 if (t->state != THREAD_STATE_TERMINATED) {
873 thread_set_state(t, THREAD_STATE_TIMED_PARKED);
875 DEBUGTHREADS("is TIMED_PARKED", t);
880 /* thread_set_state_terminated *************************************************
882 Set the current state of the given thread to
883 THREAD_STATE_TERMINATED.
885 *******************************************************************************/
887 void thread_set_state_terminated(threadobject *t)
889 /* Set the state inside a lock. */
891 thread_set_state(t, THREAD_STATE_TERMINATED);
893 DEBUGTHREADS("is TERMINATED", t);
897 /* thread_get_thread **********************************************************
899 Return the thread data structure of the given Java thread object.
902 h ... java.lang.{VM}Thread object
908 Usage of this function without the thread list lock held is
909 almost certainly a bug.
911 *******************************************************************************/
913 threadobject *thread_get_thread(java_handle_t *h)
915 return ThreadRuntime::get_threadobject_from_thread(h);
919 /* threads_thread_is_alive *****************************************************
921 Returns if the give thread is alive.
923 *******************************************************************************/
925 bool threads_thread_is_alive(threadobject *t)
929 state = cacaothread_get_state(t);
932 case THREAD_STATE_NEW:
933 case THREAD_STATE_TERMINATED:
936 case THREAD_STATE_RUNNABLE:
937 case THREAD_STATE_BLOCKED:
938 case THREAD_STATE_WAITING:
939 case THREAD_STATE_TIMED_WAITING:
940 case THREAD_STATE_PARKED:
941 case THREAD_STATE_TIMED_PARKED:
945 vm_abort("threads_thread_is_alive: unknown thread state %d", state);
948 /* keep compiler happy */
953 /* thread_is_interrupted *******************************************************
955 Check if the given thread has been interrupted.
958 t ... the thread to check
961 true, if the given thread had been interrupted
963 *******************************************************************************/
965 bool thread_is_interrupted(threadobject *t)
967 /* We need the mutex because classpath will call this function when
968 a blocking system call is interrupted. The mutex ensures that it will
969 see the correct value for the interrupted flag. */
971 t->waitmutex->lock();
972 bool interrupted = t->interrupted;
973 t->waitmutex->unlock();
979 /* thread_set_interrupted ******************************************************
981 Set the interrupted flag to the given value.
984 interrupted ... value to set
986 *******************************************************************************/
988 void thread_set_interrupted(threadobject *t, bool interrupted)
990 t->waitmutex->lock();
991 t->interrupted = interrupted;
992 t->waitmutex->unlock();
995 /* thread_handle_set_priority **************************************************
997 Calls threads_set_thread_priority for the threadobject associated
998 with the thread indicated by handle th, while holding the thread
1001 *******************************************************************************/
1003 void thread_handle_set_priority(java_handle_t *th, int priority)
1005 threadobject *t = thread_get_thread(th);
1006 /* For GNU classpath, this should not happen, because both
1007 setPriority() and start() are synchronized. */
1009 threads_set_thread_priority(t->tid, priority);
1012 /* thread_handle_is_interrupted ************************************************
1014 Calls thread_is_interrupted for the threadobject associated with
1015 the thread indicated by handle th, while holding the thread list
1018 *******************************************************************************/
1020 bool thread_handle_is_interrupted(java_handle_t *th)
1022 threadobject *t = thread_get_thread(th);
1023 return t ? thread_is_interrupted(t) : false;
1026 /* thread_handle_interrupt *****************************************************
1028 Calls threads_thread_interrupt for the threadobject associated with
1029 the thread indicated by handle th, while holding the thread list
1032 *******************************************************************************/
1034 void thread_handle_interrupt(java_handle_t *th)
1036 threadobject *t = thread_get_thread(th);
1037 /* For GNU classpath, this should not happen, because both
1038 interrupt() and start() are synchronized. */
1040 threads_thread_interrupt(t);
1043 /* thread_handle_get_state *****************************************************
1045 Calls cacaothread_get_state for the threadobject associated with
1046 the thread indicated by handle th, while holding the thread list
1049 *******************************************************************************/
1051 int thread_handle_get_state(java_handle_t *th)
1053 threadobject *t = thread_get_thread(th);
1054 return t ? cacaothread_get_state(t) : THREAD_STATE_NEW;
1059 * These are local overrides for various environment variables in Emacs.
1060 * Please do not remove this and leave it at the end of the file, where
1061 * Emacs will automagically detect them.
1062 * ---------------------------------------------------------------------
1065 * indent-tabs-mode: t
1069 * vim:noexpandtab:sw=4:ts=4: