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 /* Add the thread to the thread list. */
144 ThreadList::add_to_active_thread_list(mainthread);
146 /* The main thread should always have index 1. */
148 if (mainthread->index != 1)
149 vm_abort("threads_preinit: main thread index not 1: %d != 1",
152 /* Thread is already running. */
154 mainthread->state = THREAD_STATE_RUNNABLE;
156 /* Store the internal thread data-structure in the TSD. */
158 thread_set_current(mainthread);
162 /* threads_init ****************************************************************
164 Initialize the main thread.
166 *******************************************************************************/
168 void threads_init(void)
170 TRACESUBSYSTEMINITIALIZATION("threads_init");
172 /* Create the system and main thread groups. */
174 ThreadRuntime::thread_create_initial_threadgroups(&threadgroup_main, &threadgroup_system);
176 /* Cache the java.lang.Thread initialization method. */
178 thread_method_init = ThreadRuntime::get_thread_init_method();
180 if (thread_method_init == NULL)
181 vm_abort("threads_init: failed to resolve thread init method");
183 thread_create_initial_thread();
187 /* thread_create_object ********************************************************
189 Create a Java thread object for the given thread data-structure,
190 initializes it and adds the thread to the threadgroup.
195 name .... thread name
196 group ... threadgroup
200 *******************************************************************************/
202 static bool thread_create_object(threadobject *t, java_handle_t *name, java_handle_t *group)
204 /* Create a java.lang.Thread Java object. */
206 java_handle_t* h = builtin_new(class_java_lang_Thread);
211 java_lang_Thread jlt(h);
213 // Set the Java object in the thread data-structure. This
214 // indicates that the thread is attached to the VM.
215 thread_set_object(t, jlt.get_handle());
217 return ThreadRuntime::invoke_thread_initializer(jlt, t, thread_method_init, name, group);
221 /* thread_create_initial_thread ***********************************************
223 Create the initial thread: main
225 *******************************************************************************/
227 static void thread_create_initial_thread(void)
232 /* Get the main-thread (NOTE: The main thread is always the first
233 thread in the list). */
235 t = ThreadList::get_main_thread();
237 /* The thread name. */
239 name = javastring_new(utf_main);
241 #if defined(ENABLE_INTRP)
242 /* create interpreter stack */
245 MSET(intrp_main_stack, 0, u1, opt_stacksize);
246 mainthread->_global_sp = (Cell*) (intrp_main_stack + opt_stacksize);
250 /* Create the Java thread object. */
252 if (!thread_create_object(t, name, threadgroup_main))
253 vm_abort("thread_create_initial_thread: failed to create Java object");
255 /* Initialize the implementation specific bits. */
259 DEBUGTHREADS("starting (main)", t);
263 /* thread_new ******************************************************************
265 Allocates and initializes an internal thread data-structure and
266 adds it to the threads list.
268 *******************************************************************************/
270 static threadobject *thread_new(int32_t flags)
275 /* Lock the thread lists */
279 index = ThreadList::get_free_thread_index();
281 /* Allocate a thread data structure. */
283 /* First, try to get one from the free-list. */
285 t = ThreadList::get_free_thread();
287 /* Unlock the thread lists. */
289 ThreadList::unlock();
292 /* Equivalent of MZERO on the else path */
294 threads_impl_thread_clear(t);
297 #if defined(ENABLE_GC_BOEHM)
298 t = GCNEW_UNCOLLECTABLE(threadobject, 1);
300 t = NEW(threadobject);
303 #if defined(ENABLE_STATISTICS)
305 size_threadobject += sizeof(threadobject);
310 MZERO(t, threadobject, 1);
312 // Initialize the mutex and the condition.
313 t->flc_lock = new Mutex();
314 t->flc_cond = new Condition();
316 t->waitmutex = new Mutex();
317 t->waitcond = new Condition();
319 t->suspendmutex = new Mutex();
320 t->suspendcond = new Condition();
322 #if defined(ENABLE_TLH)
326 #if defined(ENABLE_GC_CACAO)
327 /* Register reference to java.lang.Thread with the GC. */
328 /* FIXME is it ok to do this only once? */
330 gc_reference_register(&(t->object), GC_REFTYPE_THREADOBJECT);
331 gc_reference_register(&(t->_exceptionptr), GC_REFTYPE_THREADOBJECT);
334 t->_dumpmemory = new DumpMemory();
337 /* Pre-compute the thinlock-word. */
342 t->thinlock = Lockword::pre_compute_thinlock(t->index);
344 t->state = THREAD_STATE_NEW;
346 #if defined(ENABLE_GC_CACAO)
347 t->flags |= THREAD_FLAG_IN_NATIVE;
350 /* Initialize the implementation-specific bits. */
352 threads_impl_thread_reuse(t);
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 /* Add the thread to the thread list. */
408 ThreadList::add_to_active_thread_list(t);
410 /* The thread is flagged as (non-)daemon thread, we can leave the
413 threads_mutex_join_unlock();
415 /* Create the Java thread object. */
417 if (!thread_create_object(t, javastring_new(name), threadgroup_system))
420 /* Start the thread. */
422 threads_impl_thread_start(t, f);
424 /* everything's ok */
430 /* threads_thread_start ********************************************************
432 Start a Java thread in the JVM. Only the java thread object exists
436 object.....the java thread object java.lang.Thread
438 *******************************************************************************/
440 void threads_thread_start(java_handle_t *object)
442 java_lang_Thread jlt(object);
444 /* Enter the join-mutex, so if the main-thread is currently
445 waiting to join all threads, the number of non-daemon threads
448 threads_mutex_join_lock();
450 /* Create internal thread data-structure. */
452 threadobject* t = thread_new(THREAD_FLAG_JAVA);
454 #if defined(ENABLE_JAVASE)
455 /* Is this a daemon thread? */
457 if (jlt.get_daemon() == true)
458 t->flags |= THREAD_FLAG_DAEMON;
461 /* Link the two objects together. */
463 thread_set_object(t, object);
465 /* Add the thread to the thread list. */
467 ThreadList::add_to_active_thread_list(t);
469 threads_mutex_join_unlock();
471 ThreadRuntime::setup_thread_vmdata(jlt, t);
473 /* Start the thread. Don't pass a function pointer (NULL) since
474 we want Thread.run()V here. */
476 threads_impl_thread_start(t, NULL);
481 * Attaches the current thread to the VM.
483 * @param vm_aargs Attach arguments.
484 * @param isdaemon true if the attached thread should be a daemon
487 * @return true on success, false otherwise.
489 bool thread_attach_current_thread(JavaVMAttachArgs *vm_aargs, bool isdaemon)
495 java_handle_t *group;
497 /* If the current thread has already been attached, this operation
500 result = thread_current_is_attached();
505 /* Enter the join-mutex, so if the main-thread is currently
506 waiting to join all threads, the number of non-daemon threads
509 threads_mutex_join_lock();
511 /* Create internal thread data structure. */
513 t = thread_new(THREAD_FLAG_JAVA);
516 t->flags |= THREAD_FLAG_DAEMON;
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 threads_mutex_join_unlock();
531 DEBUGTHREADS("attaching", t);
533 /* Get the thread name. */
535 if (vm_aargs != NULL) {
536 u = utf_new_char(vm_aargs->name);
542 name = javastring_new(u);
544 #if defined(ENABLE_JAVASE)
545 /* Get the threadgroup. */
547 if (vm_aargs != NULL)
548 group = (java_handle_t *) vm_aargs->group;
552 /* If no threadgroup was given, use the main threadgroup. */
555 group = threadgroup_main;
558 #if defined(ENABLE_INTRP)
559 /* create interpreter stack */
562 MSET(intrp_main_stack, 0, u1, opt_stacksize);
563 thread->_global_sp = (Cell *) (intrp_main_stack + opt_stacksize);
567 /* Create the Java thread object. */
569 if (!thread_create_object(t, name, group))
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 (thread_get_object(t) == NULL)
668 java_lang_Thread jlt(thread_get_object(t));
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(thread_get_object(t));
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. */
899 thread_set_state(t, THREAD_STATE_TERMINATED);
901 DEBUGTHREADS("is TERMINATED", t);
903 ThreadList::unlock();
907 /* thread_get_thread **********************************************************
909 Return the thread data structure of the given Java thread object.
912 h ... java.lang.{VM}Thread object
918 Usage of this function without the thread list lock held is
919 almost certainly a bug.
921 *******************************************************************************/
923 threadobject *thread_get_thread(java_handle_t *h)
925 return ThreadRuntime::get_threadobject_from_thread(h);
929 /* threads_thread_is_alive *****************************************************
931 Returns if the give thread is alive.
933 *******************************************************************************/
935 bool threads_thread_is_alive(threadobject *t)
939 state = cacaothread_get_state(t);
942 case THREAD_STATE_NEW:
943 case THREAD_STATE_TERMINATED:
946 case THREAD_STATE_RUNNABLE:
947 case THREAD_STATE_BLOCKED:
948 case THREAD_STATE_WAITING:
949 case THREAD_STATE_TIMED_WAITING:
950 case THREAD_STATE_PARKED:
951 case THREAD_STATE_TIMED_PARKED:
955 vm_abort("threads_thread_is_alive: unknown thread state %d", state);
958 /* keep compiler happy */
963 /* thread_is_interrupted *******************************************************
965 Check if the given thread has been interrupted.
968 t ... the thread to check
971 true, if the given thread had been interrupted
973 *******************************************************************************/
975 bool thread_is_interrupted(threadobject *t)
977 /* We need the mutex because classpath will call this function when
978 a blocking system call is interrupted. The mutex ensures that it will
979 see the correct value for the interrupted flag. */
981 t->waitmutex->lock();
982 bool interrupted = t->interrupted;
983 t->waitmutex->unlock();
989 /* thread_set_interrupted ******************************************************
991 Set the interrupted flag to the given value.
994 interrupted ... value to set
996 *******************************************************************************/
998 void thread_set_interrupted(threadobject *t, bool interrupted)
1000 t->waitmutex->lock();
1001 t->interrupted = interrupted;
1002 t->waitmutex->unlock();
1005 /* thread_handle_set_priority **************************************************
1007 Calls threads_set_thread_priority for the threadobject associated
1008 with the thread indicated by handle th, while holding the thread
1011 *******************************************************************************/
1013 void thread_handle_set_priority(java_handle_t *th, int priority)
1017 threadobject *t = thread_get_thread(th);
1018 /* For GNU classpath, this should not happen, because both
1019 setPriority() and start() are synchronized. */
1021 threads_set_thread_priority(t->tid, priority);
1024 /* thread_handle_is_interrupted ************************************************
1026 Calls thread_is_interrupted for the threadobject associated with
1027 the thread indicated by handle th, while holding the thread list
1030 *******************************************************************************/
1032 bool thread_handle_is_interrupted(java_handle_t *th)
1036 threadobject *t = thread_get_thread(th);
1037 return t ? thread_is_interrupted(t) : false;
1040 /* thread_handle_interrupt *****************************************************
1042 Calls threads_thread_interrupt for the threadobject associated with
1043 the thread indicated by handle th, while holding the thread list
1046 *******************************************************************************/
1048 void thread_handle_interrupt(java_handle_t *th)
1052 threadobject *t = thread_get_thread(th);
1053 /* For GNU classpath, this should not happen, because both
1054 interrupt() and start() are synchronized. */
1056 threads_thread_interrupt(t);
1059 /* thread_handle_get_state *****************************************************
1061 Calls cacaothread_get_state for the threadobject associated with
1062 the thread indicated by handle th, while holding the thread list
1065 *******************************************************************************/
1067 int thread_handle_get_state(java_handle_t *th)
1071 threadobject *t = thread_get_thread(th);
1072 return t ? cacaothread_get_state(t) : THREAD_STATE_NEW;
1077 * These are local overrides for various environment variables in Emacs.
1078 * Please do not remove this and leave it at the end of the file, where
1079 * Emacs will automagically detect them.
1080 * ---------------------------------------------------------------------
1083 * indent-tabs-mode: t
1087 * vim:noexpandtab:sw=4:ts=4: