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