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/globals.hpp"
53 #include "vm/javaobjects.hpp"
54 #include "vm/method.hpp"
55 #include "vm/options.h"
56 #include "vm/string.hpp"
60 #if defined(ENABLE_STATISTICS)
61 # include "vm/statistics.h"
64 #include "vm/jit/stacktrace.hpp"
67 /* global variables ***********************************************************/
69 static methodinfo *thread_method_init;
70 static java_handle_t *threadgroup_system;
71 static java_handle_t *threadgroup_main;
73 #if defined(__LINUX__)
74 /* XXX Remove for exact-GC. */
75 bool threads_pthreads_implementation_nptl;
79 /* static functions ***********************************************************/
81 static void thread_create_initial_thread(void);
82 static threadobject *thread_new(int32_t flags);
85 /* threads_preinit *************************************************************
87 Do some early initialization of stuff required.
89 *******************************************************************************/
91 void threads_preinit(void)
93 threadobject *mainthread;
94 #if defined(__LINUX__) && defined(_CS_GNU_LIBPTHREAD_VERSION)
99 TRACESUBSYSTEMINITIALIZATION("threads_preinit");
101 #if defined(__LINUX__)
102 /* XXX Remove for exact-GC. */
104 /* On Linux we need to check the pthread implementation. */
106 /* _CS_GNU_LIBPTHREAD_VERSION (GNU C library only; since glibc 2.3.2) */
107 /* If the glibc is a pre-2.3.2 version, we fall back to
110 # if defined(_CS_GNU_LIBPTHREAD_VERSION)
111 len = confstr(_CS_GNU_LIBPTHREAD_VERSION, NULL, (size_t) 0);
113 /* Some systems return as length 0 (maybe cross-compilation
114 related). In this case we also fall back to linuxthreads. */
117 pathbuf = MNEW(char, len);
119 (void) confstr(_CS_GNU_LIBPTHREAD_VERSION, pathbuf, len);
121 if (strstr(pathbuf, "NPTL") != NULL)
122 threads_pthreads_implementation_nptl = true;
124 threads_pthreads_implementation_nptl = false;
127 threads_pthreads_implementation_nptl = false;
129 threads_pthreads_implementation_nptl = false;
133 /* Initialize the threads implementation (sets the thinlock on the
136 threads_impl_preinit();
138 /* Create internal thread data-structure for the main thread. */
140 mainthread = thread_new(THREAD_FLAG_JAVA);
142 /* The main thread should always have index 1. */
144 if (mainthread->index != 1)
145 vm_abort("threads_preinit: main thread index not 1: %d != 1",
148 /* Thread is already running. */
150 mainthread->state = THREAD_STATE_RUNNABLE;
152 /* Store the internal thread data-structure in the TSD. */
154 thread_set_current(mainthread);
158 /* threads_init ****************************************************************
160 Initialize the main thread.
162 *******************************************************************************/
164 void threads_init(void)
166 TRACESUBSYSTEMINITIALIZATION("threads_init");
168 /* Create the system and main thread groups. */
170 ThreadRuntime::thread_create_initial_threadgroups(&threadgroup_main, &threadgroup_system);
172 /* Cache the java.lang.Thread initialization method. */
174 thread_method_init = ThreadRuntime::get_thread_init_method();
176 if (thread_method_init == NULL)
177 vm_abort("threads_init: failed to resolve thread init method");
179 thread_create_initial_thread();
183 /* thread_create_object ********************************************************
185 Create a Java thread object for the given thread data-structure,
186 initializes it and adds the thread to the threadgroup.
191 name .... thread name
192 group ... threadgroup
196 *******************************************************************************/
198 static bool thread_create_object(threadobject *t, java_handle_t *name, java_handle_t *group)
200 /* Create a java.lang.Thread Java object. */
202 java_handle_t* h = builtin_new(class_java_lang_Thread);
207 java_lang_Thread jlt(h);
209 // Set the Java object in the thread data-structure. This
210 // indicates that the thread is attached to the VM.
211 thread_set_object(t, jlt.get_handle());
213 return ThreadRuntime::invoke_thread_initializer(jlt, t, thread_method_init, name, group);
217 /* thread_create_initial_thread ***********************************************
219 Create the initial thread: main
221 *******************************************************************************/
223 static void thread_create_initial_thread(void)
228 /* Get the main-thread (NOTE: The main thread is always the first
229 thread in the list). */
231 t = ThreadList::get_main_thread();
233 /* The thread name. */
235 name = javastring_new(utf_main);
237 #if defined(ENABLE_INTRP)
238 /* create interpreter stack */
241 MSET(intrp_main_stack, 0, u1, opt_stacksize);
242 mainthread->_global_sp = (Cell*) (intrp_main_stack + opt_stacksize);
246 /* Create the Java thread object. */
248 if (!thread_create_object(t, name, threadgroup_main))
249 vm_abort("thread_create_initial_thread: failed to create Java object");
251 /* Initialize the implementation specific bits. */
255 DEBUGTHREADS("starting (main)", t);
259 /* thread_new ******************************************************************
261 Allocates and initializes an internal thread data-structure and
262 adds it to the threads list.
264 *******************************************************************************/
266 static threadobject *thread_new(int32_t flags)
271 /* Lock the thread lists */
275 index = ThreadList::get_free_thread_index();
277 /* Allocate a thread data structure. */
279 /* First, try to get one from the free-list. */
281 t = ThreadList::get_free_thread();
284 /* Equivalent of MZERO on the else path */
286 threads_impl_thread_clear(t);
289 #if defined(ENABLE_GC_BOEHM)
290 t = GCNEW_UNCOLLECTABLE(threadobject, 1);
292 t = NEW(threadobject);
295 #if defined(ENABLE_STATISTICS)
297 size_threadobject += sizeof(threadobject);
302 MZERO(t, threadobject, 1);
304 // Initialize the mutex and the condition.
305 t->flc_lock = new Mutex();
306 t->flc_cond = new Condition();
308 t->waitmutex = new Mutex();
309 t->waitcond = new Condition();
311 t->suspendmutex = new Mutex();
312 t->suspendcond = new Condition();
314 #if defined(ENABLE_TLH)
318 #if defined(ENABLE_GC_CACAO)
319 /* Register reference to java.lang.Thread with the GC. */
320 /* FIXME is it ok to do this only once? */
322 gc_reference_register(&(t->object), GC_REFTYPE_THREADOBJECT);
323 gc_reference_register(&(t->_exceptionptr), GC_REFTYPE_THREADOBJECT);
326 t->_dumpmemory = new DumpMemory();
329 /* Pre-compute the thinlock-word. */
334 t->thinlock = Lockword::pre_compute_thinlock(t->index);
336 t->state = THREAD_STATE_NEW;
338 #if defined(ENABLE_GC_CACAO)
339 t->flags |= THREAD_FLAG_IN_NATIVE;
342 /* Initialize the implementation-specific bits. */
344 threads_impl_thread_reuse(t);
346 /* Add the thread to the thread list. */
348 ThreadList::add_to_active_thread_list(t);
350 /* Unlock the thread lists. */
352 ThreadList::unlock();
358 /* thread_free *****************************************************************
360 Remove the thread from the threads-list and free the internal
361 thread data structure. The thread index is added to the
362 thread-index free-list.
365 t ... thread data structure
367 *******************************************************************************/
369 void thread_free(threadobject *t)
371 /* Set the reference to the Java object to NULL. */
373 thread_set_object(t, NULL);
375 /* Release the thread. */
377 ThreadList::release_thread(t);
381 /* threads_thread_start_internal ***********************************************
383 Start an internal thread in the JVM. No Java thread objects exists
387 name.......UTF-8 name of the thread
388 f..........function pointer to C function to start
390 *******************************************************************************/
392 bool threads_thread_start_internal(utf *name, functionptr f)
396 /* Enter the join-mutex, so if the main-thread is currently
397 waiting to join all threads, the number of non-daemon threads
400 threads_mutex_join_lock();
402 /* Create internal thread data-structure. */
404 t = thread_new(THREAD_FLAG_INTERNAL | THREAD_FLAG_DAEMON);
406 /* The thread is flagged as (non-)daemon thread, we can leave the
409 threads_mutex_join_unlock();
411 /* Create the Java thread object. */
413 if (!thread_create_object(t, javastring_new(name), threadgroup_system))
416 /* Start the thread. */
418 threads_impl_thread_start(t, f);
420 /* everything's ok */
426 /* threads_thread_start ********************************************************
428 Start a Java thread in the JVM. Only the java thread object exists
432 object.....the java thread object java.lang.Thread
434 *******************************************************************************/
436 void threads_thread_start(java_handle_t *object)
438 java_lang_Thread jlt(object);
440 /* Enter the join-mutex, so if the main-thread is currently
441 waiting to join all threads, the number of non-daemon threads
444 threads_mutex_join_lock();
446 /* Create internal thread data-structure. */
448 threadobject* t = thread_new(THREAD_FLAG_JAVA);
450 #if defined(ENABLE_JAVASE)
451 /* Is this a daemon thread? */
453 if (jlt.get_daemon() == true)
454 t->flags |= THREAD_FLAG_DAEMON;
457 /* The thread is flagged and (non-)daemon thread, we can leave the
460 threads_mutex_join_unlock();
462 /* Link the two objects together. */
464 thread_set_object(t, object);
466 ThreadRuntime::setup_thread_vmdata(jlt, 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 /* Enter the join-mutex, so if the main-thread is currently
501 waiting to join all threads, the number of non-daemon threads
504 threads_mutex_join_lock();
506 /* Create internal thread data structure. */
508 t = thread_new(THREAD_FLAG_JAVA);
511 t->flags |= THREAD_FLAG_DAEMON;
513 /* Store the internal thread data-structure in the TSD. */
515 thread_set_current(t);
517 /* The thread is flagged and (non-)daemon thread, we can leave the
520 threads_mutex_join_unlock();
522 DEBUGTHREADS("attaching", t);
524 /* Get the thread name. */
526 if (vm_aargs != NULL) {
527 u = utf_new_char(vm_aargs->name);
533 name = javastring_new(u);
535 #if defined(ENABLE_JAVASE)
536 /* Get the threadgroup. */
538 if (vm_aargs != NULL)
539 group = (java_handle_t *) vm_aargs->group;
543 /* If no threadgroup was given, use the main threadgroup. */
546 group = threadgroup_main;
549 #if defined(ENABLE_INTRP)
550 /* create interpreter stack */
553 MSET(intrp_main_stack, 0, u1, opt_stacksize);
554 thread->_global_sp = (Cell *) (intrp_main_stack + opt_stacksize);
558 /* Create the Java thread object. */
560 if (!thread_create_object(t, name, group))
563 /* The thread is completely initialized. */
565 thread_set_state_runnable(t);
572 * Attaches the current external thread to the VM. This function is
573 * called by JNI's AttachCurrentThread.
575 * @param vm_aargs Attach arguments.
576 * @param isdaemon true if the attached thread should be a daemon
579 * @return true on success, false otherwise.
581 bool thread_attach_current_external_thread(JavaVMAttachArgs *vm_aargs, bool isdaemon)
585 #if defined(ENABLE_GC_BOEHM)
586 struct GC_stack_base sb;
588 /* Register the thread with Boehm-GC. This must happen before the
589 thread allocates any memory from the GC heap.*/
591 result = GC_get_stack_base(&sb);
593 if (result != GC_SUCCESS)
594 vm_abort("threads_attach_current_thread: GC_get_stack_base failed");
596 GC_register_my_thread(&sb);
599 result = thread_attach_current_thread(vm_aargs, isdaemon);
601 if (result == false) {
602 #if defined(ENABLE_GC_BOEHM)
603 /* Unregister the thread. */
605 GC_unregister_my_thread();
616 * Detaches the current external thread from the VM. This function is
617 * called by JNI's DetachCurrentThread.
619 * @return true on success, false otherwise.
621 bool thread_detach_current_external_thread(void)
625 result = thread_detach_current_thread();
630 #if defined(ENABLE_GC_BOEHM)
631 /* Unregister the thread with Boehm-GC. This must happen after
632 the thread allocates any memory from the GC heap. */
634 /* Don't detach the main thread. This is a workaround for
635 OpenJDK's java launcher. */
636 if (thread_get_current()->index != 1)
637 GC_unregister_my_thread();
644 /* thread_fprint_name **********************************************************
646 Print the name of the given thread to the given stream.
649 t ........ thread data-structure
650 stream ... stream to print to
652 *******************************************************************************/
654 void thread_fprint_name(threadobject *t, FILE *stream)
656 if (thread_get_object(t) == NULL)
659 java_lang_Thread jlt(thread_get_object(t));
661 ThreadRuntime::print_thread_name(jlt, stream);
665 /* thread_print_info ***********************************************************
667 Print information of the passed thread.
670 t ... thread data-structure.
672 *******************************************************************************/
674 void thread_print_info(threadobject *t)
676 java_lang_Thread jlt(thread_get_object(t));
678 /* Print as much as we can when we are in state NEW. */
680 if (jlt.get_handle() != NULL) {
681 /* Print thread name. */
684 thread_fprint_name(t, stdout);
690 if (thread_is_daemon(t))
693 if (jlt.get_handle() != NULL) {
694 printf(" prio=%d", jlt.get_priority());
697 #if SIZEOF_VOID_P == 8
698 printf(" t=0x%016lx tid=0x%016lx (%ld)",
699 (ptrint) t, (ptrint) t->tid, (ptrint) t->tid);
701 printf(" t=0x%08x tid=0x%08x (%d)",
702 (ptrint) t, (ptrint) t->tid, (ptrint) t->tid);
705 printf(" index=%d", t->index);
707 /* Print thread state. */
709 int state = cacaothread_get_state(t);
712 case THREAD_STATE_NEW:
715 case THREAD_STATE_RUNNABLE:
718 case THREAD_STATE_BLOCKED:
721 case THREAD_STATE_WAITING:
724 case THREAD_STATE_TIMED_WAITING:
725 printf(" waiting on condition");
727 case THREAD_STATE_PARKED:
730 case THREAD_STATE_TIMED_PARKED:
731 printf(" timed parked");
733 case THREAD_STATE_TERMINATED:
734 printf(" terminated");
737 vm_abort("thread_print_info: unknown thread state %d", state);
742 /* threads_get_current_tid *****************************************************
744 Return the tid of the current thread.
749 *******************************************************************************/
751 intptr_t threads_get_current_tid(void)
753 threadobject *thread;
755 thread = THREADOBJECT;
757 /* this may happen during bootstrap */
762 return (intptr_t) thread->tid;
767 * Set the current state of the given thread. This method should only
768 * be called while holding the threadlist-lock and after checking that
769 * the new state is valid. It is best to not call this method directly
770 * but call the specific setter methods below.
772 static inline void thread_set_state(threadobject *t, int state)
774 // Set the state of our internal threadobject.
777 ThreadRuntime::set_javathread_state(t, state);
781 /* thread_set_state_runnable ***************************************************
783 Set the current state of the given thread to THREAD_STATE_RUNNABLE.
785 NOTE: If the thread has already terminated, don't set the state.
786 This is important for threads_detach_thread.
788 *******************************************************************************/
790 void thread_set_state_runnable(threadobject *t)
792 if (t->state != THREAD_STATE_TERMINATED) {
793 thread_set_state(t, THREAD_STATE_RUNNABLE);
795 DEBUGTHREADS("is RUNNABLE", t);
800 /* thread_set_state_waiting ****************************************************
802 Set the current state of the given thread to THREAD_STATE_WAITING.
804 NOTE: If the thread has already terminated, don't set the state.
805 This is important for threads_detach_thread.
807 *******************************************************************************/
809 void thread_set_state_waiting(threadobject *t)
811 if (t->state != THREAD_STATE_TERMINATED) {
812 thread_set_state(t, THREAD_STATE_WAITING);
814 DEBUGTHREADS("is WAITING", t);
819 /* thread_set_state_timed_waiting **********************************************
821 Set the current state of the given thread to
822 THREAD_STATE_TIMED_WAITING.
824 NOTE: If the thread has already terminated, don't set the state.
825 This is important for threads_detach_thread.
827 *******************************************************************************/
829 void thread_set_state_timed_waiting(threadobject *t)
831 if (t->state != THREAD_STATE_TERMINATED) {
832 thread_set_state(t, THREAD_STATE_TIMED_WAITING);
834 DEBUGTHREADS("is TIMED_WAITING", t);
839 /* thread_set_state_parked *****************************************************
841 Set the current state of the given thread to THREAD_STATE_PARKED.
843 NOTE: If the thread has already terminated, don't set the state.
844 This is important for threads_detach_thread.
846 *******************************************************************************/
848 void thread_set_state_parked(threadobject *t)
850 if (t->state != THREAD_STATE_TERMINATED) {
851 thread_set_state(t, THREAD_STATE_PARKED);
853 DEBUGTHREADS("is PARKED", t);
858 /* thread_set_state_timed_parked ***********************************************
860 Set the current state of the given thread to THREAD_STATE_TIMED_PARKED.
862 NOTE: If the thread has already terminated, don't set the state.
863 This is important for threads_detach_thread.
865 *******************************************************************************/
867 void thread_set_state_timed_parked(threadobject *t)
869 if (t->state != THREAD_STATE_TERMINATED) {
870 thread_set_state(t, THREAD_STATE_TIMED_PARKED);
872 DEBUGTHREADS("is TIMED_PARKED", t);
877 /* thread_set_state_terminated *************************************************
879 Set the current state of the given thread to
880 THREAD_STATE_TERMINATED.
882 *******************************************************************************/
884 void thread_set_state_terminated(threadobject *t)
886 /* Set the state inside a lock. */
890 thread_set_state(t, THREAD_STATE_TERMINATED);
892 DEBUGTHREADS("is TERMINATED", t);
894 ThreadList::unlock();
898 /* thread_get_thread **********************************************************
900 Return the thread data structure of the given Java thread object.
903 h ... java.lang.{VM}Thread object
909 Usage of this function without the thread list lock held is
910 almost certainly a bug.
912 *******************************************************************************/
914 threadobject *thread_get_thread(java_handle_t *h)
916 return ThreadRuntime::get_threadobject_from_thread(h);
920 /* threads_thread_is_alive *****************************************************
922 Returns if the give thread is alive.
924 *******************************************************************************/
926 bool threads_thread_is_alive(threadobject *t)
930 state = cacaothread_get_state(t);
933 case THREAD_STATE_NEW:
934 case THREAD_STATE_TERMINATED:
937 case THREAD_STATE_RUNNABLE:
938 case THREAD_STATE_BLOCKED:
939 case THREAD_STATE_WAITING:
940 case THREAD_STATE_TIMED_WAITING:
941 case THREAD_STATE_PARKED:
942 case THREAD_STATE_TIMED_PARKED:
946 vm_abort("threads_thread_is_alive: unknown thread state %d", state);
949 /* keep compiler happy */
954 /* thread_is_interrupted *******************************************************
956 Check if the given thread has been interrupted.
959 t ... the thread to check
962 true, if the given thread had been interrupted
964 *******************************************************************************/
966 bool thread_is_interrupted(threadobject *t)
968 /* We need the mutex because classpath will call this function when
969 a blocking system call is interrupted. The mutex ensures that it will
970 see the correct value for the interrupted flag. */
972 t->waitmutex->lock();
973 bool interrupted = t->interrupted;
974 t->waitmutex->unlock();
980 /* thread_set_interrupted ******************************************************
982 Set the interrupted flag to the given value.
985 interrupted ... value to set
987 *******************************************************************************/
989 void thread_set_interrupted(threadobject *t, bool interrupted)
991 t->waitmutex->lock();
992 t->interrupted = interrupted;
993 t->waitmutex->unlock();
996 /* thread_handle_set_priority **************************************************
998 Calls threads_set_thread_priority for the threadobject associated
999 with the thread indicated by handle th, while holding the thread
1002 *******************************************************************************/
1004 void thread_handle_set_priority(java_handle_t *th, int priority)
1008 threadobject *t = thread_get_thread(th);
1009 /* For GNU classpath, this should not happen, because both
1010 setPriority() and start() are synchronized. */
1012 threads_set_thread_priority(t->tid, priority);
1015 /* thread_handle_is_interrupted ************************************************
1017 Calls thread_is_interrupted for the threadobject associated with
1018 the thread indicated by handle th, while holding the thread list
1021 *******************************************************************************/
1023 bool thread_handle_is_interrupted(java_handle_t *th)
1027 threadobject *t = thread_get_thread(th);
1028 return t ? thread_is_interrupted(t) : false;
1031 /* thread_handle_interrupt *****************************************************
1033 Calls threads_thread_interrupt for the threadobject associated with
1034 the thread indicated by handle th, while holding the thread list
1037 *******************************************************************************/
1039 void thread_handle_interrupt(java_handle_t *th)
1043 threadobject *t = thread_get_thread(th);
1044 /* For GNU classpath, this should not happen, because both
1045 interrupt() and start() are synchronized. */
1047 threads_thread_interrupt(t);
1050 /* thread_handle_get_state *****************************************************
1052 Calls cacaothread_get_state for the threadobject associated with
1053 the thread indicated by handle th, while holding the thread list
1056 *******************************************************************************/
1058 int thread_handle_get_state(java_handle_t *th)
1062 threadobject *t = thread_get_thread(th);
1063 return t ? cacaothread_get_state(t) : THREAD_STATE_NEW;
1068 * These are local overrides for various environment variables in Emacs.
1069 * Please do not remove this and leave it at the end of the file, where
1070 * Emacs will automagically detect them.
1071 * ---------------------------------------------------------------------
1074 * indent-tabs-mode: t
1078 * vim:noexpandtab:sw=4:ts=4: