thread.cpp revision 1472
0N/A/*
0N/A * Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
0N/A * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
0N/A *
0N/A * This code is free software; you can redistribute it and/or modify it
0N/A * under the terms of the GNU General Public License version 2 only, as
0N/A * published by the Free Software Foundation.
0N/A *
0N/A * This code is distributed in the hope that it will be useful, but WITHOUT
0N/A * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
0N/A * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
0N/A * version 2 for more details (a copy is included in the LICENSE file that
0N/A * accompanied this code).
0N/A *
0N/A * You should have received a copy of the GNU General Public License version
0N/A * 2 along with this work; if not, write to the Free Software Foundation,
0N/A * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
0N/A *
873N/A * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
0N/A * or visit www.oracle.com if you need additional information or have any
0N/A * questions.
0N/A *
0N/A */
0N/A
5037N/A# include "incls/_precompiled.incl"
5286N/A# include "incls/_thread.cpp.incl"
0N/A
0N/A#ifdef DTRACE_ENABLED
0N/A
0N/A// Only bother with this argument setup if dtrace is available
0N/A
0N/AHS_DTRACE_PROBE_DECL(hotspot, vm__init__begin);
0N/AHS_DTRACE_PROBE_DECL(hotspot, vm__init__end);
0N/AHS_DTRACE_PROBE_DECL5(hotspot, thread__start, char*, intptr_t,
3012N/A intptr_t, intptr_t, bool);
5040N/AHS_DTRACE_PROBE_DECL5(hotspot, thread__stop, char*, intptr_t,
3381N/A intptr_t, intptr_t, bool);
3349N/A
3349N/A#define DTRACE_THREAD_PROBE(probe, javathread) \
3012N/A { \
1083N/A ResourceMark rm(this); \
1083N/A int len = 0; \
1083N/A const char* name = (javathread)->get_thread_name(); \
1083N/A len = strlen(name); \
4156N/A HS_DTRACE_PROBE5(hotspot, thread__##probe, \
1083N/A name, len, \
1083N/A java_lang_Thread::thread_id((javathread)->threadObj()), \
1083N/A (javathread)->osthread()->thread_id(), \
1083N/A java_lang_Thread::is_daemon((javathread)->threadObj())); \
3090N/A }
3090N/A
3214N/A#else // ndef DTRACE_ENABLED
3764N/A
1083N/A#define DTRACE_THREAD_PROBE(probe, javathread)
1083N/A
1083N/A#endif // ndef DTRACE_ENABLED
1083N/A
233N/A// Class hierarchy
712N/A// - Thread
1177N/A// - VMThread
564N/A// - WatcherThread
0N/A// - ConcurrentMarkSweepThread
0N/A// - JavaThread
0N/A// - CompilerThread
0N/A
712N/A// ======= Thread ========
0N/A
0N/A// Support for forcing alignment of thread objects for biased locking
0N/Avoid* Thread::operator new(size_t size) {
0N/A if (UseBiasedLocking) {
0N/A const int alignment = markOopDesc::biased_lock_alignment;
233N/A size_t aligned_size = size + (alignment - sizeof(intptr_t));
233N/A void* real_malloc_addr = CHeapObj::operator new(aligned_size);
0N/A void* aligned_addr = (void*) align_size_up((intptr_t) real_malloc_addr, alignment);
0N/A assert(((uintptr_t) aligned_addr + (uintptr_t) size) <=
0N/A ((uintptr_t) real_malloc_addr + (uintptr_t) aligned_size),
0N/A "JavaThread alignment code overflowed allocated storage");
0N/A if (TraceBiasedLocking) {
0N/A if (aligned_addr != real_malloc_addr)
0N/A tty->print_cr("Aligned thread " INTPTR_FORMAT " to " INTPTR_FORMAT,
0N/A real_malloc_addr, aligned_addr);
567N/A }
567N/A ((Thread*) aligned_addr)->_real_malloc_address = real_malloc_addr;
567N/A return aligned_addr;
567N/A } else {
2046N/A return CHeapObj::operator new(size);
2046N/A }
1210N/A}
2033N/A
712N/Avoid Thread::operator delete(void* p) {
2033N/A if (UseBiasedLocking) {
2046N/A void* real_malloc_addr = ((Thread*) p)->_real_malloc_address;
712N/A CHeapObj::operator delete(real_malloc_addr);
675N/A } else {
5058N/A CHeapObj::operator delete(p);
712N/A }
675N/A}
567N/A
0N/A
5058N/A// Base class for all threads: VMThread, WatcherThread, ConcurrentMarkSweepThread,
712N/A// JavaThread
422N/A
0N/A
422N/AThread::Thread() {
0N/A // stack
422N/A _stack_base = NULL;
0N/A _stack_size = 0;
0N/A _self_raw_id = 0;
0N/A _lgrp_id = -1;
0N/A _osthread = NULL;
902N/A
902N/A // allocated data structures
902N/A set_resource_area(new ResourceArea());
902N/A set_handle_area(new HandleArea(NULL));
0N/A set_active_handles(NULL);
0N/A set_free_handle_block(NULL);
0N/A set_last_handle_mark(NULL);
0N/A set_osthread(NULL);
233N/A
233N/A // This initial value ==> never claimed.
233N/A _oops_do_parity = 0;
233N/A
730N/A // the handle mark links itself to last_handle_mark
730N/A new HandleMark(this);
730N/A
0N/A // plain initialization
729N/A debug_only(_owned_locks = NULL;)
729N/A debug_only(_allow_allocation_count = 0;)
729N/A NOT_PRODUCT(_allow_safepoint_count = 0;)
0N/A NOT_PRODUCT(_skip_gcalot = false;)
0N/A CHECK_UNHANDLED_OOPS_ONLY(_gc_locked_out_count = 0;)
0N/A _jvmti_env_iteration_count = 0;
110N/A _vm_operation_started_count = 0;
110N/A _vm_operation_completed_count = 0;
121N/A _current_pending_monitor = NULL;
699N/A _current_pending_monitor_is_from_java = true;
0N/A _current_waiting_monitor = NULL;
0N/A _num_nested_signal = 0;
1008N/A omFreeList = NULL ;
1008N/A omFreeCount = 0 ;
1008N/A omFreeProvision = 32 ;
1008N/A
3214N/A _SR_lock = new Monitor(Mutex::suspend_resume, "SR_lock", true);
3381N/A _suspend_flags = 0;
2086N/A
3646N/A // thread-specific hashCode stream generator state - Marsaglia shift-xor form
3646N/A _hashStateX = os::random() ;
3646N/A _hashStateY = 842502087 ;
2086N/A _hashStateZ = 0x8767 ; // (int)(3579807591LL & 0xffff) ;
3646N/A _hashStateW = 273326509 ;
1177N/A
3980N/A _OnTrap = 0 ;
3980N/A _schedctl = NULL ;
5058N/A _Stalled = 0 ;
3980N/A _TypeTag = 0x2BAD ;
3980N/A
3349N/A // Many of the following fields are effectively final - immutable
3349N/A // Note that nascent threads can't use the Native Monitor-Mutex
3349N/A // construct until the _MutexEvent is initialized ...
3349N/A // CONSIDER: instead of using a fixed set of purpose-dedicated ParkEvents
4686N/A // we might instead use a stack of ParkEvents that we could provision on-demand.
3349N/A // The stack would act as a cache to avoid calls to ParkEvent::Allocate()
3349N/A // and ::Release()
3381N/A _ParkEvent = ParkEvent::Allocate (this) ;
3381N/A _SleepEvent = ParkEvent::Allocate (this) ;
3349N/A _MutexEvent = ParkEvent::Allocate (this) ;
3381N/A _MuxEvent = ParkEvent::Allocate (this) ;
4156N/A
4156N/A#ifdef CHECK_UNHANDLED_OOPS
4156N/A if (CheckUnhandledOops) {
4156N/A _unhandled_oops = new UnhandledOops(this);
4156N/A }
4156N/A#endif // CHECK_UNHANDLED_OOPS
4156N/A#ifdef ASSERT
4156N/A if (UseBiasedLocking) {
4156N/A assert((((uintptr_t) this) & (markOopDesc::biased_lock_alignment - 1)) == 0, "forced alignment of thread object failed");
4156N/A assert(this == _real_malloc_address ||
4156N/A this == (void*) align_size_up((intptr_t) _real_malloc_address, markOopDesc::biased_lock_alignment),
4156N/A "bug in forced alignment of thread objects");
4156N/A }
4156N/A#endif /* ASSERT */
4156N/A}
4156N/A
4156N/Avoid Thread::initialize_thread_local_storage() {
0N/A // Note: Make sure this method only calls
0N/A // non-blocking operations. Otherwise, it might not work
0N/A // with the thread-startup/safepoint interaction.
0N/A
3381N/A // During Java thread startup, safepoint code should allow this
5058N/A // method to complete because it may need to allocate memory to
5058N/A // store information for the new thread.
5058N/A
3381N/A // initialize structure dependent on thread local storage
0N/A ThreadLocalStorage::set_thread(this);
5058N/A
5058N/A // set up any platform-specific state.
1177N/A os::initialize_thread();
1177N/A
0N/A}
0N/A
0N/Avoid Thread::record_stack_base_and_size() {
3853N/A set_stack_base(os::current_stack_base());
1177N/A set_stack_size(os::current_stack_size());
1177N/A}
0N/A
3853N/A
3853N/AThread::~Thread() {
3853N/A // Reclaim the objectmonitors from the omFreeList of the moribund thread.
3853N/A ObjectSynchronizer::omFlush (this) ;
3853N/A
0N/A // deallocate data structures
3853N/A delete resource_area();
3853N/A // since the handle marks are using the handle area, we have to deallocated the root
3853N/A // handle mark before deallocating the thread's handle area,
3853N/A assert(last_handle_mark() != NULL, "check we have an element");
3853N/A delete last_handle_mark();
0N/A assert(last_handle_mark() == NULL, "check we have reached the end");
0N/A
0N/A // It's possible we can encounter a null _ParkEvent, etc., in stillborn threads.
0N/A // We NULL out the fields for good hygiene.
1177N/A ParkEvent::Release (_ParkEvent) ; _ParkEvent = NULL ;
1177N/A ParkEvent::Release (_SleepEvent) ; _SleepEvent = NULL ;
0N/A ParkEvent::Release (_MutexEvent) ; _MutexEvent = NULL ;
0N/A ParkEvent::Release (_MuxEvent) ; _MuxEvent = NULL ;
3381N/A
3381N/A delete handle_area();
0N/A
0N/A // osthread() can be NULL, if creation of thread failed.
3090N/A if (osthread() != NULL) os::free_thread(osthread());
1177N/A
1177N/A delete _SR_lock;
0N/A
0N/A // clear thread local storage if the Thread is deleting itself
2086N/A if (this == Thread::current()) {
2086N/A ThreadLocalStorage::set_thread(NULL);
2086N/A } else {
2086N/A // In the case where we're not the current thread, invalidate all the
2086N/A // caches in case some code tries to get the current thread or the
2086N/A // thread that was destroyed, and gets stale information.
2086N/A ThreadLocalStorage::invalidate_all();
2086N/A }
2086N/A CHECK_UNHANDLED_OOPS_ONLY(if (CheckUnhandledOops) delete unhandled_oops();)
2086N/A}
2086N/A
2086N/A// NOTE: dummy function for assertion purpose.
2086N/Avoid Thread::run() {
2086N/A ShouldNotReachHere();
2086N/A}
2086N/A
2086N/A#ifdef ASSERT
2086N/A// Private method to check for dangling thread pointer
2086N/Avoid check_for_dangling_thread_pointer(Thread *thread) {
2086N/A assert(!thread->is_Java_thread() || Thread::current() == thread || Threads_lock->owned_by_self(),
2086N/A "possibility of dangling Thread pointer");
2086N/A}
2086N/A#endif
2086N/A
2086N/A
2086N/A#ifndef PRODUCT
2086N/A// Tracing method for basic thread operations
2086N/Avoid Thread::trace(const char* msg, const Thread* const thread) {
2086N/A if (!TraceThreadEvents) return;
2086N/A ResourceMark rm;
2086N/A ThreadCritical tc;
2086N/A const char *name = "non-Java thread";
2284N/A int prio = -1;
2284N/A if (thread->is_Java_thread()
2284N/A && !thread->is_Compiler_thread()) {
2086N/A // The Threads_lock must be held to get information about
2086N/A // this thread but may not be in some situations when
2086N/A // tracing thread events.
2086N/A bool release_Threads_lock = false;
2086N/A if (!Threads_lock->owned_by_self()) {
2086N/A Threads_lock->lock();
2086N/A release_Threads_lock = true;
2086N/A }
2086N/A JavaThread* jt = (JavaThread *)thread;
2086N/A name = (char *)jt->get_thread_name();
2086N/A oop thread_oop = jt->threadObj();
2086N/A if (thread_oop != NULL) {
2086N/A prio = java_lang_Thread::priority(thread_oop);
2086N/A }
2086N/A if (release_Threads_lock) {
2086N/A Threads_lock->unlock();
2086N/A }
2086N/A }
2086N/A tty->print_cr("Thread::%s " INTPTR_FORMAT " [%lx] %s (prio: %d)", msg, thread, thread->osthread()->thread_id(), name, prio);
2086N/A}
2086N/A#endif
2086N/A
2086N/A
2086N/AThreadPriority Thread::get_priority(const Thread* const thread) {
2086N/A trace("get priority", thread);
2086N/A ThreadPriority priority;
2086N/A // Can return an error!
2086N/A (void)os::get_priority(thread, priority);
2086N/A assert(MinPriority <= priority && priority <= MaxPriority, "non-Java priority found");
2086N/A return priority;
2086N/A}
2086N/A
2086N/Avoid Thread::set_priority(Thread* thread, ThreadPriority priority) {
2086N/A trace("set priority", thread);
2086N/A debug_only(check_for_dangling_thread_pointer(thread);)
2086N/A // Can return an error!
3034N/A (void)os::set_priority(thread, priority);
3034N/A}
3034N/A
3853N/A
3853N/Avoid Thread::start(Thread* thread) {
3853N/A trace("start", thread);
4156N/A // Start is different from resume in that its safety is guaranteed by context or
4156N/A // being called from a Java method synchronized on the Thread object.
4358N/A if (!DisableStartThread) {
2086N/A if (thread->is_Java_thread()) {
0N/A // Initialize the thread state to RUNNABLE before starting this thread.
4156N/A // Can not set it after the thread started because we do not know the
4156N/A // exact thread state at that time. It could be in MONITOR_WAIT or
4156N/A // in SLEEPING or some other state.
4156N/A java_lang_Thread::set_thread_status(((JavaThread*)thread)->threadObj(),
4156N/A java_lang_Thread::RUNNABLE);
4156N/A }
4156N/A os::start_thread(thread);
4156N/A }
4156N/A}
4156N/A
4156N/A// Enqueue a VM_Operation to do the job for us - sometime later
4156N/Avoid Thread::send_async_exception(oop java_thread, oop java_throwable) {
4156N/A VM_ThreadStop* vm_stop = new VM_ThreadStop(java_thread, java_throwable);
4156N/A VMThread::execute(vm_stop);
0N/A}
0N/A
3853N/A
0N/A//
0N/A// Check if an external suspend request has completed (or has been
2342N/A// cancelled). Returns true if the thread is externally suspended and
1008N/A// false otherwise.
1008N/A//
1008N/A// The bits parameter returns information about the code path through
1008N/A// the routine. Useful for debugging:
0N/A//
0N/A// set in is_ext_suspend_completed():
0N/A// 0x00000001 - routine was entered
1177N/A// 0x00000010 - routine return false at end
121N/A// 0x00000100 - thread exited (return false)
1177N/A// 0x00000200 - suspend request cancelled (return false)
1177N/A// 0x00000400 - thread suspended (return true)
1177N/A// 0x00001000 - thread is in a suspend equivalent state (return true)
0N/A// 0x00002000 - thread is native and walkable (return true)
0N/A// 0x00004000 - thread is native_trans and walkable (needed retry)
1273N/A//
1273N/A// set in wait_for_ext_suspend_completion():
1273N/A// 0x00010000 - routine was entered
1273N/A// 0x00020000 - suspend request cancelled before loop (return false)
5178N/A// 0x00040000 - thread suspended before loop (return true)
1273N/A// 0x00080000 - suspend request cancelled in loop (return false)
5038N/A// 0x00100000 - thread suspended in loop (return true)
1273N/A// 0x00200000 - suspend not completed during retry loop (return false)
1273N/A//
1273N/A
1273N/A// Helper class for tracing suspend wait debug bits.
1273N/A//
1273N/A// 0x00000100 indicates that the target thread exited before it could
1273N/A// self-suspend which is not a wait failure. 0x00000200, 0x00020000 and
1273N/A// 0x00080000 each indicate a cancelled suspend request so they don't
1273N/A// count as wait failures either.
1273N/A#define DEBUG_FALSE_BITS (0x00000010 | 0x00200000)
1273N/A
1273N/Aclass TraceSuspendDebugBits : public StackObj {
1273N/A private:
1273N/A JavaThread * jt;
1273N/A bool is_wait;
1273N/A bool called_by_wait; // meaningful when !is_wait
1273N/A uint32_t * bits;
1273N/A
1273N/A public:
1273N/A TraceSuspendDebugBits(JavaThread *_jt, bool _is_wait, bool _called_by_wait,
1273N/A uint32_t *_bits) {
1960N/A jt = _jt;
1273N/A is_wait = _is_wait;
1273N/A called_by_wait = _called_by_wait;
5058N/A bits = _bits;
0N/A }
121N/A
1177N/A ~TraceSuspendDebugBits() {
1177N/A if (!is_wait) {
1177N/A#if 1
1177N/A // By default, don't trace bits for is_ext_suspend_completed() calls.
1177N/A // That trace is very chatty.
1559N/A return;
1559N/A#else
1559N/A if (!called_by_wait) {
3381N/A // If tracing for is_ext_suspend_completed() is enabled, then only
0N/A // trace calls to it from wait_for_ext_suspend_completion()
1234N/A return;
1234N/A }
0N/A#endif
0N/A }
984N/A
0N/A if (AssertOnSuspendWaitFailure || TraceSuspendWaitFailures) {
0N/A if (bits != NULL && (*bits & DEBUG_FALSE_BITS) != 0) {
0N/A MutexLocker ml(Threads_lock); // needed for get_thread_name()
0N/A ResourceMark rm;
0N/A
0N/A tty->print_cr(
0N/A "Failed wait_for_ext_suspend_completion(thread=%s, debug_bits=%x)",
0N/A jt->get_thread_name(), *bits);
0N/A
0N/A guarantee(!AssertOnSuspendWaitFailure, "external suspend wait failed");
0N/A }
0N/A }
0N/A }
0N/A};
0N/A#undef DEBUG_FALSE_BITS
0N/A
0N/A
0N/Abool JavaThread::is_ext_suspend_completed(bool called_by_wait, int delay, uint32_t *bits) {
0N/A TraceSuspendDebugBits tsdb(this, false /* !is_wait */, called_by_wait, bits);
0N/A
0N/A bool did_trans_retry = false; // only do thread_in_native_trans retry once
0N/A bool do_trans_retry; // flag to force the retry
3381N/A
3349N/A *bits |= 0x00000001;
3349N/A
3349N/A do {
3349N/A do_trans_retry = false;
3349N/A
3349N/A if (is_exiting()) {
3349N/A // Thread is in the process of exiting. This is always checked
3349N/A // first to reduce the risk of dereferencing a freed JavaThread.
3349N/A *bits |= 0x00000100;
3349N/A return false;
3349N/A }
3349N/A
3381N/A if (!is_external_suspend()) {
3853N/A // Suspend request is cancelled. This is always checked before
3853N/A // is_ext_suspended() to reduce the risk of a rogue resume
3853N/A // confusing the thread that made the suspend request.
3853N/A *bits |= 0x00000200;
3853N/A return false;
3853N/A }
3853N/A
3853N/A if (is_ext_suspended()) {
729N/A // thread is suspended
729N/A *bits |= 0x00000400;
729N/A return true;
729N/A }
729N/A
729N/A // Now that we no longer do hard suspends of threads running
729N/A // native code, the target thread can be changing thread state
729N/A // while we are in this routine:
729N/A //
729N/A // _thread_in_native -> _thread_in_native_trans -> _thread_blocked
729N/A //
729N/A // We save a copy of the thread state as observed at this moment
729N/A // and make our decision about suspend completeness based on the
729N/A // copy. This closes the race where the thread state is seen as
729N/A // _thread_in_native_trans in the if-thread_blocked check, but is
729N/A // seen as _thread_blocked in if-thread_in_native_trans check.
729N/A JavaThreadState save_state = thread_state();
729N/A
729N/A if (save_state == _thread_blocked && is_suspend_equivalent()) {
729N/A // If the thread's state is _thread_blocked and this blocking
729N/A // condition is known to be equivalent to a suspend, then we can
0N/A // consider the thread to be externally suspended. This means that
4274N/A // the code that sets _thread_blocked has been modified to do
4274N/A // self-suspension if the blocking condition releases. We also
4274N/A // used to check for CONDVAR_WAIT here, but that is now covered by
4274N/A // the _thread_blocked with self-suspension check.
4274N/A //
4274N/A // Return true since we wouldn't be here unless there was still an
4274N/A // external suspend request.
4274N/A *bits |= 0x00001000;
4274N/A return true;
4274N/A } else if (save_state == _thread_in_native && frame_anchor()->walkable()) {
4274N/A // Threads running native code will self-suspend on native==>VM/Java
4274N/A // transitions. If its stack is walkable (should always be the case
4274N/A // unless this function is called before the actual java_suspend()
4274N/A // call), then the wait is done.
4274N/A *bits |= 0x00002000;
0N/A return true;
1344N/A } else if (!called_by_wait && !did_trans_retry &&
1344N/A save_state == _thread_in_native_trans &&
1344N/A frame_anchor()->walkable()) {
1344N/A // The thread is transitioning from thread_in_native to another
1344N/A // thread state. check_safepoint_and_suspend_for_native_trans()
1344N/A // will force the thread to self-suspend. If it hasn't gotten
1344N/A // there yet we may have caught the thread in-between the native
1344N/A // code check above and the self-suspend. Lucky us. If we were
1344N/A // called by wait_for_ext_suspend_completion(), then it
1344N/A // will be doing the retries so we don't have to.
1344N/A //
1344N/A // Since we use the saved thread state in the if-statement above,
1344N/A // there is a chance that the thread has already transitioned to
109N/A // _thread_blocked by the time we get here. In that case, we will
109N/A // make a single unnecessary pass through the logic below. This
109N/A // doesn't hurt anything since we still do the trans retry.
109N/A
4274N/A *bits |= 0x00004000;
4760N/A
109N/A // Once the thread leaves thread_in_native_trans for another
1238N/A // thread state, we break out of this retry loop. We shouldn't
109N/A // need this flag to prevent us from getting back here, but
1344N/A // sometimes paranoia is good.
1344N/A did_trans_retry = true;
1344N/A
1344N/A // We wait for the thread to transition to a more usable state.
1344N/A for (int i = 1; i <= SuspendRetryCount; i++) {
1344N/A // We used to do an "os::yield_all(i)" call here with the intention
110N/A // that yielding would increase on each retry. However, the parameter
109N/A // is ignored on Linux which means the yield didn't scale up. Waiting
109N/A // on the SR_lock below provides a much more predictable scale up for
109N/A // the delay. It also provides a simple/direct point to check for any
109N/A // safepoint requests from the VMThread
109N/A
109N/A // temporarily drops SR_lock while doing wait with safepoint check
0N/A // (if we're a JavaThread - the WatcherThread can also call this)
0N/A // and increase delay with each retry
0N/A SR_lock()->wait(!Thread::current()->is_Java_thread(), i * delay);
0N/A
0N/A // check the actual thread state instead of what we saved above
1344N/A if (thread_state() != _thread_in_native_trans) {
1344N/A // the thread has transitioned to another thread state so
1344N/A // try all the checks (except this one) one more time.
1344N/A do_trans_retry = true;
1344N/A break;
1344N/A }
729N/A } // end retry loop
729N/A
729N/A
729N/A }
729N/A } while (do_trans_retry);
729N/A
729N/A *bits |= 0x00000010;
729N/A return false;
729N/A}
729N/A
1344N/A//
729N/A// Wait for an external suspend request to complete (or be cancelled).
729N/A// Returns true if the thread is externally suspended and false otherwise.
729N/A//
729N/Abool JavaThread::wait_for_ext_suspend_completion(int retries, int delay,
0N/A uint32_t *bits) {
0N/A TraceSuspendDebugBits tsdb(this, true /* is_wait */,
5044N/A false /* !called_by_wait */, bits);
730N/A
0N/A // local flag copies to minimize SR_lock hold time
0N/A bool is_suspended;
0N/A bool pending;
567N/A uint32_t reset_bits;
662N/A
0N/A // set a marker so is_ext_suspend_completed() knows we are the caller
2086N/A *bits |= 0x00010000;
2086N/A
2086N/A // We use reset_bits to reinitialize the bits value at the top of
2086N/A // each retry loop. This allows the caller to make use of any
2086N/A // unused bits for their own marking purposes.
2086N/A reset_bits = *bits;
2086N/A
2086N/A {
2086N/A MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag);
2086N/A is_suspended = is_ext_suspend_completed(true /* called_by_wait */,
0N/A delay, bits);
0N/A pending = is_external_suspend();
662N/A }
1210N/A // must release SR_lock to allow suspension to complete
1210N/A
1210N/A if (!pending) {
1210N/A // A cancelled suspend request is the only false return from
1210N/A // is_ext_suspend_completed() that keeps us from entering the
1210N/A // retry loop.
567N/A *bits |= 0x00020000;
567N/A return false;
3387N/A }
3387N/A
3387N/A if (is_suspended) {
3387N/A *bits |= 0x00040000;
3387N/A return true;
3387N/A }
567N/A
563N/A for (int i = 1; i <= retries; i++) {
567N/A *bits = reset_bits; // reinit to only track last retry
712N/A
712N/A // We used to do an "os::yield_all(i)" call here with the intention
730N/A // that yielding would increase on each retry. However, the parameter
2033N/A // is ignored on Linux which means the yield didn't scale up. Waiting
712N/A // on the SR_lock below provides a much more predictable scale up for
712N/A // the delay. It also provides a simple/direct point to check for any
0N/A // safepoint requests from the VMThread
3381N/A
3381N/A {
3381N/A MutexLocker ml(SR_lock());
3381N/A // wait with safepoint check (if we're a JavaThread - the WatcherThread
3381N/A // can also call this) and increase delay with each retry
3381N/A SR_lock()->wait(!Thread::current()->is_Java_thread(), i * delay);
0N/A
0N/A is_suspended = is_ext_suspend_completed(true /* called_by_wait */,
0N/A delay, bits);
0N/A
0N/A // It is possible for the external suspend request to be cancelled
0N/A // (by a resume) before the actual suspend operation is completed.
2058N/A // Refresh our local copy to see if we still need to wait.
0N/A pending = is_external_suspend();
0N/A }
114N/A
114N/A if (!pending) {
114N/A // A cancelled suspend request is the only false return from
114N/A // is_ext_suspend_completed() that keeps us from staying in the
114N/A // retry loop.
114N/A *bits |= 0x00080000;
0N/A return false;
0N/A }
0N/A
0N/A if (is_suspended) {
121N/A *bits |= 0x00100000;
729N/A return true;
4760N/A }
121N/A } // end retry loop
121N/A
1210N/A // thread did not suspend after all our retries
0N/A *bits |= 0x00200000;
121N/A return false;
2086N/A}
0N/A
0N/A#ifndef PRODUCT
4156N/Avoid JavaThread::record_jump(address target, address instr, const char* file, int line) {
4156N/A
4156N/A // This should not need to be atomic as the only way for simultaneous
4156N/A // updates is via interrupts. Even then this should be rare or non-existant
4358N/A // and we don't care that much anyway.
2095N/A
4156N/A int index = _jmp_ring_index;
5178N/A _jmp_ring_index = (index + 1 ) & (jump_ring_buffer_size - 1);
2095N/A _jmp_ring[index]._target = (intptr_t) target;
0N/A _jmp_ring[index]._instruction = (intptr_t) instr;
0N/A _jmp_ring[index]._file = file;
0N/A _jmp_ring[index]._line = line;
0N/A}
0N/A#endif /* PRODUCT */
0N/A
2046N/A// Called by flat profiler
2033N/A// Callers have already called wait_for_ext_suspend_completion
2046N/A// The assertion for that is currently too complex to put here:
4156N/Abool JavaThread::profile_last_Java_frame(frame* _fr) {
4156N/A bool gotframe = false;
4156N/A // self suspension saves needed state.
0N/A if (has_last_Java_frame() && _anchor.walkable()) {
0N/A *_fr = pd_last_frame();
1607N/A gotframe = true;
1607N/A }
1607N/A return gotframe;
2033N/A}
2033N/A
1607N/Avoid Thread::interrupt(Thread* thread) {
0N/A trace("interrupt", thread);
0N/A debug_only(check_for_dangling_thread_pointer(thread);)
1177N/A os::interrupt(thread);
1177N/A}
567N/A
1559N/Abool Thread::is_interrupted(Thread* thread, bool clear_interrupted) {
567N/A trace("is_interrupted", thread);
567N/A debug_only(check_for_dangling_thread_pointer(thread);)
1210N/A // Note: If clear_interrupted==false, this simply fetches and
5178N/A // returns the value of the field osthread()->interrupted().
5178N/A return os::is_interrupted(thread, clear_interrupted);
1210N/A}
1210N/A
1210N/A
1210N/A// GC Support
1210N/Abool Thread::claim_oops_do_par_case(int strong_roots_parity) {
1210N/A jint thread_parity = _oops_do_parity;
1210N/A if (thread_parity != strong_roots_parity) {
1210N/A jint res = Atomic::cmpxchg(strong_roots_parity, &_oops_do_parity, thread_parity);
1210N/A if (res == thread_parity) return true;
2115N/A else {
5178N/A guarantee(res == strong_roots_parity, "Or else what?");
5178N/A assert(SharedHeap::heap()->n_par_threads() > 0,
1008N/A "Should only fail when parallel.");
1008N/A return false;
1210N/A }
1008N/A }
1008N/A assert(SharedHeap::heap()->n_par_threads() > 0,
2086N/A "Should only fail when parallel.");
2115N/A return false;
2086N/A}
2086N/A
2086N/Avoid Thread::oops_do(OopClosure* f, CodeBlobClosure* cf) {
2115N/A active_handles()->oops_do(f);
2115N/A // Do oop for ThreadShadow
2115N/A f->do_oop((oop*)&_pending_exception);
1008N/A handle_area()->oops_do(f);
1008N/A}
5178N/A
5178N/Avoid Thread::nmethods_do(CodeBlobClosure* cf) {
567N/A // no nmethods in a generic thread...
567N/A}
0N/A
567N/Avoid Thread::print_on(outputStream* st) const {
567N/A // get_priority assumes osthread initialized
567N/A if (osthread() != NULL) {
567N/A st->print("prio=%d tid=" INTPTR_FORMAT " ", get_priority(this), this);
567N/A osthread()->print_on(st);
567N/A }
567N/A debug_only(if (WizardMode) print_owned_locks_on(st);)
567N/A}
567N/A
567N/A// Thread::print_on_error() is called by fatal error handler. Don't use
567N/A// any lock or allocate memory.
2115N/Avoid Thread::print_on_error(outputStream* st, char* buf, int buflen) const {
2115N/A if (is_VM_thread()) st->print("VMThread");
2115N/A else if (is_Compiler_thread()) st->print("CompilerThread");
2115N/A else if (is_Java_thread()) st->print("JavaThread");
2115N/A else if (is_GC_task_thread()) st->print("GCTaskThread");
2556N/A else if (is_Watcher_thread()) st->print("WatcherThread");
563N/A else if (is_ConcurrentGC_thread()) st->print("ConcurrentGCThread");
712N/A else st->print("Thread");
1177N/A
2710N/A st->print(" [stack: " PTR_FORMAT "," PTR_FORMAT "]",
2710N/A _stack_base - _stack_size, _stack_base);
2710N/A
2710N/A if (osthread()) {
2710N/A st->print(" [id=%d]", osthread()->thread_id());
2710N/A }
2710N/A}
2710N/A
2710N/A#ifdef ASSERT
3980N/Avoid Thread::print_owned_locks_on(outputStream* st) const {
3980N/A Monitor *cur = _owned_locks;
3989N/A if (cur == NULL) {
5058N/A st->print(" (no locks) ");
5058N/A } else {
5058N/A st->print_cr(" Locks owned:");
5058N/A while(cur) {
3980N/A cur->print_on(st);
5058N/A cur = cur->next();
5058N/A }
5058N/A }
5058N/A}
5058N/A
5058N/Astatic int ref_use_count = 0;
5058N/A
5058N/Abool Thread::owns_locks_but_compiled_lock() const {
5058N/A for(Monitor *cur = _owned_locks; cur; cur = cur->next()) {
5058N/A if (cur != Compile_lock) return true;
5058N/A }
5058N/A return false;
5058N/A}
5058N/A
5058N/A
5058N/A#endif
5058N/A
5058N/A#ifndef PRODUCT
5058N/A
5058N/A// The flag: potential_vm_operation notifies if this particular safepoint state could potential
5058N/A// invoke the vm-thread (i.e., and oop allocation). In that case, we also have to make sure that
5058N/A// no threads which allow_vm_block's are held
5058N/Avoid Thread::check_for_valid_safepoint_state(bool potential_vm_operation) {
5058N/A // Check if current thread is allowed to block at a safepoint
5058N/A if (!(_allow_safepoint_count == 0))
5058N/A fatal("Possible safepoint reached by thread that does not allow it");
3980N/A if (is_Java_thread() && ((JavaThread*)this)->thread_state() != _thread_in_vm) {
2710N/A fatal("LEAF method calling lock?");
0N/A }
563N/A
0N/A#ifdef ASSERT
0N/A if (potential_vm_operation && is_Java_thread()
0N/A && !Universe::is_bootstrapping()) {
0N/A // Make sure we do not hold any locks that the VM thread also uses.
2143N/A // This could potentially lead to deadlocks
0N/A for(Monitor *cur = _owned_locks; cur; cur = cur->next()) {
0N/A // Threads_lock is special, since the safepoint synchronization will not start before this is
1362N/A // acquired. Hence, a JavaThread cannot be holding it at a safepoint. So is VMOperationRequest_lock,
1362N/A // since it is used to transfer control between JavaThreads and the VMThread
1362N/A // Do not *exclude* any locks unless you are absolutly sure it is correct. Ask someone else first!
1362N/A if ( (cur->allow_vm_block() &&
1362N/A cur != Threads_lock &&
1362N/A cur != Compile_lock && // Temporary: should not be necessary when we get spearate compilation
1362N/A cur != VMOperationRequest_lock &&
1362N/A cur != VMOperationQueue_lock) ||
1362N/A cur->rank() == Mutex::special) {
1362N/A warning("Thread holding lock at safepoint that vm can block on: %s", cur->name());
1362N/A }
1362N/A }
0N/A }
0N/A
1960N/A if (GCALotAtAllSafepoints) {
0N/A // We could enter a safepoint here and thus have a gc
0N/A InterfaceSupport::check_gc_alot();
0N/A }
1960N/A#endif
0N/A}
563N/A#endif
563N/A
712N/Abool Thread::is_in_stack(address adr) const {
1008N/A assert(Thread::current() == this, "is_in_stack can only be called from current thread");
1008N/A address end = os::current_stack_pointer();
1008N/A if (stack_base() >= adr && adr >= end) return true;
4156N/A
4156N/A return false;
4156N/A}
0N/A
0N/A
2098N/A// We had to move these methods here, because vm threads get into ObjectSynchronizer::enter
4156N/A// However, there is a note in JavaThread::is_lock_owned() about the VM threads not being
5178N/A// used for compilation in the future. If that change is made, the need for these methods
0N/A// should be revisited, and they should be removed if possible.
0N/A
0N/Abool Thread::is_lock_owned(address adr) const {
0N/A return (_stack_base >= adr && adr >= (_stack_base - _stack_size));
0N/A}
0N/A
0N/Abool Thread::set_as_starting_thread() {
0N/A // NOTE: this must be called inside the main thread.
2046N/A return os::create_main_thread((JavaThread*)this);
2033N/A}
2046N/A
4156N/Astatic void initialize_class(symbolHandle class_name, TRAPS) {
4156N/A klassOop klass = SystemDictionary::resolve_or_fail(class_name, true, CHECK);
4156N/A instanceKlass::cast(klass)->initialize(CHECK);
0N/A}
0N/A
3381N/A
1607N/A// Creates the initial ThreadGroup
1607N/Astatic Handle create_initial_thread_group(TRAPS) {
2046N/A klassOop k = SystemDictionary::resolve_or_fail(vmSymbolHandles::java_lang_ThreadGroup(), true, CHECK_NH);
2033N/A instanceKlassHandle klass (THREAD, k);
1607N/A
1607N/A Handle system_instance = klass->allocate_instance_handle(CHECK_NH);
2086N/A {
2710N/A JavaValue result(T_VOID);
2086N/A JavaCalls::call_special(&result,
3980N/A system_instance,
2122N/A klass,
2122N/A vmSymbolHandles::object_initializer_name(),
2122N/A vmSymbolHandles::void_method_signature(),
2122N/A CHECK_NH);
0N/A }
1960N/A Universe::set_system_thread_group(system_instance());
2033N/A
2046N/A Handle main_instance = klass->allocate_instance_handle(CHECK_NH);
2046N/A {
712N/A JavaValue result(T_VOID);
563N/A Handle string = java_lang_String::create_from_str("main", CHECK_NH);
563N/A JavaCalls::call_special(&result,
1210N/A main_instance,
5178N/A klass,
5178N/A vmSymbolHandles::object_initializer_name(),
1210N/A vmSymbolHandles::threadgroup_string_void_signature(),
1210N/A system_instance,
1210N/A string,
1210N/A CHECK_NH);
1210N/A }
1210N/A return main_instance;
1210N/A}
1210N/A
1210N/A// Creates the initial Thread
4358N/Astatic oop create_initial_thread(Handle thread_group, JavaThread* thread, TRAPS) {
5178N/A klassOop k = SystemDictionary::resolve_or_fail(vmSymbolHandles::java_lang_Thread(), true, CHECK_NULL);
5178N/A instanceKlassHandle klass (THREAD, k);
1008N/A instanceHandle thread_oop = klass->allocate_instance_handle(CHECK_NULL);
1008N/A
1210N/A java_lang_Thread::set_thread(thread_oop(), thread);
1008N/A java_lang_Thread::set_priority(thread_oop(), NormPriority);
1008N/A thread->set_threadObj(thread_oop());
4495N/A
4495N/A Handle string = java_lang_String::create_from_str("main", CHECK_NULL);
4495N/A
4495N/A JavaValue result(T_VOID);
4495N/A JavaCalls::call_special(&result, thread_oop,
4495N/A klass,
4495N/A vmSymbolHandles::object_initializer_name(),
1008N/A vmSymbolHandles::threadgroup_string_void_signature(),
1008N/A thread_group,
1083N/A string,
5178N/A CHECK_NULL);
563N/A return thread_oop();
563N/A}
1008N/A
1008N/Astatic void call_initializeSystemClass(TRAPS) {
1008N/A klassOop k = SystemDictionary::resolve_or_fail(vmSymbolHandles::java_lang_System(), true, CHECK);
1008N/A instanceKlassHandle klass (THREAD, k);
1008N/A
4495N/A JavaValue result(T_VOID);
1008N/A JavaCalls::call_static(&result, klass, vmSymbolHandles::initializeSystemClass_name(),
563N/A vmSymbolHandles::void_method_signature(), CHECK);
563N/A}
563N/A
1008N/A#ifdef KERNEL
563N/Astatic void set_jkernel_boot_classloader_hook(TRAPS) {
563N/A klassOop k = SystemDictionary::sun_jkernel_DownloadManager_klass();
563N/A instanceKlassHandle klass (THREAD, k);
563N/A
563N/A if (k == NULL) {
563N/A // sun.jkernel.DownloadManager may not present in the JDK; just return
712N/A return;
4156N/A }
4156N/A
4156N/A JavaValue result(T_VOID);
4156N/A JavaCalls::call_static(&result, klass, vmSymbolHandles::setBootClassLoaderHook_name(),
4358N/A vmSymbolHandles::void_method_signature(), CHECK);
1008N/A}
1008N/A#endif // KERNEL
0N/A
0N/Astatic void reset_vm_info_property(TRAPS) {
0N/A // the vm info string
3214N/A ResourceMark rm(THREAD);
3214N/A const char *vm_info = VM_Version::vm_info_string();
3214N/A
3381N/A // java.lang.System class
3381N/A klassOop k = SystemDictionary::resolve_or_fail(vmSymbolHandles::java_lang_System(), true, CHECK);
3214N/A instanceKlassHandle klass (THREAD, k);
3214N/A
3214N/A // setProperty arguments
3090N/A Handle key_str = java_lang_String::create_from_str("java.vm.info", CHECK);
3214N/A Handle value_str = java_lang_String::create_from_str(vm_info, CHECK);
3214N/A
3214N/A // return value
3214N/A JavaValue r(T_OBJECT);
3090N/A
3090N/A // public static String setProperty(String key, String value);
3090N/A JavaCalls::call_static(&r,
3090N/A klass,
3090N/A vmSymbolHandles::setProperty_name(),
3090N/A vmSymbolHandles::string_string_string_signature(),
3090N/A key_str,
3214N/A value_str,
3764N/A CHECK);
3381N/A}
3214N/A
3214N/A
3214N/Avoid JavaThread::allocate_threadObj(Handle thread_group, char* thread_name, bool daemon, TRAPS) {
3214N/A assert(thread_group.not_null(), "thread group should be specified");
3214N/A assert(threadObj() == NULL, "should only create Java thread object once");
3214N/A
3214N/A klassOop k = SystemDictionary::resolve_or_fail(vmSymbolHandles::java_lang_Thread(), true, CHECK);
3214N/A instanceKlassHandle klass (THREAD, k);
3214N/A instanceHandle thread_oop = klass->allocate_instance_handle(CHECK);
3214N/A
3214N/A java_lang_Thread::set_thread(thread_oop(), this);
3214N/A java_lang_Thread::set_priority(thread_oop(), NormPriority);
3214N/A set_threadObj(thread_oop());
3214N/A
3214N/A JavaValue result(T_VOID);
3214N/A if (thread_name != NULL) {
3214N/A Handle name = java_lang_String::create_from_str(thread_name, CHECK);
3214N/A // Thread gets assigned specified name and null target
3764N/A JavaCalls::call_special(&result,
3214N/A thread_oop,
3381N/A klass,
3090N/A vmSymbolHandles::object_initializer_name(),
0N/A vmSymbolHandles::threadgroup_string_void_signature(),
0N/A thread_group, // Argument 1
121N/A name, // Argument 2
0N/A THREAD);
0N/A } else {
1960N/A // Thread gets assigned name "Thread-nnn" and null target
0N/A // (java.lang.Thread doesn't have a constructor taking only a ThreadGroup argument)
2556N/A JavaCalls::call_special(&result,
2556N/A thread_oop,
2556N/A klass,
2556N/A vmSymbolHandles::object_initializer_name(),
2556N/A vmSymbolHandles::threadgroup_runnable_void_signature(),
2556N/A thread_group, // Argument 1
2556N/A Handle(), // Argument 2
2556N/A THREAD);
2556N/A }
2556N/A
3349N/A
3853N/A if (daemon) {
2556N/A java_lang_Thread::set_daemon(thread_oop());
3108N/A }
2556N/A
2556N/A if (HAS_PENDING_EXCEPTION) {
2556N/A return;
2556N/A }
2556N/A
2556N/A KlassHandle group(this, SystemDictionary::ThreadGroup_klass());
2556N/A Handle threadObj(this, this->threadObj());
3853N/A
3853N/A JavaCalls::call_special(&result,
3853N/A thread_group,
3853N/A group,
3853N/A vmSymbolHandles::add_method_name(),
2556N/A vmSymbolHandles::thread_void_signature(),
2556N/A threadObj, // Arg 1
2556N/A THREAD);
2556N/A
2556N/A
2556N/A}
2556N/A
2556N/A// NamedThread -- non-JavaThread subclasses with multiple
2556N/A// uniquely named instances should derive from this.
2556N/ANamedThread::NamedThread() : Thread() {
0N/A _name = NULL;
2086N/A _processed_thread = NULL;
2086N/A}
2710N/A
2086N/ANamedThread::~NamedThread() {
3980N/A if (_name != NULL) {
3980N/A FREE_C_HEAP_ARRAY(char, _name);
3980N/A _name = NULL;
3980N/A }
2122N/A}
2122N/A
2122N/Avoid NamedThread::set_name(const char* format, ...) {
3381N/A guarantee(_name == NULL, "Only get to set name once.");
1960N/A _name = NEW_C_HEAP_ARRAY(char, max_name_len);
2556N/A guarantee(_name != NULL, "alloc failure");
5040N/A va_list ap;
4495N/A va_start(ap, format);
4495N/A jio_vsnprintf(_name, max_name_len, format, ap);
4495N/A va_end(ap);
4495N/A}
4495N/A
4495N/A// ======= WatcherThread ========
4495N/A
4495N/A// The watcher thread exists to simulate timer interrupts. It should
4495N/A// be replaced by an abstraction over whatever native support for
4495N/A// timer interrupts exists on the platform.
4495N/A
4495N/AWatcherThread* WatcherThread::_watcher_thread = NULL;
4495N/Abool WatcherThread::_should_terminate = false;
4495N/A
4495N/AWatcherThread::WatcherThread() : Thread() {
4495N/A assert(watcher_thread() == NULL, "we can only allocate one WatcherThread");
4495N/A if (os::create_thread(this, os::watcher_thread)) {
4495N/A _watcher_thread = this;
4495N/A
4495N/A // Set the watcher thread to the highest OS priority which should not be
4495N/A // used, unless a Java thread with priority java.lang.Thread.MAX_PRIORITY
4495N/A // is created. The only normal thread using this priority is the reference
4495N/A // handler thread, which runs for very short intervals only.
4495N/A // If the VMThread's priority is not lower than the WatcherThread profiling
4495N/A // will be inaccurate.
4495N/A os::set_priority(this, MaxPriority);
4495N/A if (!DisableStartThread) {
4495N/A os::start_thread(this);
4495N/A }
4495N/A }
4495N/A}
4495N/A
4495N/Avoid WatcherThread::run() {
4495N/A assert(this == watcher_thread(), "just checking");
4495N/A
4495N/A this->record_stack_base_and_size();
4495N/A this->initialize_thread_local_storage();
4897N/A this->set_active_handles(JNIHandleBlock::allocate_block());
4897N/A while(!_should_terminate) {
4897N/A assert(watcher_thread() == Thread::current(), "thread consistency check");
4897N/A assert(watcher_thread() == this, "thread consistency check");
712N/A
5020N/A // Calculate how long it'll be until the next PeriodicTask work
5020N/A // should be done, and sleep that amount of time.
5020N/A const size_t time_to_wait = PeriodicTask::time_to_wait();
5020N/A os::sleep(this, time_to_wait, false);
5020N/A
563N/A if (is_error_reported()) {
563N/A // A fatal error has happened, the error handler(VMError::report_and_die)
712N/A // should abort JVM after creating an error log file. However in some
0N/A // rare cases, the error handler itself might deadlock. Here we try to
0N/A // kill JVM if the fatal error handler fails to abort in 2 minutes.
0N/A //
3381N/A // This code is in WatcherThread because WatcherThread wakes up
1008N/A // periodically so the fatal error handler doesn't need to do anything;
1008N/A // also because the WatcherThread is less likely to crash than other
1008N/A // threads.
4358N/A
3824N/A for (;;) {
3824N/A if (!ShowMessageBoxOnError
3824N/A && (OnError == NULL || OnError[0] == '\0')
3381N/A && Arguments::abort_hook() == NULL) {
3534N/A os::sleep(this, 2 * 60 * 1000, false);
3534N/A fdStream err(defaultStream::output_fd());
2976N/A err.print_raw_cr("# [ timer expired, abort... ]");
2976N/A // skip atexit/vm_exit/vm_abort hooks
1194N/A os::die();
2976N/A }
2976N/A
1008N/A // Wake up 5 seconds later, the fatal handler may reset OnError or
0N/A // ShowMessageBoxOnError when it is ready to abort.
4156N/A os::sleep(this, 5 * 1000, false);
0N/A }
3381N/A }
3349N/A
3381N/A PeriodicTask::real_time_tick(time_to_wait);
4156N/A
4156N/A // If we have no more tasks left due to dynamic disenrollment,
920N/A // shut down the thread since we don't currently support dynamic enrollment
920N/A if (PeriodicTask::num_tasks() == 0) {
5040N/A _should_terminate = true;
4495N/A }
4495N/A }
4495N/A
920N/A // Signal that it is terminated
920N/A {
920N/A MutexLockerEx mu(Terminator_lock, Mutex::_no_safepoint_check_flag);
920N/A _watcher_thread = NULL;
920N/A Terminator_lock->notify();
920N/A }
920N/A
920N/A // Thread destructor usually does this..
920N/A ThreadLocalStorage::set_thread(NULL);
920N/A}
920N/A
920N/Avoid WatcherThread::start() {
920N/A if (watcher_thread() == NULL) {
0N/A _should_terminate = false;
0N/A // Create the single instance of WatcherThread
0N/A new WatcherThread();
4358N/A }
3853N/A}
3853N/A
3853N/Avoid WatcherThread::stop() {
0N/A // it is ok to take late safepoints here, if needed
0N/A MutexLocker mu(Terminator_lock);
0N/A _should_terminate = true;
0N/A while(watcher_thread() != NULL) {
0N/A // This wait should make safepoint checks, wait without a timeout,
107N/A // and wait as a suspend-equivalent condition.
107N/A //
107N/A // Note: If the FlatProfiler is running, then this thread is waiting
107N/A // for the WatcherThread to terminate and the WatcherThread, via the
29N/A // FlatProfiler task, is waiting for the external suspend request on
29N/A // this thread to complete. wait_for_ext_suspend_completion() will
29N/A // eventually timeout, but that takes time. Making this wait a
29N/A // suspend-equivalent condition solves that timeout problem.
29N/A //
29N/A Terminator_lock->wait(!Mutex::_no_safepoint_check_flag, 0,
29N/A Mutex::_as_suspend_equivalent_flag);
3012N/A }
2911N/A}
2911N/A
2911N/Avoid WatcherThread::print_on(outputStream* st) const {
3012N/A st->print("\"%s\" ", name());
2911N/A Thread::print_on(st);
3537N/A st->cr();
3537N/A}
3537N/A
3537N/A// ======= JavaThread ========
2911N/A
3012N/A// A JavaThread is a normal Java thread
3012N/A
2549N/Avoid JavaThread::initialize() {
547N/A // Initialize fields
2549N/A
547N/A // Set the claimed par_id to -1 (ie not claiming any par_ids)
84N/A set_claimed_par_id(-1);
565N/A
712N/A set_saved_exception_pc(NULL);
1345N/A set_threadObj(NULL);
2556N/A _anchor.clear();
2556N/A set_entry_point(NULL);
2556N/A set_jni_functions(jni_functions());
2556N/A set_callee_target(NULL);
2556N/A set_vm_result(NULL);
2556N/A set_vm_result_2(NULL);
2556N/A set_vframe_array_head(NULL);
2556N/A set_vframe_array_last(NULL);
2556N/A set_deferred_locals(NULL);
2556N/A set_deopt_mark(NULL);
2556N/A clear_must_deopt_id();
2556N/A set_monitor_chunks(NULL);
2556N/A set_next(NULL);
2556N/A set_thread_state(_thread_new);
2556N/A _terminated = _not_terminated;
2556N/A _privileged_stack_top = NULL;
2556N/A _array_for_gc = NULL;
3853N/A _suspend_equivalent = false;
3853N/A _in_deopt_handler = 0;
2556N/A _doing_unsafe_access = false;
2556N/A _stack_guard_state = stack_guard_unused;
2556N/A _exception_oop = NULL;
3853N/A _exception_pc = 0;
2556N/A _exception_handler_pc = 0;
2556N/A _exception_stack_size = 0;
2556N/A _jvmti_thread_state= NULL;
485N/A _should_post_on_exceptions_flag = JNI_FALSE;
485N/A _jvmti_get_loaded_classes_closure = NULL;
485N/A _interp_only_mode = 0;
485N/A _special_runtime_exit_condition = _no_async_condition;
1197N/A _pending_async_exception = NULL;
1197N/A _is_compiling = false;
2976N/A _thread_stat = NULL;
2976N/A _thread_stat = new ThreadStatistics();
0N/A _blocked_on_compilation = false;
4575N/A _jni_active_critical = 0;
4575N/A _do_not_unlock_if_synchronized = false;
0N/A _cached_monitor_info = NULL;
0N/A _parker = Parker::Allocate(this) ;
0N/A
0N/A#ifndef PRODUCT
0N/A _jmp_ring_index = 0;
1960N/A for (int ji = 0 ; ji < jump_ring_buffer_size ; ji++ ) {
3100N/A record_jump(NULL, NULL, NULL, 0);
3100N/A }
1960N/A#endif /* PRODUCT */
3853N/A
0N/A set_thread_profiler(NULL);
499N/A if (FlatProfiler::is_active()) {
2976N/A // This is where we would decide to either give each thread it's own profiler
1194N/A // or use one global one from FlatProfiler,
1960N/A // or up to some count of the number of profiled threads, etc.
1960N/A ThreadProfiler* pp = new ThreadProfiler();
499N/A pp->engage();
1960N/A set_thread_profiler(pp);
1210N/A }
3853N/A
499N/A // Setup safepoint state info for this thread
0N/A ThreadSafepointState::create(this);
1559N/A
3381N/A debug_only(_java_call_counter = 0);
2308N/A
2308N/A // JVMTI PopFrame support
2308N/A _popframe_condition = popframe_inactive;
2308N/A _popframe_preserved_args = NULL;
2308N/A _popframe_preserved_args_size = 0;
0N/A
0N/A pd_initialize();
3069N/A}
3069N/A
3069N/A#ifndef SERIALGC
3069N/ASATBMarkQueueSet JavaThread::_satb_mark_queue_set;
3069N/ADirtyCardQueueSet JavaThread::_dirty_card_queue_set;
3069N/A#endif // !SERIALGC
3069N/A
3069N/AJavaThread::JavaThread(bool is_attaching) :
3069N/A Thread()
3069N/A#ifndef SERIALGC
3069N/A , _satb_mark_queue(&_satb_mark_queue_set),
3069N/A _dirty_card_queue(&_dirty_card_queue_set)
3069N/A#endif // !SERIALGC
3069N/A{
3069N/A initialize();
3069N/A _is_attaching = is_attaching;
3079N/A assert(_deferred_card_mark.is_empty(), "Default MemRegion ctor");
3069N/A}
3069N/A
3069N/Abool JavaThread::reguard_stack(address cur_sp) {
3069N/A if (_stack_guard_state != stack_guard_yellow_disabled) {
3069N/A return true; // Stack already guarded or guard pages not needed.
3069N/A }
3079N/A
3069N/A if (register_stack_overflow()) {
3069N/A // For those architectures which have separate register and
3069N/A // memory stacks, we must check the register stack to see if
3069N/A // it has overflowed.
3069N/A return false;
3069N/A }
3069N/A
3069N/A // Java code never executes within the yellow zone: the latter is only
3069N/A // there to provoke an exception during stack banging. If java code
3069N/A // is executing there, either StackShadowPages should be larger, or
3069N/A // some exception code in c1, c2 or the interpreter isn't unwinding
3069N/A // when it should.
3069N/A guarantee(cur_sp > stack_yellow_zone_base(), "not enough space to reguard - increase StackShadowPages");
3069N/A
3069N/A enable_stack_yellow_zone();
3069N/A return true;
3069N/A}
3069N/A
3069N/Abool JavaThread::reguard_stack(void) {
3069N/A return reguard_stack(os::current_stack_pointer());
3069N/A}
3069N/A
3381N/A
3069N/Avoid JavaThread::block_if_vm_exited() {
3069N/A if (_terminated == _vm_exited) {
3069N/A // _vm_exited is set at safepoint, and Threads_lock is never released
3069N/A // we will block here forever
3069N/A Threads_lock->lock_without_safepoint_check();
3069N/A ShouldNotReachHere();
3069N/A }
3069N/A}
3069N/A
3069N/A
3069N/A// Remove this ifdef when C1 is ported to the compiler interface.
3084N/Astatic void compiler_thread_entry(JavaThread* thread, TRAPS);
3069N/A
3069N/AJavaThread::JavaThread(ThreadFunction entry_point, size_t stack_sz) :
1177N/A Thread()
1177N/A#ifndef SERIALGC
0N/A , _satb_mark_queue(&_satb_mark_queue_set),
0N/A _dirty_card_queue(&_dirty_card_queue_set)
0N/A#endif // !SERIALGC
0N/A{
0N/A if (TraceThreadEvents) {
0N/A tty->print_cr("creating thread %p", this);
0N/A }
0N/A initialize();
0N/A _is_attaching = false;
0N/A set_entry_point(entry_point);
0N/A // Create the native thread itself.
0N/A // %note runtime_23
0N/A os::ThreadType thr_type = os::java_thread;
0N/A thr_type = entry_point == &compiler_thread_entry ? os::compiler_thread :
0N/A os::java_thread;
0N/A os::create_thread(this, thr_type, stack_sz);
0N/A
0N/A // The _osthread may be NULL here because we ran out of memory (too many threads active).
0N/A // We need to throw and OutOfMemoryError - however we cannot do this here because the caller
0N/A // may hold a lock and all locks must be unlocked before throwing the exception (throwing
0N/A // the exception consists of creating the exception object & initializing it, initialization
5178N/A // will leave the VM via a JavaCall and then all locks must be unlocked).
5178N/A //
0N/A // The thread is still suspended when we reach here. Thread must be explicit started
0N/A // by creator! Furthermore, the thread must also explicitly be added to the Threads list
3107N/A // by calling Threads:add. The reason why this is not done here, is because the thread
0N/A // object must be fully initialized (take a look at JVM_Start)
0N/A}
0N/A
0N/AJavaThread::~JavaThread() {
0N/A if (TraceThreadEvents) {
0N/A tty->print_cr("terminate thread %p", this);
0N/A }
0N/A
0N/A // JSR166 -- return the parker to the free list
5178N/A Parker::Release(_parker);
5178N/A _parker = NULL ;
0N/A
0N/A // Free any remaining previous UnrollBlock
3107N/A vframeArray* old_array = vframe_array_last();
0N/A
0N/A if (old_array != NULL) {
0N/A Deoptimization::UnrollBlock* old_info = old_array->unroll_block();
0N/A old_array->set_unroll_block(NULL);
0N/A delete old_info;
0N/A delete old_array;
0N/A }
0N/A
0N/A GrowableArray<jvmtiDeferredLocalVariableSet*>* deferred = deferred_locals();
0N/A if (deferred != NULL) {
3000N/A // This can only happen if thread is destroyed before deoptimization occurs.
3000N/A assert(deferred->length() != 0, "empty array!");
3000N/A do {
3000N/A jvmtiDeferredLocalVariableSet* dlv = deferred->at(0);
3000N/A deferred->remove_at(0);
1960N/A // individual jvmtiDeferredLocalVariableSet are CHeapObj's
0N/A delete dlv;
0N/A } while (deferred->length() != 0);
0N/A delete deferred;
0N/A }
0N/A
0N/A // All Java related clean up happens in exit
0N/A ThreadSafepointState::destroy(this);
0N/A if (_thread_profiler != NULL) delete _thread_profiler;
0N/A if (_thread_stat != NULL) delete _thread_stat;
3058N/A}
3058N/A
3058N/A
3058N/A// The first routine called by a new Java thread
3058N/Avoid JavaThread::run() {
3058N/A // initialize thread-local alloc buffer related fields
0N/A this->initialize_tlab();
0N/A
0N/A // used to test validitity of stack trace backs
3058N/A this->record_base_of_stack_pointer();
4495N/A
4495N/A // Record real stack base and size.
4495N/A this->record_stack_base_and_size();
4495N/A
4495N/A // Initialize thread local storage; set before calling MutexLocker
4495N/A this->initialize_thread_local_storage();
4495N/A
5020N/A this->create_stack_guard_pages();
5020N/A
0N/A // Thread is now sufficient initialized to be handled by the safepoint code as being
0N/A // in the VM. Change thread state from _thread_new to _thread_in_vm
0N/A ThreadStateTransition::transition_and_fence(this, _thread_new, _thread_in_vm);
605N/A
0N/A assert(JavaThread::current() == this, "sanity check");
0N/A assert(!Thread::current()->owns_locks(), "sanity check");
0N/A
0N/A DTRACE_THREAD_PROBE(start, this);
0N/A
0N/A // This operation might block. We call that after all safepoint checks for a new thread has
0N/A // been completed.
0N/A this->set_active_handles(JNIHandleBlock::allocate_block());
1008N/A
0N/A if (JvmtiExport::should_post_thread_life()) {
0N/A JvmtiExport::post_thread_start(this);
0N/A }
5178N/A
0N/A // We call another function to do the rest so we are sure that the stack addresses used
0N/A // from there will be lower than the stack base just computed
0N/A thread_main_inner();
0N/A
0N/A // Note, thread is no longer valid at this point!
0N/A}
0N/A
0N/A
0N/Avoid JavaThread::thread_main_inner() {
0N/A assert(JavaThread::current() == this, "sanity check");
0N/A assert(this->threadObj() != NULL, "just checking");
2528N/A
2528N/A // Execute thread entry point. If this thread is being asked to restart,
2528N/A // or has been stopped before starting, do not reexecute entry point.
2528N/A // Note: Due to JVM_StopThread we can have pending exceptions already!
0N/A if (!this->has_pending_exception() && !java_lang_Thread::is_stillborn(this->threadObj())) {
0N/A // enter the thread's entry point only if we have no pending exceptions
1527N/A HandleMark hm(this);
0N/A this->entry_point()(this, this);
0N/A }
4156N/A
1008N/A DTRACE_THREAD_PROBE(stop, this);
1527N/A
0N/A this->exit(false);
2255N/A delete this;
0N/A}
0N/A
0N/A
0N/Astatic void ensure_join(JavaThread* thread) {
2900N/A // We do not need to grap the Threads_lock, since we are operating on ourself.
2896N/A Handle threadObj(thread, thread->threadObj());
2900N/A assert(threadObj.not_null(), "java thread object must exist");
2900N/A ObjectLocker lock(threadObj, thread);
2896N/A // Ignore pending exception (ThreadDeath), since we are exiting anyway
2896N/A thread->clear_pending_exception();
2896N/A // It is of profound importance that we set the stillborn bit and reset the thread object,
2900N/A // before we do the notify. Since, changing these two variable will make JVM_IsAlive return
2896N/A // false. So in case another thread is doing a join on this thread , it will detect that the thread
2900N/A // is dead when it gets notified.
2896N/A java_lang_Thread::set_stillborn(threadObj());
2900N/A // Thread is exiting. So set thread_status field in java.lang.Thread class to TERMINATED.
2900N/A java_lang_Thread::set_thread_status(threadObj(), java_lang_Thread::TERMINATED);
2900N/A java_lang_Thread::set_thread(threadObj(), NULL);
2896N/A lock.notify_all(thread);
2896N/A // Ignore pending exception (ThreadDeath), since we are exiting anyway
2900N/A thread->clear_pending_exception();
2900N/A}
2896N/A
2900N/A
2900N/A// For any new cleanup additions, please check to see if they need to be applied to
2896N/A// cleanup_failed_attach_current_thread as well.
2896N/Avoid JavaThread::exit(bool destroy_vm, ExitType exit_type) {
2900N/A assert(this == JavaThread::current(), "thread consistency check");
2896N/A if (!InitializeJavaLangSystem) return;
2896N/A
2900N/A HandleMark hm(this);
2896N/A Handle uncaught_exception(this, this->pending_exception());
2900N/A this->clear_pending_exception();
3853N/A Handle threadObj(this, this->threadObj());
2896N/A assert(threadObj.not_null(), "Java thread object should be created");
2896N/A
2896N/A if (get_thread_profiler() != NULL) {
2896N/A get_thread_profiler()->disengage();
2896N/A ResourceMark rm;
2896N/A get_thread_profiler()->print(get_thread_name());
2896N/A }
2900N/A
2900N/A
2900N/A // FIXIT: This code should be moved into else part, when reliable 1.2/1.3 check is in place
2900N/A {
2896N/A EXCEPTION_MARK;
2900N/A
2900N/A CLEAR_PENDING_EXCEPTION;
2896N/A }
2896N/A // FIXIT: The is_null check is only so it works better on JDK1.2 VM's. This
2900N/A // has to be fixed by a runtime query method
2900N/A if (!destroy_vm || JDK_Version::is_jdk12x_version()) {
2900N/A // JSR-166: change call from from ThreadGroup.uncaughtException to
2900N/A // java.lang.Thread.dispatchUncaughtException
2900N/A if (uncaught_exception.not_null()) {
2900N/A Handle group(this, java_lang_Thread::threadGroup(threadObj()));
2900N/A Events::log("uncaught exception INTPTR_FORMAT " " INTPTR_FORMAT " " INTPTR_FORMAT",
2900N/A (address)uncaught_exception(), (address)threadObj(), (address)group());
2900N/A {
2900N/A EXCEPTION_MARK;
2900N/A // Check if the method Thread.dispatchUncaughtException() exists. If so
2900N/A // call it. Otherwise we have an older library without the JSR-166 changes,
2900N/A // so call ThreadGroup.uncaughtException()
2900N/A KlassHandle recvrKlass(THREAD, threadObj->klass());
3005N/A CallInfo callinfo;
2900N/A KlassHandle thread_klass(THREAD, SystemDictionary::Thread_klass());
2900N/A LinkResolver::resolve_virtual_call(callinfo, threadObj, recvrKlass, thread_klass,
2900N/A vmSymbolHandles::dispatchUncaughtException_name(),
2900N/A vmSymbolHandles::throwable_void_signature(),
2900N/A KlassHandle(), false, false, THREAD);
2900N/A CLEAR_PENDING_EXCEPTION;
2900N/A methodHandle method = callinfo.selected_method();
2900N/A if (method.not_null()) {
2900N/A JavaValue result(T_VOID);
2900N/A JavaCalls::call_virtual(&result,
2900N/A threadObj, thread_klass,
2900N/A vmSymbolHandles::dispatchUncaughtException_name(),
2900N/A vmSymbolHandles::throwable_void_signature(),
2900N/A uncaught_exception,
2900N/A THREAD);
2900N/A } else {
2896N/A KlassHandle thread_group(THREAD, SystemDictionary::ThreadGroup_klass());
2896N/A JavaValue result(T_VOID);
2896N/A JavaCalls::call_virtual(&result,
2896N/A group, thread_group,
2896N/A vmSymbolHandles::uncaughtException_name(),
2896N/A vmSymbolHandles::thread_throwable_void_signature(),
2896N/A threadObj, // Arg 1
2896N/A uncaught_exception, // Arg 2
2896N/A THREAD);
2896N/A }
2900N/A CLEAR_PENDING_EXCEPTION;
2896N/A }
2896N/A }
4235N/A
4235N/A // Call Thread.exit(). We try 3 times in case we got another Thread.stop during
2900N/A // the execution of the method. If that is not enough, then we don't really care. Thread.stop
2896N/A // is deprecated anyhow.
2900N/A { int count = 3;
2896N/A while (java_lang_Thread::threadGroup(threadObj()) != NULL && (count-- > 0)) {
2896N/A EXCEPTION_MARK;
2896N/A JavaValue result(T_VOID);
2896N/A KlassHandle thread_klass(THREAD, SystemDictionary::Thread_klass());
2896N/A JavaCalls::call_virtual(&result,
2896N/A threadObj, thread_klass,
2896N/A vmSymbolHandles::exit_method_name(),
2896N/A vmSymbolHandles::void_method_signature(),
2896N/A THREAD);
2900N/A CLEAR_PENDING_EXCEPTION;
2896N/A }
2896N/A }
2896N/A
2896N/A // notify JVMTI
2896N/A if (JvmtiExport::should_post_thread_life()) {
2896N/A JvmtiExport::post_thread_end(this);
2896N/A }
2896N/A
2896N/A // We have notified the agents that we are exiting, before we go on,
4235N/A // we must check for a pending external suspend request and honor it
4235N/A // in order to not surprise the thread that made the suspend request.
4235N/A while (true) {
4235N/A {
2896N/A MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag);
2900N/A if (!is_external_suspend()) {
3853N/A set_terminated(_thread_exiting);
121N/A ThreadService::current_thread_exiting(this);
121N/A break;
0N/A }
0N/A // Implied else:
0N/A // Things get a little tricky here. We have a pending external
0N/A // suspend request, but we are holding the SR_lock so we
0N/A // can't just self-suspend. So we temporarily drop the lock
0N/A // and then self-suspend.
0N/A }
0N/A
0N/A ThreadBlockInVM tbivm(this);
0N/A java_suspend_self();
1527N/A
1527N/A // We're done with this suspend request, but we have to loop around
1527N/A // and check again. Eventually we will get SR_lock without a pending
1527N/A // external suspend request and will be able to mark ourselves as
0N/A // exiting.
0N/A }
0N/A // no more external suspends are allowed at this point
3381N/A } else {
3381N/A // before_exit() has already posted JVMTI THREAD_END events
3083N/A }
3083N/A
3083N/A // Notify waiters on thread object. This has to be done after exit() is called
3083N/A // on the thread (if the thread is the last thread in a daemon ThreadGroup the
3083N/A // group should have the destroyed bit set before waiters are notified).
3381N/A ensure_join(this);
3083N/A assert(!this->has_pending_exception(), "ensure_join should have cleared");
3083N/A
3083N/A // 6282335 JNI DetachCurrentThread spec states that all Java monitors
3083N/A // held by this thread must be released. A detach operation must only
3381N/A // get here if there are no Java frames on the stack. Therefore, any
3083N/A // owned monitors at this point MUST be JNI-acquired monitors which are
3083N/A // pre-inflated and in the monitor cache.
3083N/A //
3083N/A // ensure_join() ignores IllegalThreadStateExceptions, and so does this.
4156N/A if (exit_type == jni_detach && JNIDetachReleasesMonitors) {
4156N/A assert(!this->has_last_Java_frame(), "detaching with Java frames?");
4156N/A ObjectSynchronizer::release_monitors_owned_by_thread(this);
3083N/A assert(!this->has_pending_exception(), "release_monitors should have cleared");
4156N/A }
5178N/A
3083N/A // These things needs to be done while we are still a Java Thread. Make sure that thread
3083N/A // is in a consistent state, in case GC happens
3083N/A assert(_privileged_stack_top == NULL, "must be NULL when we get here");
3083N/A
3083N/A if (active_handles() != NULL) {
3083N/A JNIHandleBlock* block = active_handles();
3083N/A set_active_handles(NULL);
3083N/A JNIHandleBlock::release_block(block);
3083N/A }
3083N/A
4156N/A if (free_handle_block() != NULL) {
4156N/A JNIHandleBlock* block = free_handle_block();
4156N/A set_free_handle_block(NULL);
3083N/A JNIHandleBlock::release_block(block);
3083N/A }
3083N/A
3083N/A // These have to be removed while this is still a valid thread.
3083N/A remove_stack_guard_pages();
3083N/A
3083N/A if (UseTLAB) {
3083N/A tlab().make_parsable(true); // retire TLAB
3083N/A }
3381N/A
3083N/A if (jvmti_thread_state() != NULL) {
0N/A JvmtiExport::cleanup_thread(this);
0N/A }
0N/A
0N/A#ifndef SERIALGC
0N/A // We must flush G1-related buffers before removing a thread from
0N/A // the list of active threads.
0N/A if (UseG1GC) {
0N/A flush_barrier_queues();
0N/A }
0N/A#endif
0N/A
0N/A // Remove from list of active threads list, and notify VM thread if we are the last non-daemon thread
0N/A Threads::remove(this);
0N/A}
0N/A
0N/A#ifndef SERIALGC
0N/A// Flush G1-related queues.
5178N/Avoid JavaThread::flush_barrier_queues() {
5178N/A satb_mark_queue().flush();
3349N/A dirty_card_queue().flush();
0N/A}
0N/A#endif
0N/A
0N/Avoid JavaThread::cleanup_failed_attach_current_thread() {
0N/A if (get_thread_profiler() != NULL) {
0N/A get_thread_profiler()->disengage();
0N/A ResourceMark rm;
0N/A get_thread_profiler()->print(get_thread_name());
0N/A }
0N/A
0N/A if (active_handles() != NULL) {
0N/A JNIHandleBlock* block = active_handles();
1527N/A set_active_handles(NULL);
0N/A JNIHandleBlock::release_block(block);
0N/A }
2900N/A
2407N/A if (free_handle_block() != NULL) {
2407N/A JNIHandleBlock* block = free_handle_block();
2407N/A set_free_handle_block(NULL);
2407N/A JNIHandleBlock::release_block(block);
712N/A }
3349N/A
3349N/A // These have to be removed while this is still a valid thread.
3381N/A remove_stack_guard_pages();
233N/A
675N/A if (UseTLAB) {
675N/A tlab().make_parsable(true); // retire TLAB, if any
675N/A }
675N/A
675N/A#ifndef SERIALGC
675N/A if (UseG1GC) {
675N/A flush_barrier_queues();
675N/A }
675N/A#endif
675N/A
675N/A Threads::remove(this);
675N/A delete this;
1559N/A}
2123N/A
1559N/A
1559N/A
1559N/A
1559N/AJavaThread* JavaThread::active() {
1559N/A Thread* thread = ThreadLocalStorage::thread();
1559N/A assert(thread != NULL, "just checking");
1559N/A if (thread->is_Java_thread()) {
1559N/A return (JavaThread*) thread;
1559N/A } else {
1559N/A assert(thread->is_VM_thread(), "this must be a vm thread");
1559N/A VM_Operation* op = ((VMThread*) thread)->vm_operation();
1559N/A JavaThread *ret=op == NULL ? NULL : (JavaThread *)op->calling_thread();
675N/A assert(ret->is_Java_thread(), "must be a Java thread");
2556N/A return ret;
1559N/A }
2123N/A}
1559N/A
1559N/Abool JavaThread::is_lock_owned(address adr) const {
1559N/A if (Thread::is_lock_owned(adr)) return true;
1559N/A
1559N/A for (MonitorChunk* chunk = monitor_chunks(); chunk != NULL; chunk = chunk->next()) {
1559N/A if (chunk->contains(adr)) return true;
1559N/A }
1559N/A
1559N/A return false;
1559N/A}
1559N/A
1559N/A
675N/Avoid JavaThread::add_monitor_chunk(MonitorChunk* chunk) {
675N/A chunk->set_next(monitor_chunks());
675N/A set_monitor_chunks(chunk);
675N/A}
675N/A
675N/Avoid JavaThread::remove_monitor_chunk(MonitorChunk* chunk) {
675N/A guarantee(monitor_chunks() != NULL, "must be non empty");
675N/A if (monitor_chunks() == chunk) {
675N/A set_monitor_chunks(chunk->next());
675N/A } else {
675N/A MonitorChunk* prev = monitor_chunks();
675N/A while (prev->next() != chunk) prev = prev->next();
675N/A prev->set_next(chunk->next());
675N/A }
675N/A}
675N/A
675N/A// JVM support.
712N/A
233N/A// Note: this function shouldn't block if it's called in
233N/A// _thread_in_native_trans state (such as from
564N/A// check_special_condition_for_native_trans()).
233N/Avoid JavaThread::check_and_handle_async_exceptions(bool check_unsafe_error) {
233N/A
233N/A if (has_last_Java_frame() && has_async_condition()) {
233N/A // If we are at a polling page safepoint (not a poll return)
712N/A // then we must defer async exception because live registers
567N/A // will be clobbered by the exception path. Poll return is
712N/A // ok because the call we a returning from already collides
567N/A // with exception handling registers and so there is no issue.
318N/A // (The exception handling path kills call result registers but
712N/A // this is ok since the exception kills the result anyway).
712N/A
233N/A if (is_at_poll_safepoint()) {
1177N/A // if the code we are returning to has deoptimized we must defer
1177N/A // the exception otherwise live registers get clobbered on the
1008N/A // exception path before deoptimization is able to retrieve them.
712N/A //
712N/A RegisterMap map(this, false);
712N/A frame caller_fr = last_frame().sender(&map);
712N/A assert(caller_fr.is_compiled_frame(), "what?");
1008N/A if (caller_fr.is_deoptimized_frame()) {
712N/A if (TraceExceptions) {
1008N/A ResourceMark rm;
712N/A tty->print_cr("deferred async exception at compiled safepoint");
233N/A }
712N/A return;
712N/A }
712N/A }
712N/A }
712N/A
712N/A JavaThread::AsyncRequests condition = clear_special_runtime_exit_condition();
712N/A if (condition == _no_async_condition) {
712N/A // Conditions have changed since has_special_runtime_exit_condition()
712N/A // was called:
712N/A // - if we were here only because of an external suspend request,
712N/A // then that was taken care of above (or cancelled) so we are done
712N/A // - if we were here because of another async request, then it has
1008N/A // been cleared between the has_special_runtime_exit_condition()
712N/A // and now so again we are done
0N/A return;
0N/A }
1177N/A
1177N/A // Check for pending async. exception
675N/A if (_pending_async_exception != NULL) {
675N/A // Only overwrite an already pending exception, if it is not a threadDeath.
675N/A if (!has_pending_exception() || !pending_exception()->is_a(SystemDictionary::ThreadDeath_klass())) {
675N/A
675N/A // We cannot call Exceptions::_throw(...) here because we cannot block
675N/A set_pending_exception(_pending_async_exception, __FILE__, __LINE__);
675N/A
21N/A if (TraceExceptions) {
675N/A ResourceMark rm;
675N/A tty->print("Async. exception installed at runtime exit (" INTPTR_FORMAT ")", this);
675N/A if (has_last_Java_frame() ) {
675N/A frame f = last_frame();
675N/A tty->print(" (pc: " INTPTR_FORMAT " sp: " INTPTR_FORMAT " )", f.pc(), f.sp());
675N/A }
699N/A tty->print_cr(" of type: %s", instanceKlass::cast(_pending_async_exception->klass())->external_name());
699N/A }
699N/A _pending_async_exception = NULL;
699N/A clear_has_async_exception();
699N/A }
699N/A }
675N/A
675N/A if (check_unsafe_error &&
675N/A condition == _async_unsafe_access_error && !has_pending_exception()) {
675N/A condition = _no_async_condition; // done
1849N/A switch (thread_state()) {
1849N/A case _thread_in_vm:
1849N/A {
1849N/A JavaThread* THREAD = this;
1849N/A THROW_MSG(vmSymbols::java_lang_InternalError(), "a fault occurred in an unsafe memory access operation");
1849N/A }
1849N/A case _thread_in_native:
1849N/A {
1849N/A ThreadInVMfromNative tiv(this);
1849N/A JavaThread* THREAD = this;
1849N/A THROW_MSG(vmSymbols::java_lang_InternalError(), "a fault occurred in an unsafe memory access operation");
1849N/A }
675N/A case _thread_in_Java:
675N/A {
675N/A ThreadInVMfromJava tiv(this);
675N/A JavaThread* THREAD = this;
675N/A THROW_MSG(vmSymbols::java_lang_InternalError(), "a fault occurred in a recent unsafe memory access operation in compiled Java code");
675N/A }
675N/A default:
675N/A ShouldNotReachHere();
675N/A }
729N/A }
729N/A
729N/A assert(condition == _no_async_condition || has_pending_exception() ||
675N/A (!check_unsafe_error && condition == _async_unsafe_access_error),
675N/A "must have handled the async condition, if no exception");
675N/A}
675N/A
675N/Avoid JavaThread::handle_special_runtime_exit_condition(bool check_asyncs) {
712N/A //
699N/A // Check for pending external suspend. Internal suspend requests do
1849N/A // not use handle_special_runtime_exit_condition().
1849N/A // If JNIEnv proxies are allowed, don't self-suspend if the target
675N/A // thread is not the current thread. In older versions of jdbx, jdbx
712N/A // threads could call into the VM with another thread's JNIEnv so we
21N/A // can be here operating on behalf of a suspended thread (4432884).
1177N/A bool do_self_suspend = is_external_suspend_with_lock();
1177N/A if (do_self_suspend && (!AllowJNIEnvProxy || this == JavaThread::current())) {
0N/A //
185N/A // Because thread is external suspended the safepoint code will count
185N/A // thread as at a safepoint. This can be odd because we can be here
185N/A // as _thread_in_Java which would normally transition to _thread_blocked
185N/A // at a safepoint. We would like to mark the thread as _thread_blocked
1177N/A // before calling java_suspend_self like all other callers of it but
1177N/A // we must then observe proper safepoint protocol. (We can't leave
318N/A // _thread_blocked with a safepoint in progress). However we can be
699N/A // here as _thread_in_native_trans so we can't use a normal transition
712N/A // constructor/destructor pair because they assert on that type of
318N/A // transition. We could do something like:
185N/A //
1177N/A // JavaThreadState state = thread_state();
1177N/A // set_thread_state(_thread_in_vm);
185N/A // {
185N/A // ThreadBlockInVM tbivm(this);
3083N/A // java_suspend_self()
712N/A // }
185N/A // set_thread_state(_thread_in_vm_trans);
185N/A // if (safepoint) block;
185N/A // set_thread_state(state);
1177N/A //
185N/A // but that is pretty messy. Instead we just go with the way the
21N/A // code has worked before and note that this is the only path to
1238N/A // java_suspend_self that doesn't put the thread in _thread_blocked
712N/A // mode.
121N/A
121N/A frame_anchor()->make_walkable(this);
5037N/A java_suspend_self();
5037N/A
5044N/A // We might be here for reasons in addition to the self-suspend request
5037N/A // so check for other async requests.
5037N/A }
5037N/A
5037N/A if (check_asyncs) {
5037N/A check_and_handle_async_exceptions();
5037N/A }
5037N/A}
1177N/A
121N/Avoid JavaThread::send_thread_stop(oop java_throwable) {
121N/A assert(Thread::current()->is_VM_thread(), "should be in the vm thread");
675N/A assert(Threads_lock->is_locked(), "Threads_lock should be locked by safepoint code");
699N/A assert(SafepointSynchronize::is_at_safepoint(), "all threads are stopped");
121N/A
121N/A // Do not throw asynchronous exceptions against the compiler thread
233N/A // (the compiler thread should not be a Java thread -- fix in 1.4.2)
233N/A if (is_Compiler_thread()) return;
675N/A
699N/A // This is a change from JDK 1.1, but JDK 1.2 will also do it:
233N/A if (java_throwable->is_a(SystemDictionary::ThreadDeath_klass())) {
233N/A java_lang_Thread::set_stillborn(threadObj());
318N/A }
699N/A
675N/A {
318N/A // Actually throw the Throwable against the target Thread - however
318N/A // only if there is no thread death exception installed already.
712N/A if (_pending_async_exception == NULL || !_pending_async_exception->is_a(SystemDictionary::ThreadDeath_klass())) {
712N/A // If the topmost frame is a runtime stub, then we are calling into
712N/A // OptoRuntime from compiled code. Some runtime stubs (new, monitor_exit..)
712N/A // must deoptimize the caller before continuing, as the compiled exception handler table
712N/A // may not be valid
712N/A if (has_last_Java_frame()) {
2342N/A frame f = last_frame();
2342N/A if (f.is_runtime_frame() || f.is_safepoint_blob_frame()) {
2342N/A // BiasedLocking needs an updated RegisterMap for the revoke monitors pass
2342N/A RegisterMap reg_map(this, UseBiasedLocking);
2342N/A frame compiled_frame = f.sender(&reg_map);
2342N/A if (compiled_frame.can_be_deoptimized()) {
2342N/A Deoptimization::deoptimize(this, compiled_frame, &reg_map);
2342N/A }
2342N/A }
2342N/A }
2342N/A
2342N/A // Set async. pending exception in thread.
2342N/A set_pending_async_exception(java_throwable);
2342N/A
2342N/A if (TraceExceptions) {
2342N/A ResourceMark rm;
2342N/A tty->print_cr("Pending Async. exception installed of type: %s", instanceKlass::cast(_pending_async_exception->klass())->external_name());
2342N/A }
2342N/A // for AbortVMOnException flag
2342N/A NOT_PRODUCT(Exceptions::debug_check_abort(instanceKlass::cast(_pending_async_exception->klass())->external_name()));
2342N/A }
2342N/A }
2342N/A
2342N/A
2392N/A // Interrupt thread so it will wake up from a potential wait()
2392N/A Thread::interrupt(this);
2392N/A}
2392N/A
2392N/A// External suspension mechanism.
2392N/A//
2392N/A// Tell the VM to suspend a thread when ever it knows that it does not hold on
2342N/A// to any VM_locks and it is at a transition
2342N/A// Self-suspension will happen on the transition out of the vm.
2342N/A// Catch "this" coming in from JNIEnv pointers when the thread has been freed
2342N/A//
2342N/A// Guarantees on return:
2342N/A// + Target thread will not execute any new bytecode (that's why we need to
2342N/A// force a safepoint)
2342N/A// + Target thread will not enter any new monitors
2342N/A//
2342N/Avoid JavaThread::java_suspend() {
1016N/A { MutexLocker mu(Threads_lock);
1016N/A if (!Threads::includes(this) || is_exiting() || this->threadObj() == NULL) {
1016N/A return;
1016N/A }
2342N/A }
2342N/A
2342N/A { MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag);
2342N/A if (!is_external_suspend()) {
2342N/A // a racing resume has cancelled us; bail out now
712N/A return;
712N/A }
712N/A
3538N/A // suspend is done
902N/A uint32_t debug_bits = 0;
902N/A // Warning: is_ext_suspend_completed() may temporarily drop the
902N/A // SR_lock to allow the thread to reach a stable thread state if
902N/A // it is currently in a transient thread state.
1960N/A if (is_ext_suspend_completed(false /* !called_by_wait */,
902N/A SuspendRetryDelay, &debug_bits) ) {
3538N/A return;
2342N/A }
2342N/A }
2342N/A
2342N/A VM_ForceSafepoint vm_suspend;
2342N/A VMThread::execute(&vm_suspend);
2342N/A}
2342N/A
902N/A// Part II of external suspension.
1666N/A// A JavaThread self suspends when it detects a pending external suspend
1666N/A// request. This is usually on transitions. It is also done in places
1666N/A// where continuing to the next transition would surprise the caller,
1666N/A// e.g., monitor entry.
1666N/A//
1666N/A// Returns the number of times that the thread self-suspended.
1666N/A//
712N/A// Note: DO NOT call java_suspend_self() when you just want to block current
712N/A// thread. java_suspend_self() is the second stage of cooperative
712N/A// suspension for external suspend requests and should only be used
984N/A// to complete an external suspend request.
712N/A//
712N/Aint JavaThread::java_suspend_self() {
712N/A int ret = 0;
712N/A
984N/A // we are in the process of exiting so don't suspend
712N/A if (is_exiting()) {
712N/A clear_external_suspend();
712N/A return ret;
1666N/A }
1666N/A
984N/A assert(_anchor.walkable() ||
712N/A (is_Java_thread() && !((JavaThread*)this)->has_last_Java_frame()),
2342N/A "must have walkable stack");
2342N/A
2342N/A MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag);
2342N/A
4006N/A assert(!this->is_ext_suspended(),
712N/A "a thread trying to self-suspend should not already be suspended");
712N/A
712N/A if (this->is_suspend_equivalent()) {
1177N/A // If we are self-suspending as a result of the lifting of a
1177N/A // suspend equivalent condition, then the suspend_equivalent
121N/A // flag is not cleared until we set the ext_suspended flag so
121N/A // that wait_for_ext_suspend_completion() returns consistent
712N/A // results.
5037N/A this->clear_suspend_equivalent();
712N/A }
0N/A
1008N/A // A racing resume may have cancelled us before we grabbed SR_lock
0N/A // above. Or another external suspend request could be waiting for us
0N/A // by the time we return from SR_lock()->wait(). The thread
0N/A // that requested the suspension may already be trying to walk our
0N/A // stack and if we return now, we can change the stack out from under
0N/A // it. This would be a "bad thing (TM)" and cause the stack walker
0N/A // to crash. We stay self-suspended until there are no more pending
0N/A // external suspend requests.
0N/A while (is_external_suspend()) {
185N/A ret++;
161N/A this->set_ext_suspended();
161N/A
161N/A // _ext_suspended flag is cleared by java_resume()
161N/A while (is_ext_suspended()) {
161N/A this->SR_lock()->wait(Mutex::_no_safepoint_check_flag);
503N/A }
2342N/A }
2342N/A
2342N/A return ret;
2342N/A}
2342N/A
2342N/A#ifdef ASSERT
2342N/A// verify the JavaThread has not yet been published in the Threads::list, and
2342N/A// hence doesn't need protection from concurrent access at this stage
2342N/Avoid JavaThread::verify_not_published() {
2342N/A if (!Threads_lock->owned_by_self()) {
2342N/A MutexLockerEx ml(Threads_lock, Mutex::_no_safepoint_check_flag);
2342N/A assert( !Threads::includes(this),
2342N/A "java thread shouldn't have been published yet!");
2342N/A }
2342N/A else {
503N/A assert( !Threads::includes(this),
503N/A "java thread shouldn't have been published yet!");
712N/A }
503N/A}
503N/A#endif
503N/A
503N/A// Slow path when the native==>VM/Java barriers detect a safepoint is in
712N/A// progress or when _suspend_flags is non-zero.
1016N/A// Current thread needs to self-suspend if there is a suspend request and/or
1016N/A// block if a safepoint is in progress.
1016N/A// Async exception ISN'T checked.
1016N/A// Note only the ThreadInVMfromNative transition can call this function
1016N/A// directly and when thread state is _thread_in_native_trans
1016N/Avoid JavaThread::check_safepoint_and_suspend_for_native_trans(JavaThread *thread) {
1016N/A assert(thread->thread_state() == _thread_in_native_trans, "wrong state");
1016N/A
3538N/A JavaThread *curJT = JavaThread::current();
1590N/A bool do_self_suspend = thread->is_external_suspend();
3538N/A
3538N/A assert(!curJT->has_last_Java_frame() || curJT->frame_anchor()->walkable(), "Unwalkable stack in native->vm transition");
902N/A
3538N/A // If JNIEnv proxies are allowed, don't self-suspend if the target
902N/A // thread is not the current thread. In older versions of jdbx, jdbx
902N/A // threads could call into the VM with another thread's JNIEnv so we
902N/A // can be here operating on behalf of a suspended thread (4432884).
2342N/A if (do_self_suspend && (!AllowJNIEnvProxy || curJT == thread)) {
2342N/A JavaThreadState state = thread->thread_state();
2342N/A
2342N/A // We mark this thread_blocked state as a suspend-equivalent so
2342N/A // that a caller to is_ext_suspend_completed() won't be confused.
2342N/A // The suspend-equivalent state is cleared by java_suspend_self().
2342N/A thread->set_suspend_equivalent();
2342N/A
2342N/A // If the safepoint code sees the _thread_in_native_trans state, it will
2342N/A // wait until the thread changes to other thread state. There is no
2342N/A // guarantee on how soon we can obtain the SR_lock and complete the
2342N/A // self-suspend request. It would be a bad idea to let safepoint wait for
2342N/A // too long. Temporarily change the state to _thread_blocked to
2342N/A // let the VM thread know that this thread is ready for GC. The problem
2342N/A // of changing thread state is that safepoint could happen just after
2342N/A // java_suspend_self() returns after being resumed, and VM thread will
2556N/A // see the _thread_blocked state. We must check for safepoint
2556N/A // after restoring the state and make sure we won't leave while a safepoint
2556N/A // is in progress.
2342N/A thread->set_thread_state(_thread_blocked);
2342N/A thread->java_suspend_self();
2342N/A thread->set_thread_state(state);
2342N/A // Make sure new state is seen by VM thread
2342N/A if (os::is_MP()) {
2342N/A if (UseMembar) {
2342N/A // Force a fence between the write above and read below
2342N/A OrderAccess::fence();
2342N/A } else {
2342N/A // Must use this rather than serialization page in particular on Windows
2342N/A InterfaceSupport::serialize_memory(thread);
2342N/A }
2342N/A }
2342N/A }
2342N/A
2342N/A if (SafepointSynchronize::do_call_back()) {
2556N/A // If we are safepointing, then block the caller which may not be
2556N/A // the same as the target thread (see above).
2342N/A SafepointSynchronize::block(curJT);
2342N/A }
2342N/A
2342N/A if (thread->is_deopt_suspend()) {
2342N/A thread->clear_deopt_suspend();
902N/A RegisterMap map(thread, false);
712N/A frame f = thread->last_frame();
712N/A while ( f.id() != thread->must_deopt_id() && ! f.is_first_frame()) {
712N/A f = f.sender(&map);
712N/A }
712N/A if (f.id() == thread->must_deopt_id()) {
1008N/A thread->clear_must_deopt_id();
712N/A // Since we know we're safe to deopt the current state is a safe state
712N/A f.deoptimize(thread, true);
712N/A } else {
712N/A fatal("missed deoptimization!");
712N/A }
712N/A }
2342N/A}
712N/A
712N/A// Slow path when the native==>VM/Java barriers detect a safepoint is in
712N/A// progress or when _suspend_flags is non-zero.
712N/A// Current thread needs to self-suspend if there is a suspend request and/or
0N/A// block if a safepoint is in progress.
0N/A// Also check for pending async exception (not including unsafe access error).
151N/A// Note only the native==>VM/Java barriers can call this function and when
1527N/A// thread state is _thread_in_native_trans.
151N/Avoid JavaThread::check_special_condition_for_native_trans(JavaThread *thread) {
2086N/A check_safepoint_and_suspend_for_native_trans(thread);
0N/A
42N/A if (thread->has_async_exception()) {
0N/A // We are in _thread_in_native_trans state, don't handle unsafe
151N/A // access error since that may block.
0N/A thread->check_and_handle_async_exceptions(false);
0N/A }
0N/A}
2046N/A
1559N/A// We need to guarantee the Threads_lock here, since resumes are not
1559N/A// allowed during safepoint synchronization
1559N/A// Can only resume from an external suspension
1559N/Avoid JavaThread::java_resume() {
0N/A assert_locked_or_safepoint(Threads_lock);
0N/A
0N/A // Sanity check: thread is gone, has started exiting or the thread
3381N/A // was not externally suspended.
3349N/A if (!Threads::includes(this) || is_exiting() || !is_external_suspend()) {
3349N/A return;
3349N/A }
3381N/A
0N/A MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag);
422N/A
42N/A clear_external_suspend();
151N/A
5058N/A if (is_ext_suspended()) {
937N/A clear_ext_suspended();
3368N/A SR_lock()->notify_all();
503N/A }
1016N/A}
3538N/A
2342N/Avoid JavaThread::create_stack_guard_pages() {
2342N/A if (! os::uses_stack_guard_pages() || _stack_guard_state != stack_guard_unused) return;
371N/A address low_addr = stack_base() - stack_size();
712N/A size_t len = (StackYellowPages + StackRedPages) * os::vm_page_size();
2342N/A
2342N/A int allocate = os::allocate_stack_guard_pages();
2342N/A // warning("Guarding at " PTR_FORMAT " for len " SIZE_FORMAT "\n", low_addr, len);
2342N/A
233N/A if (allocate && !os::create_stack_guard_pages((char *) low_addr, len)) {
0N/A warning("Attempt to allocate stack guard pages failed.");
121N/A return;
712N/A }
712N/A
712N/A if (os::guard_memory((char *) low_addr, len)) {
1008N/A _stack_guard_state = stack_guard_enabled;
712N/A } else {
712N/A warning("Attempt to protect stack guard pages failed.");
712N/A if (os::uncommit_memory((char *) low_addr, len)) {
712N/A warning("Attempt to deallocate stack guard pages failed.");
1960N/A }
712N/A }
42N/A}
95N/A
422N/Avoid JavaThread::remove_stack_guard_pages() {
1008N/A if (_stack_guard_state == stack_guard_unused) return;
1008N/A address low_addr = stack_base() - stack_size();
422N/A size_t len = (StackYellowPages + StackRedPages) * os::vm_page_size();
42N/A
724N/A if (os::allocate_stack_guard_pages()) {
422N/A if (os::remove_stack_guard_pages((char *) low_addr, len)) {
724N/A _stack_guard_state = stack_guard_unused;
42N/A } else {
712N/A warning("Attempt to deallocate stack guard pages failed.");
42N/A }
121N/A } else {
712N/A if (_stack_guard_state == stack_guard_unused) return;
712N/A if (os::unguard_memory((char *) low_addr, len)) {
712N/A _stack_guard_state = stack_guard_unused;
0N/A } else {
0N/A warning("Attempt to unprotect stack guard pages failed.");
1177N/A }
1177N/A }
318N/A}
984N/A
984N/Avoid JavaThread::enable_stack_yellow_zone() {
984N/A assert(_stack_guard_state != stack_guard_unused, "must be using guard pages.");
984N/A assert(_stack_guard_state != stack_guard_enabled, "already enabled");
984N/A
984N/A // The base notation is from the stacks point of view, growing downward.
984N/A // We need to adjust it to work correctly with guard_memory()
984N/A address base = stack_yellow_zone_base() - stack_yellow_zone_size();
984N/A
984N/A guarantee(base < stack_base(),"Error calculating stack yellow zone");
984N/A guarantee(base < os::current_stack_pointer(),"Error calculating stack yellow zone");
984N/A
1177N/A if (os::guard_memory((char *) base, stack_yellow_zone_size())) {
1177N/A _stack_guard_state = stack_guard_enabled;
21N/A } else {
21N/A warning("Attempt to guard stack yellow zone failed.");
0N/A }
0N/A enable_register_stack_guard();
0N/A}
0N/A
0N/Avoid JavaThread::disable_stack_yellow_zone() {
0N/A assert(_stack_guard_state != stack_guard_unused, "must be using guard pages.");
0N/A assert(_stack_guard_state != stack_guard_yellow_disabled, "already disabled");
0N/A
0N/A // Simply return if called for a thread that does not use guard pages.
0N/A if (_stack_guard_state == stack_guard_unused) return;
121N/A
3381N/A // The base notation is from the stacks point of view, growing downward.
3381N/A // We need to adjust it to work correctly with guard_memory()
1177N/A address base = stack_yellow_zone_base() - stack_yellow_zone_size();
233N/A
233N/A if (os::unguard_memory((char *)base, stack_yellow_zone_size())) {
233N/A _stack_guard_state = stack_guard_yellow_disabled;
233N/A } else {
3646N/A warning("Attempt to unguard stack yellow zone failed.");
3646N/A }
2086N/A disable_register_stack_guard();
2086N/A}
2086N/A
2086N/Avoid JavaThread::enable_stack_red_zone() {
2086N/A // The base notation is from the stacks point of view, growing downward.
2086N/A // We need to adjust it to work correctly with guard_memory()
2940N/A assert(_stack_guard_state != stack_guard_unused, "must be using guard pages.");
2940N/A address base = stack_red_zone_base() - stack_red_zone_size();
2940N/A
5178N/A guarantee(base < stack_base(),"Error calculating stack red zone");
5178N/A guarantee(base < os::current_stack_pointer(),"Error calculating stack red zone");
2086N/A
2086N/A if(!os::guard_memory((char *) base, stack_red_zone_size())) {
2086N/A warning("Attempt to guard stack red zone failed.");
233N/A }
5178N/A}
5178N/A
233N/Avoid JavaThread::disable_stack_red_zone() {
233N/A // The base notation is from the stacks point of view, growing downward.
233N/A // We need to adjust it to work correctly with guard_memory()
233N/A assert(_stack_guard_state != stack_guard_unused, "must be using guard pages.");
233N/A address base = stack_red_zone_base() - stack_red_zone_size();
233N/A if (!os::unguard_memory((char *)base, stack_red_zone_size())) {
233N/A warning("Attempt to unguard stack red zone failed.");
578N/A }
578N/A}
578N/A
578N/Avoid JavaThread::frames_do(void f(frame*, const RegisterMap* map)) {
729N/A // ignore is there is no stack
729N/A if (!has_last_Java_frame()) return;
729N/A // traverse the stack frames. Starts from top frame.
729N/A for(StackFrameStream fst(this); !fst.is_done(); fst.next()) {
729N/A frame* fr = fst.current();
233N/A f(fr, fst.register_map());
233N/A }
233N/A}
233N/A
564N/A
233N/A#ifndef PRODUCT
233N/A// Deoptimization
1008N/A// Function for testing deoptimization
1177N/Avoid JavaThread::deoptimize() {
1177N/A // BiasedLocking needs an updated RegisterMap for the revoke monitors pass
1008N/A StackFrameStream fst(this, UseBiasedLocking);
2459N/A bool deopt = false; // Dump stack only if a deopt actually happens.
1177N/A bool only_at = strlen(DeoptimizeOnlyAt) > 0;
1177N/A // Iterate over all frames in the thread and deoptimize
1177N/A for(; !fst.is_done(); fst.next()) {
1177N/A if(fst.current()->can_be_deoptimized()) {
1177N/A
1177N/A if (only_at) {
1238N/A // Deoptimize only at particular bcis. DeoptimizeOnlyAt
1177N/A // consists of comma or carriage return separated numbers so
1177N/A // search for the current bci in that string.
1177N/A address pc = fst.current()->pc();
1177N/A nmethod* nm = (nmethod*) fst.current()->cb();
1177N/A ScopeDesc* sd = nm->scope_desc_at( pc);
1238N/A char buffer[8];
1602N/A jio_snprintf(buffer, sizeof(buffer), "%d", sd->bci());
1177N/A size_t len = strlen(buffer);
1177N/A const char * found = strstr(DeoptimizeOnlyAt, buffer);
5058N/A while (found != NULL) {
1177N/A if ((found[len] == ',' || found[len] == '\n' || found[len] == '\0') &&
4156N/A (found == DeoptimizeOnlyAt || found[-1] == ',' || found[-1] == '\n')) {
1177N/A // Check that the bci found is bracketed by terminators.
2813N/A break;
5058N/A }
5058N/A found = strstr(found + 1, buffer);
1177N/A }
1177N/A if (!found) {
1177N/A continue;
3381N/A }
3381N/A }
1177N/A
5058N/A if (DebugDeoptimization && !deopt) {
5058N/A deopt = true; // One-time only print before deopt
5058N/A tty->print_cr("[BEFORE Deoptimization]");
5058N/A trace_frames();
5058N/A trace_stack();
5058N/A }
5058N/A Deoptimization::deoptimize(this, *fst.current(), fst.register_map());
1008N/A }
4156N/A }
4156N/A
1008N/A if (DebugDeoptimization && deopt) {
1008N/A tty->print_cr("[AFTER Deoptimization]");
5058N/A trace_frames();
1008N/A }
1008N/A}
1008N/A
1008N/A
1008N/A// Make zombies
5058N/Avoid JavaThread::make_zombies() {
1008N/A for(StackFrameStream fst(this); !fst.is_done(); fst.next()) {
1008N/A if (fst.current()->can_be_deoptimized()) {
1008N/A // it is a Java nmethod
4156N/A nmethod* nm = CodeCache::find_nmethod(fst.current()->pc());
4156N/A nm->make_not_entrant();
1008N/A }
1008N/A }
5058N/A}
1008N/A#endif // PRODUCT
1008N/A
1008N/A
1008N/Avoid JavaThread::deoptimized_wrt_marked_nmethods() {
1008N/A if (!has_last_Java_frame()) return;
5058N/A // BiasedLocking needs an updated RegisterMap for the revoke monitors pass
1008N/A StackFrameStream fst(this, UseBiasedLocking);
1008N/A for(; !fst.is_done(); fst.next()) {
1008N/A if (fst.current()->should_be_deoptimized()) {
4156N/A Deoptimization::deoptimize(this, *fst.current(), fst.register_map());
4156N/A }
1008N/A }
1008N/A}
5058N/A
1008N/A
1008N/A// GC support
1008N/Astatic void frame_gc_epilogue(frame* f, const RegisterMap* map) { f->gc_epilogue(); }
1008N/A
1008N/Avoid JavaThread::gc_epilogue() {
5058N/A frames_do(frame_gc_epilogue);
1008N/A}
1008N/A
1008N/A
1008N/Astatic void frame_gc_prologue(frame* f, const RegisterMap* map) { f->gc_prologue(); }
4156N/A
4156N/Avoid JavaThread::gc_prologue() {
1008N/A frames_do(frame_gc_prologue);
1008N/A}
5058N/A
1008N/A// If the caller is a NamedThread, then remember, in the current scope,
1008N/A// the given JavaThread in its _processed_thread field.
1530N/Aclass RememberProcessedThread: public StackObj {
4156N/A NamedThread* _cur_thr;
4156N/Apublic:
1530N/A RememberProcessedThread(JavaThread* jthr) {
1530N/A Thread* thread = Thread::current();
5058N/A if (thread->is_Named_thread()) {
1530N/A _cur_thr = (NamedThread *)thread;
1530N/A _cur_thr->set_processed_thread(jthr);
1140N/A } else {
4156N/A _cur_thr = NULL;
4156N/A }
1140N/A }
1140N/A
5058N/A ~RememberProcessedThread() {
1140N/A if (_cur_thr) {
3381N/A _cur_thr->set_processed_thread(NULL);
1008N/A }
1008N/A }
1008N/A};
4156N/A
5058N/Avoid JavaThread::oops_do(OopClosure* f, CodeBlobClosure* cf) {
5058N/A // Verify that the deferred card marks have been flushed.
5058N/A assert(deferred_card_mark().is_empty(), "Should be empty during GC");
1008N/A
1008N/A // The ThreadProfiler oops_do is done from FlatProfiler::oops_do
1008N/A // since there may be more than one thread using each ThreadProfiler.
1008N/A
1008N/A // Traverse the GCHandles
1008N/A Thread::oops_do(f, cf);
1177N/A
1177N/A assert( (!has_last_Java_frame() && java_call_counter() == 0) ||
1008N/A (has_last_Java_frame() && java_call_counter() > 0), "wrong java_sp info!");
3853N/A
1008N/A if (has_last_Java_frame()) {
1008N/A // Record JavaThread to GC thread
1008N/A RememberProcessedThread rpt(this);
1008N/A
1008N/A // Traverse the privileged stack
1008N/A if (_privileged_stack_top != NULL) {
2459N/A _privileged_stack_top->oops_do(f);
1008N/A }
1008N/A
1008N/A // traverse the registered growable array
1008N/A if (_array_for_gc != NULL) {
1530N/A for (int index = 0; index < _array_for_gc->length(); index++) {
1008N/A f->do_oop(_array_for_gc->adr_at(index));
1008N/A }
1008N/A }
2086N/A
3853N/A // Traverse the monitor chunks
2086N/A for (MonitorChunk* chunk = monitor_chunks(); chunk != NULL; chunk = chunk->next()) {
2086N/A chunk->oops_do(f);
2086N/A }
2086N/A
1395N/A // Traverse the execution stack
1395N/A for(StackFrameStream fst(this); !fst.is_done(); fst.next()) {
1395N/A fst.current()->oops_do(f, cf, fst.register_map());
1395N/A }
1395N/A }
1395N/A
1395N/A // callee_target is never live across a gc point so NULL it here should
1395N/A // it still contain a methdOop.
1395N/A
1395N/A set_callee_target(NULL);
1395N/A
1395N/A assert(vframe_array_head() == NULL, "deopt in progress at a safepoint!");
1395N/A // If we have deferred set_locals there might be oops waiting to be
2033N/A // written
1395N/A GrowableArray<jvmtiDeferredLocalVariableSet*>* list = deferred_locals();
1395N/A if (list != NULL) {
1395N/A for (int i = 0; i < list->length(); i++) {
1395N/A list->at(i)->oops_do(f);
3381N/A }
3381N/A }
1008N/A
1008N/A // Traverse instance variables at the end since the GC may be moving things
1008N/A // around using this function
1008N/A f->do_oop((oop*) &_threadObj);
1008N/A f->do_oop((oop*) &_vm_result);
1008N/A f->do_oop((oop*) &_vm_result_2);
1008N/A f->do_oop((oop*) &_exception_oop);
1008N/A f->do_oop((oop*) &_pending_async_exception);
1008N/A
1008N/A if (jvmti_thread_state() != NULL) {
1008N/A jvmti_thread_state()->oops_do(f);
1008N/A }
1008N/A}
3646N/A
1008N/Avoid JavaThread::nmethods_do(CodeBlobClosure* cf) {
1008N/A Thread::nmethods_do(cf); // (super method is a no-op)
1008N/A
1008N/A assert( (!has_last_Java_frame() && java_call_counter() == 0) ||
1008N/A (has_last_Java_frame() && java_call_counter() > 0), "wrong java_sp info!");
1008N/A
1008N/A if (has_last_Java_frame()) {
1008N/A // Traverse the execution stack
1008N/A for(StackFrameStream fst(this); !fst.is_done(); fst.next()) {
1008N/A fst.current()->nmethods_do(cf);
1008N/A }
1008N/A }
1008N/A}
3646N/A
3646N/A// Printing
3646N/Aconst char* _get_thread_state_name(JavaThreadState _thread_state) {
1008N/A switch (_thread_state) {
1008N/A case _thread_uninitialized: return "_thread_uninitialized";
1008N/A case _thread_new: return "_thread_new";
1008N/A case _thread_new_trans: return "_thread_new_trans";
1008N/A case _thread_in_native: return "_thread_in_native";
1008N/A case _thread_in_native_trans: return "_thread_in_native_trans";
3381N/A case _thread_in_vm: return "_thread_in_vm";
3349N/A case _thread_in_vm_trans: return "_thread_in_vm_trans";
3349N/A case _thread_in_Java: return "_thread_in_Java";
3349N/A case _thread_in_Java_trans: return "_thread_in_Java_trans";
3349N/A case _thread_blocked: return "_thread_blocked";
3381N/A case _thread_blocked_trans: return "_thread_blocked_trans";
3349N/A default: return "unknown thread state";
4009N/A }
4009N/A}
4009N/A
4009N/A#ifndef PRODUCT
3349N/Avoid JavaThread::print_thread_state_on(outputStream *st) const {
3381N/A st->print_cr(" JavaThread state: %s", _get_thread_state_name(_thread_state));
3349N/A};
3381N/Avoid JavaThread::print_thread_state() const {
3349N/A print_thread_state_on(tty);
3349N/A};
3349N/A#endif // PRODUCT
3349N/A
3349N/A// Called by Threads::print() for VM_PrintThreads operation
3349N/Avoid JavaThread::print_on(outputStream *st) const {
3381N/A st->print("\"%s\" ", get_thread_name());
3349N/A oop thread_oop = threadObj();
3349N/A if (thread_oop != NULL && java_lang_Thread::is_daemon(thread_oop)) st->print("daemon ");
3349N/A Thread::print_on(st);
3349N/A // print guess for valid stack memory region (assume 4K pages); helps lock debugging
3349N/A st->print_cr("[" INTPTR_FORMAT "]", (intptr_t)last_Java_sp() & ~right_n_bits(12));
3381N/A if (thread_oop != NULL && JDK_Version::is_gte_jdk15x_version()) {
5286N/A st->print_cr(" java.lang.Thread.State: %s", java_lang_Thread::thread_status_name(thread_oop));
5286N/A }
5286N/A#ifndef PRODUCT
5286N/A print_thread_state_on(st);
3349N/A _safepoint_state->print_on(st);
3349N/A#endif // PRODUCT
3381N/A}
3349N/A
4008N/A// Called by fatal error handler. The difference between this and
3349N/A// JavaThread::print() is that we can't grab lock or allocate memory.
3349N/Avoid JavaThread::print_on_error(outputStream* st, char *buf, int buflen) const {
3381N/A st->print("JavaThread \"%s\"", get_thread_name_string(buf, buflen));
3349N/A oop thread_obj = threadObj();
3349N/A if (thread_obj != NULL) {
3349N/A if (java_lang_Thread::is_daemon(thread_obj)) st->print(" daemon");
3349N/A }
3349N/A st->print(" [");
3349N/A st->print("%s", _get_thread_state_name(_thread_state));
3349N/A if (osthread()) {
3381N/A st->print(", id=%d", osthread()->thread_id());
3349N/A }
3349N/A st->print(", stack(" PTR_FORMAT "," PTR_FORMAT ")",
3349N/A _stack_base - _stack_size, _stack_base);
3349N/A st->print("]");
3349N/A return;
3349N/A}
3349N/A
3349N/A// Verification
3349N/A
3381N/Astatic void frame_verify(frame* f, const RegisterMap *map) { f->verify(map); }
3349N/A
3349N/Avoid JavaThread::verify() {
5178N/A // Verify oops in the thread.
3349N/A oops_do(&VerifyOopClosure::verify_oop, NULL);
3349N/A
3349N/A // Verify the stack frames.
3349N/A frames_do(frame_verify);
3349N/A}
3349N/A
3349N/A// CR 6300358 (sub-CR 2137150)
3349N/A// Most callers of this method assume that it can't return NULL but a
3349N/A// thread may not have a name whilst it is in the process of attaching to
3349N/A// the VM - see CR 6412693, and there are places where a JavaThread can be
3349N/A// seen prior to having it's threadObj set (eg JNI attaching threads and
3349N/A// if vm exit occurs during initialization). These cases can all be accounted
3349N/A// for such that this method never returns NULL.
3349N/Aconst char* JavaThread::get_thread_name() const {
3381N/A#ifdef ASSERT
3349N/A // early safepoints can hit while current thread does not yet have TLS
3381N/A if (!SafepointSynchronize::is_at_safepoint()) {
3349N/A Thread *cur = Thread::current();
3349N/A if (!(cur->is_Java_thread() && cur == this)) {
3349N/A // Current JavaThreads are allowed to get their own name without
3349N/A // the Threads_lock.
3349N/A assert_locked_or_safepoint(Threads_lock);
3349N/A }
3349N/A }
3349N/A#endif // ASSERT
3349N/A return get_thread_name_string();
3349N/A}
3349N/A
3381N/A// Returns a non-NULL representation of this thread's name, or a suitable
3349N/A// descriptive string if there is no set name
3349N/Aconst char* JavaThread::get_thread_name_string(char* buf, int buflen) const {
3349N/A const char* name_str;
3349N/A oop thread_obj = threadObj();
3381N/A if (thread_obj != NULL) {
3349N/A typeArrayOop name = java_lang_Thread::name(thread_obj);
3349N/A if (name != NULL) {
3349N/A if (buf == NULL) {
3349N/A name_str = UNICODE::as_utf8((jchar*) name->base(T_CHAR), name->length());
3853N/A }
3853N/A else {
3853N/A name_str = UNICODE::as_utf8((jchar*) name->base(T_CHAR), name->length(), buf, buflen);
3853N/A }
3853N/A }
3853N/A else if (is_attaching()) { // workaround for 6412693 - see 6404306
3853N/A name_str = "<no-name - thread is attaching>";
4686N/A }
4686N/A else {
4686N/A name_str = Thread::name();
4686N/A }
4686N/A }
4686N/A else {
3349N/A name_str = Thread::name();
3349N/A }
3349N/A assert(name_str != NULL, "unexpected NULL thread name");
3381N/A return name_str;
3349N/A}
3349N/A
3349N/A
3349N/Aconst char* JavaThread::get_threadgroup_name() const {
5178N/A debug_only(if (JavaThread::current() != this) assert_locked_or_safepoint(Threads_lock);)
5178N/A oop thread_obj = threadObj();
3349N/A if (thread_obj != NULL) {
3349N/A oop thread_group = java_lang_Thread::threadGroup(thread_obj);
3349N/A if (thread_group != NULL) {
3349N/A typeArrayOop name = java_lang_ThreadGroup::name(thread_group);
3349N/A // ThreadGroup.name can be null
3349N/A if (name != NULL) {
3349N/A const char* str = UNICODE::as_utf8((jchar*) name->base(T_CHAR), name->length());
3349N/A return str;
3349N/A }
3349N/A }
3349N/A }
3381N/A return NULL;
3349N/A}
3349N/A
3349N/Aconst char* JavaThread::get_parent_name() const {
3349N/A debug_only(if (JavaThread::current() != this) assert_locked_or_safepoint(Threads_lock);)
3349N/A oop thread_obj = threadObj();
3349N/A if (thread_obj != NULL) {
3349N/A oop thread_group = java_lang_Thread::threadGroup(thread_obj);
3349N/A if (thread_group != NULL) {
3349N/A oop parent = java_lang_ThreadGroup::parent(thread_group);
3381N/A if (parent != NULL) {
5306N/A typeArrayOop name = java_lang_ThreadGroup::name(parent);
3860N/A // ThreadGroup.name can be null
4156N/A if (name != NULL) {
4156N/A const char* str = UNICODE::as_utf8((jchar*) name->base(T_CHAR), name->length());
4156N/A return str;
4156N/A }
4156N/A }
4156N/A }
4156N/A }
4156N/A return NULL;
4156N/A}
4156N/A
4156N/AThreadPriority JavaThread::java_priority() const {
4156N/A oop thr_oop = threadObj();
4156N/A if (thr_oop == NULL) return NormPriority; // Bootstrapping
4156N/A ThreadPriority priority = java_lang_Thread::priority(thr_oop);
4156N/A assert(MinPriority <= priority && priority <= MaxPriority, "sanity check");
4156N/A return priority;
4156N/A}
4156N/A
4156N/Avoid JavaThread::prepare(jobject jni_thread, ThreadPriority prio) {
4156N/A
4156N/A assert(Threads_lock->owner() == Thread::current(), "must have threads lock");
4156N/A // Link Java Thread object <-> C++ Thread
4330N/A
0N/A // Get the C++ thread object (an oop) from the JNI handle (a jthread)
// and put it into a new Handle. The Handle "thread_oop" can then
// be used to pass the C++ thread object to other methods.
// Set the Java level thread object (jthread) field of the
// new thread (a JavaThread *) to C++ thread object using the
// "thread_oop" handle.
// Set the thread field (a JavaThread *) of the
// oop representing the java_lang_Thread to the new thread (a JavaThread *).
Handle thread_oop(Thread::current(),
JNIHandles::resolve_non_null(jni_thread));
assert(instanceKlass::cast(thread_oop->klass())->is_linked(),
"must be initialized");
set_threadObj(thread_oop());
java_lang_Thread::set_thread(thread_oop(), this);
if (prio == NoPriority) {
prio = java_lang_Thread::priority(thread_oop());
assert(prio != NoPriority, "A valid priority should be present");
}
// Push the Java priority down to the native thread; needs Threads_lock
Thread::set_priority(this, prio);
// Add the new thread to the Threads list and set it in motion.
// We must have threads lock in order to call Threads::add.
// It is crucial that we do not block before the thread is
// added to the Threads list for if a GC happens, then the java_thread oop
// will not be visited by GC.
Threads::add(this);
}
oop JavaThread::current_park_blocker() {
// Support for JSR-166 locks
oop thread_oop = threadObj();
if (thread_oop != NULL &&
JDK_Version::current().supports_thread_park_blocker()) {
return java_lang_Thread::park_blocker(thread_oop);
}
return NULL;
}
void JavaThread::print_stack_on(outputStream* st) {
if (!has_last_Java_frame()) return;
ResourceMark rm;
HandleMark hm;
RegisterMap reg_map(this);
vframe* start_vf = last_java_vframe(&reg_map);
int count = 0;
for (vframe* f = start_vf; f; f = f->sender() ) {
if (f->is_java_frame()) {
javaVFrame* jvf = javaVFrame::cast(f);
java_lang_Throwable::print_stack_element(st, jvf->method(), jvf->bci());
// Print out lock information
if (JavaMonitorsInStackTrace) {
jvf->print_lock_info_on(st, count);
}
} else {
// Ignore non-Java frames
}
// Bail-out case for too deep stacks
count++;
if (MaxJavaStackTraceDepth == count) return;
}
}
// JVMTI PopFrame support
void JavaThread::popframe_preserve_args(ByteSize size_in_bytes, void* start) {
assert(_popframe_preserved_args == NULL, "should not wipe out old PopFrame preserved arguments");
if (in_bytes(size_in_bytes) != 0) {
_popframe_preserved_args = NEW_C_HEAP_ARRAY(char, in_bytes(size_in_bytes));
_popframe_preserved_args_size = in_bytes(size_in_bytes);
Copy::conjoint_bytes(start, _popframe_preserved_args, _popframe_preserved_args_size);
}
}
void* JavaThread::popframe_preserved_args() {
return _popframe_preserved_args;
}
ByteSize JavaThread::popframe_preserved_args_size() {
return in_ByteSize(_popframe_preserved_args_size);
}
WordSize JavaThread::popframe_preserved_args_size_in_words() {
int sz = in_bytes(popframe_preserved_args_size());
assert(sz % wordSize == 0, "argument size must be multiple of wordSize");
return in_WordSize(sz / wordSize);
}
void JavaThread::popframe_free_preserved_args() {
assert(_popframe_preserved_args != NULL, "should not free PopFrame preserved arguments twice");
FREE_C_HEAP_ARRAY(char, (char*) _popframe_preserved_args);
_popframe_preserved_args = NULL;
_popframe_preserved_args_size = 0;
}
#ifndef PRODUCT
void JavaThread::trace_frames() {
tty->print_cr("[Describe stack]");
int frame_no = 1;
for(StackFrameStream fst(this); !fst.is_done(); fst.next()) {
tty->print(" %d. ", frame_no++);
fst.current()->print_value_on(tty,this);
tty->cr();
}
}
void JavaThread::trace_stack_from(vframe* start_vf) {
ResourceMark rm;
int vframe_no = 1;
for (vframe* f = start_vf; f; f = f->sender() ) {
if (f->is_java_frame()) {
javaVFrame::cast(f)->print_activation(vframe_no++);
} else {
f->print();
}
if (vframe_no > StackPrintLimit) {
tty->print_cr("...<more frames>...");
return;
}
}
}
void JavaThread::trace_stack() {
if (!has_last_Java_frame()) return;
ResourceMark rm;
HandleMark hm;
RegisterMap reg_map(this);
trace_stack_from(last_java_vframe(&reg_map));
}
#endif // PRODUCT
javaVFrame* JavaThread::last_java_vframe(RegisterMap *reg_map) {
assert(reg_map != NULL, "a map must be given");
frame f = last_frame();
for (vframe* vf = vframe::new_vframe(&f, reg_map, this); vf; vf = vf->sender() ) {
if (vf->is_java_frame()) return javaVFrame::cast(vf);
}
return NULL;
}
klassOop JavaThread::security_get_caller_class(int depth) {
vframeStream vfst(this);
vfst.security_get_caller_frame(depth);
if (!vfst.at_end()) {
return vfst.method()->method_holder();
}
return NULL;
}
static void compiler_thread_entry(JavaThread* thread, TRAPS) {
assert(thread->is_Compiler_thread(), "must be compiler thread");
CompileBroker::compiler_thread_loop();
}
// Create a CompilerThread
CompilerThread::CompilerThread(CompileQueue* queue, CompilerCounters* counters)
: JavaThread(&compiler_thread_entry) {
_env = NULL;
_log = NULL;
_task = NULL;
_queue = queue;
_counters = counters;
#ifndef PRODUCT
_ideal_graph_printer = NULL;
#endif
}
// ======= Threads ========
// The Threads class links together all active threads, and provides
// operations over all threads. It is protected by its own Mutex
// lock, which is also used in other contexts to protect thread
// operations from having the thread being operated on from exiting
// and going away unexpectedly (e.g., safepoint synchronization)
JavaThread* Threads::_thread_list = NULL;
int Threads::_number_of_threads = 0;
int Threads::_number_of_non_daemon_threads = 0;
int Threads::_return_code = 0;
size_t JavaThread::_stack_size_at_create = 0;
// All JavaThreads
#define ALL_JAVA_THREADS(X) for (JavaThread* X = _thread_list; X; X = X->next())
void os_stream();
// All JavaThreads + all non-JavaThreads (i.e., every thread in the system)
void Threads::threads_do(ThreadClosure* tc) {
assert_locked_or_safepoint(Threads_lock);
// ALL_JAVA_THREADS iterates through all JavaThreads
ALL_JAVA_THREADS(p) {
tc->do_thread(p);
}
// Someday we could have a table or list of all non-JavaThreads.
// For now, just manually iterate through them.
tc->do_thread(VMThread::vm_thread());
Universe::heap()->gc_threads_do(tc);
WatcherThread *wt = WatcherThread::watcher_thread();
// Strictly speaking, the following NULL check isn't sufficient to make sure
// the data for WatcherThread is still valid upon being examined. However,
// considering that WatchThread terminates when the VM is on the way to
// exit at safepoint, the chance of the above is extremely small. The right
// way to prevent termination of WatcherThread would be to acquire
// Terminator_lock, but we can't do that without violating the lock rank
// checking in some cases.
if (wt != NULL)
tc->do_thread(wt);
// If CompilerThreads ever become non-JavaThreads, add them here
}
jint Threads::create_vm(JavaVMInitArgs* args, bool* canTryAgain) {
extern void JDK_Version_init();
// Check version
if (!is_supported_jni_version(args->version)) return JNI_EVERSION;
// Initialize the output stream module
ostream_init();
// Process java launcher properties.
Arguments::process_sun_java_launcher_properties(args);
// Initialize the os module before using TLS
os::init();
// Initialize system properties.
Arguments::init_system_properties();
// So that JDK version can be used as a discrimintor when parsing arguments
JDK_Version_init();
// Parse arguments
jint parse_result = Arguments::parse(args);
if (parse_result != JNI_OK) return parse_result;
if (PauseAtStartup) {
os::pause();
}
HS_DTRACE_PROBE(hotspot, vm__init__begin);
// Record VM creation timing statistics
TraceVmCreationTime create_vm_timer;
create_vm_timer.start();
// Timing (must come after argument parsing)
TraceTime timer("Create VM", TraceStartupTime);
// Initialize the os module after parsing the args
jint os_init_2_result = os::init_2();
if (os_init_2_result != JNI_OK) return os_init_2_result;
// Initialize output stream logging
ostream_init_log();
// Convert -Xrun to -agentlib: if there is no JVM_OnLoad
// Must be before create_vm_init_agents()
if (Arguments::init_libraries_at_startup()) {
convert_vm_init_libraries_to_agents();
}
// Launch -agentlib/-agentpath and converted -Xrun agents
if (Arguments::init_agents_at_startup()) {
create_vm_init_agents();
}
// Initialize Threads state
_thread_list = NULL;
_number_of_threads = 0;
_number_of_non_daemon_threads = 0;
// Initialize TLS
ThreadLocalStorage::init();
// Initialize global data structures and create system classes in heap
vm_init_globals();
// Attach the main thread to this os thread
JavaThread* main_thread = new JavaThread();
main_thread->set_thread_state(_thread_in_vm);
// must do this before set_active_handles and initialize_thread_local_storage
// Note: on solaris initialize_thread_local_storage() will (indirectly)
// change the stack size recorded here to one based on the java thread
// stacksize. This adjusted size is what is used to figure the placement
// of the guard pages.
main_thread->record_stack_base_and_size();
main_thread->initialize_thread_local_storage();
main_thread->set_active_handles(JNIHandleBlock::allocate_block());
if (!main_thread->set_as_starting_thread()) {
vm_shutdown_during_initialization(
"Failed necessary internal allocation. Out of swap space");
delete main_thread;
*canTryAgain = false; // don't let caller call JNI_CreateJavaVM again
return JNI_ENOMEM;
}
// Enable guard page *after* os::create_main_thread(), otherwise it would
// crash Linux VM, see notes in os_linux.cpp.
main_thread->create_stack_guard_pages();
// Initialize Java-Leve synchronization subsystem
ObjectSynchronizer::Initialize() ;
// Initialize global modules
jint status = init_globals();
if (status != JNI_OK) {
delete main_thread;
*canTryAgain = false; // don't let caller call JNI_CreateJavaVM again
return status;
}
HandleMark hm;
{ MutexLocker mu(Threads_lock);
Threads::add(main_thread);
}
// Any JVMTI raw monitors entered in onload will transition into
// real raw monitor. VM is setup enough here for raw monitor enter.
JvmtiExport::transition_pending_onload_raw_monitors();
if (VerifyBeforeGC &&
Universe::heap()->total_collections() >= VerifyGCStartAt) {
Universe::heap()->prepare_for_verify();
Universe::verify(); // make sure we're starting with a clean slate
}
// Create the VMThread
{ TraceTime timer("Start VMThread", TraceStartupTime);
VMThread::create();
Thread* vmthread = VMThread::vm_thread();
if (!os::create_thread(vmthread, os::vm_thread))
vm_exit_during_initialization("Cannot create VM thread. Out of system resources.");
// Wait for the VM thread to become ready, and VMThread::run to initialize
// Monitors can have spurious returns, must always check another state flag
{
MutexLocker ml(Notify_lock);
os::start_thread(vmthread);
while (vmthread->active_handles() == NULL) {
Notify_lock->wait();
}
}
}
assert (Universe::is_fully_initialized(), "not initialized");
EXCEPTION_MARK;
// At this point, the Universe is initialized, but we have not executed
// any byte code. Now is a good time (the only time) to dump out the
// internal state of the JVM for sharing.
if (DumpSharedSpaces) {
Universe::heap()->preload_and_dump(CHECK_0);
ShouldNotReachHere();
}
// Always call even when there are not JVMTI environments yet, since environments
// may be attached late and JVMTI must track phases of VM execution
JvmtiExport::enter_start_phase();
// Notify JVMTI agents that VM has started (JNI is up) - nop if no agents.
JvmtiExport::post_vm_start();
{
TraceTime timer("Initialize java.lang classes", TraceStartupTime);
if (EagerXrunInit && Arguments::init_libraries_at_startup()) {
create_vm_init_libraries();
}
if (InitializeJavaLangString) {
initialize_class(vmSymbolHandles::java_lang_String(), CHECK_0);
} else {
warning("java.lang.String not initialized");
}
if (AggressiveOpts) {
{
// Forcibly initialize java/util/HashMap and mutate the private
// static final "frontCacheEnabled" field before we start creating instances
#ifdef ASSERT
klassOop tmp_k = SystemDictionary::find(vmSymbolHandles::java_util_HashMap(), Handle(), Handle(), CHECK_0);
assert(tmp_k == NULL, "java/util/HashMap should not be loaded yet");
#endif
klassOop k_o = SystemDictionary::resolve_or_null(vmSymbolHandles::java_util_HashMap(), Handle(), Handle(), CHECK_0);
KlassHandle k = KlassHandle(THREAD, k_o);
guarantee(k.not_null(), "Must find java/util/HashMap");
instanceKlassHandle ik = instanceKlassHandle(THREAD, k());
ik->initialize(CHECK_0);
fieldDescriptor fd;
// Possible we might not find this field; if so, don't break
if (ik->find_local_field(vmSymbols::frontCacheEnabled_name(), vmSymbols::bool_signature(), &fd)) {
k()->bool_field_put(fd.offset(), true);
}
}
if (UseStringCache) {
// Forcibly initialize java/lang/StringValue and mutate the private
// static final "stringCacheEnabled" field before we start creating instances
klassOop k_o = SystemDictionary::resolve_or_null(vmSymbolHandles::java_lang_StringValue(), Handle(), Handle(), CHECK_0);
// Possible that StringValue isn't present: if so, silently don't break
if (k_o != NULL) {
KlassHandle k = KlassHandle(THREAD, k_o);
instanceKlassHandle ik = instanceKlassHandle(THREAD, k());
ik->initialize(CHECK_0);
fieldDescriptor fd;
// Possible we might not find this field: if so, silently don't break
if (ik->find_local_field(vmSymbols::stringCacheEnabled_name(), vmSymbols::bool_signature(), &fd)) {
k()->bool_field_put(fd.offset(), true);
}
}
}
}
// Initialize java_lang.System (needed before creating the thread)
if (InitializeJavaLangSystem) {
initialize_class(vmSymbolHandles::java_lang_System(), CHECK_0);
initialize_class(vmSymbolHandles::java_lang_ThreadGroup(), CHECK_0);
Handle thread_group = create_initial_thread_group(CHECK_0);
Universe::set_main_thread_group(thread_group());
initialize_class(vmSymbolHandles::java_lang_Thread(), CHECK_0);
oop thread_object = create_initial_thread(thread_group, main_thread, CHECK_0);
main_thread->set_threadObj(thread_object);
// Set thread status to running since main thread has
// been started and running.
java_lang_Thread::set_thread_status(thread_object,
java_lang_Thread::RUNNABLE);
// The VM preresolve methods to these classes. Make sure that get initialized
initialize_class(vmSymbolHandles::java_lang_reflect_Method(), CHECK_0);
initialize_class(vmSymbolHandles::java_lang_ref_Finalizer(), CHECK_0);
// The VM creates & returns objects of this class. Make sure it's initialized.
initialize_class(vmSymbolHandles::java_lang_Class(), CHECK_0);
call_initializeSystemClass(CHECK_0);
} else {
warning("java.lang.System not initialized");
}
// an instance of OutOfMemory exception has been allocated earlier
if (InitializeJavaLangExceptionsErrors) {
initialize_class(vmSymbolHandles::java_lang_OutOfMemoryError(), CHECK_0);
initialize_class(vmSymbolHandles::java_lang_NullPointerException(), CHECK_0);
initialize_class(vmSymbolHandles::java_lang_ClassCastException(), CHECK_0);
initialize_class(vmSymbolHandles::java_lang_ArrayStoreException(), CHECK_0);
initialize_class(vmSymbolHandles::java_lang_ArithmeticException(), CHECK_0);
initialize_class(vmSymbolHandles::java_lang_StackOverflowError(), CHECK_0);
initialize_class(vmSymbolHandles::java_lang_IllegalMonitorStateException(), CHECK_0);
} else {
warning("java.lang.OutOfMemoryError has not been initialized");
warning("java.lang.NullPointerException has not been initialized");
warning("java.lang.ClassCastException has not been initialized");
warning("java.lang.ArrayStoreException has not been initialized");
warning("java.lang.ArithmeticException has not been initialized");
warning("java.lang.StackOverflowError has not been initialized");
}
if (EnableInvokeDynamic) {
// JSR 292: An intialized java.dyn.InvokeDynamic is required in
// the compiler.
initialize_class(vmSymbolHandles::java_dyn_InvokeDynamic(), CHECK_0);
}
}
// See : bugid 4211085.
// Background : the static initializer of java.lang.Compiler tries to read
// property"java.compiler" and read & write property "java.vm.info".
// When a security manager is installed through the command line
// option "-Djava.security.manager", the above properties are not
// readable and the static initializer for java.lang.Compiler fails
// resulting in a NoClassDefFoundError. This can happen in any
// user code which calls methods in java.lang.Compiler.
// Hack : the hack is to pre-load and initialize this class, so that only
// system domains are on the stack when the properties are read.
// Currently even the AWT code has calls to methods in java.lang.Compiler.
// On the classic VM, java.lang.Compiler is loaded very early to load the JIT.
// Future Fix : the best fix is to grant everyone permissions to read "java.compiler" and
// read and write"java.vm.info" in the default policy file. See bugid 4211383
// Once that is done, we should remove this hack.
initialize_class(vmSymbolHandles::java_lang_Compiler(), CHECK_0);
// More hackery - the static initializer of java.lang.Compiler adds the string "nojit" to
// the java.vm.info property if no jit gets loaded through java.lang.Compiler (the hotspot
// compiler does not get loaded through java.lang.Compiler). "java -version" with the
// hotspot vm says "nojit" all the time which is confusing. So, we reset it here.
// This should also be taken out as soon as 4211383 gets fixed.
reset_vm_info_property(CHECK_0);
quicken_jni_functions();
// Set flag that basic initialization has completed. Used by exceptions and various
// debug stuff, that does not work until all basic classes have been initialized.
set_init_completed();
HS_DTRACE_PROBE(hotspot, vm__init__end);
// record VM initialization completion time
Management::record_vm_init_completed();
// Compute system loader. Note that this has to occur after set_init_completed, since
// valid exceptions may be thrown in the process.
// Note that we do not use CHECK_0 here since we are inside an EXCEPTION_MARK and
// set_init_completed has just been called, causing exceptions not to be shortcut
// anymore. We call vm_exit_during_initialization directly instead.
SystemDictionary::compute_java_system_loader(THREAD);
if (HAS_PENDING_EXCEPTION) {
vm_exit_during_initialization(Handle(THREAD, PENDING_EXCEPTION));
}
#ifdef KERNEL
if (JDK_Version::is_gte_jdk17x_version()) {
set_jkernel_boot_classloader_hook(THREAD);
}
#endif // KERNEL
#ifndef SERIALGC
// Support for ConcurrentMarkSweep. This should be cleaned up
// and better encapsulated. The ugly nested if test would go away
// once things are properly refactored. XXX YSR
if (UseConcMarkSweepGC || UseG1GC) {
if (UseConcMarkSweepGC) {
ConcurrentMarkSweepThread::makeSurrogateLockerThread(THREAD);
} else {
ConcurrentMarkThread::makeSurrogateLockerThread(THREAD);
}
if (HAS_PENDING_EXCEPTION) {
vm_exit_during_initialization(Handle(THREAD, PENDING_EXCEPTION));
}
}
#endif // SERIALGC
// Always call even when there are not JVMTI environments yet, since environments
// may be attached late and JVMTI must track phases of VM execution
JvmtiExport::enter_live_phase();
// Signal Dispatcher needs to be started before VMInit event is posted
os::signal_init();
// Start Attach Listener if +StartAttachListener or it can't be started lazily
if (!DisableAttachMechanism) {
if (StartAttachListener || AttachListener::init_at_startup()) {
AttachListener::init();
}
}
// Launch -Xrun agents
// Must be done in the JVMTI live phase so that for backward compatibility the JDWP
// back-end can launch with -Xdebug -Xrunjdwp.
if (!EagerXrunInit && Arguments::init_libraries_at_startup()) {
create_vm_init_libraries();
}
// Notify JVMTI agents that VM initialization is complete - nop if no agents.
JvmtiExport::post_vm_initialized();
Chunk::start_chunk_pool_cleaner_task();
// initialize compiler(s)
CompileBroker::compilation_init();
Management::initialize(THREAD);
if (HAS_PENDING_EXCEPTION) {
// management agent fails to start possibly due to
// configuration problem and is responsible for printing
// stack trace if appropriate. Simply exit VM.
vm_exit(1);
}
if (Arguments::has_profile()) FlatProfiler::engage(main_thread, true);
if (Arguments::has_alloc_profile()) AllocationProfiler::engage();
if (MemProfiling) MemProfiler::engage();
StatSampler::engage();
if (CheckJNICalls) JniPeriodicChecker::engage();
BiasedLocking::init();
// Start up the WatcherThread if there are any periodic tasks
// NOTE: All PeriodicTasks should be registered by now. If they
// aren't, late joiners might appear to start slowly (we might
// take a while to process their first tick).
if (PeriodicTask::num_tasks() > 0) {
WatcherThread::start();
}
create_vm_timer.end();
return JNI_OK;
}
// type for the Agent_OnLoad and JVM_OnLoad entry points
extern "C" {
typedef jint (JNICALL *OnLoadEntry_t)(JavaVM *, char *, void *);
}
// Find a command line agent library and return its entry point for
// -agentlib: -agentpath: -Xrun
// num_symbol_entries must be passed-in since only the caller knows the number of symbols in the array.
static OnLoadEntry_t lookup_on_load(AgentLibrary* agent, const char *on_load_symbols[], size_t num_symbol_entries) {
OnLoadEntry_t on_load_entry = NULL;
void *library = agent->os_lib(); // check if we have looked it up before
if (library == NULL) {
char buffer[JVM_MAXPATHLEN];
char ebuf[1024];
const char *name = agent->name();
if (agent->is_absolute_path()) {
library = hpi::dll_load(name, ebuf, sizeof ebuf);
if (library == NULL) {
// If we can't find the agent, exit.
vm_exit_during_initialization("Could not find agent library in absolute path", name);
}
} else {
// Try to load the agent from the standard dll directory
hpi::dll_build_name(buffer, sizeof(buffer), Arguments::get_dll_dir(), name);
library = hpi::dll_load(buffer, ebuf, sizeof ebuf);
#ifdef KERNEL
// Download instrument dll
if (library == NULL && strcmp(name, "instrument") == 0) {
char *props = Arguments::get_kernel_properties();
char *home = Arguments::get_java_home();
const char *fmt = "%s/bin/java %s -Dkernel.background.download=false"
" sun.jkernel.DownloadManager -download client_jvm";
int length = strlen(props) + strlen(home) + strlen(fmt) + 1;
char *cmd = AllocateHeap(length);
jio_snprintf(cmd, length, fmt, home, props);
int status = os::fork_and_exec(cmd);
FreeHeap(props);
FreeHeap(cmd);
if (status == -1) {
warning(cmd);
vm_exit_during_initialization("fork_and_exec failed: %s",
strerror(errno));
}
// when this comes back the instrument.dll should be where it belongs.
library = hpi::dll_load(buffer, ebuf, sizeof ebuf);
}
#endif // KERNEL
if (library == NULL) { // Try the local directory
char ns[1] = {0};
hpi::dll_build_name(buffer, sizeof(buffer), ns, name);
library = hpi::dll_load(buffer, ebuf, sizeof ebuf);
if (library == NULL) {
// If we can't find the agent, exit.
vm_exit_during_initialization("Could not find agent library on the library path or in the local directory", name);
}
}
}
agent->set_os_lib(library);
}
// Find the OnLoad function.
for (size_t symbol_index = 0; symbol_index < num_symbol_entries; symbol_index++) {
on_load_entry = CAST_TO_FN_PTR(OnLoadEntry_t, hpi::dll_lookup(library, on_load_symbols[symbol_index]));
if (on_load_entry != NULL) break;
}
return on_load_entry;
}
// Find the JVM_OnLoad entry point
static OnLoadEntry_t lookup_jvm_on_load(AgentLibrary* agent) {
const char *on_load_symbols[] = JVM_ONLOAD_SYMBOLS;
return lookup_on_load(agent, on_load_symbols, sizeof(on_load_symbols) / sizeof(char*));
}
// Find the Agent_OnLoad entry point
static OnLoadEntry_t lookup_agent_on_load(AgentLibrary* agent) {
const char *on_load_symbols[] = AGENT_ONLOAD_SYMBOLS;
return lookup_on_load(agent, on_load_symbols, sizeof(on_load_symbols) / sizeof(char*));
}
// For backwards compatibility with -Xrun
// Convert libraries with no JVM_OnLoad, but which have Agent_OnLoad to be
// treated like -agentpath:
// Must be called before agent libraries are created
void Threads::convert_vm_init_libraries_to_agents() {
AgentLibrary* agent;
AgentLibrary* next;
for (agent = Arguments::libraries(); agent != NULL; agent = next) {
next = agent->next(); // cache the next agent now as this agent may get moved off this list
OnLoadEntry_t on_load_entry = lookup_jvm_on_load(agent);
// If there is an JVM_OnLoad function it will get called later,
// otherwise see if there is an Agent_OnLoad
if (on_load_entry == NULL) {
on_load_entry = lookup_agent_on_load(agent);
if (on_load_entry != NULL) {
// switch it to the agent list -- so that Agent_OnLoad will be called,
// JVM_OnLoad won't be attempted and Agent_OnUnload will
Arguments::convert_library_to_agent(agent);
} else {
vm_exit_during_initialization("Could not find JVM_OnLoad or Agent_OnLoad function in the library", agent->name());
}
}
}
}
// Create agents for -agentlib: -agentpath: and converted -Xrun
// Invokes Agent_OnLoad
// Called very early -- before JavaThreads exist
void Threads::create_vm_init_agents() {
extern struct JavaVM_ main_vm;
AgentLibrary* agent;
JvmtiExport::enter_onload_phase();
for (agent = Arguments::agents(); agent != NULL; agent = agent->next()) {
OnLoadEntry_t on_load_entry = lookup_agent_on_load(agent);
if (on_load_entry != NULL) {
// Invoke the Agent_OnLoad function
jint err = (*on_load_entry)(&main_vm, agent->options(), NULL);
if (err != JNI_OK) {
vm_exit_during_initialization("agent library failed to init", agent->name());
}
} else {
vm_exit_during_initialization("Could not find Agent_OnLoad function in the agent library", agent->name());
}
}
JvmtiExport::enter_primordial_phase();
}
extern "C" {
typedef void (JNICALL *Agent_OnUnload_t)(JavaVM *);
}
void Threads::shutdown_vm_agents() {
// Send any Agent_OnUnload notifications
const char *on_unload_symbols[] = AGENT_ONUNLOAD_SYMBOLS;
extern struct JavaVM_ main_vm;
for (AgentLibrary* agent = Arguments::agents(); agent != NULL; agent = agent->next()) {
// Find the Agent_OnUnload function.
for (uint symbol_index = 0; symbol_index < ARRAY_SIZE(on_unload_symbols); symbol_index++) {
Agent_OnUnload_t unload_entry = CAST_TO_FN_PTR(Agent_OnUnload_t,
hpi::dll_lookup(agent->os_lib(), on_unload_symbols[symbol_index]));
// Invoke the Agent_OnUnload function
if (unload_entry != NULL) {
JavaThread* thread = JavaThread::current();
ThreadToNativeFromVM ttn(thread);
HandleMark hm(thread);
(*unload_entry)(&main_vm);
break;
}
}
}
}
// Called for after the VM is initialized for -Xrun libraries which have not been converted to agent libraries
// Invokes JVM_OnLoad
void Threads::create_vm_init_libraries() {
extern struct JavaVM_ main_vm;
AgentLibrary* agent;
for (agent = Arguments::libraries(); agent != NULL; agent = agent->next()) {
OnLoadEntry_t on_load_entry = lookup_jvm_on_load(agent);
if (on_load_entry != NULL) {
// Invoke the JVM_OnLoad function
JavaThread* thread = JavaThread::current();
ThreadToNativeFromVM ttn(thread);
HandleMark hm(thread);
jint err = (*on_load_entry)(&main_vm, agent->options(), NULL);
if (err != JNI_OK) {
vm_exit_during_initialization("-Xrun library failed to init", agent->name());
}
} else {
vm_exit_during_initialization("Could not find JVM_OnLoad function in -Xrun library", agent->name());
}
}
}
// Last thread running calls java.lang.Shutdown.shutdown()
void JavaThread::invoke_shutdown_hooks() {
HandleMark hm(this);
// We could get here with a pending exception, if so clear it now.
if (this->has_pending_exception()) {
this->clear_pending_exception();
}
EXCEPTION_MARK;
klassOop k =
SystemDictionary::resolve_or_null(vmSymbolHandles::java_lang_Shutdown(),
THREAD);
if (k != NULL) {
// SystemDictionary::resolve_or_null will return null if there was
// an exception. If we cannot load the Shutdown class, just don't
// call Shutdown.shutdown() at all. This will mean the shutdown hooks
// and finalizers (if runFinalizersOnExit is set) won't be run.
// Note that if a shutdown hook was registered or runFinalizersOnExit
// was called, the Shutdown class would have already been loaded
// (Runtime.addShutdownHook and runFinalizersOnExit will load it).
instanceKlassHandle shutdown_klass (THREAD, k);
JavaValue result(T_VOID);
JavaCalls::call_static(&result,
shutdown_klass,
vmSymbolHandles::shutdown_method_name(),
vmSymbolHandles::void_method_signature(),
THREAD);
}
CLEAR_PENDING_EXCEPTION;
}
// Threads::destroy_vm() is normally called from jni_DestroyJavaVM() when
// the program falls off the end of main(). Another VM exit path is through
// vm_exit() when the program calls System.exit() to return a value or when
// there is a serious error in VM. The two shutdown paths are not exactly
// the same, but they share Shutdown.shutdown() at Java level and before_exit()
// and VM_Exit op at VM level.
//
// Shutdown sequence:
// + Wait until we are the last non-daemon thread to execute
// <-- every thing is still working at this moment -->
// + Call java.lang.Shutdown.shutdown(), which will invoke Java level
// shutdown hooks, run finalizers if finalization-on-exit
// + Call before_exit(), prepare for VM exit
// > run VM level shutdown hooks (they are registered through JVM_OnExit(),
// currently the only user of this mechanism is File.deleteOnExit())
// > stop flat profiler, StatSampler, watcher thread, CMS threads,
// post thread end and vm death events to JVMTI,
// stop signal thread
// + Call JavaThread::exit(), it will:
// > release JNI handle blocks, remove stack guard pages
// > remove this thread from Threads list
// <-- no more Java code from this thread after this point -->
// + Stop VM thread, it will bring the remaining VM to a safepoint and stop
// the compiler threads at safepoint
// <-- do not use anything that could get blocked by Safepoint -->
// + Disable tracing at JNI/JVM barriers
// + Set _vm_exited flag for threads that are still running native code
// + Delete this thread
// + Call exit_globals()
// > deletes tty
// > deletes PerfMemory resources
// + Return to caller
bool Threads::destroy_vm() {
JavaThread* thread = JavaThread::current();
// Wait until we are the last non-daemon thread to execute
{ MutexLocker nu(Threads_lock);
while (Threads::number_of_non_daemon_threads() > 1 )
// This wait should make safepoint checks, wait without a timeout,
// and wait as a suspend-equivalent condition.
//
// Note: If the FlatProfiler is running and this thread is waiting
// for another non-daemon thread to finish, then the FlatProfiler
// is waiting for the external suspend request on this thread to
// complete. wait_for_ext_suspend_completion() will eventually
// timeout, but that takes time. Making this wait a suspend-
// equivalent condition solves that timeout problem.
//
Threads_lock->wait(!Mutex::_no_safepoint_check_flag, 0,
Mutex::_as_suspend_equivalent_flag);
}
// Hang forever on exit if we are reporting an error.
if (ShowMessageBoxOnError && is_error_reported()) {
os::infinite_sleep();
}
if (JDK_Version::is_jdk12x_version()) {
// We are the last thread running, so check if finalizers should be run.
// For 1.3 or later this is done in thread->invoke_shutdown_hooks()
HandleMark rm(thread);
Universe::run_finalizers_on_exit();
} else {
// run Java level shutdown hooks
thread->invoke_shutdown_hooks();
}
before_exit(thread);
thread->exit(true);
// Stop VM thread.
{
// 4945125 The vm thread comes to a safepoint during exit.
// GC vm_operations can get caught at the safepoint, and the
// heap is unparseable if they are caught. Grab the Heap_lock
// to prevent this. The GC vm_operations will not be able to
// queue until after the vm thread is dead.
MutexLocker ml(Heap_lock);
VMThread::wait_for_vm_thread_exit();
assert(SafepointSynchronize::is_at_safepoint(), "VM thread should exit at Safepoint");
VMThread::destroy();
}
// clean up ideal graph printers
#if defined(COMPILER2) && !defined(PRODUCT)
IdealGraphPrinter::clean_up();
#endif
// Now, all Java threads are gone except daemon threads. Daemon threads
// running Java code or in VM are stopped by the Safepoint. However,
// daemon threads executing native code are still running. But they
// will be stopped at native=>Java/VM barriers. Note that we can't
// simply kill or suspend them, as it is inherently deadlock-prone.
#ifndef PRODUCT
// disable function tracing at JNI/JVM barriers
TraceHPI = false;
TraceJNICalls = false;
TraceJVMCalls = false;
TraceRuntimeCalls = false;
#endif
VM_Exit::set_vm_exited();
notify_vm_shutdown();
delete thread;
// exit_globals() will delete tty
exit_globals();
return true;
}
jboolean Threads::is_supported_jni_version_including_1_1(jint version) {
if (version == JNI_VERSION_1_1) return JNI_TRUE;
return is_supported_jni_version(version);
}
jboolean Threads::is_supported_jni_version(jint version) {
if (version == JNI_VERSION_1_2) return JNI_TRUE;
if (version == JNI_VERSION_1_4) return JNI_TRUE;
if (version == JNI_VERSION_1_6) return JNI_TRUE;
return JNI_FALSE;
}
void Threads::add(JavaThread* p, bool force_daemon) {
// The threads lock must be owned at this point
assert_locked_or_safepoint(Threads_lock);
p->set_next(_thread_list);
_thread_list = p;
_number_of_threads++;
oop threadObj = p->threadObj();
bool daemon = true;
// Bootstrapping problem: threadObj can be null for initial
// JavaThread (or for threads attached via JNI)
if ((!force_daemon) && (threadObj == NULL || !java_lang_Thread::is_daemon(threadObj))) {
_number_of_non_daemon_threads++;
daemon = false;
}
ThreadService::add_thread(p, daemon);
// Possible GC point.
Events::log("Thread added: " INTPTR_FORMAT, p);
}
void Threads::remove(JavaThread* p) {
// Extra scope needed for Thread_lock, so we can check
// that we do not remove thread without safepoint code notice
{ MutexLocker ml(Threads_lock);
assert(includes(p), "p must be present");
JavaThread* current = _thread_list;
JavaThread* prev = NULL;
while (current != p) {
prev = current;
current = current->next();
}
if (prev) {
prev->set_next(current->next());
} else {
_thread_list = p->next();
}
_number_of_threads--;
oop threadObj = p->threadObj();
bool daemon = true;
if (threadObj == NULL || !java_lang_Thread::is_daemon(threadObj)) {
_number_of_non_daemon_threads--;
daemon = false;
// Only one thread left, do a notify on the Threads_lock so a thread waiting
// on destroy_vm will wake up.
if (number_of_non_daemon_threads() == 1)
Threads_lock->notify_all();
}
ThreadService::remove_thread(p, daemon);
// Make sure that safepoint code disregard this thread. This is needed since
// the thread might mess around with locks after this point. This can cause it
// to do callbacks into the safepoint code. However, the safepoint code is not aware
// of this thread since it is removed from the queue.
p->set_terminated_value();
} // unlock Threads_lock
// Since Events::log uses a lock, we grab it outside the Threads_lock
Events::log("Thread exited: " INTPTR_FORMAT, p);
}
// Threads_lock must be held when this is called (or must be called during a safepoint)
bool Threads::includes(JavaThread* p) {
assert(Threads_lock->is_locked(), "sanity check");
ALL_JAVA_THREADS(q) {
if (q == p ) {
return true;
}
}
return false;
}
// Operations on the Threads list for GC. These are not explicitly locked,
// but the garbage collector must provide a safe context for them to run.
// In particular, these things should never be called when the Threads_lock
// is held by some other thread. (Note: the Safepoint abstraction also
// uses the Threads_lock to gurantee this property. It also makes sure that
// all threads gets blocked when exiting or starting).
void Threads::oops_do(OopClosure* f, CodeBlobClosure* cf) {
ALL_JAVA_THREADS(p) {
p->oops_do(f, cf);
}
VMThread::vm_thread()->oops_do(f, cf);
}
void Threads::possibly_parallel_oops_do(OopClosure* f, CodeBlobClosure* cf) {
// Introduce a mechanism allowing parallel threads to claim threads as
// root groups. Overhead should be small enough to use all the time,
// even in sequential code.
SharedHeap* sh = SharedHeap::heap();
bool is_par = (sh->n_par_threads() > 0);
int cp = SharedHeap::heap()->strong_roots_parity();
ALL_JAVA_THREADS(p) {
if (p->claim_oops_do(is_par, cp)) {
p->oops_do(f, cf);
}
}
VMThread* vmt = VMThread::vm_thread();
if (vmt->claim_oops_do(is_par, cp))
vmt->oops_do(f, cf);
}
#ifndef SERIALGC
// Used by ParallelScavenge
void Threads::create_thread_roots_tasks(GCTaskQueue* q) {
ALL_JAVA_THREADS(p) {
q->enqueue(new ThreadRootsTask(p));
}
q->enqueue(new ThreadRootsTask(VMThread::vm_thread()));
}
// Used by Parallel Old
void Threads::create_thread_roots_marking_tasks(GCTaskQueue* q) {
ALL_JAVA_THREADS(p) {
q->enqueue(new ThreadRootsMarkingTask(p));
}
q->enqueue(new ThreadRootsMarkingTask(VMThread::vm_thread()));
}
#endif // SERIALGC
void Threads::nmethods_do(CodeBlobClosure* cf) {
ALL_JAVA_THREADS(p) {
p->nmethods_do(cf);
}
VMThread::vm_thread()->nmethods_do(cf);
}
void Threads::gc_epilogue() {
ALL_JAVA_THREADS(p) {
p->gc_epilogue();
}
}
void Threads::gc_prologue() {
ALL_JAVA_THREADS(p) {
p->gc_prologue();
}
}
void Threads::deoptimized_wrt_marked_nmethods() {
ALL_JAVA_THREADS(p) {
p->deoptimized_wrt_marked_nmethods();
}
}
// Get count Java threads that are waiting to enter the specified monitor.
GrowableArray<JavaThread*>* Threads::get_pending_threads(int count,
address monitor, bool doLock) {
assert(doLock || SafepointSynchronize::is_at_safepoint(),
"must grab Threads_lock or be at safepoint");
GrowableArray<JavaThread*>* result = new GrowableArray<JavaThread*>(count);
int i = 0;
{
MutexLockerEx ml(doLock ? Threads_lock : NULL);
ALL_JAVA_THREADS(p) {
if (p->is_Compiler_thread()) continue;
address pending = (address)p->current_pending_monitor();
if (pending == monitor) { // found a match
if (i < count) result->append(p); // save the first count matches
i++;
}
}
}
return result;
}
JavaThread *Threads::owning_thread_from_monitor_owner(address owner, bool doLock) {
assert(doLock ||
Threads_lock->owned_by_self() ||
SafepointSynchronize::is_at_safepoint(),
"must grab Threads_lock or be at safepoint");
// NULL owner means not locked so we can skip the search
if (owner == NULL) return NULL;
{
MutexLockerEx ml(doLock ? Threads_lock : NULL);
ALL_JAVA_THREADS(p) {
// first, see if owner is the address of a Java thread
if (owner == (address)p) return p;
}
}
assert(UseHeavyMonitors == false, "Did not find owning Java thread with UseHeavyMonitors enabled");
if (UseHeavyMonitors) return NULL;
//
// If we didn't find a matching Java thread and we didn't force use of
// heavyweight monitors, then the owner is the stack address of the
// Lock Word in the owning Java thread's stack.
//
JavaThread* the_owner = NULL;
{
MutexLockerEx ml(doLock ? Threads_lock : NULL);
ALL_JAVA_THREADS(q) {
if (q->is_lock_owned(owner)) {
the_owner = q;
break;
}
}
}
assert(the_owner != NULL, "Did not find owning Java thread for lock word address");
return the_owner;
}
// Threads::print_on() is called at safepoint by VM_PrintThreads operation.
void Threads::print_on(outputStream* st, bool print_stacks, bool internal_format, bool print_concurrent_locks) {
char buf[32];
st->print_cr(os::local_time_string(buf, sizeof(buf)));
st->print_cr("Full thread dump %s (%s %s):",
Abstract_VM_Version::vm_name(),
Abstract_VM_Version::vm_release(),
Abstract_VM_Version::vm_info_string()
);
st->cr();
#ifndef SERIALGC
// Dump concurrent locks
ConcurrentLocksDump concurrent_locks;
if (print_concurrent_locks) {
concurrent_locks.dump_at_safepoint();
}
#endif // SERIALGC
ALL_JAVA_THREADS(p) {
ResourceMark rm;
p->print_on(st);
if (print_stacks) {
if (internal_format) {
p->trace_stack();
} else {
p->print_stack_on(st);
}
}
st->cr();
#ifndef SERIALGC
if (print_concurrent_locks) {
concurrent_locks.print_locks_on(p, st);
}
#endif // SERIALGC
}
VMThread::vm_thread()->print_on(st);
st->cr();
Universe::heap()->print_gc_threads_on(st);
WatcherThread* wt = WatcherThread::watcher_thread();
if (wt != NULL) wt->print_on(st);
st->cr();
CompileBroker::print_compiler_threads_on(st);
st->flush();
}
// Threads::print_on_error() is called by fatal error handler. It's possible
// that VM is not at safepoint and/or current thread is inside signal handler.
// Don't print stack trace, as the stack may not be walkable. Don't allocate
// memory (even in resource area), it might deadlock the error handler.
void Threads::print_on_error(outputStream* st, Thread* current, char* buf, int buflen) {
bool found_current = false;
st->print_cr("Java Threads: ( => current thread )");
ALL_JAVA_THREADS(thread) {
bool is_current = (current == thread);
found_current = found_current || is_current;
st->print("%s", is_current ? "=>" : " ");
st->print(PTR_FORMAT, thread);
st->print(" ");
thread->print_on_error(st, buf, buflen);
st->cr();
}
st->cr();
st->print_cr("Other Threads:");
if (VMThread::vm_thread()) {
bool is_current = (current == VMThread::vm_thread());
found_current = found_current || is_current;
st->print("%s", current == VMThread::vm_thread() ? "=>" : " ");
st->print(PTR_FORMAT, VMThread::vm_thread());
st->print(" ");
VMThread::vm_thread()->print_on_error(st, buf, buflen);
st->cr();
}
WatcherThread* wt = WatcherThread::watcher_thread();
if (wt != NULL) {
bool is_current = (current == wt);
found_current = found_current || is_current;
st->print("%s", is_current ? "=>" : " ");
st->print(PTR_FORMAT, wt);
st->print(" ");
wt->print_on_error(st, buf, buflen);
st->cr();
}
if (!found_current) {
st->cr();
st->print("=>" PTR_FORMAT " (exited) ", current);
current->print_on_error(st, buf, buflen);
st->cr();
}
}
// Lifecycle management for TSM ParkEvents.
// ParkEvents are type-stable (TSM).
// In our particular implementation they happen to be immortal.
//
// We manage concurrency on the FreeList with a CAS-based
// detach-modify-reattach idiom that avoids the ABA problems
// that would otherwise be present in a simple CAS-based
// push-pop implementation. (push-one and pop-all)
//
// Caveat: Allocate() and Release() may be called from threads
// other than the thread associated with the Event!
// If we need to call Allocate() when running as the thread in
// question then look for the PD calls to initialize native TLS.
// Native TLS (Win32/Linux/Solaris) can only be initialized or
// accessed by the associated thread.
// See also pd_initialize().
//
// Note that we could defer associating a ParkEvent with a thread
// until the 1st time the thread calls park(). unpark() calls to
// an unprovisioned thread would be ignored. The first park() call
// for a thread would allocate and associate a ParkEvent and return
// immediately.
volatile int ParkEvent::ListLock = 0 ;
ParkEvent * volatile ParkEvent::FreeList = NULL ;
ParkEvent * ParkEvent::Allocate (Thread * t) {
// In rare cases -- JVM_RawMonitor* operations -- we can find t == null.
ParkEvent * ev ;
// Start by trying to recycle an existing but unassociated
// ParkEvent from the global free list.
for (;;) {
ev = FreeList ;
if (ev == NULL) break ;
// 1: Detach - sequester or privatize the list
// Tantamount to ev = Swap (&FreeList, NULL)
if (Atomic::cmpxchg_ptr (NULL, &FreeList, ev) != ev) {
continue ;
}
// We've detached the list. The list in-hand is now
// local to this thread. This thread can operate on the
// list without risk of interference from other threads.
// 2: Extract -- pop the 1st element from the list.
ParkEvent * List = ev->FreeNext ;
if (List == NULL) break ;
for (;;) {
// 3: Try to reattach the residual list
guarantee (List != NULL, "invariant") ;
ParkEvent * Arv = (ParkEvent *) Atomic::cmpxchg_ptr (List, &FreeList, NULL) ;
if (Arv == NULL) break ;
// New nodes arrived. Try to detach the recent arrivals.
if (Atomic::cmpxchg_ptr (NULL, &FreeList, Arv) != Arv) {
continue ;
}
guarantee (Arv != NULL, "invariant") ;
// 4: Merge Arv into List
ParkEvent * Tail = List ;
while (Tail->FreeNext != NULL) Tail = Tail->FreeNext ;
Tail->FreeNext = Arv ;
}
break ;
}
if (ev != NULL) {
guarantee (ev->AssociatedWith == NULL, "invariant") ;
} else {
// Do this the hard way -- materialize a new ParkEvent.
// In rare cases an allocating thread might detach a long list --
// installing null into FreeList -- and then stall or be obstructed.
// A 2nd thread calling Allocate() would see FreeList == null.
// The list held privately by the 1st thread is unavailable to the 2nd thread.
// In that case the 2nd thread would have to materialize a new ParkEvent,
// even though free ParkEvents existed in the system. In this case we end up
// with more ParkEvents in circulation than we need, but the race is
// rare and the outcome is benign. Ideally, the # of extant ParkEvents
// is equal to the maximum # of threads that existed at any one time.
// Because of the race mentioned above, segments of the freelist
// can be transiently inaccessible. At worst we may end up with the
// # of ParkEvents in circulation slightly above the ideal.
// Note that if we didn't have the TSM/immortal constraint, then
// when reattaching, above, we could trim the list.
ev = new ParkEvent () ;
guarantee ((intptr_t(ev) & 0xFF) == 0, "invariant") ;
}
ev->reset() ; // courtesy to caller
ev->AssociatedWith = t ; // Associate ev with t
ev->FreeNext = NULL ;
return ev ;
}
void ParkEvent::Release (ParkEvent * ev) {
if (ev == NULL) return ;
guarantee (ev->FreeNext == NULL , "invariant") ;
ev->AssociatedWith = NULL ;
for (;;) {
// Push ev onto FreeList
// The mechanism is "half" lock-free.
ParkEvent * List = FreeList ;
ev->FreeNext = List ;
if (Atomic::cmpxchg_ptr (ev, &FreeList, List) == List) break ;
}
}
// Override operator new and delete so we can ensure that the
// least significant byte of ParkEvent addresses is 0.
// Beware that excessive address alignment is undesirable
// as it can result in D$ index usage imbalance as
// well as bank access imbalance on Niagara-like platforms,
// although Niagara's hash function should help.
void * ParkEvent::operator new (size_t sz) {
return (void *) ((intptr_t (CHeapObj::operator new (sz + 256)) + 256) & -256) ;
}
void ParkEvent::operator delete (void * a) {
// ParkEvents are type-stable and immortal ...
ShouldNotReachHere();
}
// 6399321 As a temporary measure we copied & modified the ParkEvent::
// allocate() and release() code for use by Parkers. The Parker:: forms
// will eventually be removed as we consolide and shift over to ParkEvents
// for both builtin synchronization and JSR166 operations.
volatile int Parker::ListLock = 0 ;
Parker * volatile Parker::FreeList = NULL ;
Parker * Parker::Allocate (JavaThread * t) {
guarantee (t != NULL, "invariant") ;
Parker * p ;
// Start by trying to recycle an existing but unassociated
// Parker from the global free list.
for (;;) {
p = FreeList ;
if (p == NULL) break ;
// 1: Detach
// Tantamount to p = Swap (&FreeList, NULL)
if (Atomic::cmpxchg_ptr (NULL, &FreeList, p) != p) {
continue ;
}
// We've detached the list. The list in-hand is now
// local to this thread. This thread can operate on the
// list without risk of interference from other threads.
// 2: Extract -- pop the 1st element from the list.
Parker * List = p->FreeNext ;
if (List == NULL) break ;
for (;;) {
// 3: Try to reattach the residual list
guarantee (List != NULL, "invariant") ;
Parker * Arv = (Parker *) Atomic::cmpxchg_ptr (List, &FreeList, NULL) ;
if (Arv == NULL) break ;
// New nodes arrived. Try to detach the recent arrivals.
if (Atomic::cmpxchg_ptr (NULL, &FreeList, Arv) != Arv) {
continue ;
}
guarantee (Arv != NULL, "invariant") ;
// 4: Merge Arv into List
Parker * Tail = List ;
while (Tail->FreeNext != NULL) Tail = Tail->FreeNext ;
Tail->FreeNext = Arv ;
}
break ;
}
if (p != NULL) {
guarantee (p->AssociatedWith == NULL, "invariant") ;
} else {
// Do this the hard way -- materialize a new Parker..
// In rare cases an allocating thread might detach
// a long list -- installing null into FreeList --and
// then stall. Another thread calling Allocate() would see
// FreeList == null and then invoke the ctor. In this case we
// end up with more Parkers in circulation than we need, but
// the race is rare and the outcome is benign.
// Ideally, the # of extant Parkers is equal to the
// maximum # of threads that existed at any one time.
// Because of the race mentioned above, segments of the
// freelist can be transiently inaccessible. At worst
// we may end up with the # of Parkers in circulation
// slightly above the ideal.
p = new Parker() ;
}
p->AssociatedWith = t ; // Associate p with t
p->FreeNext = NULL ;
return p ;
}
void Parker::Release (Parker * p) {
if (p == NULL) return ;
guarantee (p->AssociatedWith != NULL, "invariant") ;
guarantee (p->FreeNext == NULL , "invariant") ;
p->AssociatedWith = NULL ;
for (;;) {
// Push p onto FreeList
Parker * List = FreeList ;
p->FreeNext = List ;
if (Atomic::cmpxchg_ptr (p, &FreeList, List) == List) break ;
}
}
void Threads::verify() {
ALL_JAVA_THREADS(p) {
p->verify();
}
VMThread* thread = VMThread::vm_thread();
if (thread != NULL) thread->verify();
}