1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 1.2 +++ b/src/share/vm/runtime/thread.cpp Wed Apr 27 01:25:04 2016 +0800 1.3 @@ -0,0 +1,4686 @@ 1.4 +/* 1.5 + * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. 1.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 1.7 + * 1.8 + * This code is free software; you can redistribute it and/or modify it 1.9 + * under the terms of the GNU General Public License version 2 only, as 1.10 + * published by the Free Software Foundation. 1.11 + * 1.12 + * This code is distributed in the hope that it will be useful, but WITHOUT 1.13 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 1.14 + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 1.15 + * version 2 for more details (a copy is included in the LICENSE file that 1.16 + * accompanied this code). 1.17 + * 1.18 + * You should have received a copy of the GNU General Public License version 1.19 + * 2 along with this work; if not, write to the Free Software Foundation, 1.20 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 1.21 + * 1.22 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 1.23 + * or visit www.oracle.com if you need additional information or have any 1.24 + * questions. 1.25 + * 1.26 + */ 1.27 + 1.28 +#include "precompiled.hpp" 1.29 +#include "classfile/classLoader.hpp" 1.30 +#include "classfile/javaClasses.hpp" 1.31 +#include "classfile/systemDictionary.hpp" 1.32 +#include "classfile/vmSymbols.hpp" 1.33 +#include "code/scopeDesc.hpp" 1.34 +#include "compiler/compileBroker.hpp" 1.35 +#include "interpreter/interpreter.hpp" 1.36 +#include "interpreter/linkResolver.hpp" 1.37 +#include "interpreter/oopMapCache.hpp" 1.38 +#include "jvmtifiles/jvmtiEnv.hpp" 1.39 +#include "memory/gcLocker.inline.hpp" 1.40 +#include "memory/metaspaceShared.hpp" 1.41 +#include "memory/oopFactory.hpp" 1.42 +#include "memory/universe.inline.hpp" 1.43 +#include "oops/instanceKlass.hpp" 1.44 +#include "oops/objArrayOop.hpp" 1.45 +#include "oops/oop.inline.hpp" 1.46 +#include "oops/symbol.hpp" 1.47 +#include "prims/jvm_misc.hpp" 1.48 +#include "prims/jvmtiExport.hpp" 1.49 +#include "prims/jvmtiThreadState.hpp" 1.50 +#include "prims/privilegedStack.hpp" 1.51 +#include "runtime/arguments.hpp" 1.52 +#include "runtime/biasedLocking.hpp" 1.53 +#include "runtime/deoptimization.hpp" 1.54 +#include "runtime/fprofiler.hpp" 1.55 +#include "runtime/frame.inline.hpp" 1.56 +#include "runtime/init.hpp" 1.57 +#include "runtime/interfaceSupport.hpp" 1.58 +#include "runtime/java.hpp" 1.59 +#include "runtime/javaCalls.hpp" 1.60 +#include "runtime/jniPeriodicChecker.hpp" 1.61 +#include "runtime/memprofiler.hpp" 1.62 +#include "runtime/mutexLocker.hpp" 1.63 +#include "runtime/objectMonitor.hpp" 1.64 +#include "runtime/osThread.hpp" 1.65 +#include "runtime/safepoint.hpp" 1.66 +#include "runtime/sharedRuntime.hpp" 1.67 +#include "runtime/statSampler.hpp" 1.68 +#include "runtime/stubRoutines.hpp" 1.69 +#include "runtime/task.hpp" 1.70 +#include "runtime/thread.inline.hpp" 1.71 +#include "runtime/threadCritical.hpp" 1.72 +#include "runtime/threadLocalStorage.hpp" 1.73 +#include "runtime/vframe.hpp" 1.74 +#include "runtime/vframeArray.hpp" 1.75 +#include "runtime/vframe_hp.hpp" 1.76 +#include "runtime/vmThread.hpp" 1.77 +#include "runtime/vm_operations.hpp" 1.78 +#include "services/attachListener.hpp" 1.79 +#include "services/management.hpp" 1.80 +#include "services/memTracker.hpp" 1.81 +#include "services/threadService.hpp" 1.82 +#include "trace/tracing.hpp" 1.83 +#include "trace/traceMacros.hpp" 1.84 +#include "utilities/defaultStream.hpp" 1.85 +#include "utilities/dtrace.hpp" 1.86 +#include "utilities/events.hpp" 1.87 +#include "utilities/preserveException.hpp" 1.88 +#include "utilities/macros.hpp" 1.89 +#ifdef TARGET_OS_FAMILY_linux 1.90 +# include "os_linux.inline.hpp" 1.91 +#endif 1.92 +#ifdef TARGET_OS_FAMILY_solaris 1.93 +# include "os_solaris.inline.hpp" 1.94 +#endif 1.95 +#ifdef TARGET_OS_FAMILY_windows 1.96 +# include "os_windows.inline.hpp" 1.97 +#endif 1.98 +#ifdef TARGET_OS_FAMILY_bsd 1.99 +# include "os_bsd.inline.hpp" 1.100 +#endif 1.101 +#if INCLUDE_ALL_GCS 1.102 +#include "gc_implementation/concurrentMarkSweep/concurrentMarkSweepThread.hpp" 1.103 +#include "gc_implementation/g1/concurrentMarkThread.inline.hpp" 1.104 +#include "gc_implementation/parallelScavenge/pcTasks.hpp" 1.105 +#endif // INCLUDE_ALL_GCS 1.106 +#ifdef COMPILER1 1.107 +#include "c1/c1_Compiler.hpp" 1.108 +#endif 1.109 +#ifdef COMPILER2 1.110 +#include "opto/c2compiler.hpp" 1.111 +#include "opto/idealGraphPrinter.hpp" 1.112 +#endif 1.113 +#if INCLUDE_RTM_OPT 1.114 +#include "runtime/rtmLocking.hpp" 1.115 +#endif 1.116 + 1.117 +PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC 1.118 + 1.119 +#ifdef DTRACE_ENABLED 1.120 + 1.121 +// Only bother with this argument setup if dtrace is available 1.122 + 1.123 +#ifndef USDT2 1.124 +HS_DTRACE_PROBE_DECL(hotspot, vm__init__begin); 1.125 +HS_DTRACE_PROBE_DECL(hotspot, vm__init__end); 1.126 +HS_DTRACE_PROBE_DECL5(hotspot, thread__start, char*, intptr_t, 1.127 + intptr_t, intptr_t, bool); 1.128 +HS_DTRACE_PROBE_DECL5(hotspot, thread__stop, char*, intptr_t, 1.129 + intptr_t, intptr_t, bool); 1.130 + 1.131 +#define DTRACE_THREAD_PROBE(probe, javathread) \ 1.132 + { \ 1.133 + ResourceMark rm(this); \ 1.134 + int len = 0; \ 1.135 + const char* name = (javathread)->get_thread_name(); \ 1.136 + len = strlen(name); \ 1.137 + HS_DTRACE_PROBE5(hotspot, thread__##probe, \ 1.138 + name, len, \ 1.139 + java_lang_Thread::thread_id((javathread)->threadObj()), \ 1.140 + (javathread)->osthread()->thread_id(), \ 1.141 + java_lang_Thread::is_daemon((javathread)->threadObj())); \ 1.142 + } 1.143 + 1.144 +#else /* USDT2 */ 1.145 + 1.146 +#define HOTSPOT_THREAD_PROBE_start HOTSPOT_THREAD_PROBE_START 1.147 +#define HOTSPOT_THREAD_PROBE_stop HOTSPOT_THREAD_PROBE_STOP 1.148 + 1.149 +#define DTRACE_THREAD_PROBE(probe, javathread) \ 1.150 + { \ 1.151 + ResourceMark rm(this); \ 1.152 + int len = 0; \ 1.153 + const char* name = (javathread)->get_thread_name(); \ 1.154 + len = strlen(name); \ 1.155 + HOTSPOT_THREAD_PROBE_##probe( /* probe = start, stop */ \ 1.156 + (char *) name, len, \ 1.157 + java_lang_Thread::thread_id((javathread)->threadObj()), \ 1.158 + (uintptr_t) (javathread)->osthread()->thread_id(), \ 1.159 + java_lang_Thread::is_daemon((javathread)->threadObj())); \ 1.160 + } 1.161 + 1.162 +#endif /* USDT2 */ 1.163 + 1.164 +#else // ndef DTRACE_ENABLED 1.165 + 1.166 +#define DTRACE_THREAD_PROBE(probe, javathread) 1.167 + 1.168 +#endif // ndef DTRACE_ENABLED 1.169 + 1.170 + 1.171 +// Class hierarchy 1.172 +// - Thread 1.173 +// - VMThread 1.174 +// - WatcherThread 1.175 +// - ConcurrentMarkSweepThread 1.176 +// - JavaThread 1.177 +// - CompilerThread 1.178 + 1.179 +// ======= Thread ======== 1.180 +// Support for forcing alignment of thread objects for biased locking 1.181 +void* Thread::allocate(size_t size, bool throw_excpt, MEMFLAGS flags) { 1.182 + if (UseBiasedLocking) { 1.183 + const int alignment = markOopDesc::biased_lock_alignment; 1.184 + size_t aligned_size = size + (alignment - sizeof(intptr_t)); 1.185 + void* real_malloc_addr = throw_excpt? AllocateHeap(aligned_size, flags, CURRENT_PC) 1.186 + : AllocateHeap(aligned_size, flags, CURRENT_PC, 1.187 + AllocFailStrategy::RETURN_NULL); 1.188 + void* aligned_addr = (void*) align_size_up((intptr_t) real_malloc_addr, alignment); 1.189 + assert(((uintptr_t) aligned_addr + (uintptr_t) size) <= 1.190 + ((uintptr_t) real_malloc_addr + (uintptr_t) aligned_size), 1.191 + "JavaThread alignment code overflowed allocated storage"); 1.192 + if (TraceBiasedLocking) { 1.193 + if (aligned_addr != real_malloc_addr) 1.194 + tty->print_cr("Aligned thread " INTPTR_FORMAT " to " INTPTR_FORMAT, 1.195 + real_malloc_addr, aligned_addr); 1.196 + } 1.197 + ((Thread*) aligned_addr)->_real_malloc_address = real_malloc_addr; 1.198 + return aligned_addr; 1.199 + } else { 1.200 + return throw_excpt? AllocateHeap(size, flags, CURRENT_PC) 1.201 + : AllocateHeap(size, flags, CURRENT_PC, AllocFailStrategy::RETURN_NULL); 1.202 + } 1.203 +} 1.204 + 1.205 +void Thread::operator delete(void* p) { 1.206 + if (UseBiasedLocking) { 1.207 + void* real_malloc_addr = ((Thread*) p)->_real_malloc_address; 1.208 + FreeHeap(real_malloc_addr, mtThread); 1.209 + } else { 1.210 + FreeHeap(p, mtThread); 1.211 + } 1.212 +} 1.213 + 1.214 + 1.215 +// Base class for all threads: VMThread, WatcherThread, ConcurrentMarkSweepThread, 1.216 +// JavaThread 1.217 + 1.218 + 1.219 +Thread::Thread() { 1.220 + // stack and get_thread 1.221 + set_stack_base(NULL); 1.222 + set_stack_size(0); 1.223 + set_self_raw_id(0); 1.224 + set_lgrp_id(-1); 1.225 + 1.226 + // allocated data structures 1.227 + set_osthread(NULL); 1.228 + set_resource_area(new (mtThread)ResourceArea()); 1.229 + DEBUG_ONLY(_current_resource_mark = NULL;) 1.230 + set_handle_area(new (mtThread) HandleArea(NULL)); 1.231 + set_metadata_handles(new (ResourceObj::C_HEAP, mtClass) GrowableArray<Metadata*>(30, true)); 1.232 + set_active_handles(NULL); 1.233 + set_free_handle_block(NULL); 1.234 + set_last_handle_mark(NULL); 1.235 + 1.236 + // This initial value ==> never claimed. 1.237 + _oops_do_parity = 0; 1.238 + 1.239 + // the handle mark links itself to last_handle_mark 1.240 + new HandleMark(this); 1.241 + 1.242 + // plain initialization 1.243 + debug_only(_owned_locks = NULL;) 1.244 + debug_only(_allow_allocation_count = 0;) 1.245 + NOT_PRODUCT(_allow_safepoint_count = 0;) 1.246 + NOT_PRODUCT(_skip_gcalot = false;) 1.247 + _jvmti_env_iteration_count = 0; 1.248 + set_allocated_bytes(0); 1.249 + _vm_operation_started_count = 0; 1.250 + _vm_operation_completed_count = 0; 1.251 + _current_pending_monitor = NULL; 1.252 + _current_pending_monitor_is_from_java = true; 1.253 + _current_waiting_monitor = NULL; 1.254 + _num_nested_signal = 0; 1.255 + omFreeList = NULL ; 1.256 + omFreeCount = 0 ; 1.257 + omFreeProvision = 32 ; 1.258 + omInUseList = NULL ; 1.259 + omInUseCount = 0 ; 1.260 + 1.261 +#ifdef ASSERT 1.262 + _visited_for_critical_count = false; 1.263 +#endif 1.264 + 1.265 + _SR_lock = new Monitor(Mutex::suspend_resume, "SR_lock", true); 1.266 + _suspend_flags = 0; 1.267 + 1.268 + // thread-specific hashCode stream generator state - Marsaglia shift-xor form 1.269 + _hashStateX = os::random() ; 1.270 + _hashStateY = 842502087 ; 1.271 + _hashStateZ = 0x8767 ; // (int)(3579807591LL & 0xffff) ; 1.272 + _hashStateW = 273326509 ; 1.273 + 1.274 + _OnTrap = 0 ; 1.275 + _schedctl = NULL ; 1.276 + _Stalled = 0 ; 1.277 + _TypeTag = 0x2BAD ; 1.278 + 1.279 + // Many of the following fields are effectively final - immutable 1.280 + // Note that nascent threads can't use the Native Monitor-Mutex 1.281 + // construct until the _MutexEvent is initialized ... 1.282 + // CONSIDER: instead of using a fixed set of purpose-dedicated ParkEvents 1.283 + // we might instead use a stack of ParkEvents that we could provision on-demand. 1.284 + // The stack would act as a cache to avoid calls to ParkEvent::Allocate() 1.285 + // and ::Release() 1.286 + _ParkEvent = ParkEvent::Allocate (this) ; 1.287 + _SleepEvent = ParkEvent::Allocate (this) ; 1.288 + _MutexEvent = ParkEvent::Allocate (this) ; 1.289 + _MuxEvent = ParkEvent::Allocate (this) ; 1.290 + 1.291 +#ifdef CHECK_UNHANDLED_OOPS 1.292 + if (CheckUnhandledOops) { 1.293 + _unhandled_oops = new UnhandledOops(this); 1.294 + } 1.295 +#endif // CHECK_UNHANDLED_OOPS 1.296 +#ifdef ASSERT 1.297 + if (UseBiasedLocking) { 1.298 + assert((((uintptr_t) this) & (markOopDesc::biased_lock_alignment - 1)) == 0, "forced alignment of thread object failed"); 1.299 + assert(this == _real_malloc_address || 1.300 + this == (void*) align_size_up((intptr_t) _real_malloc_address, markOopDesc::biased_lock_alignment), 1.301 + "bug in forced alignment of thread objects"); 1.302 + } 1.303 +#endif /* ASSERT */ 1.304 +} 1.305 + 1.306 +void Thread::initialize_thread_local_storage() { 1.307 + // Note: Make sure this method only calls 1.308 + // non-blocking operations. Otherwise, it might not work 1.309 + // with the thread-startup/safepoint interaction. 1.310 + 1.311 + // During Java thread startup, safepoint code should allow this 1.312 + // method to complete because it may need to allocate memory to 1.313 + // store information for the new thread. 1.314 + 1.315 + // initialize structure dependent on thread local storage 1.316 + ThreadLocalStorage::set_thread(this); 1.317 +} 1.318 + 1.319 +void Thread::record_stack_base_and_size() { 1.320 + set_stack_base(os::current_stack_base()); 1.321 + set_stack_size(os::current_stack_size()); 1.322 + if (is_Java_thread()) { 1.323 + ((JavaThread*) this)->set_stack_overflow_limit(); 1.324 + } 1.325 + // CR 7190089: on Solaris, primordial thread's stack is adjusted 1.326 + // in initialize_thread(). Without the adjustment, stack size is 1.327 + // incorrect if stack is set to unlimited (ulimit -s unlimited). 1.328 + // So far, only Solaris has real implementation of initialize_thread(). 1.329 + // 1.330 + // set up any platform-specific state. 1.331 + os::initialize_thread(this); 1.332 + 1.333 +#if INCLUDE_NMT 1.334 + // record thread's native stack, stack grows downward 1.335 + address stack_low_addr = stack_base() - stack_size(); 1.336 + MemTracker::record_thread_stack(stack_low_addr, stack_size(), this, 1.337 + CURRENT_PC); 1.338 +#endif // INCLUDE_NMT 1.339 +} 1.340 + 1.341 + 1.342 +Thread::~Thread() { 1.343 + // Reclaim the objectmonitors from the omFreeList of the moribund thread. 1.344 + ObjectSynchronizer::omFlush (this) ; 1.345 + 1.346 + EVENT_THREAD_DESTRUCT(this); 1.347 + 1.348 + // stack_base can be NULL if the thread is never started or exited before 1.349 + // record_stack_base_and_size called. Although, we would like to ensure 1.350 + // that all started threads do call record_stack_base_and_size(), there is 1.351 + // not proper way to enforce that. 1.352 +#if INCLUDE_NMT 1.353 + if (_stack_base != NULL) { 1.354 + address low_stack_addr = stack_base() - stack_size(); 1.355 + MemTracker::release_thread_stack(low_stack_addr, stack_size(), this); 1.356 +#ifdef ASSERT 1.357 + set_stack_base(NULL); 1.358 +#endif 1.359 + } 1.360 +#endif // INCLUDE_NMT 1.361 + 1.362 + // deallocate data structures 1.363 + delete resource_area(); 1.364 + // since the handle marks are using the handle area, we have to deallocated the root 1.365 + // handle mark before deallocating the thread's handle area, 1.366 + assert(last_handle_mark() != NULL, "check we have an element"); 1.367 + delete last_handle_mark(); 1.368 + assert(last_handle_mark() == NULL, "check we have reached the end"); 1.369 + 1.370 + // It's possible we can encounter a null _ParkEvent, etc., in stillborn threads. 1.371 + // We NULL out the fields for good hygiene. 1.372 + ParkEvent::Release (_ParkEvent) ; _ParkEvent = NULL ; 1.373 + ParkEvent::Release (_SleepEvent) ; _SleepEvent = NULL ; 1.374 + ParkEvent::Release (_MutexEvent) ; _MutexEvent = NULL ; 1.375 + ParkEvent::Release (_MuxEvent) ; _MuxEvent = NULL ; 1.376 + 1.377 + delete handle_area(); 1.378 + delete metadata_handles(); 1.379 + 1.380 + // osthread() can be NULL, if creation of thread failed. 1.381 + if (osthread() != NULL) os::free_thread(osthread()); 1.382 + 1.383 + delete _SR_lock; 1.384 + 1.385 + // clear thread local storage if the Thread is deleting itself 1.386 + if (this == Thread::current()) { 1.387 + ThreadLocalStorage::set_thread(NULL); 1.388 + } else { 1.389 + // In the case where we're not the current thread, invalidate all the 1.390 + // caches in case some code tries to get the current thread or the 1.391 + // thread that was destroyed, and gets stale information. 1.392 + ThreadLocalStorage::invalidate_all(); 1.393 + } 1.394 + CHECK_UNHANDLED_OOPS_ONLY(if (CheckUnhandledOops) delete unhandled_oops();) 1.395 +} 1.396 + 1.397 +// NOTE: dummy function for assertion purpose. 1.398 +void Thread::run() { 1.399 + ShouldNotReachHere(); 1.400 +} 1.401 + 1.402 +#ifdef ASSERT 1.403 +// Private method to check for dangling thread pointer 1.404 +void check_for_dangling_thread_pointer(Thread *thread) { 1.405 + assert(!thread->is_Java_thread() || Thread::current() == thread || Threads_lock->owned_by_self(), 1.406 + "possibility of dangling Thread pointer"); 1.407 +} 1.408 +#endif 1.409 + 1.410 + 1.411 +#ifndef PRODUCT 1.412 +// Tracing method for basic thread operations 1.413 +void Thread::trace(const char* msg, const Thread* const thread) { 1.414 + if (!TraceThreadEvents) return; 1.415 + ResourceMark rm; 1.416 + ThreadCritical tc; 1.417 + const char *name = "non-Java thread"; 1.418 + int prio = -1; 1.419 + if (thread->is_Java_thread() 1.420 + && !thread->is_Compiler_thread()) { 1.421 + // The Threads_lock must be held to get information about 1.422 + // this thread but may not be in some situations when 1.423 + // tracing thread events. 1.424 + bool release_Threads_lock = false; 1.425 + if (!Threads_lock->owned_by_self()) { 1.426 + Threads_lock->lock(); 1.427 + release_Threads_lock = true; 1.428 + } 1.429 + JavaThread* jt = (JavaThread *)thread; 1.430 + name = (char *)jt->get_thread_name(); 1.431 + oop thread_oop = jt->threadObj(); 1.432 + if (thread_oop != NULL) { 1.433 + prio = java_lang_Thread::priority(thread_oop); 1.434 + } 1.435 + if (release_Threads_lock) { 1.436 + Threads_lock->unlock(); 1.437 + } 1.438 + } 1.439 + tty->print_cr("Thread::%s " INTPTR_FORMAT " [%lx] %s (prio: %d)", msg, thread, thread->osthread()->thread_id(), name, prio); 1.440 +} 1.441 +#endif 1.442 + 1.443 + 1.444 +ThreadPriority Thread::get_priority(const Thread* const thread) { 1.445 + trace("get priority", thread); 1.446 + ThreadPriority priority; 1.447 + // Can return an error! 1.448 + (void)os::get_priority(thread, priority); 1.449 + assert(MinPriority <= priority && priority <= MaxPriority, "non-Java priority found"); 1.450 + return priority; 1.451 +} 1.452 + 1.453 +void Thread::set_priority(Thread* thread, ThreadPriority priority) { 1.454 + trace("set priority", thread); 1.455 + debug_only(check_for_dangling_thread_pointer(thread);) 1.456 + // Can return an error! 1.457 + (void)os::set_priority(thread, priority); 1.458 +} 1.459 + 1.460 + 1.461 +void Thread::start(Thread* thread) { 1.462 + trace("start", thread); 1.463 + // Start is different from resume in that its safety is guaranteed by context or 1.464 + // being called from a Java method synchronized on the Thread object. 1.465 + if (!DisableStartThread) { 1.466 + if (thread->is_Java_thread()) { 1.467 + // Initialize the thread state to RUNNABLE before starting this thread. 1.468 + // Can not set it after the thread started because we do not know the 1.469 + // exact thread state at that time. It could be in MONITOR_WAIT or 1.470 + // in SLEEPING or some other state. 1.471 + java_lang_Thread::set_thread_status(((JavaThread*)thread)->threadObj(), 1.472 + java_lang_Thread::RUNNABLE); 1.473 + } 1.474 + os::start_thread(thread); 1.475 + } 1.476 +} 1.477 + 1.478 +// Enqueue a VM_Operation to do the job for us - sometime later 1.479 +void Thread::send_async_exception(oop java_thread, oop java_throwable) { 1.480 + VM_ThreadStop* vm_stop = new VM_ThreadStop(java_thread, java_throwable); 1.481 + VMThread::execute(vm_stop); 1.482 +} 1.483 + 1.484 + 1.485 +// 1.486 +// Check if an external suspend request has completed (or has been 1.487 +// cancelled). Returns true if the thread is externally suspended and 1.488 +// false otherwise. 1.489 +// 1.490 +// The bits parameter returns information about the code path through 1.491 +// the routine. Useful for debugging: 1.492 +// 1.493 +// set in is_ext_suspend_completed(): 1.494 +// 0x00000001 - routine was entered 1.495 +// 0x00000010 - routine return false at end 1.496 +// 0x00000100 - thread exited (return false) 1.497 +// 0x00000200 - suspend request cancelled (return false) 1.498 +// 0x00000400 - thread suspended (return true) 1.499 +// 0x00001000 - thread is in a suspend equivalent state (return true) 1.500 +// 0x00002000 - thread is native and walkable (return true) 1.501 +// 0x00004000 - thread is native_trans and walkable (needed retry) 1.502 +// 1.503 +// set in wait_for_ext_suspend_completion(): 1.504 +// 0x00010000 - routine was entered 1.505 +// 0x00020000 - suspend request cancelled before loop (return false) 1.506 +// 0x00040000 - thread suspended before loop (return true) 1.507 +// 0x00080000 - suspend request cancelled in loop (return false) 1.508 +// 0x00100000 - thread suspended in loop (return true) 1.509 +// 0x00200000 - suspend not completed during retry loop (return false) 1.510 +// 1.511 + 1.512 +// Helper class for tracing suspend wait debug bits. 1.513 +// 1.514 +// 0x00000100 indicates that the target thread exited before it could 1.515 +// self-suspend which is not a wait failure. 0x00000200, 0x00020000 and 1.516 +// 0x00080000 each indicate a cancelled suspend request so they don't 1.517 +// count as wait failures either. 1.518 +#define DEBUG_FALSE_BITS (0x00000010 | 0x00200000) 1.519 + 1.520 +class TraceSuspendDebugBits : public StackObj { 1.521 + private: 1.522 + JavaThread * jt; 1.523 + bool is_wait; 1.524 + bool called_by_wait; // meaningful when !is_wait 1.525 + uint32_t * bits; 1.526 + 1.527 + public: 1.528 + TraceSuspendDebugBits(JavaThread *_jt, bool _is_wait, bool _called_by_wait, 1.529 + uint32_t *_bits) { 1.530 + jt = _jt; 1.531 + is_wait = _is_wait; 1.532 + called_by_wait = _called_by_wait; 1.533 + bits = _bits; 1.534 + } 1.535 + 1.536 + ~TraceSuspendDebugBits() { 1.537 + if (!is_wait) { 1.538 +#if 1 1.539 + // By default, don't trace bits for is_ext_suspend_completed() calls. 1.540 + // That trace is very chatty. 1.541 + return; 1.542 +#else 1.543 + if (!called_by_wait) { 1.544 + // If tracing for is_ext_suspend_completed() is enabled, then only 1.545 + // trace calls to it from wait_for_ext_suspend_completion() 1.546 + return; 1.547 + } 1.548 +#endif 1.549 + } 1.550 + 1.551 + if (AssertOnSuspendWaitFailure || TraceSuspendWaitFailures) { 1.552 + if (bits != NULL && (*bits & DEBUG_FALSE_BITS) != 0) { 1.553 + MutexLocker ml(Threads_lock); // needed for get_thread_name() 1.554 + ResourceMark rm; 1.555 + 1.556 + tty->print_cr( 1.557 + "Failed wait_for_ext_suspend_completion(thread=%s, debug_bits=%x)", 1.558 + jt->get_thread_name(), *bits); 1.559 + 1.560 + guarantee(!AssertOnSuspendWaitFailure, "external suspend wait failed"); 1.561 + } 1.562 + } 1.563 + } 1.564 +}; 1.565 +#undef DEBUG_FALSE_BITS 1.566 + 1.567 + 1.568 +bool JavaThread::is_ext_suspend_completed(bool called_by_wait, int delay, uint32_t *bits) { 1.569 + TraceSuspendDebugBits tsdb(this, false /* !is_wait */, called_by_wait, bits); 1.570 + 1.571 + bool did_trans_retry = false; // only do thread_in_native_trans retry once 1.572 + bool do_trans_retry; // flag to force the retry 1.573 + 1.574 + *bits |= 0x00000001; 1.575 + 1.576 + do { 1.577 + do_trans_retry = false; 1.578 + 1.579 + if (is_exiting()) { 1.580 + // Thread is in the process of exiting. This is always checked 1.581 + // first to reduce the risk of dereferencing a freed JavaThread. 1.582 + *bits |= 0x00000100; 1.583 + return false; 1.584 + } 1.585 + 1.586 + if (!is_external_suspend()) { 1.587 + // Suspend request is cancelled. This is always checked before 1.588 + // is_ext_suspended() to reduce the risk of a rogue resume 1.589 + // confusing the thread that made the suspend request. 1.590 + *bits |= 0x00000200; 1.591 + return false; 1.592 + } 1.593 + 1.594 + if (is_ext_suspended()) { 1.595 + // thread is suspended 1.596 + *bits |= 0x00000400; 1.597 + return true; 1.598 + } 1.599 + 1.600 + // Now that we no longer do hard suspends of threads running 1.601 + // native code, the target thread can be changing thread state 1.602 + // while we are in this routine: 1.603 + // 1.604 + // _thread_in_native -> _thread_in_native_trans -> _thread_blocked 1.605 + // 1.606 + // We save a copy of the thread state as observed at this moment 1.607 + // and make our decision about suspend completeness based on the 1.608 + // copy. This closes the race where the thread state is seen as 1.609 + // _thread_in_native_trans in the if-thread_blocked check, but is 1.610 + // seen as _thread_blocked in if-thread_in_native_trans check. 1.611 + JavaThreadState save_state = thread_state(); 1.612 + 1.613 + if (save_state == _thread_blocked && is_suspend_equivalent()) { 1.614 + // If the thread's state is _thread_blocked and this blocking 1.615 + // condition is known to be equivalent to a suspend, then we can 1.616 + // consider the thread to be externally suspended. This means that 1.617 + // the code that sets _thread_blocked has been modified to do 1.618 + // self-suspension if the blocking condition releases. We also 1.619 + // used to check for CONDVAR_WAIT here, but that is now covered by 1.620 + // the _thread_blocked with self-suspension check. 1.621 + // 1.622 + // Return true since we wouldn't be here unless there was still an 1.623 + // external suspend request. 1.624 + *bits |= 0x00001000; 1.625 + return true; 1.626 + } else if (save_state == _thread_in_native && frame_anchor()->walkable()) { 1.627 + // Threads running native code will self-suspend on native==>VM/Java 1.628 + // transitions. If its stack is walkable (should always be the case 1.629 + // unless this function is called before the actual java_suspend() 1.630 + // call), then the wait is done. 1.631 + *bits |= 0x00002000; 1.632 + return true; 1.633 + } else if (!called_by_wait && !did_trans_retry && 1.634 + save_state == _thread_in_native_trans && 1.635 + frame_anchor()->walkable()) { 1.636 + // The thread is transitioning from thread_in_native to another 1.637 + // thread state. check_safepoint_and_suspend_for_native_trans() 1.638 + // will force the thread to self-suspend. If it hasn't gotten 1.639 + // there yet we may have caught the thread in-between the native 1.640 + // code check above and the self-suspend. Lucky us. If we were 1.641 + // called by wait_for_ext_suspend_completion(), then it 1.642 + // will be doing the retries so we don't have to. 1.643 + // 1.644 + // Since we use the saved thread state in the if-statement above, 1.645 + // there is a chance that the thread has already transitioned to 1.646 + // _thread_blocked by the time we get here. In that case, we will 1.647 + // make a single unnecessary pass through the logic below. This 1.648 + // doesn't hurt anything since we still do the trans retry. 1.649 + 1.650 + *bits |= 0x00004000; 1.651 + 1.652 + // Once the thread leaves thread_in_native_trans for another 1.653 + // thread state, we break out of this retry loop. We shouldn't 1.654 + // need this flag to prevent us from getting back here, but 1.655 + // sometimes paranoia is good. 1.656 + did_trans_retry = true; 1.657 + 1.658 + // We wait for the thread to transition to a more usable state. 1.659 + for (int i = 1; i <= SuspendRetryCount; i++) { 1.660 + // We used to do an "os::yield_all(i)" call here with the intention 1.661 + // that yielding would increase on each retry. However, the parameter 1.662 + // is ignored on Linux which means the yield didn't scale up. Waiting 1.663 + // on the SR_lock below provides a much more predictable scale up for 1.664 + // the delay. It also provides a simple/direct point to check for any 1.665 + // safepoint requests from the VMThread 1.666 + 1.667 + // temporarily drops SR_lock while doing wait with safepoint check 1.668 + // (if we're a JavaThread - the WatcherThread can also call this) 1.669 + // and increase delay with each retry 1.670 + SR_lock()->wait(!Thread::current()->is_Java_thread(), i * delay); 1.671 + 1.672 + // check the actual thread state instead of what we saved above 1.673 + if (thread_state() != _thread_in_native_trans) { 1.674 + // the thread has transitioned to another thread state so 1.675 + // try all the checks (except this one) one more time. 1.676 + do_trans_retry = true; 1.677 + break; 1.678 + } 1.679 + } // end retry loop 1.680 + 1.681 + 1.682 + } 1.683 + } while (do_trans_retry); 1.684 + 1.685 + *bits |= 0x00000010; 1.686 + return false; 1.687 +} 1.688 + 1.689 +// 1.690 +// Wait for an external suspend request to complete (or be cancelled). 1.691 +// Returns true if the thread is externally suspended and false otherwise. 1.692 +// 1.693 +bool JavaThread::wait_for_ext_suspend_completion(int retries, int delay, 1.694 + uint32_t *bits) { 1.695 + TraceSuspendDebugBits tsdb(this, true /* is_wait */, 1.696 + false /* !called_by_wait */, bits); 1.697 + 1.698 + // local flag copies to minimize SR_lock hold time 1.699 + bool is_suspended; 1.700 + bool pending; 1.701 + uint32_t reset_bits; 1.702 + 1.703 + // set a marker so is_ext_suspend_completed() knows we are the caller 1.704 + *bits |= 0x00010000; 1.705 + 1.706 + // We use reset_bits to reinitialize the bits value at the top of 1.707 + // each retry loop. This allows the caller to make use of any 1.708 + // unused bits for their own marking purposes. 1.709 + reset_bits = *bits; 1.710 + 1.711 + { 1.712 + MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag); 1.713 + is_suspended = is_ext_suspend_completed(true /* called_by_wait */, 1.714 + delay, bits); 1.715 + pending = is_external_suspend(); 1.716 + } 1.717 + // must release SR_lock to allow suspension to complete 1.718 + 1.719 + if (!pending) { 1.720 + // A cancelled suspend request is the only false return from 1.721 + // is_ext_suspend_completed() that keeps us from entering the 1.722 + // retry loop. 1.723 + *bits |= 0x00020000; 1.724 + return false; 1.725 + } 1.726 + 1.727 + if (is_suspended) { 1.728 + *bits |= 0x00040000; 1.729 + return true; 1.730 + } 1.731 + 1.732 + for (int i = 1; i <= retries; i++) { 1.733 + *bits = reset_bits; // reinit to only track last retry 1.734 + 1.735 + // We used to do an "os::yield_all(i)" call here with the intention 1.736 + // that yielding would increase on each retry. However, the parameter 1.737 + // is ignored on Linux which means the yield didn't scale up. Waiting 1.738 + // on the SR_lock below provides a much more predictable scale up for 1.739 + // the delay. It also provides a simple/direct point to check for any 1.740 + // safepoint requests from the VMThread 1.741 + 1.742 + { 1.743 + MutexLocker ml(SR_lock()); 1.744 + // wait with safepoint check (if we're a JavaThread - the WatcherThread 1.745 + // can also call this) and increase delay with each retry 1.746 + SR_lock()->wait(!Thread::current()->is_Java_thread(), i * delay); 1.747 + 1.748 + is_suspended = is_ext_suspend_completed(true /* called_by_wait */, 1.749 + delay, bits); 1.750 + 1.751 + // It is possible for the external suspend request to be cancelled 1.752 + // (by a resume) before the actual suspend operation is completed. 1.753 + // Refresh our local copy to see if we still need to wait. 1.754 + pending = is_external_suspend(); 1.755 + } 1.756 + 1.757 + if (!pending) { 1.758 + // A cancelled suspend request is the only false return from 1.759 + // is_ext_suspend_completed() that keeps us from staying in the 1.760 + // retry loop. 1.761 + *bits |= 0x00080000; 1.762 + return false; 1.763 + } 1.764 + 1.765 + if (is_suspended) { 1.766 + *bits |= 0x00100000; 1.767 + return true; 1.768 + } 1.769 + } // end retry loop 1.770 + 1.771 + // thread did not suspend after all our retries 1.772 + *bits |= 0x00200000; 1.773 + return false; 1.774 +} 1.775 + 1.776 +#ifndef PRODUCT 1.777 +void JavaThread::record_jump(address target, address instr, const char* file, int line) { 1.778 + 1.779 + // This should not need to be atomic as the only way for simultaneous 1.780 + // updates is via interrupts. Even then this should be rare or non-existant 1.781 + // and we don't care that much anyway. 1.782 + 1.783 + int index = _jmp_ring_index; 1.784 + _jmp_ring_index = (index + 1 ) & (jump_ring_buffer_size - 1); 1.785 + _jmp_ring[index]._target = (intptr_t) target; 1.786 + _jmp_ring[index]._instruction = (intptr_t) instr; 1.787 + _jmp_ring[index]._file = file; 1.788 + _jmp_ring[index]._line = line; 1.789 +} 1.790 +#endif /* PRODUCT */ 1.791 + 1.792 +// Called by flat profiler 1.793 +// Callers have already called wait_for_ext_suspend_completion 1.794 +// The assertion for that is currently too complex to put here: 1.795 +bool JavaThread::profile_last_Java_frame(frame* _fr) { 1.796 + bool gotframe = false; 1.797 + // self suspension saves needed state. 1.798 + if (has_last_Java_frame() && _anchor.walkable()) { 1.799 + *_fr = pd_last_frame(); 1.800 + gotframe = true; 1.801 + } 1.802 + return gotframe; 1.803 +} 1.804 + 1.805 +void Thread::interrupt(Thread* thread) { 1.806 + trace("interrupt", thread); 1.807 + debug_only(check_for_dangling_thread_pointer(thread);) 1.808 + os::interrupt(thread); 1.809 +} 1.810 + 1.811 +bool Thread::is_interrupted(Thread* thread, bool clear_interrupted) { 1.812 + trace("is_interrupted", thread); 1.813 + debug_only(check_for_dangling_thread_pointer(thread);) 1.814 + // Note: If clear_interrupted==false, this simply fetches and 1.815 + // returns the value of the field osthread()->interrupted(). 1.816 + return os::is_interrupted(thread, clear_interrupted); 1.817 +} 1.818 + 1.819 + 1.820 +// GC Support 1.821 +bool Thread::claim_oops_do_par_case(int strong_roots_parity) { 1.822 + jint thread_parity = _oops_do_parity; 1.823 + if (thread_parity != strong_roots_parity) { 1.824 + jint res = Atomic::cmpxchg(strong_roots_parity, &_oops_do_parity, thread_parity); 1.825 + if (res == thread_parity) { 1.826 + return true; 1.827 + } else { 1.828 + guarantee(res == strong_roots_parity, "Or else what?"); 1.829 + assert(SharedHeap::heap()->workers()->active_workers() > 0, 1.830 + "Should only fail when parallel."); 1.831 + return false; 1.832 + } 1.833 + } 1.834 + assert(SharedHeap::heap()->workers()->active_workers() > 0, 1.835 + "Should only fail when parallel."); 1.836 + return false; 1.837 +} 1.838 + 1.839 +void Thread::oops_do(OopClosure* f, CLDToOopClosure* cld_f, CodeBlobClosure* cf) { 1.840 + active_handles()->oops_do(f); 1.841 + // Do oop for ThreadShadow 1.842 + f->do_oop((oop*)&_pending_exception); 1.843 + handle_area()->oops_do(f); 1.844 +} 1.845 + 1.846 +void Thread::nmethods_do(CodeBlobClosure* cf) { 1.847 + // no nmethods in a generic thread... 1.848 +} 1.849 + 1.850 +void Thread::metadata_do(void f(Metadata*)) { 1.851 + if (metadata_handles() != NULL) { 1.852 + for (int i = 0; i< metadata_handles()->length(); i++) { 1.853 + f(metadata_handles()->at(i)); 1.854 + } 1.855 + } 1.856 +} 1.857 + 1.858 +void Thread::print_on(outputStream* st) const { 1.859 + // get_priority assumes osthread initialized 1.860 + if (osthread() != NULL) { 1.861 + int os_prio; 1.862 + if (os::get_native_priority(this, &os_prio) == OS_OK) { 1.863 + st->print("os_prio=%d ", os_prio); 1.864 + } 1.865 + st->print("tid=" INTPTR_FORMAT " ", this); 1.866 + osthread()->print_on(st); 1.867 + } 1.868 + debug_only(if (WizardMode) print_owned_locks_on(st);) 1.869 +} 1.870 + 1.871 +// Thread::print_on_error() is called by fatal error handler. Don't use 1.872 +// any lock or allocate memory. 1.873 +void Thread::print_on_error(outputStream* st, char* buf, int buflen) const { 1.874 + if (is_VM_thread()) st->print("VMThread"); 1.875 + else if (is_Compiler_thread()) st->print("CompilerThread"); 1.876 + else if (is_Java_thread()) st->print("JavaThread"); 1.877 + else if (is_GC_task_thread()) st->print("GCTaskThread"); 1.878 + else if (is_Watcher_thread()) st->print("WatcherThread"); 1.879 + else if (is_ConcurrentGC_thread()) st->print("ConcurrentGCThread"); 1.880 + else st->print("Thread"); 1.881 + 1.882 + st->print(" [stack: " PTR_FORMAT "," PTR_FORMAT "]", 1.883 + _stack_base - _stack_size, _stack_base); 1.884 + 1.885 + if (osthread()) { 1.886 + st->print(" [id=%d]", osthread()->thread_id()); 1.887 + } 1.888 +} 1.889 + 1.890 +#ifdef ASSERT 1.891 +void Thread::print_owned_locks_on(outputStream* st) const { 1.892 + Monitor *cur = _owned_locks; 1.893 + if (cur == NULL) { 1.894 + st->print(" (no locks) "); 1.895 + } else { 1.896 + st->print_cr(" Locks owned:"); 1.897 + while(cur) { 1.898 + cur->print_on(st); 1.899 + cur = cur->next(); 1.900 + } 1.901 + } 1.902 +} 1.903 + 1.904 +static int ref_use_count = 0; 1.905 + 1.906 +bool Thread::owns_locks_but_compiled_lock() const { 1.907 + for(Monitor *cur = _owned_locks; cur; cur = cur->next()) { 1.908 + if (cur != Compile_lock) return true; 1.909 + } 1.910 + return false; 1.911 +} 1.912 + 1.913 + 1.914 +#endif 1.915 + 1.916 +#ifndef PRODUCT 1.917 + 1.918 +// The flag: potential_vm_operation notifies if this particular safepoint state could potential 1.919 +// invoke the vm-thread (i.e., and oop allocation). In that case, we also have to make sure that 1.920 +// no threads which allow_vm_block's are held 1.921 +void Thread::check_for_valid_safepoint_state(bool potential_vm_operation) { 1.922 + // Check if current thread is allowed to block at a safepoint 1.923 + if (!(_allow_safepoint_count == 0)) 1.924 + fatal("Possible safepoint reached by thread that does not allow it"); 1.925 + if (is_Java_thread() && ((JavaThread*)this)->thread_state() != _thread_in_vm) { 1.926 + fatal("LEAF method calling lock?"); 1.927 + } 1.928 + 1.929 +#ifdef ASSERT 1.930 + if (potential_vm_operation && is_Java_thread() 1.931 + && !Universe::is_bootstrapping()) { 1.932 + // Make sure we do not hold any locks that the VM thread also uses. 1.933 + // This could potentially lead to deadlocks 1.934 + for(Monitor *cur = _owned_locks; cur; cur = cur->next()) { 1.935 + // Threads_lock is special, since the safepoint synchronization will not start before this is 1.936 + // acquired. Hence, a JavaThread cannot be holding it at a safepoint. So is VMOperationRequest_lock, 1.937 + // since it is used to transfer control between JavaThreads and the VMThread 1.938 + // Do not *exclude* any locks unless you are absolutly sure it is correct. Ask someone else first! 1.939 + if ( (cur->allow_vm_block() && 1.940 + cur != Threads_lock && 1.941 + cur != Compile_lock && // Temporary: should not be necessary when we get spearate compilation 1.942 + cur != VMOperationRequest_lock && 1.943 + cur != VMOperationQueue_lock) || 1.944 + cur->rank() == Mutex::special) { 1.945 + warning("Thread holding lock at safepoint that vm can block on: %s", cur->name()); 1.946 + } 1.947 + } 1.948 + } 1.949 + 1.950 + if (GCALotAtAllSafepoints) { 1.951 + // We could enter a safepoint here and thus have a gc 1.952 + InterfaceSupport::check_gc_alot(); 1.953 + } 1.954 +#endif 1.955 +} 1.956 +#endif 1.957 + 1.958 +bool Thread::is_in_stack(address adr) const { 1.959 + assert(Thread::current() == this, "is_in_stack can only be called from current thread"); 1.960 + address end = os::current_stack_pointer(); 1.961 + // Allow non Java threads to call this without stack_base 1.962 + if (_stack_base == NULL) return true; 1.963 + if (stack_base() >= adr && adr >= end) return true; 1.964 + 1.965 + return false; 1.966 +} 1.967 + 1.968 + 1.969 +bool Thread::is_in_usable_stack(address adr) const { 1.970 + size_t stack_guard_size = os::uses_stack_guard_pages() ? (StackYellowPages + StackRedPages) * os::vm_page_size() : 0; 1.971 + size_t usable_stack_size = _stack_size - stack_guard_size; 1.972 + 1.973 + return ((adr < stack_base()) && (adr >= stack_base() - usable_stack_size)); 1.974 +} 1.975 + 1.976 + 1.977 +// We had to move these methods here, because vm threads get into ObjectSynchronizer::enter 1.978 +// However, there is a note in JavaThread::is_lock_owned() about the VM threads not being 1.979 +// used for compilation in the future. If that change is made, the need for these methods 1.980 +// should be revisited, and they should be removed if possible. 1.981 + 1.982 +bool Thread::is_lock_owned(address adr) const { 1.983 + return on_local_stack(adr); 1.984 +} 1.985 + 1.986 +bool Thread::set_as_starting_thread() { 1.987 + // NOTE: this must be called inside the main thread. 1.988 + return os::create_main_thread((JavaThread*)this); 1.989 +} 1.990 + 1.991 +static void initialize_class(Symbol* class_name, TRAPS) { 1.992 + Klass* klass = SystemDictionary::resolve_or_fail(class_name, true, CHECK); 1.993 + InstanceKlass::cast(klass)->initialize(CHECK); 1.994 +} 1.995 + 1.996 + 1.997 +// Creates the initial ThreadGroup 1.998 +static Handle create_initial_thread_group(TRAPS) { 1.999 + Klass* k = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_ThreadGroup(), true, CHECK_NH); 1.1000 + instanceKlassHandle klass (THREAD, k); 1.1001 + 1.1002 + Handle system_instance = klass->allocate_instance_handle(CHECK_NH); 1.1003 + { 1.1004 + JavaValue result(T_VOID); 1.1005 + JavaCalls::call_special(&result, 1.1006 + system_instance, 1.1007 + klass, 1.1008 + vmSymbols::object_initializer_name(), 1.1009 + vmSymbols::void_method_signature(), 1.1010 + CHECK_NH); 1.1011 + } 1.1012 + Universe::set_system_thread_group(system_instance()); 1.1013 + 1.1014 + Handle main_instance = klass->allocate_instance_handle(CHECK_NH); 1.1015 + { 1.1016 + JavaValue result(T_VOID); 1.1017 + Handle string = java_lang_String::create_from_str("main", CHECK_NH); 1.1018 + JavaCalls::call_special(&result, 1.1019 + main_instance, 1.1020 + klass, 1.1021 + vmSymbols::object_initializer_name(), 1.1022 + vmSymbols::threadgroup_string_void_signature(), 1.1023 + system_instance, 1.1024 + string, 1.1025 + CHECK_NH); 1.1026 + } 1.1027 + return main_instance; 1.1028 +} 1.1029 + 1.1030 +// Creates the initial Thread 1.1031 +static oop create_initial_thread(Handle thread_group, JavaThread* thread, TRAPS) { 1.1032 + Klass* k = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_Thread(), true, CHECK_NULL); 1.1033 + instanceKlassHandle klass (THREAD, k); 1.1034 + instanceHandle thread_oop = klass->allocate_instance_handle(CHECK_NULL); 1.1035 + 1.1036 + java_lang_Thread::set_thread(thread_oop(), thread); 1.1037 + java_lang_Thread::set_priority(thread_oop(), NormPriority); 1.1038 + thread->set_threadObj(thread_oop()); 1.1039 + 1.1040 + Handle string = java_lang_String::create_from_str("main", CHECK_NULL); 1.1041 + 1.1042 + JavaValue result(T_VOID); 1.1043 + JavaCalls::call_special(&result, thread_oop, 1.1044 + klass, 1.1045 + vmSymbols::object_initializer_name(), 1.1046 + vmSymbols::threadgroup_string_void_signature(), 1.1047 + thread_group, 1.1048 + string, 1.1049 + CHECK_NULL); 1.1050 + return thread_oop(); 1.1051 +} 1.1052 + 1.1053 +static void call_initializeSystemClass(TRAPS) { 1.1054 + Klass* k = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_System(), true, CHECK); 1.1055 + instanceKlassHandle klass (THREAD, k); 1.1056 + 1.1057 + JavaValue result(T_VOID); 1.1058 + JavaCalls::call_static(&result, klass, vmSymbols::initializeSystemClass_name(), 1.1059 + vmSymbols::void_method_signature(), CHECK); 1.1060 +} 1.1061 + 1.1062 +char java_runtime_name[128] = ""; 1.1063 +char java_runtime_version[128] = ""; 1.1064 + 1.1065 +// extract the JRE name from sun.misc.Version.java_runtime_name 1.1066 +static const char* get_java_runtime_name(TRAPS) { 1.1067 + Klass* k = SystemDictionary::find(vmSymbols::sun_misc_Version(), 1.1068 + Handle(), Handle(), CHECK_AND_CLEAR_NULL); 1.1069 + fieldDescriptor fd; 1.1070 + bool found = k != NULL && 1.1071 + InstanceKlass::cast(k)->find_local_field(vmSymbols::java_runtime_name_name(), 1.1072 + vmSymbols::string_signature(), &fd); 1.1073 + if (found) { 1.1074 + oop name_oop = k->java_mirror()->obj_field(fd.offset()); 1.1075 + if (name_oop == NULL) 1.1076 + return NULL; 1.1077 + const char* name = java_lang_String::as_utf8_string(name_oop, 1.1078 + java_runtime_name, 1.1079 + sizeof(java_runtime_name)); 1.1080 + return name; 1.1081 + } else { 1.1082 + return NULL; 1.1083 + } 1.1084 +} 1.1085 + 1.1086 +// extract the JRE version from sun.misc.Version.java_runtime_version 1.1087 +static const char* get_java_runtime_version(TRAPS) { 1.1088 + Klass* k = SystemDictionary::find(vmSymbols::sun_misc_Version(), 1.1089 + Handle(), Handle(), CHECK_AND_CLEAR_NULL); 1.1090 + fieldDescriptor fd; 1.1091 + bool found = k != NULL && 1.1092 + InstanceKlass::cast(k)->find_local_field(vmSymbols::java_runtime_version_name(), 1.1093 + vmSymbols::string_signature(), &fd); 1.1094 + if (found) { 1.1095 + oop name_oop = k->java_mirror()->obj_field(fd.offset()); 1.1096 + if (name_oop == NULL) 1.1097 + return NULL; 1.1098 + const char* name = java_lang_String::as_utf8_string(name_oop, 1.1099 + java_runtime_version, 1.1100 + sizeof(java_runtime_version)); 1.1101 + return name; 1.1102 + } else { 1.1103 + return NULL; 1.1104 + } 1.1105 +} 1.1106 + 1.1107 +// General purpose hook into Java code, run once when the VM is initialized. 1.1108 +// The Java library method itself may be changed independently from the VM. 1.1109 +static void call_postVMInitHook(TRAPS) { 1.1110 + Klass* k = SystemDictionary::resolve_or_null(vmSymbols::sun_misc_PostVMInitHook(), THREAD); 1.1111 + instanceKlassHandle klass (THREAD, k); 1.1112 + if (klass.not_null()) { 1.1113 + JavaValue result(T_VOID); 1.1114 + JavaCalls::call_static(&result, klass, vmSymbols::run_method_name(), 1.1115 + vmSymbols::void_method_signature(), 1.1116 + CHECK); 1.1117 + } 1.1118 +} 1.1119 + 1.1120 +static void reset_vm_info_property(TRAPS) { 1.1121 + // the vm info string 1.1122 + ResourceMark rm(THREAD); 1.1123 + const char *vm_info = VM_Version::vm_info_string(); 1.1124 + 1.1125 + // java.lang.System class 1.1126 + Klass* k = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_System(), true, CHECK); 1.1127 + instanceKlassHandle klass (THREAD, k); 1.1128 + 1.1129 + // setProperty arguments 1.1130 + Handle key_str = java_lang_String::create_from_str("java.vm.info", CHECK); 1.1131 + Handle value_str = java_lang_String::create_from_str(vm_info, CHECK); 1.1132 + 1.1133 + // return value 1.1134 + JavaValue r(T_OBJECT); 1.1135 + 1.1136 + // public static String setProperty(String key, String value); 1.1137 + JavaCalls::call_static(&r, 1.1138 + klass, 1.1139 + vmSymbols::setProperty_name(), 1.1140 + vmSymbols::string_string_string_signature(), 1.1141 + key_str, 1.1142 + value_str, 1.1143 + CHECK); 1.1144 +} 1.1145 + 1.1146 + 1.1147 +void JavaThread::allocate_threadObj(Handle thread_group, char* thread_name, bool daemon, TRAPS) { 1.1148 + assert(thread_group.not_null(), "thread group should be specified"); 1.1149 + assert(threadObj() == NULL, "should only create Java thread object once"); 1.1150 + 1.1151 + Klass* k = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_Thread(), true, CHECK); 1.1152 + instanceKlassHandle klass (THREAD, k); 1.1153 + instanceHandle thread_oop = klass->allocate_instance_handle(CHECK); 1.1154 + 1.1155 + java_lang_Thread::set_thread(thread_oop(), this); 1.1156 + java_lang_Thread::set_priority(thread_oop(), NormPriority); 1.1157 + set_threadObj(thread_oop()); 1.1158 + 1.1159 + JavaValue result(T_VOID); 1.1160 + if (thread_name != NULL) { 1.1161 + Handle name = java_lang_String::create_from_str(thread_name, CHECK); 1.1162 + // Thread gets assigned specified name and null target 1.1163 + JavaCalls::call_special(&result, 1.1164 + thread_oop, 1.1165 + klass, 1.1166 + vmSymbols::object_initializer_name(), 1.1167 + vmSymbols::threadgroup_string_void_signature(), 1.1168 + thread_group, // Argument 1 1.1169 + name, // Argument 2 1.1170 + THREAD); 1.1171 + } else { 1.1172 + // Thread gets assigned name "Thread-nnn" and null target 1.1173 + // (java.lang.Thread doesn't have a constructor taking only a ThreadGroup argument) 1.1174 + JavaCalls::call_special(&result, 1.1175 + thread_oop, 1.1176 + klass, 1.1177 + vmSymbols::object_initializer_name(), 1.1178 + vmSymbols::threadgroup_runnable_void_signature(), 1.1179 + thread_group, // Argument 1 1.1180 + Handle(), // Argument 2 1.1181 + THREAD); 1.1182 + } 1.1183 + 1.1184 + 1.1185 + if (daemon) { 1.1186 + java_lang_Thread::set_daemon(thread_oop()); 1.1187 + } 1.1188 + 1.1189 + if (HAS_PENDING_EXCEPTION) { 1.1190 + return; 1.1191 + } 1.1192 + 1.1193 + KlassHandle group(this, SystemDictionary::ThreadGroup_klass()); 1.1194 + Handle threadObj(this, this->threadObj()); 1.1195 + 1.1196 + JavaCalls::call_special(&result, 1.1197 + thread_group, 1.1198 + group, 1.1199 + vmSymbols::add_method_name(), 1.1200 + vmSymbols::thread_void_signature(), 1.1201 + threadObj, // Arg 1 1.1202 + THREAD); 1.1203 + 1.1204 + 1.1205 +} 1.1206 + 1.1207 +// NamedThread -- non-JavaThread subclasses with multiple 1.1208 +// uniquely named instances should derive from this. 1.1209 +NamedThread::NamedThread() : Thread() { 1.1210 + _name = NULL; 1.1211 + _processed_thread = NULL; 1.1212 +} 1.1213 + 1.1214 +NamedThread::~NamedThread() { 1.1215 + if (_name != NULL) { 1.1216 + FREE_C_HEAP_ARRAY(char, _name, mtThread); 1.1217 + _name = NULL; 1.1218 + } 1.1219 +} 1.1220 + 1.1221 +void NamedThread::set_name(const char* format, ...) { 1.1222 + guarantee(_name == NULL, "Only get to set name once."); 1.1223 + _name = NEW_C_HEAP_ARRAY(char, max_name_len, mtThread); 1.1224 + guarantee(_name != NULL, "alloc failure"); 1.1225 + va_list ap; 1.1226 + va_start(ap, format); 1.1227 + jio_vsnprintf(_name, max_name_len, format, ap); 1.1228 + va_end(ap); 1.1229 +} 1.1230 + 1.1231 +// ======= WatcherThread ======== 1.1232 + 1.1233 +// The watcher thread exists to simulate timer interrupts. It should 1.1234 +// be replaced by an abstraction over whatever native support for 1.1235 +// timer interrupts exists on the platform. 1.1236 + 1.1237 +WatcherThread* WatcherThread::_watcher_thread = NULL; 1.1238 +bool WatcherThread::_startable = false; 1.1239 +volatile bool WatcherThread::_should_terminate = false; 1.1240 + 1.1241 +WatcherThread::WatcherThread() : Thread(), _crash_protection(NULL) { 1.1242 + assert(watcher_thread() == NULL, "we can only allocate one WatcherThread"); 1.1243 + if (os::create_thread(this, os::watcher_thread)) { 1.1244 + _watcher_thread = this; 1.1245 + 1.1246 + // Set the watcher thread to the highest OS priority which should not be 1.1247 + // used, unless a Java thread with priority java.lang.Thread.MAX_PRIORITY 1.1248 + // is created. The only normal thread using this priority is the reference 1.1249 + // handler thread, which runs for very short intervals only. 1.1250 + // If the VMThread's priority is not lower than the WatcherThread profiling 1.1251 + // will be inaccurate. 1.1252 + os::set_priority(this, MaxPriority); 1.1253 + if (!DisableStartThread) { 1.1254 + os::start_thread(this); 1.1255 + } 1.1256 + } 1.1257 +} 1.1258 + 1.1259 +int WatcherThread::sleep() const { 1.1260 + MutexLockerEx ml(PeriodicTask_lock, Mutex::_no_safepoint_check_flag); 1.1261 + 1.1262 + // remaining will be zero if there are no tasks, 1.1263 + // causing the WatcherThread to sleep until a task is 1.1264 + // enrolled 1.1265 + int remaining = PeriodicTask::time_to_wait(); 1.1266 + int time_slept = 0; 1.1267 + 1.1268 + // we expect this to timeout - we only ever get unparked when 1.1269 + // we should terminate or when a new task has been enrolled 1.1270 + OSThreadWaitState osts(this->osthread(), false /* not Object.wait() */); 1.1271 + 1.1272 + jlong time_before_loop = os::javaTimeNanos(); 1.1273 + 1.1274 + for (;;) { 1.1275 + bool timedout = PeriodicTask_lock->wait(Mutex::_no_safepoint_check_flag, remaining); 1.1276 + jlong now = os::javaTimeNanos(); 1.1277 + 1.1278 + if (remaining == 0) { 1.1279 + // if we didn't have any tasks we could have waited for a long time 1.1280 + // consider the time_slept zero and reset time_before_loop 1.1281 + time_slept = 0; 1.1282 + time_before_loop = now; 1.1283 + } else { 1.1284 + // need to recalulate since we might have new tasks in _tasks 1.1285 + time_slept = (int) ((now - time_before_loop) / 1000000); 1.1286 + } 1.1287 + 1.1288 + // Change to task list or spurious wakeup of some kind 1.1289 + if (timedout || _should_terminate) { 1.1290 + break; 1.1291 + } 1.1292 + 1.1293 + remaining = PeriodicTask::time_to_wait(); 1.1294 + if (remaining == 0) { 1.1295 + // Last task was just disenrolled so loop around and wait until 1.1296 + // another task gets enrolled 1.1297 + continue; 1.1298 + } 1.1299 + 1.1300 + remaining -= time_slept; 1.1301 + if (remaining <= 0) 1.1302 + break; 1.1303 + } 1.1304 + 1.1305 + return time_slept; 1.1306 +} 1.1307 + 1.1308 +void WatcherThread::run() { 1.1309 + assert(this == watcher_thread(), "just checking"); 1.1310 + 1.1311 + this->record_stack_base_and_size(); 1.1312 + this->initialize_thread_local_storage(); 1.1313 + this->set_active_handles(JNIHandleBlock::allocate_block()); 1.1314 + while(!_should_terminate) { 1.1315 + assert(watcher_thread() == Thread::current(), "thread consistency check"); 1.1316 + assert(watcher_thread() == this, "thread consistency check"); 1.1317 + 1.1318 + // Calculate how long it'll be until the next PeriodicTask work 1.1319 + // should be done, and sleep that amount of time. 1.1320 + int time_waited = sleep(); 1.1321 + 1.1322 + if (is_error_reported()) { 1.1323 + // A fatal error has happened, the error handler(VMError::report_and_die) 1.1324 + // should abort JVM after creating an error log file. However in some 1.1325 + // rare cases, the error handler itself might deadlock. Here we try to 1.1326 + // kill JVM if the fatal error handler fails to abort in 2 minutes. 1.1327 + // 1.1328 + // This code is in WatcherThread because WatcherThread wakes up 1.1329 + // periodically so the fatal error handler doesn't need to do anything; 1.1330 + // also because the WatcherThread is less likely to crash than other 1.1331 + // threads. 1.1332 + 1.1333 + for (;;) { 1.1334 + if (!ShowMessageBoxOnError 1.1335 + && (OnError == NULL || OnError[0] == '\0') 1.1336 + && Arguments::abort_hook() == NULL) { 1.1337 + os::sleep(this, 2 * 60 * 1000, false); 1.1338 + fdStream err(defaultStream::output_fd()); 1.1339 + err.print_raw_cr("# [ timer expired, abort... ]"); 1.1340 + // skip atexit/vm_exit/vm_abort hooks 1.1341 + os::die(); 1.1342 + } 1.1343 + 1.1344 + // Wake up 5 seconds later, the fatal handler may reset OnError or 1.1345 + // ShowMessageBoxOnError when it is ready to abort. 1.1346 + os::sleep(this, 5 * 1000, false); 1.1347 + } 1.1348 + } 1.1349 + 1.1350 + PeriodicTask::real_time_tick(time_waited); 1.1351 + } 1.1352 + 1.1353 + // Signal that it is terminated 1.1354 + { 1.1355 + MutexLockerEx mu(Terminator_lock, Mutex::_no_safepoint_check_flag); 1.1356 + _watcher_thread = NULL; 1.1357 + Terminator_lock->notify(); 1.1358 + } 1.1359 + 1.1360 + // Thread destructor usually does this.. 1.1361 + ThreadLocalStorage::set_thread(NULL); 1.1362 +} 1.1363 + 1.1364 +void WatcherThread::start() { 1.1365 + assert(PeriodicTask_lock->owned_by_self(), "PeriodicTask_lock required"); 1.1366 + 1.1367 + if (watcher_thread() == NULL && _startable) { 1.1368 + _should_terminate = false; 1.1369 + // Create the single instance of WatcherThread 1.1370 + new WatcherThread(); 1.1371 + } 1.1372 +} 1.1373 + 1.1374 +void WatcherThread::make_startable() { 1.1375 + assert(PeriodicTask_lock->owned_by_self(), "PeriodicTask_lock required"); 1.1376 + _startable = true; 1.1377 +} 1.1378 + 1.1379 +void WatcherThread::stop() { 1.1380 + { 1.1381 + MutexLockerEx ml(PeriodicTask_lock, Mutex::_no_safepoint_check_flag); 1.1382 + _should_terminate = true; 1.1383 + OrderAccess::fence(); // ensure WatcherThread sees update in main loop 1.1384 + 1.1385 + WatcherThread* watcher = watcher_thread(); 1.1386 + if (watcher != NULL) 1.1387 + watcher->unpark(); 1.1388 + } 1.1389 + 1.1390 + // it is ok to take late safepoints here, if needed 1.1391 + MutexLocker mu(Terminator_lock); 1.1392 + 1.1393 + while(watcher_thread() != NULL) { 1.1394 + // This wait should make safepoint checks, wait without a timeout, 1.1395 + // and wait as a suspend-equivalent condition. 1.1396 + // 1.1397 + // Note: If the FlatProfiler is running, then this thread is waiting 1.1398 + // for the WatcherThread to terminate and the WatcherThread, via the 1.1399 + // FlatProfiler task, is waiting for the external suspend request on 1.1400 + // this thread to complete. wait_for_ext_suspend_completion() will 1.1401 + // eventually timeout, but that takes time. Making this wait a 1.1402 + // suspend-equivalent condition solves that timeout problem. 1.1403 + // 1.1404 + Terminator_lock->wait(!Mutex::_no_safepoint_check_flag, 0, 1.1405 + Mutex::_as_suspend_equivalent_flag); 1.1406 + } 1.1407 +} 1.1408 + 1.1409 +void WatcherThread::unpark() { 1.1410 + MutexLockerEx ml(PeriodicTask_lock->owned_by_self() ? NULL : PeriodicTask_lock, Mutex::_no_safepoint_check_flag); 1.1411 + PeriodicTask_lock->notify(); 1.1412 +} 1.1413 + 1.1414 +void WatcherThread::print_on(outputStream* st) const { 1.1415 + st->print("\"%s\" ", name()); 1.1416 + Thread::print_on(st); 1.1417 + st->cr(); 1.1418 +} 1.1419 + 1.1420 +// ======= JavaThread ======== 1.1421 + 1.1422 +// A JavaThread is a normal Java thread 1.1423 + 1.1424 +void JavaThread::initialize() { 1.1425 + // Initialize fields 1.1426 + 1.1427 + // Set the claimed par_id to UINT_MAX (ie not claiming any par_ids) 1.1428 + set_claimed_par_id(UINT_MAX); 1.1429 + 1.1430 + set_saved_exception_pc(NULL); 1.1431 + set_threadObj(NULL); 1.1432 + _anchor.clear(); 1.1433 + set_entry_point(NULL); 1.1434 + set_jni_functions(jni_functions()); 1.1435 + set_callee_target(NULL); 1.1436 + set_vm_result(NULL); 1.1437 + set_vm_result_2(NULL); 1.1438 + set_vframe_array_head(NULL); 1.1439 + set_vframe_array_last(NULL); 1.1440 + set_deferred_locals(NULL); 1.1441 + set_deopt_mark(NULL); 1.1442 + set_deopt_nmethod(NULL); 1.1443 + clear_must_deopt_id(); 1.1444 + set_monitor_chunks(NULL); 1.1445 + set_next(NULL); 1.1446 + set_thread_state(_thread_new); 1.1447 +#if INCLUDE_NMT 1.1448 + set_recorder(NULL); 1.1449 +#endif 1.1450 + _terminated = _not_terminated; 1.1451 + _privileged_stack_top = NULL; 1.1452 + _array_for_gc = NULL; 1.1453 + _suspend_equivalent = false; 1.1454 + _in_deopt_handler = 0; 1.1455 + _doing_unsafe_access = false; 1.1456 + _stack_guard_state = stack_guard_unused; 1.1457 + (void)const_cast<oop&>(_exception_oop = NULL); 1.1458 + _exception_pc = 0; 1.1459 + _exception_handler_pc = 0; 1.1460 + _is_method_handle_return = 0; 1.1461 + _jvmti_thread_state= NULL; 1.1462 + _should_post_on_exceptions_flag = JNI_FALSE; 1.1463 + _jvmti_get_loaded_classes_closure = NULL; 1.1464 + _interp_only_mode = 0; 1.1465 + _special_runtime_exit_condition = _no_async_condition; 1.1466 + _pending_async_exception = NULL; 1.1467 + _thread_stat = NULL; 1.1468 + _thread_stat = new ThreadStatistics(); 1.1469 + _blocked_on_compilation = false; 1.1470 + _jni_active_critical = 0; 1.1471 + _do_not_unlock_if_synchronized = false; 1.1472 + _cached_monitor_info = NULL; 1.1473 + _parker = Parker::Allocate(this) ; 1.1474 + 1.1475 +#ifndef PRODUCT 1.1476 + _jmp_ring_index = 0; 1.1477 + for (int ji = 0 ; ji < jump_ring_buffer_size ; ji++ ) { 1.1478 + record_jump(NULL, NULL, NULL, 0); 1.1479 + } 1.1480 +#endif /* PRODUCT */ 1.1481 + 1.1482 + set_thread_profiler(NULL); 1.1483 + if (FlatProfiler::is_active()) { 1.1484 + // This is where we would decide to either give each thread it's own profiler 1.1485 + // or use one global one from FlatProfiler, 1.1486 + // or up to some count of the number of profiled threads, etc. 1.1487 + ThreadProfiler* pp = new ThreadProfiler(); 1.1488 + pp->engage(); 1.1489 + set_thread_profiler(pp); 1.1490 + } 1.1491 + 1.1492 + // Setup safepoint state info for this thread 1.1493 + ThreadSafepointState::create(this); 1.1494 + 1.1495 + debug_only(_java_call_counter = 0); 1.1496 + 1.1497 + // JVMTI PopFrame support 1.1498 + _popframe_condition = popframe_inactive; 1.1499 + _popframe_preserved_args = NULL; 1.1500 + _popframe_preserved_args_size = 0; 1.1501 + 1.1502 + pd_initialize(); 1.1503 +} 1.1504 + 1.1505 +#if INCLUDE_ALL_GCS 1.1506 +SATBMarkQueueSet JavaThread::_satb_mark_queue_set; 1.1507 +DirtyCardQueueSet JavaThread::_dirty_card_queue_set; 1.1508 +#endif // INCLUDE_ALL_GCS 1.1509 + 1.1510 +JavaThread::JavaThread(bool is_attaching_via_jni) : 1.1511 + Thread() 1.1512 +#if INCLUDE_ALL_GCS 1.1513 + , _satb_mark_queue(&_satb_mark_queue_set), 1.1514 + _dirty_card_queue(&_dirty_card_queue_set) 1.1515 +#endif // INCLUDE_ALL_GCS 1.1516 +{ 1.1517 + initialize(); 1.1518 + if (is_attaching_via_jni) { 1.1519 + _jni_attach_state = _attaching_via_jni; 1.1520 + } else { 1.1521 + _jni_attach_state = _not_attaching_via_jni; 1.1522 + } 1.1523 + assert(deferred_card_mark().is_empty(), "Default MemRegion ctor"); 1.1524 + _safepoint_visible = false; 1.1525 +} 1.1526 + 1.1527 +bool JavaThread::reguard_stack(address cur_sp) { 1.1528 + if (_stack_guard_state != stack_guard_yellow_disabled) { 1.1529 + return true; // Stack already guarded or guard pages not needed. 1.1530 + } 1.1531 + 1.1532 + if (register_stack_overflow()) { 1.1533 + // For those architectures which have separate register and 1.1534 + // memory stacks, we must check the register stack to see if 1.1535 + // it has overflowed. 1.1536 + return false; 1.1537 + } 1.1538 + 1.1539 + // Java code never executes within the yellow zone: the latter is only 1.1540 + // there to provoke an exception during stack banging. If java code 1.1541 + // is executing there, either StackShadowPages should be larger, or 1.1542 + // some exception code in c1, c2 or the interpreter isn't unwinding 1.1543 + // when it should. 1.1544 + guarantee(cur_sp > stack_yellow_zone_base(), "not enough space to reguard - increase StackShadowPages"); 1.1545 + 1.1546 + enable_stack_yellow_zone(); 1.1547 + return true; 1.1548 +} 1.1549 + 1.1550 +bool JavaThread::reguard_stack(void) { 1.1551 + return reguard_stack(os::current_stack_pointer()); 1.1552 +} 1.1553 + 1.1554 + 1.1555 +void JavaThread::block_if_vm_exited() { 1.1556 + if (_terminated == _vm_exited) { 1.1557 + // _vm_exited is set at safepoint, and Threads_lock is never released 1.1558 + // we will block here forever 1.1559 + Threads_lock->lock_without_safepoint_check(); 1.1560 + ShouldNotReachHere(); 1.1561 + } 1.1562 +} 1.1563 + 1.1564 + 1.1565 +// Remove this ifdef when C1 is ported to the compiler interface. 1.1566 +static void compiler_thread_entry(JavaThread* thread, TRAPS); 1.1567 + 1.1568 +JavaThread::JavaThread(ThreadFunction entry_point, size_t stack_sz) : 1.1569 + Thread() 1.1570 +#if INCLUDE_ALL_GCS 1.1571 + , _satb_mark_queue(&_satb_mark_queue_set), 1.1572 + _dirty_card_queue(&_dirty_card_queue_set) 1.1573 +#endif // INCLUDE_ALL_GCS 1.1574 +{ 1.1575 + if (TraceThreadEvents) { 1.1576 + tty->print_cr("creating thread %p", this); 1.1577 + } 1.1578 + initialize(); 1.1579 + _jni_attach_state = _not_attaching_via_jni; 1.1580 + set_entry_point(entry_point); 1.1581 + // Create the native thread itself. 1.1582 + // %note runtime_23 1.1583 + os::ThreadType thr_type = os::java_thread; 1.1584 + thr_type = entry_point == &compiler_thread_entry ? os::compiler_thread : 1.1585 + os::java_thread; 1.1586 + os::create_thread(this, thr_type, stack_sz); 1.1587 + _safepoint_visible = false; 1.1588 + // The _osthread may be NULL here because we ran out of memory (too many threads active). 1.1589 + // We need to throw and OutOfMemoryError - however we cannot do this here because the caller 1.1590 + // may hold a lock and all locks must be unlocked before throwing the exception (throwing 1.1591 + // the exception consists of creating the exception object & initializing it, initialization 1.1592 + // will leave the VM via a JavaCall and then all locks must be unlocked). 1.1593 + // 1.1594 + // The thread is still suspended when we reach here. Thread must be explicit started 1.1595 + // by creator! Furthermore, the thread must also explicitly be added to the Threads list 1.1596 + // by calling Threads:add. The reason why this is not done here, is because the thread 1.1597 + // object must be fully initialized (take a look at JVM_Start) 1.1598 +} 1.1599 + 1.1600 +JavaThread::~JavaThread() { 1.1601 + if (TraceThreadEvents) { 1.1602 + tty->print_cr("terminate thread %p", this); 1.1603 + } 1.1604 + 1.1605 + // By now, this thread should already be invisible to safepoint, 1.1606 + // and its per-thread recorder also collected. 1.1607 + assert(!is_safepoint_visible(), "wrong state"); 1.1608 +#if INCLUDE_NMT 1.1609 + assert(get_recorder() == NULL, "Already collected"); 1.1610 +#endif // INCLUDE_NMT 1.1611 + 1.1612 + // JSR166 -- return the parker to the free list 1.1613 + Parker::Release(_parker); 1.1614 + _parker = NULL ; 1.1615 + 1.1616 + // Free any remaining previous UnrollBlock 1.1617 + vframeArray* old_array = vframe_array_last(); 1.1618 + 1.1619 + if (old_array != NULL) { 1.1620 + Deoptimization::UnrollBlock* old_info = old_array->unroll_block(); 1.1621 + old_array->set_unroll_block(NULL); 1.1622 + delete old_info; 1.1623 + delete old_array; 1.1624 + } 1.1625 + 1.1626 + GrowableArray<jvmtiDeferredLocalVariableSet*>* deferred = deferred_locals(); 1.1627 + if (deferred != NULL) { 1.1628 + // This can only happen if thread is destroyed before deoptimization occurs. 1.1629 + assert(deferred->length() != 0, "empty array!"); 1.1630 + do { 1.1631 + jvmtiDeferredLocalVariableSet* dlv = deferred->at(0); 1.1632 + deferred->remove_at(0); 1.1633 + // individual jvmtiDeferredLocalVariableSet are CHeapObj's 1.1634 + delete dlv; 1.1635 + } while (deferred->length() != 0); 1.1636 + delete deferred; 1.1637 + } 1.1638 + 1.1639 + // All Java related clean up happens in exit 1.1640 + ThreadSafepointState::destroy(this); 1.1641 + if (_thread_profiler != NULL) delete _thread_profiler; 1.1642 + if (_thread_stat != NULL) delete _thread_stat; 1.1643 +} 1.1644 + 1.1645 + 1.1646 +// The first routine called by a new Java thread 1.1647 +void JavaThread::run() { 1.1648 + // initialize thread-local alloc buffer related fields 1.1649 + this->initialize_tlab(); 1.1650 + 1.1651 + // used to test validitity of stack trace backs 1.1652 + this->record_base_of_stack_pointer(); 1.1653 + 1.1654 + // Record real stack base and size. 1.1655 + this->record_stack_base_and_size(); 1.1656 + 1.1657 + // Initialize thread local storage; set before calling MutexLocker 1.1658 + this->initialize_thread_local_storage(); 1.1659 + 1.1660 + this->create_stack_guard_pages(); 1.1661 + 1.1662 + this->cache_global_variables(); 1.1663 + 1.1664 + // Thread is now sufficient initialized to be handled by the safepoint code as being 1.1665 + // in the VM. Change thread state from _thread_new to _thread_in_vm 1.1666 + ThreadStateTransition::transition_and_fence(this, _thread_new, _thread_in_vm); 1.1667 + 1.1668 + assert(JavaThread::current() == this, "sanity check"); 1.1669 + assert(!Thread::current()->owns_locks(), "sanity check"); 1.1670 + 1.1671 + DTRACE_THREAD_PROBE(start, this); 1.1672 + 1.1673 + // This operation might block. We call that after all safepoint checks for a new thread has 1.1674 + // been completed. 1.1675 + this->set_active_handles(JNIHandleBlock::allocate_block()); 1.1676 + 1.1677 + if (JvmtiExport::should_post_thread_life()) { 1.1678 + JvmtiExport::post_thread_start(this); 1.1679 + } 1.1680 + 1.1681 + EventThreadStart event; 1.1682 + if (event.should_commit()) { 1.1683 + event.set_javalangthread(java_lang_Thread::thread_id(this->threadObj())); 1.1684 + event.commit(); 1.1685 + } 1.1686 + 1.1687 + // We call another function to do the rest so we are sure that the stack addresses used 1.1688 + // from there will be lower than the stack base just computed 1.1689 + thread_main_inner(); 1.1690 + 1.1691 + // Note, thread is no longer valid at this point! 1.1692 +} 1.1693 + 1.1694 + 1.1695 +void JavaThread::thread_main_inner() { 1.1696 + assert(JavaThread::current() == this, "sanity check"); 1.1697 + assert(this->threadObj() != NULL, "just checking"); 1.1698 + 1.1699 + // Execute thread entry point unless this thread has a pending exception 1.1700 + // or has been stopped before starting. 1.1701 + // Note: Due to JVM_StopThread we can have pending exceptions already! 1.1702 + if (!this->has_pending_exception() && 1.1703 + !java_lang_Thread::is_stillborn(this->threadObj())) { 1.1704 + { 1.1705 + ResourceMark rm(this); 1.1706 + this->set_native_thread_name(this->get_thread_name()); 1.1707 + } 1.1708 + HandleMark hm(this); 1.1709 + this->entry_point()(this, this); 1.1710 + } 1.1711 + 1.1712 + DTRACE_THREAD_PROBE(stop, this); 1.1713 + 1.1714 + this->exit(false); 1.1715 + delete this; 1.1716 +} 1.1717 + 1.1718 + 1.1719 +static void ensure_join(JavaThread* thread) { 1.1720 + // We do not need to grap the Threads_lock, since we are operating on ourself. 1.1721 + Handle threadObj(thread, thread->threadObj()); 1.1722 + assert(threadObj.not_null(), "java thread object must exist"); 1.1723 + ObjectLocker lock(threadObj, thread); 1.1724 + // Ignore pending exception (ThreadDeath), since we are exiting anyway 1.1725 + thread->clear_pending_exception(); 1.1726 + // Thread is exiting. So set thread_status field in java.lang.Thread class to TERMINATED. 1.1727 + java_lang_Thread::set_thread_status(threadObj(), java_lang_Thread::TERMINATED); 1.1728 + // Clear the native thread instance - this makes isAlive return false and allows the join() 1.1729 + // to complete once we've done the notify_all below 1.1730 + java_lang_Thread::set_thread(threadObj(), NULL); 1.1731 + lock.notify_all(thread); 1.1732 + // Ignore pending exception (ThreadDeath), since we are exiting anyway 1.1733 + thread->clear_pending_exception(); 1.1734 +} 1.1735 + 1.1736 + 1.1737 +// For any new cleanup additions, please check to see if they need to be applied to 1.1738 +// cleanup_failed_attach_current_thread as well. 1.1739 +void JavaThread::exit(bool destroy_vm, ExitType exit_type) { 1.1740 + assert(this == JavaThread::current(), "thread consistency check"); 1.1741 + 1.1742 + HandleMark hm(this); 1.1743 + Handle uncaught_exception(this, this->pending_exception()); 1.1744 + this->clear_pending_exception(); 1.1745 + Handle threadObj(this, this->threadObj()); 1.1746 + assert(threadObj.not_null(), "Java thread object should be created"); 1.1747 + 1.1748 + if (get_thread_profiler() != NULL) { 1.1749 + get_thread_profiler()->disengage(); 1.1750 + ResourceMark rm; 1.1751 + get_thread_profiler()->print(get_thread_name()); 1.1752 + } 1.1753 + 1.1754 + 1.1755 + // FIXIT: This code should be moved into else part, when reliable 1.2/1.3 check is in place 1.1756 + { 1.1757 + EXCEPTION_MARK; 1.1758 + 1.1759 + CLEAR_PENDING_EXCEPTION; 1.1760 + } 1.1761 + // FIXIT: The is_null check is only so it works better on JDK1.2 VM's. This 1.1762 + // has to be fixed by a runtime query method 1.1763 + if (!destroy_vm || JDK_Version::is_jdk12x_version()) { 1.1764 + // JSR-166: change call from from ThreadGroup.uncaughtException to 1.1765 + // java.lang.Thread.dispatchUncaughtException 1.1766 + if (uncaught_exception.not_null()) { 1.1767 + Handle group(this, java_lang_Thread::threadGroup(threadObj())); 1.1768 + { 1.1769 + EXCEPTION_MARK; 1.1770 + // Check if the method Thread.dispatchUncaughtException() exists. If so 1.1771 + // call it. Otherwise we have an older library without the JSR-166 changes, 1.1772 + // so call ThreadGroup.uncaughtException() 1.1773 + KlassHandle recvrKlass(THREAD, threadObj->klass()); 1.1774 + CallInfo callinfo; 1.1775 + KlassHandle thread_klass(THREAD, SystemDictionary::Thread_klass()); 1.1776 + LinkResolver::resolve_virtual_call(callinfo, threadObj, recvrKlass, thread_klass, 1.1777 + vmSymbols::dispatchUncaughtException_name(), 1.1778 + vmSymbols::throwable_void_signature(), 1.1779 + KlassHandle(), false, false, THREAD); 1.1780 + CLEAR_PENDING_EXCEPTION; 1.1781 + methodHandle method = callinfo.selected_method(); 1.1782 + if (method.not_null()) { 1.1783 + JavaValue result(T_VOID); 1.1784 + JavaCalls::call_virtual(&result, 1.1785 + threadObj, thread_klass, 1.1786 + vmSymbols::dispatchUncaughtException_name(), 1.1787 + vmSymbols::throwable_void_signature(), 1.1788 + uncaught_exception, 1.1789 + THREAD); 1.1790 + } else { 1.1791 + KlassHandle thread_group(THREAD, SystemDictionary::ThreadGroup_klass()); 1.1792 + JavaValue result(T_VOID); 1.1793 + JavaCalls::call_virtual(&result, 1.1794 + group, thread_group, 1.1795 + vmSymbols::uncaughtException_name(), 1.1796 + vmSymbols::thread_throwable_void_signature(), 1.1797 + threadObj, // Arg 1 1.1798 + uncaught_exception, // Arg 2 1.1799 + THREAD); 1.1800 + } 1.1801 + if (HAS_PENDING_EXCEPTION) { 1.1802 + ResourceMark rm(this); 1.1803 + jio_fprintf(defaultStream::error_stream(), 1.1804 + "\nException: %s thrown from the UncaughtExceptionHandler" 1.1805 + " in thread \"%s\"\n", 1.1806 + pending_exception()->klass()->external_name(), 1.1807 + get_thread_name()); 1.1808 + CLEAR_PENDING_EXCEPTION; 1.1809 + } 1.1810 + } 1.1811 + } 1.1812 + 1.1813 + // Called before the java thread exit since we want to read info 1.1814 + // from java_lang_Thread object 1.1815 + EventThreadEnd event; 1.1816 + if (event.should_commit()) { 1.1817 + event.set_javalangthread(java_lang_Thread::thread_id(this->threadObj())); 1.1818 + event.commit(); 1.1819 + } 1.1820 + 1.1821 + // Call after last event on thread 1.1822 + EVENT_THREAD_EXIT(this); 1.1823 + 1.1824 + // Call Thread.exit(). We try 3 times in case we got another Thread.stop during 1.1825 + // the execution of the method. If that is not enough, then we don't really care. Thread.stop 1.1826 + // is deprecated anyhow. 1.1827 + if (!is_Compiler_thread()) { 1.1828 + int count = 3; 1.1829 + while (java_lang_Thread::threadGroup(threadObj()) != NULL && (count-- > 0)) { 1.1830 + EXCEPTION_MARK; 1.1831 + JavaValue result(T_VOID); 1.1832 + KlassHandle thread_klass(THREAD, SystemDictionary::Thread_klass()); 1.1833 + JavaCalls::call_virtual(&result, 1.1834 + threadObj, thread_klass, 1.1835 + vmSymbols::exit_method_name(), 1.1836 + vmSymbols::void_method_signature(), 1.1837 + THREAD); 1.1838 + CLEAR_PENDING_EXCEPTION; 1.1839 + } 1.1840 + } 1.1841 + // notify JVMTI 1.1842 + if (JvmtiExport::should_post_thread_life()) { 1.1843 + JvmtiExport::post_thread_end(this); 1.1844 + } 1.1845 + 1.1846 + // We have notified the agents that we are exiting, before we go on, 1.1847 + // we must check for a pending external suspend request and honor it 1.1848 + // in order to not surprise the thread that made the suspend request. 1.1849 + while (true) { 1.1850 + { 1.1851 + MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag); 1.1852 + if (!is_external_suspend()) { 1.1853 + set_terminated(_thread_exiting); 1.1854 + ThreadService::current_thread_exiting(this); 1.1855 + break; 1.1856 + } 1.1857 + // Implied else: 1.1858 + // Things get a little tricky here. We have a pending external 1.1859 + // suspend request, but we are holding the SR_lock so we 1.1860 + // can't just self-suspend. So we temporarily drop the lock 1.1861 + // and then self-suspend. 1.1862 + } 1.1863 + 1.1864 + ThreadBlockInVM tbivm(this); 1.1865 + java_suspend_self(); 1.1866 + 1.1867 + // We're done with this suspend request, but we have to loop around 1.1868 + // and check again. Eventually we will get SR_lock without a pending 1.1869 + // external suspend request and will be able to mark ourselves as 1.1870 + // exiting. 1.1871 + } 1.1872 + // no more external suspends are allowed at this point 1.1873 + } else { 1.1874 + // before_exit() has already posted JVMTI THREAD_END events 1.1875 + } 1.1876 + 1.1877 + // Notify waiters on thread object. This has to be done after exit() is called 1.1878 + // on the thread (if the thread is the last thread in a daemon ThreadGroup the 1.1879 + // group should have the destroyed bit set before waiters are notified). 1.1880 + ensure_join(this); 1.1881 + assert(!this->has_pending_exception(), "ensure_join should have cleared"); 1.1882 + 1.1883 + // 6282335 JNI DetachCurrentThread spec states that all Java monitors 1.1884 + // held by this thread must be released. A detach operation must only 1.1885 + // get here if there are no Java frames on the stack. Therefore, any 1.1886 + // owned monitors at this point MUST be JNI-acquired monitors which are 1.1887 + // pre-inflated and in the monitor cache. 1.1888 + // 1.1889 + // ensure_join() ignores IllegalThreadStateExceptions, and so does this. 1.1890 + if (exit_type == jni_detach && JNIDetachReleasesMonitors) { 1.1891 + assert(!this->has_last_Java_frame(), "detaching with Java frames?"); 1.1892 + ObjectSynchronizer::release_monitors_owned_by_thread(this); 1.1893 + assert(!this->has_pending_exception(), "release_monitors should have cleared"); 1.1894 + } 1.1895 + 1.1896 + // These things needs to be done while we are still a Java Thread. Make sure that thread 1.1897 + // is in a consistent state, in case GC happens 1.1898 + assert(_privileged_stack_top == NULL, "must be NULL when we get here"); 1.1899 + 1.1900 + if (active_handles() != NULL) { 1.1901 + JNIHandleBlock* block = active_handles(); 1.1902 + set_active_handles(NULL); 1.1903 + JNIHandleBlock::release_block(block); 1.1904 + } 1.1905 + 1.1906 + if (free_handle_block() != NULL) { 1.1907 + JNIHandleBlock* block = free_handle_block(); 1.1908 + set_free_handle_block(NULL); 1.1909 + JNIHandleBlock::release_block(block); 1.1910 + } 1.1911 + 1.1912 + // These have to be removed while this is still a valid thread. 1.1913 + remove_stack_guard_pages(); 1.1914 + 1.1915 + if (UseTLAB) { 1.1916 + tlab().make_parsable(true); // retire TLAB 1.1917 + } 1.1918 + 1.1919 + if (JvmtiEnv::environments_might_exist()) { 1.1920 + JvmtiExport::cleanup_thread(this); 1.1921 + } 1.1922 + 1.1923 + // We must flush any deferred card marks before removing a thread from 1.1924 + // the list of active threads. 1.1925 + Universe::heap()->flush_deferred_store_barrier(this); 1.1926 + assert(deferred_card_mark().is_empty(), "Should have been flushed"); 1.1927 + 1.1928 +#if INCLUDE_ALL_GCS 1.1929 + // We must flush the G1-related buffers before removing a thread 1.1930 + // from the list of active threads. We must do this after any deferred 1.1931 + // card marks have been flushed (above) so that any entries that are 1.1932 + // added to the thread's dirty card queue as a result are not lost. 1.1933 + if (UseG1GC) { 1.1934 + flush_barrier_queues(); 1.1935 + } 1.1936 +#endif // INCLUDE_ALL_GCS 1.1937 + 1.1938 + // Remove from list of active threads list, and notify VM thread if we are the last non-daemon thread 1.1939 + Threads::remove(this); 1.1940 +} 1.1941 + 1.1942 +#if INCLUDE_ALL_GCS 1.1943 +// Flush G1-related queues. 1.1944 +void JavaThread::flush_barrier_queues() { 1.1945 + satb_mark_queue().flush(); 1.1946 + dirty_card_queue().flush(); 1.1947 +} 1.1948 + 1.1949 +void JavaThread::initialize_queues() { 1.1950 + assert(!SafepointSynchronize::is_at_safepoint(), 1.1951 + "we should not be at a safepoint"); 1.1952 + 1.1953 + ObjPtrQueue& satb_queue = satb_mark_queue(); 1.1954 + SATBMarkQueueSet& satb_queue_set = satb_mark_queue_set(); 1.1955 + // The SATB queue should have been constructed with its active 1.1956 + // field set to false. 1.1957 + assert(!satb_queue.is_active(), "SATB queue should not be active"); 1.1958 + assert(satb_queue.is_empty(), "SATB queue should be empty"); 1.1959 + // If we are creating the thread during a marking cycle, we should 1.1960 + // set the active field of the SATB queue to true. 1.1961 + if (satb_queue_set.is_active()) { 1.1962 + satb_queue.set_active(true); 1.1963 + } 1.1964 + 1.1965 + DirtyCardQueue& dirty_queue = dirty_card_queue(); 1.1966 + // The dirty card queue should have been constructed with its 1.1967 + // active field set to true. 1.1968 + assert(dirty_queue.is_active(), "dirty card queue should be active"); 1.1969 +} 1.1970 +#endif // INCLUDE_ALL_GCS 1.1971 + 1.1972 +void JavaThread::cleanup_failed_attach_current_thread() { 1.1973 + if (get_thread_profiler() != NULL) { 1.1974 + get_thread_profiler()->disengage(); 1.1975 + ResourceMark rm; 1.1976 + get_thread_profiler()->print(get_thread_name()); 1.1977 + } 1.1978 + 1.1979 + if (active_handles() != NULL) { 1.1980 + JNIHandleBlock* block = active_handles(); 1.1981 + set_active_handles(NULL); 1.1982 + JNIHandleBlock::release_block(block); 1.1983 + } 1.1984 + 1.1985 + if (free_handle_block() != NULL) { 1.1986 + JNIHandleBlock* block = free_handle_block(); 1.1987 + set_free_handle_block(NULL); 1.1988 + JNIHandleBlock::release_block(block); 1.1989 + } 1.1990 + 1.1991 + // These have to be removed while this is still a valid thread. 1.1992 + remove_stack_guard_pages(); 1.1993 + 1.1994 + if (UseTLAB) { 1.1995 + tlab().make_parsable(true); // retire TLAB, if any 1.1996 + } 1.1997 + 1.1998 +#if INCLUDE_ALL_GCS 1.1999 + if (UseG1GC) { 1.2000 + flush_barrier_queues(); 1.2001 + } 1.2002 +#endif // INCLUDE_ALL_GCS 1.2003 + 1.2004 + Threads::remove(this); 1.2005 + delete this; 1.2006 +} 1.2007 + 1.2008 + 1.2009 + 1.2010 + 1.2011 +JavaThread* JavaThread::active() { 1.2012 + Thread* thread = ThreadLocalStorage::thread(); 1.2013 + assert(thread != NULL, "just checking"); 1.2014 + if (thread->is_Java_thread()) { 1.2015 + return (JavaThread*) thread; 1.2016 + } else { 1.2017 + assert(thread->is_VM_thread(), "this must be a vm thread"); 1.2018 + VM_Operation* op = ((VMThread*) thread)->vm_operation(); 1.2019 + JavaThread *ret=op == NULL ? NULL : (JavaThread *)op->calling_thread(); 1.2020 + assert(ret->is_Java_thread(), "must be a Java thread"); 1.2021 + return ret; 1.2022 + } 1.2023 +} 1.2024 + 1.2025 +bool JavaThread::is_lock_owned(address adr) const { 1.2026 + if (Thread::is_lock_owned(adr)) return true; 1.2027 + 1.2028 + for (MonitorChunk* chunk = monitor_chunks(); chunk != NULL; chunk = chunk->next()) { 1.2029 + if (chunk->contains(adr)) return true; 1.2030 + } 1.2031 + 1.2032 + return false; 1.2033 +} 1.2034 + 1.2035 + 1.2036 +void JavaThread::add_monitor_chunk(MonitorChunk* chunk) { 1.2037 + chunk->set_next(monitor_chunks()); 1.2038 + set_monitor_chunks(chunk); 1.2039 +} 1.2040 + 1.2041 +void JavaThread::remove_monitor_chunk(MonitorChunk* chunk) { 1.2042 + guarantee(monitor_chunks() != NULL, "must be non empty"); 1.2043 + if (monitor_chunks() == chunk) { 1.2044 + set_monitor_chunks(chunk->next()); 1.2045 + } else { 1.2046 + MonitorChunk* prev = monitor_chunks(); 1.2047 + while (prev->next() != chunk) prev = prev->next(); 1.2048 + prev->set_next(chunk->next()); 1.2049 + } 1.2050 +} 1.2051 + 1.2052 +// JVM support. 1.2053 + 1.2054 +// Note: this function shouldn't block if it's called in 1.2055 +// _thread_in_native_trans state (such as from 1.2056 +// check_special_condition_for_native_trans()). 1.2057 +void JavaThread::check_and_handle_async_exceptions(bool check_unsafe_error) { 1.2058 + 1.2059 + if (has_last_Java_frame() && has_async_condition()) { 1.2060 + // If we are at a polling page safepoint (not a poll return) 1.2061 + // then we must defer async exception because live registers 1.2062 + // will be clobbered by the exception path. Poll return is 1.2063 + // ok because the call we a returning from already collides 1.2064 + // with exception handling registers and so there is no issue. 1.2065 + // (The exception handling path kills call result registers but 1.2066 + // this is ok since the exception kills the result anyway). 1.2067 + 1.2068 + if (is_at_poll_safepoint()) { 1.2069 + // if the code we are returning to has deoptimized we must defer 1.2070 + // the exception otherwise live registers get clobbered on the 1.2071 + // exception path before deoptimization is able to retrieve them. 1.2072 + // 1.2073 + RegisterMap map(this, false); 1.2074 + frame caller_fr = last_frame().sender(&map); 1.2075 + assert(caller_fr.is_compiled_frame(), "what?"); 1.2076 + if (caller_fr.is_deoptimized_frame()) { 1.2077 + if (TraceExceptions) { 1.2078 + ResourceMark rm; 1.2079 + tty->print_cr("deferred async exception at compiled safepoint"); 1.2080 + } 1.2081 + return; 1.2082 + } 1.2083 + } 1.2084 + } 1.2085 + 1.2086 + JavaThread::AsyncRequests condition = clear_special_runtime_exit_condition(); 1.2087 + if (condition == _no_async_condition) { 1.2088 + // Conditions have changed since has_special_runtime_exit_condition() 1.2089 + // was called: 1.2090 + // - if we were here only because of an external suspend request, 1.2091 + // then that was taken care of above (or cancelled) so we are done 1.2092 + // - if we were here because of another async request, then it has 1.2093 + // been cleared between the has_special_runtime_exit_condition() 1.2094 + // and now so again we are done 1.2095 + return; 1.2096 + } 1.2097 + 1.2098 + // Check for pending async. exception 1.2099 + if (_pending_async_exception != NULL) { 1.2100 + // Only overwrite an already pending exception, if it is not a threadDeath. 1.2101 + if (!has_pending_exception() || !pending_exception()->is_a(SystemDictionary::ThreadDeath_klass())) { 1.2102 + 1.2103 + // We cannot call Exceptions::_throw(...) here because we cannot block 1.2104 + set_pending_exception(_pending_async_exception, __FILE__, __LINE__); 1.2105 + 1.2106 + if (TraceExceptions) { 1.2107 + ResourceMark rm; 1.2108 + tty->print("Async. exception installed at runtime exit (" INTPTR_FORMAT ")", this); 1.2109 + if (has_last_Java_frame() ) { 1.2110 + frame f = last_frame(); 1.2111 + tty->print(" (pc: " INTPTR_FORMAT " sp: " INTPTR_FORMAT " )", f.pc(), f.sp()); 1.2112 + } 1.2113 + tty->print_cr(" of type: %s", InstanceKlass::cast(_pending_async_exception->klass())->external_name()); 1.2114 + } 1.2115 + _pending_async_exception = NULL; 1.2116 + clear_has_async_exception(); 1.2117 + } 1.2118 + } 1.2119 + 1.2120 + if (check_unsafe_error && 1.2121 + condition == _async_unsafe_access_error && !has_pending_exception()) { 1.2122 + condition = _no_async_condition; // done 1.2123 + switch (thread_state()) { 1.2124 + case _thread_in_vm: 1.2125 + { 1.2126 + JavaThread* THREAD = this; 1.2127 + THROW_MSG(vmSymbols::java_lang_InternalError(), "a fault occurred in an unsafe memory access operation"); 1.2128 + } 1.2129 + case _thread_in_native: 1.2130 + { 1.2131 + ThreadInVMfromNative tiv(this); 1.2132 + JavaThread* THREAD = this; 1.2133 + THROW_MSG(vmSymbols::java_lang_InternalError(), "a fault occurred in an unsafe memory access operation"); 1.2134 + } 1.2135 + case _thread_in_Java: 1.2136 + { 1.2137 + ThreadInVMfromJava tiv(this); 1.2138 + JavaThread* THREAD = this; 1.2139 + THROW_MSG(vmSymbols::java_lang_InternalError(), "a fault occurred in a recent unsafe memory access operation in compiled Java code"); 1.2140 + } 1.2141 + default: 1.2142 + ShouldNotReachHere(); 1.2143 + } 1.2144 + } 1.2145 + 1.2146 + assert(condition == _no_async_condition || has_pending_exception() || 1.2147 + (!check_unsafe_error && condition == _async_unsafe_access_error), 1.2148 + "must have handled the async condition, if no exception"); 1.2149 +} 1.2150 + 1.2151 +void JavaThread::handle_special_runtime_exit_condition(bool check_asyncs) { 1.2152 + // 1.2153 + // Check for pending external suspend. Internal suspend requests do 1.2154 + // not use handle_special_runtime_exit_condition(). 1.2155 + // If JNIEnv proxies are allowed, don't self-suspend if the target 1.2156 + // thread is not the current thread. In older versions of jdbx, jdbx 1.2157 + // threads could call into the VM with another thread's JNIEnv so we 1.2158 + // can be here operating on behalf of a suspended thread (4432884). 1.2159 + bool do_self_suspend = is_external_suspend_with_lock(); 1.2160 + if (do_self_suspend && (!AllowJNIEnvProxy || this == JavaThread::current())) { 1.2161 + // 1.2162 + // Because thread is external suspended the safepoint code will count 1.2163 + // thread as at a safepoint. This can be odd because we can be here 1.2164 + // as _thread_in_Java which would normally transition to _thread_blocked 1.2165 + // at a safepoint. We would like to mark the thread as _thread_blocked 1.2166 + // before calling java_suspend_self like all other callers of it but 1.2167 + // we must then observe proper safepoint protocol. (We can't leave 1.2168 + // _thread_blocked with a safepoint in progress). However we can be 1.2169 + // here as _thread_in_native_trans so we can't use a normal transition 1.2170 + // constructor/destructor pair because they assert on that type of 1.2171 + // transition. We could do something like: 1.2172 + // 1.2173 + // JavaThreadState state = thread_state(); 1.2174 + // set_thread_state(_thread_in_vm); 1.2175 + // { 1.2176 + // ThreadBlockInVM tbivm(this); 1.2177 + // java_suspend_self() 1.2178 + // } 1.2179 + // set_thread_state(_thread_in_vm_trans); 1.2180 + // if (safepoint) block; 1.2181 + // set_thread_state(state); 1.2182 + // 1.2183 + // but that is pretty messy. Instead we just go with the way the 1.2184 + // code has worked before and note that this is the only path to 1.2185 + // java_suspend_self that doesn't put the thread in _thread_blocked 1.2186 + // mode. 1.2187 + 1.2188 + frame_anchor()->make_walkable(this); 1.2189 + java_suspend_self(); 1.2190 + 1.2191 + // We might be here for reasons in addition to the self-suspend request 1.2192 + // so check for other async requests. 1.2193 + } 1.2194 + 1.2195 + if (check_asyncs) { 1.2196 + check_and_handle_async_exceptions(); 1.2197 + } 1.2198 +} 1.2199 + 1.2200 +void JavaThread::send_thread_stop(oop java_throwable) { 1.2201 + assert(Thread::current()->is_VM_thread(), "should be in the vm thread"); 1.2202 + assert(Threads_lock->is_locked(), "Threads_lock should be locked by safepoint code"); 1.2203 + assert(SafepointSynchronize::is_at_safepoint(), "all threads are stopped"); 1.2204 + 1.2205 + // Do not throw asynchronous exceptions against the compiler thread 1.2206 + // (the compiler thread should not be a Java thread -- fix in 1.4.2) 1.2207 + if (is_Compiler_thread()) return; 1.2208 + 1.2209 + { 1.2210 + // Actually throw the Throwable against the target Thread - however 1.2211 + // only if there is no thread death exception installed already. 1.2212 + if (_pending_async_exception == NULL || !_pending_async_exception->is_a(SystemDictionary::ThreadDeath_klass())) { 1.2213 + // If the topmost frame is a runtime stub, then we are calling into 1.2214 + // OptoRuntime from compiled code. Some runtime stubs (new, monitor_exit..) 1.2215 + // must deoptimize the caller before continuing, as the compiled exception handler table 1.2216 + // may not be valid 1.2217 + if (has_last_Java_frame()) { 1.2218 + frame f = last_frame(); 1.2219 + if (f.is_runtime_frame() || f.is_safepoint_blob_frame()) { 1.2220 + // BiasedLocking needs an updated RegisterMap for the revoke monitors pass 1.2221 + RegisterMap reg_map(this, UseBiasedLocking); 1.2222 + frame compiled_frame = f.sender(®_map); 1.2223 + if (!StressCompiledExceptionHandlers && compiled_frame.can_be_deoptimized()) { 1.2224 + Deoptimization::deoptimize(this, compiled_frame, ®_map); 1.2225 + } 1.2226 + } 1.2227 + } 1.2228 + 1.2229 + // Set async. pending exception in thread. 1.2230 + set_pending_async_exception(java_throwable); 1.2231 + 1.2232 + if (TraceExceptions) { 1.2233 + ResourceMark rm; 1.2234 + tty->print_cr("Pending Async. exception installed of type: %s", InstanceKlass::cast(_pending_async_exception->klass())->external_name()); 1.2235 + } 1.2236 + // for AbortVMOnException flag 1.2237 + NOT_PRODUCT(Exceptions::debug_check_abort(InstanceKlass::cast(_pending_async_exception->klass())->external_name())); 1.2238 + } 1.2239 + } 1.2240 + 1.2241 + 1.2242 + // Interrupt thread so it will wake up from a potential wait() 1.2243 + Thread::interrupt(this); 1.2244 +} 1.2245 + 1.2246 +// External suspension mechanism. 1.2247 +// 1.2248 +// Tell the VM to suspend a thread when ever it knows that it does not hold on 1.2249 +// to any VM_locks and it is at a transition 1.2250 +// Self-suspension will happen on the transition out of the vm. 1.2251 +// Catch "this" coming in from JNIEnv pointers when the thread has been freed 1.2252 +// 1.2253 +// Guarantees on return: 1.2254 +// + Target thread will not execute any new bytecode (that's why we need to 1.2255 +// force a safepoint) 1.2256 +// + Target thread will not enter any new monitors 1.2257 +// 1.2258 +void JavaThread::java_suspend() { 1.2259 + { MutexLocker mu(Threads_lock); 1.2260 + if (!Threads::includes(this) || is_exiting() || this->threadObj() == NULL) { 1.2261 + return; 1.2262 + } 1.2263 + } 1.2264 + 1.2265 + { MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag); 1.2266 + if (!is_external_suspend()) { 1.2267 + // a racing resume has cancelled us; bail out now 1.2268 + return; 1.2269 + } 1.2270 + 1.2271 + // suspend is done 1.2272 + uint32_t debug_bits = 0; 1.2273 + // Warning: is_ext_suspend_completed() may temporarily drop the 1.2274 + // SR_lock to allow the thread to reach a stable thread state if 1.2275 + // it is currently in a transient thread state. 1.2276 + if (is_ext_suspend_completed(false /* !called_by_wait */, 1.2277 + SuspendRetryDelay, &debug_bits) ) { 1.2278 + return; 1.2279 + } 1.2280 + } 1.2281 + 1.2282 + VM_ForceSafepoint vm_suspend; 1.2283 + VMThread::execute(&vm_suspend); 1.2284 +} 1.2285 + 1.2286 +// Part II of external suspension. 1.2287 +// A JavaThread self suspends when it detects a pending external suspend 1.2288 +// request. This is usually on transitions. It is also done in places 1.2289 +// where continuing to the next transition would surprise the caller, 1.2290 +// e.g., monitor entry. 1.2291 +// 1.2292 +// Returns the number of times that the thread self-suspended. 1.2293 +// 1.2294 +// Note: DO NOT call java_suspend_self() when you just want to block current 1.2295 +// thread. java_suspend_self() is the second stage of cooperative 1.2296 +// suspension for external suspend requests and should only be used 1.2297 +// to complete an external suspend request. 1.2298 +// 1.2299 +int JavaThread::java_suspend_self() { 1.2300 + int ret = 0; 1.2301 + 1.2302 + // we are in the process of exiting so don't suspend 1.2303 + if (is_exiting()) { 1.2304 + clear_external_suspend(); 1.2305 + return ret; 1.2306 + } 1.2307 + 1.2308 + assert(_anchor.walkable() || 1.2309 + (is_Java_thread() && !((JavaThread*)this)->has_last_Java_frame()), 1.2310 + "must have walkable stack"); 1.2311 + 1.2312 + MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag); 1.2313 + 1.2314 + assert(!this->is_ext_suspended(), 1.2315 + "a thread trying to self-suspend should not already be suspended"); 1.2316 + 1.2317 + if (this->is_suspend_equivalent()) { 1.2318 + // If we are self-suspending as a result of the lifting of a 1.2319 + // suspend equivalent condition, then the suspend_equivalent 1.2320 + // flag is not cleared until we set the ext_suspended flag so 1.2321 + // that wait_for_ext_suspend_completion() returns consistent 1.2322 + // results. 1.2323 + this->clear_suspend_equivalent(); 1.2324 + } 1.2325 + 1.2326 + // A racing resume may have cancelled us before we grabbed SR_lock 1.2327 + // above. Or another external suspend request could be waiting for us 1.2328 + // by the time we return from SR_lock()->wait(). The thread 1.2329 + // that requested the suspension may already be trying to walk our 1.2330 + // stack and if we return now, we can change the stack out from under 1.2331 + // it. This would be a "bad thing (TM)" and cause the stack walker 1.2332 + // to crash. We stay self-suspended until there are no more pending 1.2333 + // external suspend requests. 1.2334 + while (is_external_suspend()) { 1.2335 + ret++; 1.2336 + this->set_ext_suspended(); 1.2337 + 1.2338 + // _ext_suspended flag is cleared by java_resume() 1.2339 + while (is_ext_suspended()) { 1.2340 + this->SR_lock()->wait(Mutex::_no_safepoint_check_flag); 1.2341 + } 1.2342 + } 1.2343 + 1.2344 + return ret; 1.2345 +} 1.2346 + 1.2347 +#ifdef ASSERT 1.2348 +// verify the JavaThread has not yet been published in the Threads::list, and 1.2349 +// hence doesn't need protection from concurrent access at this stage 1.2350 +void JavaThread::verify_not_published() { 1.2351 + if (!Threads_lock->owned_by_self()) { 1.2352 + MutexLockerEx ml(Threads_lock, Mutex::_no_safepoint_check_flag); 1.2353 + assert( !Threads::includes(this), 1.2354 + "java thread shouldn't have been published yet!"); 1.2355 + } 1.2356 + else { 1.2357 + assert( !Threads::includes(this), 1.2358 + "java thread shouldn't have been published yet!"); 1.2359 + } 1.2360 +} 1.2361 +#endif 1.2362 + 1.2363 +// Slow path when the native==>VM/Java barriers detect a safepoint is in 1.2364 +// progress or when _suspend_flags is non-zero. 1.2365 +// Current thread needs to self-suspend if there is a suspend request and/or 1.2366 +// block if a safepoint is in progress. 1.2367 +// Async exception ISN'T checked. 1.2368 +// Note only the ThreadInVMfromNative transition can call this function 1.2369 +// directly and when thread state is _thread_in_native_trans 1.2370 +void JavaThread::check_safepoint_and_suspend_for_native_trans(JavaThread *thread) { 1.2371 + assert(thread->thread_state() == _thread_in_native_trans, "wrong state"); 1.2372 + 1.2373 + JavaThread *curJT = JavaThread::current(); 1.2374 + bool do_self_suspend = thread->is_external_suspend(); 1.2375 + 1.2376 + assert(!curJT->has_last_Java_frame() || curJT->frame_anchor()->walkable(), "Unwalkable stack in native->vm transition"); 1.2377 + 1.2378 + // If JNIEnv proxies are allowed, don't self-suspend if the target 1.2379 + // thread is not the current thread. In older versions of jdbx, jdbx 1.2380 + // threads could call into the VM with another thread's JNIEnv so we 1.2381 + // can be here operating on behalf of a suspended thread (4432884). 1.2382 + if (do_self_suspend && (!AllowJNIEnvProxy || curJT == thread)) { 1.2383 + JavaThreadState state = thread->thread_state(); 1.2384 + 1.2385 + // We mark this thread_blocked state as a suspend-equivalent so 1.2386 + // that a caller to is_ext_suspend_completed() won't be confused. 1.2387 + // The suspend-equivalent state is cleared by java_suspend_self(). 1.2388 + thread->set_suspend_equivalent(); 1.2389 + 1.2390 + // If the safepoint code sees the _thread_in_native_trans state, it will 1.2391 + // wait until the thread changes to other thread state. There is no 1.2392 + // guarantee on how soon we can obtain the SR_lock and complete the 1.2393 + // self-suspend request. It would be a bad idea to let safepoint wait for 1.2394 + // too long. Temporarily change the state to _thread_blocked to 1.2395 + // let the VM thread know that this thread is ready for GC. The problem 1.2396 + // of changing thread state is that safepoint could happen just after 1.2397 + // java_suspend_self() returns after being resumed, and VM thread will 1.2398 + // see the _thread_blocked state. We must check for safepoint 1.2399 + // after restoring the state and make sure we won't leave while a safepoint 1.2400 + // is in progress. 1.2401 + thread->set_thread_state(_thread_blocked); 1.2402 + thread->java_suspend_self(); 1.2403 + thread->set_thread_state(state); 1.2404 + // Make sure new state is seen by VM thread 1.2405 + if (os::is_MP()) { 1.2406 + if (UseMembar) { 1.2407 + // Force a fence between the write above and read below 1.2408 + OrderAccess::fence(); 1.2409 + } else { 1.2410 + // Must use this rather than serialization page in particular on Windows 1.2411 + InterfaceSupport::serialize_memory(thread); 1.2412 + } 1.2413 + } 1.2414 + } 1.2415 + 1.2416 + if (SafepointSynchronize::do_call_back()) { 1.2417 + // If we are safepointing, then block the caller which may not be 1.2418 + // the same as the target thread (see above). 1.2419 + SafepointSynchronize::block(curJT); 1.2420 + } 1.2421 + 1.2422 + if (thread->is_deopt_suspend()) { 1.2423 + thread->clear_deopt_suspend(); 1.2424 + RegisterMap map(thread, false); 1.2425 + frame f = thread->last_frame(); 1.2426 + while ( f.id() != thread->must_deopt_id() && ! f.is_first_frame()) { 1.2427 + f = f.sender(&map); 1.2428 + } 1.2429 + if (f.id() == thread->must_deopt_id()) { 1.2430 + thread->clear_must_deopt_id(); 1.2431 + f.deoptimize(thread); 1.2432 + } else { 1.2433 + fatal("missed deoptimization!"); 1.2434 + } 1.2435 + } 1.2436 +} 1.2437 + 1.2438 +// Slow path when the native==>VM/Java barriers detect a safepoint is in 1.2439 +// progress or when _suspend_flags is non-zero. 1.2440 +// Current thread needs to self-suspend if there is a suspend request and/or 1.2441 +// block if a safepoint is in progress. 1.2442 +// Also check for pending async exception (not including unsafe access error). 1.2443 +// Note only the native==>VM/Java barriers can call this function and when 1.2444 +// thread state is _thread_in_native_trans. 1.2445 +void JavaThread::check_special_condition_for_native_trans(JavaThread *thread) { 1.2446 + check_safepoint_and_suspend_for_native_trans(thread); 1.2447 + 1.2448 + if (thread->has_async_exception()) { 1.2449 + // We are in _thread_in_native_trans state, don't handle unsafe 1.2450 + // access error since that may block. 1.2451 + thread->check_and_handle_async_exceptions(false); 1.2452 + } 1.2453 +} 1.2454 + 1.2455 +// This is a variant of the normal 1.2456 +// check_special_condition_for_native_trans with slightly different 1.2457 +// semantics for use by critical native wrappers. It does all the 1.2458 +// normal checks but also performs the transition back into 1.2459 +// thread_in_Java state. This is required so that critical natives 1.2460 +// can potentially block and perform a GC if they are the last thread 1.2461 +// exiting the GC_locker. 1.2462 +void JavaThread::check_special_condition_for_native_trans_and_transition(JavaThread *thread) { 1.2463 + check_special_condition_for_native_trans(thread); 1.2464 + 1.2465 + // Finish the transition 1.2466 + thread->set_thread_state(_thread_in_Java); 1.2467 + 1.2468 + if (thread->do_critical_native_unlock()) { 1.2469 + ThreadInVMfromJavaNoAsyncException tiv(thread); 1.2470 + GC_locker::unlock_critical(thread); 1.2471 + thread->clear_critical_native_unlock(); 1.2472 + } 1.2473 +} 1.2474 + 1.2475 +// We need to guarantee the Threads_lock here, since resumes are not 1.2476 +// allowed during safepoint synchronization 1.2477 +// Can only resume from an external suspension 1.2478 +void JavaThread::java_resume() { 1.2479 + assert_locked_or_safepoint(Threads_lock); 1.2480 + 1.2481 + // Sanity check: thread is gone, has started exiting or the thread 1.2482 + // was not externally suspended. 1.2483 + if (!Threads::includes(this) || is_exiting() || !is_external_suspend()) { 1.2484 + return; 1.2485 + } 1.2486 + 1.2487 + MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag); 1.2488 + 1.2489 + clear_external_suspend(); 1.2490 + 1.2491 + if (is_ext_suspended()) { 1.2492 + clear_ext_suspended(); 1.2493 + SR_lock()->notify_all(); 1.2494 + } 1.2495 +} 1.2496 + 1.2497 +void JavaThread::create_stack_guard_pages() { 1.2498 + if (! os::uses_stack_guard_pages() || _stack_guard_state != stack_guard_unused) return; 1.2499 + address low_addr = stack_base() - stack_size(); 1.2500 + size_t len = (StackYellowPages + StackRedPages) * os::vm_page_size(); 1.2501 + 1.2502 + int allocate = os::allocate_stack_guard_pages(); 1.2503 + // warning("Guarding at " PTR_FORMAT " for len " SIZE_FORMAT "\n", low_addr, len); 1.2504 + 1.2505 + if (allocate && !os::create_stack_guard_pages((char *) low_addr, len)) { 1.2506 + warning("Attempt to allocate stack guard pages failed."); 1.2507 + return; 1.2508 + } 1.2509 + 1.2510 + if (os::guard_memory((char *) low_addr, len)) { 1.2511 + _stack_guard_state = stack_guard_enabled; 1.2512 + } else { 1.2513 + warning("Attempt to protect stack guard pages failed."); 1.2514 + if (os::uncommit_memory((char *) low_addr, len)) { 1.2515 + warning("Attempt to deallocate stack guard pages failed."); 1.2516 + } 1.2517 + } 1.2518 +} 1.2519 + 1.2520 +void JavaThread::remove_stack_guard_pages() { 1.2521 + assert(Thread::current() == this, "from different thread"); 1.2522 + if (_stack_guard_state == stack_guard_unused) return; 1.2523 + address low_addr = stack_base() - stack_size(); 1.2524 + size_t len = (StackYellowPages + StackRedPages) * os::vm_page_size(); 1.2525 + 1.2526 + if (os::allocate_stack_guard_pages()) { 1.2527 + if (os::remove_stack_guard_pages((char *) low_addr, len)) { 1.2528 + _stack_guard_state = stack_guard_unused; 1.2529 + } else { 1.2530 + warning("Attempt to deallocate stack guard pages failed."); 1.2531 + } 1.2532 + } else { 1.2533 + if (_stack_guard_state == stack_guard_unused) return; 1.2534 + if (os::unguard_memory((char *) low_addr, len)) { 1.2535 + _stack_guard_state = stack_guard_unused; 1.2536 + } else { 1.2537 + warning("Attempt to unprotect stack guard pages failed."); 1.2538 + } 1.2539 + } 1.2540 +} 1.2541 + 1.2542 +void JavaThread::enable_stack_yellow_zone() { 1.2543 + assert(_stack_guard_state != stack_guard_unused, "must be using guard pages."); 1.2544 + assert(_stack_guard_state != stack_guard_enabled, "already enabled"); 1.2545 + 1.2546 + // The base notation is from the stacks point of view, growing downward. 1.2547 + // We need to adjust it to work correctly with guard_memory() 1.2548 + address base = stack_yellow_zone_base() - stack_yellow_zone_size(); 1.2549 + 1.2550 + guarantee(base < stack_base(),"Error calculating stack yellow zone"); 1.2551 + guarantee(base < os::current_stack_pointer(),"Error calculating stack yellow zone"); 1.2552 + 1.2553 + if (os::guard_memory((char *) base, stack_yellow_zone_size())) { 1.2554 + _stack_guard_state = stack_guard_enabled; 1.2555 + } else { 1.2556 + warning("Attempt to guard stack yellow zone failed."); 1.2557 + } 1.2558 + enable_register_stack_guard(); 1.2559 +} 1.2560 + 1.2561 +void JavaThread::disable_stack_yellow_zone() { 1.2562 + assert(_stack_guard_state != stack_guard_unused, "must be using guard pages."); 1.2563 + assert(_stack_guard_state != stack_guard_yellow_disabled, "already disabled"); 1.2564 + 1.2565 + // Simply return if called for a thread that does not use guard pages. 1.2566 + if (_stack_guard_state == stack_guard_unused) return; 1.2567 + 1.2568 + // The base notation is from the stacks point of view, growing downward. 1.2569 + // We need to adjust it to work correctly with guard_memory() 1.2570 + address base = stack_yellow_zone_base() - stack_yellow_zone_size(); 1.2571 + 1.2572 + if (os::unguard_memory((char *)base, stack_yellow_zone_size())) { 1.2573 + _stack_guard_state = stack_guard_yellow_disabled; 1.2574 + } else { 1.2575 + warning("Attempt to unguard stack yellow zone failed."); 1.2576 + } 1.2577 + disable_register_stack_guard(); 1.2578 +} 1.2579 + 1.2580 +void JavaThread::enable_stack_red_zone() { 1.2581 + // The base notation is from the stacks point of view, growing downward. 1.2582 + // We need to adjust it to work correctly with guard_memory() 1.2583 + assert(_stack_guard_state != stack_guard_unused, "must be using guard pages."); 1.2584 + address base = stack_red_zone_base() - stack_red_zone_size(); 1.2585 + 1.2586 + guarantee(base < stack_base(),"Error calculating stack red zone"); 1.2587 + guarantee(base < os::current_stack_pointer(),"Error calculating stack red zone"); 1.2588 + 1.2589 + if(!os::guard_memory((char *) base, stack_red_zone_size())) { 1.2590 + warning("Attempt to guard stack red zone failed."); 1.2591 + } 1.2592 +} 1.2593 + 1.2594 +void JavaThread::disable_stack_red_zone() { 1.2595 + // The base notation is from the stacks point of view, growing downward. 1.2596 + // We need to adjust it to work correctly with guard_memory() 1.2597 + assert(_stack_guard_state != stack_guard_unused, "must be using guard pages."); 1.2598 + address base = stack_red_zone_base() - stack_red_zone_size(); 1.2599 + if (!os::unguard_memory((char *)base, stack_red_zone_size())) { 1.2600 + warning("Attempt to unguard stack red zone failed."); 1.2601 + } 1.2602 +} 1.2603 + 1.2604 +void JavaThread::frames_do(void f(frame*, const RegisterMap* map)) { 1.2605 + // ignore is there is no stack 1.2606 + if (!has_last_Java_frame()) return; 1.2607 + // traverse the stack frames. Starts from top frame. 1.2608 + for(StackFrameStream fst(this); !fst.is_done(); fst.next()) { 1.2609 + frame* fr = fst.current(); 1.2610 + f(fr, fst.register_map()); 1.2611 + } 1.2612 +} 1.2613 + 1.2614 + 1.2615 +#ifndef PRODUCT 1.2616 +// Deoptimization 1.2617 +// Function for testing deoptimization 1.2618 +void JavaThread::deoptimize() { 1.2619 + // BiasedLocking needs an updated RegisterMap for the revoke monitors pass 1.2620 + StackFrameStream fst(this, UseBiasedLocking); 1.2621 + bool deopt = false; // Dump stack only if a deopt actually happens. 1.2622 + bool only_at = strlen(DeoptimizeOnlyAt) > 0; 1.2623 + // Iterate over all frames in the thread and deoptimize 1.2624 + for(; !fst.is_done(); fst.next()) { 1.2625 + if(fst.current()->can_be_deoptimized()) { 1.2626 + 1.2627 + if (only_at) { 1.2628 + // Deoptimize only at particular bcis. DeoptimizeOnlyAt 1.2629 + // consists of comma or carriage return separated numbers so 1.2630 + // search for the current bci in that string. 1.2631 + address pc = fst.current()->pc(); 1.2632 + nmethod* nm = (nmethod*) fst.current()->cb(); 1.2633 + ScopeDesc* sd = nm->scope_desc_at( pc); 1.2634 + char buffer[8]; 1.2635 + jio_snprintf(buffer, sizeof(buffer), "%d", sd->bci()); 1.2636 + size_t len = strlen(buffer); 1.2637 + const char * found = strstr(DeoptimizeOnlyAt, buffer); 1.2638 + while (found != NULL) { 1.2639 + if ((found[len] == ',' || found[len] == '\n' || found[len] == '\0') && 1.2640 + (found == DeoptimizeOnlyAt || found[-1] == ',' || found[-1] == '\n')) { 1.2641 + // Check that the bci found is bracketed by terminators. 1.2642 + break; 1.2643 + } 1.2644 + found = strstr(found + 1, buffer); 1.2645 + } 1.2646 + if (!found) { 1.2647 + continue; 1.2648 + } 1.2649 + } 1.2650 + 1.2651 + if (DebugDeoptimization && !deopt) { 1.2652 + deopt = true; // One-time only print before deopt 1.2653 + tty->print_cr("[BEFORE Deoptimization]"); 1.2654 + trace_frames(); 1.2655 + trace_stack(); 1.2656 + } 1.2657 + Deoptimization::deoptimize(this, *fst.current(), fst.register_map()); 1.2658 + } 1.2659 + } 1.2660 + 1.2661 + if (DebugDeoptimization && deopt) { 1.2662 + tty->print_cr("[AFTER Deoptimization]"); 1.2663 + trace_frames(); 1.2664 + } 1.2665 +} 1.2666 + 1.2667 + 1.2668 +// Make zombies 1.2669 +void JavaThread::make_zombies() { 1.2670 + for(StackFrameStream fst(this); !fst.is_done(); fst.next()) { 1.2671 + if (fst.current()->can_be_deoptimized()) { 1.2672 + // it is a Java nmethod 1.2673 + nmethod* nm = CodeCache::find_nmethod(fst.current()->pc()); 1.2674 + nm->make_not_entrant(); 1.2675 + } 1.2676 + } 1.2677 +} 1.2678 +#endif // PRODUCT 1.2679 + 1.2680 + 1.2681 +void JavaThread::deoptimized_wrt_marked_nmethods() { 1.2682 + if (!has_last_Java_frame()) return; 1.2683 + // BiasedLocking needs an updated RegisterMap for the revoke monitors pass 1.2684 + StackFrameStream fst(this, UseBiasedLocking); 1.2685 + for(; !fst.is_done(); fst.next()) { 1.2686 + if (fst.current()->should_be_deoptimized()) { 1.2687 + if (LogCompilation && xtty != NULL) { 1.2688 + nmethod* nm = fst.current()->cb()->as_nmethod_or_null(); 1.2689 + xtty->elem("deoptimized thread='" UINTX_FORMAT "' compile_id='%d'", 1.2690 + this->name(), nm != NULL ? nm->compile_id() : -1); 1.2691 + } 1.2692 + 1.2693 + Deoptimization::deoptimize(this, *fst.current(), fst.register_map()); 1.2694 + } 1.2695 + } 1.2696 +} 1.2697 + 1.2698 + 1.2699 +// GC support 1.2700 +static void frame_gc_epilogue(frame* f, const RegisterMap* map) { f->gc_epilogue(); } 1.2701 + 1.2702 +void JavaThread::gc_epilogue() { 1.2703 + frames_do(frame_gc_epilogue); 1.2704 +} 1.2705 + 1.2706 + 1.2707 +static void frame_gc_prologue(frame* f, const RegisterMap* map) { f->gc_prologue(); } 1.2708 + 1.2709 +void JavaThread::gc_prologue() { 1.2710 + frames_do(frame_gc_prologue); 1.2711 +} 1.2712 + 1.2713 +// If the caller is a NamedThread, then remember, in the current scope, 1.2714 +// the given JavaThread in its _processed_thread field. 1.2715 +class RememberProcessedThread: public StackObj { 1.2716 + NamedThread* _cur_thr; 1.2717 +public: 1.2718 + RememberProcessedThread(JavaThread* jthr) { 1.2719 + Thread* thread = Thread::current(); 1.2720 + if (thread->is_Named_thread()) { 1.2721 + _cur_thr = (NamedThread *)thread; 1.2722 + _cur_thr->set_processed_thread(jthr); 1.2723 + } else { 1.2724 + _cur_thr = NULL; 1.2725 + } 1.2726 + } 1.2727 + 1.2728 + ~RememberProcessedThread() { 1.2729 + if (_cur_thr) { 1.2730 + _cur_thr->set_processed_thread(NULL); 1.2731 + } 1.2732 + } 1.2733 +}; 1.2734 + 1.2735 +void JavaThread::oops_do(OopClosure* f, CLDToOopClosure* cld_f, CodeBlobClosure* cf) { 1.2736 + // Verify that the deferred card marks have been flushed. 1.2737 + assert(deferred_card_mark().is_empty(), "Should be empty during GC"); 1.2738 + 1.2739 + // The ThreadProfiler oops_do is done from FlatProfiler::oops_do 1.2740 + // since there may be more than one thread using each ThreadProfiler. 1.2741 + 1.2742 + // Traverse the GCHandles 1.2743 + Thread::oops_do(f, cld_f, cf); 1.2744 + 1.2745 + assert( (!has_last_Java_frame() && java_call_counter() == 0) || 1.2746 + (has_last_Java_frame() && java_call_counter() > 0), "wrong java_sp info!"); 1.2747 + 1.2748 + if (has_last_Java_frame()) { 1.2749 + // Record JavaThread to GC thread 1.2750 + RememberProcessedThread rpt(this); 1.2751 + 1.2752 + // Traverse the privileged stack 1.2753 + if (_privileged_stack_top != NULL) { 1.2754 + _privileged_stack_top->oops_do(f); 1.2755 + } 1.2756 + 1.2757 + // traverse the registered growable array 1.2758 + if (_array_for_gc != NULL) { 1.2759 + for (int index = 0; index < _array_for_gc->length(); index++) { 1.2760 + f->do_oop(_array_for_gc->adr_at(index)); 1.2761 + } 1.2762 + } 1.2763 + 1.2764 + // Traverse the monitor chunks 1.2765 + for (MonitorChunk* chunk = monitor_chunks(); chunk != NULL; chunk = chunk->next()) { 1.2766 + chunk->oops_do(f); 1.2767 + } 1.2768 + 1.2769 + // Traverse the execution stack 1.2770 + for(StackFrameStream fst(this); !fst.is_done(); fst.next()) { 1.2771 + fst.current()->oops_do(f, cld_f, cf, fst.register_map()); 1.2772 + } 1.2773 + } 1.2774 + 1.2775 + // callee_target is never live across a gc point so NULL it here should 1.2776 + // it still contain a methdOop. 1.2777 + 1.2778 + set_callee_target(NULL); 1.2779 + 1.2780 + assert(vframe_array_head() == NULL, "deopt in progress at a safepoint!"); 1.2781 + // If we have deferred set_locals there might be oops waiting to be 1.2782 + // written 1.2783 + GrowableArray<jvmtiDeferredLocalVariableSet*>* list = deferred_locals(); 1.2784 + if (list != NULL) { 1.2785 + for (int i = 0; i < list->length(); i++) { 1.2786 + list->at(i)->oops_do(f); 1.2787 + } 1.2788 + } 1.2789 + 1.2790 + // Traverse instance variables at the end since the GC may be moving things 1.2791 + // around using this function 1.2792 + f->do_oop((oop*) &_threadObj); 1.2793 + f->do_oop((oop*) &_vm_result); 1.2794 + f->do_oop((oop*) &_exception_oop); 1.2795 + f->do_oop((oop*) &_pending_async_exception); 1.2796 + 1.2797 + if (jvmti_thread_state() != NULL) { 1.2798 + jvmti_thread_state()->oops_do(f); 1.2799 + } 1.2800 +} 1.2801 + 1.2802 +void JavaThread::nmethods_do(CodeBlobClosure* cf) { 1.2803 + Thread::nmethods_do(cf); // (super method is a no-op) 1.2804 + 1.2805 + assert( (!has_last_Java_frame() && java_call_counter() == 0) || 1.2806 + (has_last_Java_frame() && java_call_counter() > 0), "wrong java_sp info!"); 1.2807 + 1.2808 + if (has_last_Java_frame()) { 1.2809 + // Traverse the execution stack 1.2810 + for(StackFrameStream fst(this); !fst.is_done(); fst.next()) { 1.2811 + fst.current()->nmethods_do(cf); 1.2812 + } 1.2813 + } 1.2814 +} 1.2815 + 1.2816 +void JavaThread::metadata_do(void f(Metadata*)) { 1.2817 + Thread::metadata_do(f); 1.2818 + if (has_last_Java_frame()) { 1.2819 + // Traverse the execution stack to call f() on the methods in the stack 1.2820 + for(StackFrameStream fst(this); !fst.is_done(); fst.next()) { 1.2821 + fst.current()->metadata_do(f); 1.2822 + } 1.2823 + } else if (is_Compiler_thread()) { 1.2824 + // need to walk ciMetadata in current compile tasks to keep alive. 1.2825 + CompilerThread* ct = (CompilerThread*)this; 1.2826 + if (ct->env() != NULL) { 1.2827 + ct->env()->metadata_do(f); 1.2828 + } 1.2829 + } 1.2830 +} 1.2831 + 1.2832 +// Printing 1.2833 +const char* _get_thread_state_name(JavaThreadState _thread_state) { 1.2834 + switch (_thread_state) { 1.2835 + case _thread_uninitialized: return "_thread_uninitialized"; 1.2836 + case _thread_new: return "_thread_new"; 1.2837 + case _thread_new_trans: return "_thread_new_trans"; 1.2838 + case _thread_in_native: return "_thread_in_native"; 1.2839 + case _thread_in_native_trans: return "_thread_in_native_trans"; 1.2840 + case _thread_in_vm: return "_thread_in_vm"; 1.2841 + case _thread_in_vm_trans: return "_thread_in_vm_trans"; 1.2842 + case _thread_in_Java: return "_thread_in_Java"; 1.2843 + case _thread_in_Java_trans: return "_thread_in_Java_trans"; 1.2844 + case _thread_blocked: return "_thread_blocked"; 1.2845 + case _thread_blocked_trans: return "_thread_blocked_trans"; 1.2846 + default: return "unknown thread state"; 1.2847 + } 1.2848 +} 1.2849 + 1.2850 +#ifndef PRODUCT 1.2851 +void JavaThread::print_thread_state_on(outputStream *st) const { 1.2852 + st->print_cr(" JavaThread state: %s", _get_thread_state_name(_thread_state)); 1.2853 +}; 1.2854 +void JavaThread::print_thread_state() const { 1.2855 + print_thread_state_on(tty); 1.2856 +}; 1.2857 +#endif // PRODUCT 1.2858 + 1.2859 +// Called by Threads::print() for VM_PrintThreads operation 1.2860 +void JavaThread::print_on(outputStream *st) const { 1.2861 + st->print("\"%s\" ", get_thread_name()); 1.2862 + oop thread_oop = threadObj(); 1.2863 + if (thread_oop != NULL) { 1.2864 + st->print("#" INT64_FORMAT " ", java_lang_Thread::thread_id(thread_oop)); 1.2865 + if (java_lang_Thread::is_daemon(thread_oop)) st->print("daemon "); 1.2866 + st->print("prio=%d ", java_lang_Thread::priority(thread_oop)); 1.2867 + } 1.2868 + Thread::print_on(st); 1.2869 + // print guess for valid stack memory region (assume 4K pages); helps lock debugging 1.2870 + st->print_cr("[" INTPTR_FORMAT "]", (intptr_t)last_Java_sp() & ~right_n_bits(12)); 1.2871 + if (thread_oop != NULL && JDK_Version::is_gte_jdk15x_version()) { 1.2872 + st->print_cr(" java.lang.Thread.State: %s", java_lang_Thread::thread_status_name(thread_oop)); 1.2873 + } 1.2874 +#ifndef PRODUCT 1.2875 + print_thread_state_on(st); 1.2876 + _safepoint_state->print_on(st); 1.2877 +#endif // PRODUCT 1.2878 +} 1.2879 + 1.2880 +// Called by fatal error handler. The difference between this and 1.2881 +// JavaThread::print() is that we can't grab lock or allocate memory. 1.2882 +void JavaThread::print_on_error(outputStream* st, char *buf, int buflen) const { 1.2883 + st->print("JavaThread \"%s\"", get_thread_name_string(buf, buflen)); 1.2884 + oop thread_obj = threadObj(); 1.2885 + if (thread_obj != NULL) { 1.2886 + if (java_lang_Thread::is_daemon(thread_obj)) st->print(" daemon"); 1.2887 + } 1.2888 + st->print(" ["); 1.2889 + st->print("%s", _get_thread_state_name(_thread_state)); 1.2890 + if (osthread()) { 1.2891 + st->print(", id=%d", osthread()->thread_id()); 1.2892 + } 1.2893 + st->print(", stack(" PTR_FORMAT "," PTR_FORMAT ")", 1.2894 + _stack_base - _stack_size, _stack_base); 1.2895 + st->print("]"); 1.2896 + return; 1.2897 +} 1.2898 + 1.2899 +// Verification 1.2900 + 1.2901 +static void frame_verify(frame* f, const RegisterMap *map) { f->verify(map); } 1.2902 + 1.2903 +void JavaThread::verify() { 1.2904 + // Verify oops in the thread. 1.2905 + oops_do(&VerifyOopClosure::verify_oop, NULL, NULL); 1.2906 + 1.2907 + // Verify the stack frames. 1.2908 + frames_do(frame_verify); 1.2909 +} 1.2910 + 1.2911 +// CR 6300358 (sub-CR 2137150) 1.2912 +// Most callers of this method assume that it can't return NULL but a 1.2913 +// thread may not have a name whilst it is in the process of attaching to 1.2914 +// the VM - see CR 6412693, and there are places where a JavaThread can be 1.2915 +// seen prior to having it's threadObj set (eg JNI attaching threads and 1.2916 +// if vm exit occurs during initialization). These cases can all be accounted 1.2917 +// for such that this method never returns NULL. 1.2918 +const char* JavaThread::get_thread_name() const { 1.2919 +#ifdef ASSERT 1.2920 + // early safepoints can hit while current thread does not yet have TLS 1.2921 + if (!SafepointSynchronize::is_at_safepoint()) { 1.2922 + Thread *cur = Thread::current(); 1.2923 + if (!(cur->is_Java_thread() && cur == this)) { 1.2924 + // Current JavaThreads are allowed to get their own name without 1.2925 + // the Threads_lock. 1.2926 + assert_locked_or_safepoint(Threads_lock); 1.2927 + } 1.2928 + } 1.2929 +#endif // ASSERT 1.2930 + return get_thread_name_string(); 1.2931 +} 1.2932 + 1.2933 +// Returns a non-NULL representation of this thread's name, or a suitable 1.2934 +// descriptive string if there is no set name 1.2935 +const char* JavaThread::get_thread_name_string(char* buf, int buflen) const { 1.2936 + const char* name_str; 1.2937 + oop thread_obj = threadObj(); 1.2938 + if (thread_obj != NULL) { 1.2939 + typeArrayOop name = java_lang_Thread::name(thread_obj); 1.2940 + if (name != NULL) { 1.2941 + if (buf == NULL) { 1.2942 + name_str = UNICODE::as_utf8((jchar*) name->base(T_CHAR), name->length()); 1.2943 + } 1.2944 + else { 1.2945 + name_str = UNICODE::as_utf8((jchar*) name->base(T_CHAR), name->length(), buf, buflen); 1.2946 + } 1.2947 + } 1.2948 + else if (is_attaching_via_jni()) { // workaround for 6412693 - see 6404306 1.2949 + name_str = "<no-name - thread is attaching>"; 1.2950 + } 1.2951 + else { 1.2952 + name_str = Thread::name(); 1.2953 + } 1.2954 + } 1.2955 + else { 1.2956 + name_str = Thread::name(); 1.2957 + } 1.2958 + assert(name_str != NULL, "unexpected NULL thread name"); 1.2959 + return name_str; 1.2960 +} 1.2961 + 1.2962 + 1.2963 +const char* JavaThread::get_threadgroup_name() const { 1.2964 + debug_only(if (JavaThread::current() != this) assert_locked_or_safepoint(Threads_lock);) 1.2965 + oop thread_obj = threadObj(); 1.2966 + if (thread_obj != NULL) { 1.2967 + oop thread_group = java_lang_Thread::threadGroup(thread_obj); 1.2968 + if (thread_group != NULL) { 1.2969 + typeArrayOop name = java_lang_ThreadGroup::name(thread_group); 1.2970 + // ThreadGroup.name can be null 1.2971 + if (name != NULL) { 1.2972 + const char* str = UNICODE::as_utf8((jchar*) name->base(T_CHAR), name->length()); 1.2973 + return str; 1.2974 + } 1.2975 + } 1.2976 + } 1.2977 + return NULL; 1.2978 +} 1.2979 + 1.2980 +const char* JavaThread::get_parent_name() const { 1.2981 + debug_only(if (JavaThread::current() != this) assert_locked_or_safepoint(Threads_lock);) 1.2982 + oop thread_obj = threadObj(); 1.2983 + if (thread_obj != NULL) { 1.2984 + oop thread_group = java_lang_Thread::threadGroup(thread_obj); 1.2985 + if (thread_group != NULL) { 1.2986 + oop parent = java_lang_ThreadGroup::parent(thread_group); 1.2987 + if (parent != NULL) { 1.2988 + typeArrayOop name = java_lang_ThreadGroup::name(parent); 1.2989 + // ThreadGroup.name can be null 1.2990 + if (name != NULL) { 1.2991 + const char* str = UNICODE::as_utf8((jchar*) name->base(T_CHAR), name->length()); 1.2992 + return str; 1.2993 + } 1.2994 + } 1.2995 + } 1.2996 + } 1.2997 + return NULL; 1.2998 +} 1.2999 + 1.3000 +ThreadPriority JavaThread::java_priority() const { 1.3001 + oop thr_oop = threadObj(); 1.3002 + if (thr_oop == NULL) return NormPriority; // Bootstrapping 1.3003 + ThreadPriority priority = java_lang_Thread::priority(thr_oop); 1.3004 + assert(MinPriority <= priority && priority <= MaxPriority, "sanity check"); 1.3005 + return priority; 1.3006 +} 1.3007 + 1.3008 +void JavaThread::prepare(jobject jni_thread, ThreadPriority prio) { 1.3009 + 1.3010 + assert(Threads_lock->owner() == Thread::current(), "must have threads lock"); 1.3011 + // Link Java Thread object <-> C++ Thread 1.3012 + 1.3013 + // Get the C++ thread object (an oop) from the JNI handle (a jthread) 1.3014 + // and put it into a new Handle. The Handle "thread_oop" can then 1.3015 + // be used to pass the C++ thread object to other methods. 1.3016 + 1.3017 + // Set the Java level thread object (jthread) field of the 1.3018 + // new thread (a JavaThread *) to C++ thread object using the 1.3019 + // "thread_oop" handle. 1.3020 + 1.3021 + // Set the thread field (a JavaThread *) of the 1.3022 + // oop representing the java_lang_Thread to the new thread (a JavaThread *). 1.3023 + 1.3024 + Handle thread_oop(Thread::current(), 1.3025 + JNIHandles::resolve_non_null(jni_thread)); 1.3026 + assert(InstanceKlass::cast(thread_oop->klass())->is_linked(), 1.3027 + "must be initialized"); 1.3028 + set_threadObj(thread_oop()); 1.3029 + java_lang_Thread::set_thread(thread_oop(), this); 1.3030 + 1.3031 + if (prio == NoPriority) { 1.3032 + prio = java_lang_Thread::priority(thread_oop()); 1.3033 + assert(prio != NoPriority, "A valid priority should be present"); 1.3034 + } 1.3035 + 1.3036 + // Push the Java priority down to the native thread; needs Threads_lock 1.3037 + Thread::set_priority(this, prio); 1.3038 + 1.3039 + // Add the new thread to the Threads list and set it in motion. 1.3040 + // We must have threads lock in order to call Threads::add. 1.3041 + // It is crucial that we do not block before the thread is 1.3042 + // added to the Threads list for if a GC happens, then the java_thread oop 1.3043 + // will not be visited by GC. 1.3044 + Threads::add(this); 1.3045 +} 1.3046 + 1.3047 +oop JavaThread::current_park_blocker() { 1.3048 + // Support for JSR-166 locks 1.3049 + oop thread_oop = threadObj(); 1.3050 + if (thread_oop != NULL && 1.3051 + JDK_Version::current().supports_thread_park_blocker()) { 1.3052 + return java_lang_Thread::park_blocker(thread_oop); 1.3053 + } 1.3054 + return NULL; 1.3055 +} 1.3056 + 1.3057 + 1.3058 +void JavaThread::print_stack_on(outputStream* st) { 1.3059 + if (!has_last_Java_frame()) return; 1.3060 + ResourceMark rm; 1.3061 + HandleMark hm; 1.3062 + 1.3063 + RegisterMap reg_map(this); 1.3064 + vframe* start_vf = last_java_vframe(®_map); 1.3065 + int count = 0; 1.3066 + for (vframe* f = start_vf; f; f = f->sender() ) { 1.3067 + if (f->is_java_frame()) { 1.3068 + javaVFrame* jvf = javaVFrame::cast(f); 1.3069 + java_lang_Throwable::print_stack_element(st, jvf->method(), jvf->bci()); 1.3070 + 1.3071 + // Print out lock information 1.3072 + if (JavaMonitorsInStackTrace) { 1.3073 + jvf->print_lock_info_on(st, count); 1.3074 + } 1.3075 + } else { 1.3076 + // Ignore non-Java frames 1.3077 + } 1.3078 + 1.3079 + // Bail-out case for too deep stacks 1.3080 + count++; 1.3081 + if (MaxJavaStackTraceDepth == count) return; 1.3082 + } 1.3083 +} 1.3084 + 1.3085 + 1.3086 +// JVMTI PopFrame support 1.3087 +void JavaThread::popframe_preserve_args(ByteSize size_in_bytes, void* start) { 1.3088 + assert(_popframe_preserved_args == NULL, "should not wipe out old PopFrame preserved arguments"); 1.3089 + if (in_bytes(size_in_bytes) != 0) { 1.3090 + _popframe_preserved_args = NEW_C_HEAP_ARRAY(char, in_bytes(size_in_bytes), mtThread); 1.3091 + _popframe_preserved_args_size = in_bytes(size_in_bytes); 1.3092 + Copy::conjoint_jbytes(start, _popframe_preserved_args, _popframe_preserved_args_size); 1.3093 + } 1.3094 +} 1.3095 + 1.3096 +void* JavaThread::popframe_preserved_args() { 1.3097 + return _popframe_preserved_args; 1.3098 +} 1.3099 + 1.3100 +ByteSize JavaThread::popframe_preserved_args_size() { 1.3101 + return in_ByteSize(_popframe_preserved_args_size); 1.3102 +} 1.3103 + 1.3104 +WordSize JavaThread::popframe_preserved_args_size_in_words() { 1.3105 + int sz = in_bytes(popframe_preserved_args_size()); 1.3106 + assert(sz % wordSize == 0, "argument size must be multiple of wordSize"); 1.3107 + return in_WordSize(sz / wordSize); 1.3108 +} 1.3109 + 1.3110 +void JavaThread::popframe_free_preserved_args() { 1.3111 + assert(_popframe_preserved_args != NULL, "should not free PopFrame preserved arguments twice"); 1.3112 + FREE_C_HEAP_ARRAY(char, (char*) _popframe_preserved_args, mtThread); 1.3113 + _popframe_preserved_args = NULL; 1.3114 + _popframe_preserved_args_size = 0; 1.3115 +} 1.3116 + 1.3117 +#ifndef PRODUCT 1.3118 + 1.3119 +void JavaThread::trace_frames() { 1.3120 + tty->print_cr("[Describe stack]"); 1.3121 + int frame_no = 1; 1.3122 + for(StackFrameStream fst(this); !fst.is_done(); fst.next()) { 1.3123 + tty->print(" %d. ", frame_no++); 1.3124 + fst.current()->print_value_on(tty,this); 1.3125 + tty->cr(); 1.3126 + } 1.3127 +} 1.3128 + 1.3129 +class PrintAndVerifyOopClosure: public OopClosure { 1.3130 + protected: 1.3131 + template <class T> inline void do_oop_work(T* p) { 1.3132 + oop obj = oopDesc::load_decode_heap_oop(p); 1.3133 + if (obj == NULL) return; 1.3134 + tty->print(INTPTR_FORMAT ": ", p); 1.3135 + if (obj->is_oop_or_null()) { 1.3136 + if (obj->is_objArray()) { 1.3137 + tty->print_cr("valid objArray: " INTPTR_FORMAT, (oopDesc*) obj); 1.3138 + } else { 1.3139 + obj->print(); 1.3140 + } 1.3141 + } else { 1.3142 + tty->print_cr("invalid oop: " INTPTR_FORMAT, (oopDesc*) obj); 1.3143 + } 1.3144 + tty->cr(); 1.3145 + } 1.3146 + public: 1.3147 + virtual void do_oop(oop* p) { do_oop_work(p); } 1.3148 + virtual void do_oop(narrowOop* p) { do_oop_work(p); } 1.3149 +}; 1.3150 + 1.3151 + 1.3152 +static void oops_print(frame* f, const RegisterMap *map) { 1.3153 + PrintAndVerifyOopClosure print; 1.3154 + f->print_value(); 1.3155 + f->oops_do(&print, NULL, NULL, (RegisterMap*)map); 1.3156 +} 1.3157 + 1.3158 +// Print our all the locations that contain oops and whether they are 1.3159 +// valid or not. This useful when trying to find the oldest frame 1.3160 +// where an oop has gone bad since the frame walk is from youngest to 1.3161 +// oldest. 1.3162 +void JavaThread::trace_oops() { 1.3163 + tty->print_cr("[Trace oops]"); 1.3164 + frames_do(oops_print); 1.3165 +} 1.3166 + 1.3167 + 1.3168 +#ifdef ASSERT 1.3169 +// Print or validate the layout of stack frames 1.3170 +void JavaThread::print_frame_layout(int depth, bool validate_only) { 1.3171 + ResourceMark rm; 1.3172 + PRESERVE_EXCEPTION_MARK; 1.3173 + FrameValues values; 1.3174 + int frame_no = 0; 1.3175 + for(StackFrameStream fst(this, false); !fst.is_done(); fst.next()) { 1.3176 + fst.current()->describe(values, ++frame_no); 1.3177 + if (depth == frame_no) break; 1.3178 + } 1.3179 + if (validate_only) { 1.3180 + values.validate(); 1.3181 + } else { 1.3182 + tty->print_cr("[Describe stack layout]"); 1.3183 + values.print(this); 1.3184 + } 1.3185 +} 1.3186 +#endif 1.3187 + 1.3188 +void JavaThread::trace_stack_from(vframe* start_vf) { 1.3189 + ResourceMark rm; 1.3190 + int vframe_no = 1; 1.3191 + for (vframe* f = start_vf; f; f = f->sender() ) { 1.3192 + if (f->is_java_frame()) { 1.3193 + javaVFrame::cast(f)->print_activation(vframe_no++); 1.3194 + } else { 1.3195 + f->print(); 1.3196 + } 1.3197 + if (vframe_no > StackPrintLimit) { 1.3198 + tty->print_cr("...<more frames>..."); 1.3199 + return; 1.3200 + } 1.3201 + } 1.3202 +} 1.3203 + 1.3204 + 1.3205 +void JavaThread::trace_stack() { 1.3206 + if (!has_last_Java_frame()) return; 1.3207 + ResourceMark rm; 1.3208 + HandleMark hm; 1.3209 + RegisterMap reg_map(this); 1.3210 + trace_stack_from(last_java_vframe(®_map)); 1.3211 +} 1.3212 + 1.3213 + 1.3214 +#endif // PRODUCT 1.3215 + 1.3216 + 1.3217 +javaVFrame* JavaThread::last_java_vframe(RegisterMap *reg_map) { 1.3218 + assert(reg_map != NULL, "a map must be given"); 1.3219 + frame f = last_frame(); 1.3220 + for (vframe* vf = vframe::new_vframe(&f, reg_map, this); vf; vf = vf->sender() ) { 1.3221 + if (vf->is_java_frame()) return javaVFrame::cast(vf); 1.3222 + } 1.3223 + return NULL; 1.3224 +} 1.3225 + 1.3226 + 1.3227 +Klass* JavaThread::security_get_caller_class(int depth) { 1.3228 + vframeStream vfst(this); 1.3229 + vfst.security_get_caller_frame(depth); 1.3230 + if (!vfst.at_end()) { 1.3231 + return vfst.method()->method_holder(); 1.3232 + } 1.3233 + return NULL; 1.3234 +} 1.3235 + 1.3236 +static void compiler_thread_entry(JavaThread* thread, TRAPS) { 1.3237 + assert(thread->is_Compiler_thread(), "must be compiler thread"); 1.3238 + CompileBroker::compiler_thread_loop(); 1.3239 +} 1.3240 + 1.3241 +// Create a CompilerThread 1.3242 +CompilerThread::CompilerThread(CompileQueue* queue, CompilerCounters* counters) 1.3243 +: JavaThread(&compiler_thread_entry) { 1.3244 + _env = NULL; 1.3245 + _log = NULL; 1.3246 + _task = NULL; 1.3247 + _queue = queue; 1.3248 + _counters = counters; 1.3249 + _buffer_blob = NULL; 1.3250 + _scanned_nmethod = NULL; 1.3251 + _compiler = NULL; 1.3252 + 1.3253 +#ifndef PRODUCT 1.3254 + _ideal_graph_printer = NULL; 1.3255 +#endif 1.3256 +} 1.3257 + 1.3258 +void CompilerThread::oops_do(OopClosure* f, CLDToOopClosure* cld_f, CodeBlobClosure* cf) { 1.3259 + JavaThread::oops_do(f, cld_f, cf); 1.3260 + if (_scanned_nmethod != NULL && cf != NULL) { 1.3261 + // Safepoints can occur when the sweeper is scanning an nmethod so 1.3262 + // process it here to make sure it isn't unloaded in the middle of 1.3263 + // a scan. 1.3264 + cf->do_code_blob(_scanned_nmethod); 1.3265 + } 1.3266 +} 1.3267 + 1.3268 + 1.3269 +// ======= Threads ======== 1.3270 + 1.3271 +// The Threads class links together all active threads, and provides 1.3272 +// operations over all threads. It is protected by its own Mutex 1.3273 +// lock, which is also used in other contexts to protect thread 1.3274 +// operations from having the thread being operated on from exiting 1.3275 +// and going away unexpectedly (e.g., safepoint synchronization) 1.3276 + 1.3277 +JavaThread* Threads::_thread_list = NULL; 1.3278 +int Threads::_number_of_threads = 0; 1.3279 +int Threads::_number_of_non_daemon_threads = 0; 1.3280 +int Threads::_return_code = 0; 1.3281 +size_t JavaThread::_stack_size_at_create = 0; 1.3282 +#ifdef ASSERT 1.3283 +bool Threads::_vm_complete = false; 1.3284 +#endif 1.3285 + 1.3286 +// All JavaThreads 1.3287 +#define ALL_JAVA_THREADS(X) for (JavaThread* X = _thread_list; X; X = X->next()) 1.3288 + 1.3289 +// All JavaThreads + all non-JavaThreads (i.e., every thread in the system) 1.3290 +void Threads::threads_do(ThreadClosure* tc) { 1.3291 + assert_locked_or_safepoint(Threads_lock); 1.3292 + // ALL_JAVA_THREADS iterates through all JavaThreads 1.3293 + ALL_JAVA_THREADS(p) { 1.3294 + tc->do_thread(p); 1.3295 + } 1.3296 + // Someday we could have a table or list of all non-JavaThreads. 1.3297 + // For now, just manually iterate through them. 1.3298 + tc->do_thread(VMThread::vm_thread()); 1.3299 + Universe::heap()->gc_threads_do(tc); 1.3300 + WatcherThread *wt = WatcherThread::watcher_thread(); 1.3301 + // Strictly speaking, the following NULL check isn't sufficient to make sure 1.3302 + // the data for WatcherThread is still valid upon being examined. However, 1.3303 + // considering that WatchThread terminates when the VM is on the way to 1.3304 + // exit at safepoint, the chance of the above is extremely small. The right 1.3305 + // way to prevent termination of WatcherThread would be to acquire 1.3306 + // Terminator_lock, but we can't do that without violating the lock rank 1.3307 + // checking in some cases. 1.3308 + if (wt != NULL) 1.3309 + tc->do_thread(wt); 1.3310 + 1.3311 + // If CompilerThreads ever become non-JavaThreads, add them here 1.3312 +} 1.3313 + 1.3314 +jint Threads::create_vm(JavaVMInitArgs* args, bool* canTryAgain) { 1.3315 + 1.3316 + extern void JDK_Version_init(); 1.3317 + 1.3318 + // Check version 1.3319 + if (!is_supported_jni_version(args->version)) return JNI_EVERSION; 1.3320 + 1.3321 + // Initialize the output stream module 1.3322 + ostream_init(); 1.3323 + 1.3324 + // Process java launcher properties. 1.3325 + Arguments::process_sun_java_launcher_properties(args); 1.3326 + 1.3327 + // Initialize the os module before using TLS 1.3328 + os::init(); 1.3329 + 1.3330 + // Initialize system properties. 1.3331 + Arguments::init_system_properties(); 1.3332 + 1.3333 + // So that JDK version can be used as a discrimintor when parsing arguments 1.3334 + JDK_Version_init(); 1.3335 + 1.3336 + // Update/Initialize System properties after JDK version number is known 1.3337 + Arguments::init_version_specific_system_properties(); 1.3338 + 1.3339 + // Parse arguments 1.3340 + jint parse_result = Arguments::parse(args); 1.3341 + if (parse_result != JNI_OK) return parse_result; 1.3342 + 1.3343 + os::init_before_ergo(); 1.3344 + 1.3345 + jint ergo_result = Arguments::apply_ergo(); 1.3346 + if (ergo_result != JNI_OK) return ergo_result; 1.3347 + 1.3348 + if (PauseAtStartup) { 1.3349 + os::pause(); 1.3350 + } 1.3351 + 1.3352 +#ifndef USDT2 1.3353 + HS_DTRACE_PROBE(hotspot, vm__init__begin); 1.3354 +#else /* USDT2 */ 1.3355 + HOTSPOT_VM_INIT_BEGIN(); 1.3356 +#endif /* USDT2 */ 1.3357 + 1.3358 + // Record VM creation timing statistics 1.3359 + TraceVmCreationTime create_vm_timer; 1.3360 + create_vm_timer.start(); 1.3361 + 1.3362 + // Timing (must come after argument parsing) 1.3363 + TraceTime timer("Create VM", TraceStartupTime); 1.3364 + 1.3365 + // Initialize the os module after parsing the args 1.3366 + jint os_init_2_result = os::init_2(); 1.3367 + if (os_init_2_result != JNI_OK) return os_init_2_result; 1.3368 + 1.3369 + jint adjust_after_os_result = Arguments::adjust_after_os(); 1.3370 + if (adjust_after_os_result != JNI_OK) return adjust_after_os_result; 1.3371 + 1.3372 + // intialize TLS 1.3373 + ThreadLocalStorage::init(); 1.3374 + 1.3375 + // Bootstrap native memory tracking, so it can start recording memory 1.3376 + // activities before worker thread is started. This is the first phase 1.3377 + // of bootstrapping, VM is currently running in single-thread mode. 1.3378 + MemTracker::bootstrap_single_thread(); 1.3379 + 1.3380 + // Initialize output stream logging 1.3381 + ostream_init_log(); 1.3382 + 1.3383 + // Convert -Xrun to -agentlib: if there is no JVM_OnLoad 1.3384 + // Must be before create_vm_init_agents() 1.3385 + if (Arguments::init_libraries_at_startup()) { 1.3386 + convert_vm_init_libraries_to_agents(); 1.3387 + } 1.3388 + 1.3389 + // Launch -agentlib/-agentpath and converted -Xrun agents 1.3390 + if (Arguments::init_agents_at_startup()) { 1.3391 + create_vm_init_agents(); 1.3392 + } 1.3393 + 1.3394 + // Initialize Threads state 1.3395 + _thread_list = NULL; 1.3396 + _number_of_threads = 0; 1.3397 + _number_of_non_daemon_threads = 0; 1.3398 + 1.3399 + // Initialize global data structures and create system classes in heap 1.3400 + vm_init_globals(); 1.3401 + 1.3402 + // Attach the main thread to this os thread 1.3403 + JavaThread* main_thread = new JavaThread(); 1.3404 + main_thread->set_thread_state(_thread_in_vm); 1.3405 + // must do this before set_active_handles and initialize_thread_local_storage 1.3406 + // Note: on solaris initialize_thread_local_storage() will (indirectly) 1.3407 + // change the stack size recorded here to one based on the java thread 1.3408 + // stacksize. This adjusted size is what is used to figure the placement 1.3409 + // of the guard pages. 1.3410 + main_thread->record_stack_base_and_size(); 1.3411 + main_thread->initialize_thread_local_storage(); 1.3412 + 1.3413 + main_thread->set_active_handles(JNIHandleBlock::allocate_block()); 1.3414 + 1.3415 + if (!main_thread->set_as_starting_thread()) { 1.3416 + vm_shutdown_during_initialization( 1.3417 + "Failed necessary internal allocation. Out of swap space"); 1.3418 + delete main_thread; 1.3419 + *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again 1.3420 + return JNI_ENOMEM; 1.3421 + } 1.3422 + 1.3423 + // Enable guard page *after* os::create_main_thread(), otherwise it would 1.3424 + // crash Linux VM, see notes in os_linux.cpp. 1.3425 + main_thread->create_stack_guard_pages(); 1.3426 + 1.3427 + // Initialize Java-Level synchronization subsystem 1.3428 + ObjectMonitor::Initialize() ; 1.3429 + 1.3430 + // Second phase of bootstrapping, VM is about entering multi-thread mode 1.3431 + MemTracker::bootstrap_multi_thread(); 1.3432 + 1.3433 + // Initialize global modules 1.3434 + jint status = init_globals(); 1.3435 + if (status != JNI_OK) { 1.3436 + delete main_thread; 1.3437 + *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again 1.3438 + return status; 1.3439 + } 1.3440 + 1.3441 + // Should be done after the heap is fully created 1.3442 + main_thread->cache_global_variables(); 1.3443 + 1.3444 + HandleMark hm; 1.3445 + 1.3446 + { MutexLocker mu(Threads_lock); 1.3447 + Threads::add(main_thread); 1.3448 + } 1.3449 + 1.3450 + // Any JVMTI raw monitors entered in onload will transition into 1.3451 + // real raw monitor. VM is setup enough here for raw monitor enter. 1.3452 + JvmtiExport::transition_pending_onload_raw_monitors(); 1.3453 + 1.3454 + // Fully start NMT 1.3455 + MemTracker::start(); 1.3456 + 1.3457 + // Create the VMThread 1.3458 + { TraceTime timer("Start VMThread", TraceStartupTime); 1.3459 + VMThread::create(); 1.3460 + Thread* vmthread = VMThread::vm_thread(); 1.3461 + 1.3462 + if (!os::create_thread(vmthread, os::vm_thread)) 1.3463 + vm_exit_during_initialization("Cannot create VM thread. Out of system resources."); 1.3464 + 1.3465 + // Wait for the VM thread to become ready, and VMThread::run to initialize 1.3466 + // Monitors can have spurious returns, must always check another state flag 1.3467 + { 1.3468 + MutexLocker ml(Notify_lock); 1.3469 + os::start_thread(vmthread); 1.3470 + while (vmthread->active_handles() == NULL) { 1.3471 + Notify_lock->wait(); 1.3472 + } 1.3473 + } 1.3474 + } 1.3475 + 1.3476 + assert (Universe::is_fully_initialized(), "not initialized"); 1.3477 + if (VerifyDuringStartup) { 1.3478 + // Make sure we're starting with a clean slate. 1.3479 + VM_Verify verify_op; 1.3480 + VMThread::execute(&verify_op); 1.3481 + } 1.3482 + 1.3483 + EXCEPTION_MARK; 1.3484 + 1.3485 + // At this point, the Universe is initialized, but we have not executed 1.3486 + // any byte code. Now is a good time (the only time) to dump out the 1.3487 + // internal state of the JVM for sharing. 1.3488 + if (DumpSharedSpaces) { 1.3489 + MetaspaceShared::preload_and_dump(CHECK_0); 1.3490 + ShouldNotReachHere(); 1.3491 + } 1.3492 + 1.3493 + // Always call even when there are not JVMTI environments yet, since environments 1.3494 + // may be attached late and JVMTI must track phases of VM execution 1.3495 + JvmtiExport::enter_start_phase(); 1.3496 + 1.3497 + // Notify JVMTI agents that VM has started (JNI is up) - nop if no agents. 1.3498 + JvmtiExport::post_vm_start(); 1.3499 + 1.3500 + { 1.3501 + TraceTime timer("Initialize java.lang classes", TraceStartupTime); 1.3502 + 1.3503 + if (EagerXrunInit && Arguments::init_libraries_at_startup()) { 1.3504 + create_vm_init_libraries(); 1.3505 + } 1.3506 + 1.3507 + initialize_class(vmSymbols::java_lang_String(), CHECK_0); 1.3508 + 1.3509 + // Initialize java_lang.System (needed before creating the thread) 1.3510 + initialize_class(vmSymbols::java_lang_System(), CHECK_0); 1.3511 + initialize_class(vmSymbols::java_lang_ThreadGroup(), CHECK_0); 1.3512 + Handle thread_group = create_initial_thread_group(CHECK_0); 1.3513 + Universe::set_main_thread_group(thread_group()); 1.3514 + initialize_class(vmSymbols::java_lang_Thread(), CHECK_0); 1.3515 + oop thread_object = create_initial_thread(thread_group, main_thread, CHECK_0); 1.3516 + main_thread->set_threadObj(thread_object); 1.3517 + // Set thread status to running since main thread has 1.3518 + // been started and running. 1.3519 + java_lang_Thread::set_thread_status(thread_object, 1.3520 + java_lang_Thread::RUNNABLE); 1.3521 + 1.3522 + // The VM creates & returns objects of this class. Make sure it's initialized. 1.3523 + initialize_class(vmSymbols::java_lang_Class(), CHECK_0); 1.3524 + 1.3525 + // The VM preresolves methods to these classes. Make sure that they get initialized 1.3526 + initialize_class(vmSymbols::java_lang_reflect_Method(), CHECK_0); 1.3527 + initialize_class(vmSymbols::java_lang_ref_Finalizer(), CHECK_0); 1.3528 + call_initializeSystemClass(CHECK_0); 1.3529 + 1.3530 + // get the Java runtime name after java.lang.System is initialized 1.3531 + JDK_Version::set_runtime_name(get_java_runtime_name(THREAD)); 1.3532 + JDK_Version::set_runtime_version(get_java_runtime_version(THREAD)); 1.3533 + 1.3534 + // an instance of OutOfMemory exception has been allocated earlier 1.3535 + initialize_class(vmSymbols::java_lang_OutOfMemoryError(), CHECK_0); 1.3536 + initialize_class(vmSymbols::java_lang_NullPointerException(), CHECK_0); 1.3537 + initialize_class(vmSymbols::java_lang_ClassCastException(), CHECK_0); 1.3538 + initialize_class(vmSymbols::java_lang_ArrayStoreException(), CHECK_0); 1.3539 + initialize_class(vmSymbols::java_lang_ArithmeticException(), CHECK_0); 1.3540 + initialize_class(vmSymbols::java_lang_StackOverflowError(), CHECK_0); 1.3541 + initialize_class(vmSymbols::java_lang_IllegalMonitorStateException(), CHECK_0); 1.3542 + initialize_class(vmSymbols::java_lang_IllegalArgumentException(), CHECK_0); 1.3543 + } 1.3544 + 1.3545 + // See : bugid 4211085. 1.3546 + // Background : the static initializer of java.lang.Compiler tries to read 1.3547 + // property"java.compiler" and read & write property "java.vm.info". 1.3548 + // When a security manager is installed through the command line 1.3549 + // option "-Djava.security.manager", the above properties are not 1.3550 + // readable and the static initializer for java.lang.Compiler fails 1.3551 + // resulting in a NoClassDefFoundError. This can happen in any 1.3552 + // user code which calls methods in java.lang.Compiler. 1.3553 + // Hack : the hack is to pre-load and initialize this class, so that only 1.3554 + // system domains are on the stack when the properties are read. 1.3555 + // Currently even the AWT code has calls to methods in java.lang.Compiler. 1.3556 + // On the classic VM, java.lang.Compiler is loaded very early to load the JIT. 1.3557 + // Future Fix : the best fix is to grant everyone permissions to read "java.compiler" and 1.3558 + // read and write"java.vm.info" in the default policy file. See bugid 4211383 1.3559 + // Once that is done, we should remove this hack. 1.3560 + initialize_class(vmSymbols::java_lang_Compiler(), CHECK_0); 1.3561 + 1.3562 + // More hackery - the static initializer of java.lang.Compiler adds the string "nojit" to 1.3563 + // the java.vm.info property if no jit gets loaded through java.lang.Compiler (the hotspot 1.3564 + // compiler does not get loaded through java.lang.Compiler). "java -version" with the 1.3565 + // hotspot vm says "nojit" all the time which is confusing. So, we reset it here. 1.3566 + // This should also be taken out as soon as 4211383 gets fixed. 1.3567 + reset_vm_info_property(CHECK_0); 1.3568 + 1.3569 + quicken_jni_functions(); 1.3570 + 1.3571 + // Must be run after init_ft which initializes ft_enabled 1.3572 + if (TRACE_INITIALIZE() != JNI_OK) { 1.3573 + vm_exit_during_initialization("Failed to initialize tracing backend"); 1.3574 + } 1.3575 + 1.3576 + // Set flag that basic initialization has completed. Used by exceptions and various 1.3577 + // debug stuff, that does not work until all basic classes have been initialized. 1.3578 + set_init_completed(); 1.3579 + 1.3580 + Metaspace::post_initialize(); 1.3581 + 1.3582 +#ifndef USDT2 1.3583 + HS_DTRACE_PROBE(hotspot, vm__init__end); 1.3584 +#else /* USDT2 */ 1.3585 + HOTSPOT_VM_INIT_END(); 1.3586 +#endif /* USDT2 */ 1.3587 + 1.3588 + // record VM initialization completion time 1.3589 +#if INCLUDE_MANAGEMENT 1.3590 + Management::record_vm_init_completed(); 1.3591 +#endif // INCLUDE_MANAGEMENT 1.3592 + 1.3593 + // Compute system loader. Note that this has to occur after set_init_completed, since 1.3594 + // valid exceptions may be thrown in the process. 1.3595 + // Note that we do not use CHECK_0 here since we are inside an EXCEPTION_MARK and 1.3596 + // set_init_completed has just been called, causing exceptions not to be shortcut 1.3597 + // anymore. We call vm_exit_during_initialization directly instead. 1.3598 + SystemDictionary::compute_java_system_loader(THREAD); 1.3599 + if (HAS_PENDING_EXCEPTION) { 1.3600 + vm_exit_during_initialization(Handle(THREAD, PENDING_EXCEPTION)); 1.3601 + } 1.3602 + 1.3603 +#if INCLUDE_ALL_GCS 1.3604 + // Support for ConcurrentMarkSweep. This should be cleaned up 1.3605 + // and better encapsulated. The ugly nested if test would go away 1.3606 + // once things are properly refactored. XXX YSR 1.3607 + if (UseConcMarkSweepGC || UseG1GC) { 1.3608 + if (UseConcMarkSweepGC) { 1.3609 + ConcurrentMarkSweepThread::makeSurrogateLockerThread(THREAD); 1.3610 + } else { 1.3611 + ConcurrentMarkThread::makeSurrogateLockerThread(THREAD); 1.3612 + } 1.3613 + if (HAS_PENDING_EXCEPTION) { 1.3614 + vm_exit_during_initialization(Handle(THREAD, PENDING_EXCEPTION)); 1.3615 + } 1.3616 + } 1.3617 +#endif // INCLUDE_ALL_GCS 1.3618 + 1.3619 + // Always call even when there are not JVMTI environments yet, since environments 1.3620 + // may be attached late and JVMTI must track phases of VM execution 1.3621 + JvmtiExport::enter_live_phase(); 1.3622 + 1.3623 + // Signal Dispatcher needs to be started before VMInit event is posted 1.3624 + os::signal_init(); 1.3625 + 1.3626 + // Start Attach Listener if +StartAttachListener or it can't be started lazily 1.3627 + if (!DisableAttachMechanism) { 1.3628 + AttachListener::vm_start(); 1.3629 + if (StartAttachListener || AttachListener::init_at_startup()) { 1.3630 + AttachListener::init(); 1.3631 + } 1.3632 + } 1.3633 + 1.3634 + // Launch -Xrun agents 1.3635 + // Must be done in the JVMTI live phase so that for backward compatibility the JDWP 1.3636 + // back-end can launch with -Xdebug -Xrunjdwp. 1.3637 + if (!EagerXrunInit && Arguments::init_libraries_at_startup()) { 1.3638 + create_vm_init_libraries(); 1.3639 + } 1.3640 + 1.3641 + // Notify JVMTI agents that VM initialization is complete - nop if no agents. 1.3642 + JvmtiExport::post_vm_initialized(); 1.3643 + 1.3644 + if (TRACE_START() != JNI_OK) { 1.3645 + vm_exit_during_initialization("Failed to start tracing backend."); 1.3646 + } 1.3647 + 1.3648 + if (CleanChunkPoolAsync) { 1.3649 + Chunk::start_chunk_pool_cleaner_task(); 1.3650 + } 1.3651 + 1.3652 + // initialize compiler(s) 1.3653 +#if defined(COMPILER1) || defined(COMPILER2) || defined(SHARK) 1.3654 + CompileBroker::compilation_init(); 1.3655 +#endif 1.3656 + 1.3657 + if (EnableInvokeDynamic) { 1.3658 + // Pre-initialize some JSR292 core classes to avoid deadlock during class loading. 1.3659 + // It is done after compilers are initialized, because otherwise compilations of 1.3660 + // signature polymorphic MH intrinsics can be missed 1.3661 + // (see SystemDictionary::find_method_handle_intrinsic). 1.3662 + initialize_class(vmSymbols::java_lang_invoke_MethodHandle(), CHECK_0); 1.3663 + initialize_class(vmSymbols::java_lang_invoke_MemberName(), CHECK_0); 1.3664 + initialize_class(vmSymbols::java_lang_invoke_MethodHandleNatives(), CHECK_0); 1.3665 + } 1.3666 + 1.3667 +#if INCLUDE_MANAGEMENT 1.3668 + Management::initialize(THREAD); 1.3669 +#endif // INCLUDE_MANAGEMENT 1.3670 + 1.3671 + if (HAS_PENDING_EXCEPTION) { 1.3672 + // management agent fails to start possibly due to 1.3673 + // configuration problem and is responsible for printing 1.3674 + // stack trace if appropriate. Simply exit VM. 1.3675 + vm_exit(1); 1.3676 + } 1.3677 + 1.3678 + if (Arguments::has_profile()) FlatProfiler::engage(main_thread, true); 1.3679 + if (MemProfiling) MemProfiler::engage(); 1.3680 + StatSampler::engage(); 1.3681 + if (CheckJNICalls) JniPeriodicChecker::engage(); 1.3682 + 1.3683 + BiasedLocking::init(); 1.3684 + 1.3685 +#if INCLUDE_RTM_OPT 1.3686 + RTMLockingCounters::init(); 1.3687 +#endif 1.3688 + 1.3689 + if (JDK_Version::current().post_vm_init_hook_enabled()) { 1.3690 + call_postVMInitHook(THREAD); 1.3691 + // The Java side of PostVMInitHook.run must deal with all 1.3692 + // exceptions and provide means of diagnosis. 1.3693 + if (HAS_PENDING_EXCEPTION) { 1.3694 + CLEAR_PENDING_EXCEPTION; 1.3695 + } 1.3696 + } 1.3697 + 1.3698 + { 1.3699 + MutexLockerEx ml(PeriodicTask_lock, Mutex::_no_safepoint_check_flag); 1.3700 + // Make sure the watcher thread can be started by WatcherThread::start() 1.3701 + // or by dynamic enrollment. 1.3702 + WatcherThread::make_startable(); 1.3703 + // Start up the WatcherThread if there are any periodic tasks 1.3704 + // NOTE: All PeriodicTasks should be registered by now. If they 1.3705 + // aren't, late joiners might appear to start slowly (we might 1.3706 + // take a while to process their first tick). 1.3707 + if (PeriodicTask::num_tasks() > 0) { 1.3708 + WatcherThread::start(); 1.3709 + } 1.3710 + } 1.3711 + 1.3712 + // Give os specific code one last chance to start 1.3713 + os::init_3(); 1.3714 + 1.3715 + create_vm_timer.end(); 1.3716 +#ifdef ASSERT 1.3717 + _vm_complete = true; 1.3718 +#endif 1.3719 + return JNI_OK; 1.3720 +} 1.3721 + 1.3722 +// type for the Agent_OnLoad and JVM_OnLoad entry points 1.3723 +extern "C" { 1.3724 + typedef jint (JNICALL *OnLoadEntry_t)(JavaVM *, char *, void *); 1.3725 +} 1.3726 +// Find a command line agent library and return its entry point for 1.3727 +// -agentlib: -agentpath: -Xrun 1.3728 +// num_symbol_entries must be passed-in since only the caller knows the number of symbols in the array. 1.3729 +static OnLoadEntry_t lookup_on_load(AgentLibrary* agent, const char *on_load_symbols[], size_t num_symbol_entries) { 1.3730 + OnLoadEntry_t on_load_entry = NULL; 1.3731 + void *library = NULL; 1.3732 + 1.3733 + if (!agent->valid()) { 1.3734 + char buffer[JVM_MAXPATHLEN]; 1.3735 + char ebuf[1024]; 1.3736 + const char *name = agent->name(); 1.3737 + const char *msg = "Could not find agent library "; 1.3738 + 1.3739 + // First check to see if agent is statically linked into executable 1.3740 + if (os::find_builtin_agent(agent, on_load_symbols, num_symbol_entries)) { 1.3741 + library = agent->os_lib(); 1.3742 + } else if (agent->is_absolute_path()) { 1.3743 + library = os::dll_load(name, ebuf, sizeof ebuf); 1.3744 + if (library == NULL) { 1.3745 + const char *sub_msg = " in absolute path, with error: "; 1.3746 + size_t len = strlen(msg) + strlen(name) + strlen(sub_msg) + strlen(ebuf) + 1; 1.3747 + char *buf = NEW_C_HEAP_ARRAY(char, len, mtThread); 1.3748 + jio_snprintf(buf, len, "%s%s%s%s", msg, name, sub_msg, ebuf); 1.3749 + // If we can't find the agent, exit. 1.3750 + vm_exit_during_initialization(buf, NULL); 1.3751 + FREE_C_HEAP_ARRAY(char, buf, mtThread); 1.3752 + } 1.3753 + } else { 1.3754 + // Try to load the agent from the standard dll directory 1.3755 + if (os::dll_build_name(buffer, sizeof(buffer), Arguments::get_dll_dir(), 1.3756 + name)) { 1.3757 + library = os::dll_load(buffer, ebuf, sizeof ebuf); 1.3758 + } 1.3759 + if (library == NULL) { // Try the local directory 1.3760 + char ns[1] = {0}; 1.3761 + if (os::dll_build_name(buffer, sizeof(buffer), ns, name)) { 1.3762 + library = os::dll_load(buffer, ebuf, sizeof ebuf); 1.3763 + } 1.3764 + if (library == NULL) { 1.3765 + const char *sub_msg = " on the library path, with error: "; 1.3766 + size_t len = strlen(msg) + strlen(name) + strlen(sub_msg) + strlen(ebuf) + 1; 1.3767 + char *buf = NEW_C_HEAP_ARRAY(char, len, mtThread); 1.3768 + jio_snprintf(buf, len, "%s%s%s%s", msg, name, sub_msg, ebuf); 1.3769 + // If we can't find the agent, exit. 1.3770 + vm_exit_during_initialization(buf, NULL); 1.3771 + FREE_C_HEAP_ARRAY(char, buf, mtThread); 1.3772 + } 1.3773 + } 1.3774 + } 1.3775 + agent->set_os_lib(library); 1.3776 + agent->set_valid(); 1.3777 + } 1.3778 + 1.3779 + // Find the OnLoad function. 1.3780 + on_load_entry = 1.3781 + CAST_TO_FN_PTR(OnLoadEntry_t, os::find_agent_function(agent, 1.3782 + false, 1.3783 + on_load_symbols, 1.3784 + num_symbol_entries)); 1.3785 + return on_load_entry; 1.3786 +} 1.3787 + 1.3788 +// Find the JVM_OnLoad entry point 1.3789 +static OnLoadEntry_t lookup_jvm_on_load(AgentLibrary* agent) { 1.3790 + const char *on_load_symbols[] = JVM_ONLOAD_SYMBOLS; 1.3791 + return lookup_on_load(agent, on_load_symbols, sizeof(on_load_symbols) / sizeof(char*)); 1.3792 +} 1.3793 + 1.3794 +// Find the Agent_OnLoad entry point 1.3795 +static OnLoadEntry_t lookup_agent_on_load(AgentLibrary* agent) { 1.3796 + const char *on_load_symbols[] = AGENT_ONLOAD_SYMBOLS; 1.3797 + return lookup_on_load(agent, on_load_symbols, sizeof(on_load_symbols) / sizeof(char*)); 1.3798 +} 1.3799 + 1.3800 +// For backwards compatibility with -Xrun 1.3801 +// Convert libraries with no JVM_OnLoad, but which have Agent_OnLoad to be 1.3802 +// treated like -agentpath: 1.3803 +// Must be called before agent libraries are created 1.3804 +void Threads::convert_vm_init_libraries_to_agents() { 1.3805 + AgentLibrary* agent; 1.3806 + AgentLibrary* next; 1.3807 + 1.3808 + for (agent = Arguments::libraries(); agent != NULL; agent = next) { 1.3809 + next = agent->next(); // cache the next agent now as this agent may get moved off this list 1.3810 + OnLoadEntry_t on_load_entry = lookup_jvm_on_load(agent); 1.3811 + 1.3812 + // If there is an JVM_OnLoad function it will get called later, 1.3813 + // otherwise see if there is an Agent_OnLoad 1.3814 + if (on_load_entry == NULL) { 1.3815 + on_load_entry = lookup_agent_on_load(agent); 1.3816 + if (on_load_entry != NULL) { 1.3817 + // switch it to the agent list -- so that Agent_OnLoad will be called, 1.3818 + // JVM_OnLoad won't be attempted and Agent_OnUnload will 1.3819 + Arguments::convert_library_to_agent(agent); 1.3820 + } else { 1.3821 + vm_exit_during_initialization("Could not find JVM_OnLoad or Agent_OnLoad function in the library", agent->name()); 1.3822 + } 1.3823 + } 1.3824 + } 1.3825 +} 1.3826 + 1.3827 +// Create agents for -agentlib: -agentpath: and converted -Xrun 1.3828 +// Invokes Agent_OnLoad 1.3829 +// Called very early -- before JavaThreads exist 1.3830 +void Threads::create_vm_init_agents() { 1.3831 + extern struct JavaVM_ main_vm; 1.3832 + AgentLibrary* agent; 1.3833 + 1.3834 + JvmtiExport::enter_onload_phase(); 1.3835 + 1.3836 + for (agent = Arguments::agents(); agent != NULL; agent = agent->next()) { 1.3837 + OnLoadEntry_t on_load_entry = lookup_agent_on_load(agent); 1.3838 + 1.3839 + if (on_load_entry != NULL) { 1.3840 + // Invoke the Agent_OnLoad function 1.3841 + jint err = (*on_load_entry)(&main_vm, agent->options(), NULL); 1.3842 + if (err != JNI_OK) { 1.3843 + vm_exit_during_initialization("agent library failed to init", agent->name()); 1.3844 + } 1.3845 + } else { 1.3846 + vm_exit_during_initialization("Could not find Agent_OnLoad function in the agent library", agent->name()); 1.3847 + } 1.3848 + } 1.3849 + JvmtiExport::enter_primordial_phase(); 1.3850 +} 1.3851 + 1.3852 +extern "C" { 1.3853 + typedef void (JNICALL *Agent_OnUnload_t)(JavaVM *); 1.3854 +} 1.3855 + 1.3856 +void Threads::shutdown_vm_agents() { 1.3857 + // Send any Agent_OnUnload notifications 1.3858 + const char *on_unload_symbols[] = AGENT_ONUNLOAD_SYMBOLS; 1.3859 + size_t num_symbol_entries = ARRAY_SIZE(on_unload_symbols); 1.3860 + extern struct JavaVM_ main_vm; 1.3861 + for (AgentLibrary* agent = Arguments::agents(); agent != NULL; agent = agent->next()) { 1.3862 + 1.3863 + // Find the Agent_OnUnload function. 1.3864 + Agent_OnUnload_t unload_entry = CAST_TO_FN_PTR(Agent_OnUnload_t, 1.3865 + os::find_agent_function(agent, 1.3866 + false, 1.3867 + on_unload_symbols, 1.3868 + num_symbol_entries)); 1.3869 + 1.3870 + // Invoke the Agent_OnUnload function 1.3871 + if (unload_entry != NULL) { 1.3872 + JavaThread* thread = JavaThread::current(); 1.3873 + ThreadToNativeFromVM ttn(thread); 1.3874 + HandleMark hm(thread); 1.3875 + (*unload_entry)(&main_vm); 1.3876 + } 1.3877 + } 1.3878 +} 1.3879 + 1.3880 +// Called for after the VM is initialized for -Xrun libraries which have not been converted to agent libraries 1.3881 +// Invokes JVM_OnLoad 1.3882 +void Threads::create_vm_init_libraries() { 1.3883 + extern struct JavaVM_ main_vm; 1.3884 + AgentLibrary* agent; 1.3885 + 1.3886 + for (agent = Arguments::libraries(); agent != NULL; agent = agent->next()) { 1.3887 + OnLoadEntry_t on_load_entry = lookup_jvm_on_load(agent); 1.3888 + 1.3889 + if (on_load_entry != NULL) { 1.3890 + // Invoke the JVM_OnLoad function 1.3891 + JavaThread* thread = JavaThread::current(); 1.3892 + ThreadToNativeFromVM ttn(thread); 1.3893 + HandleMark hm(thread); 1.3894 + jint err = (*on_load_entry)(&main_vm, agent->options(), NULL); 1.3895 + if (err != JNI_OK) { 1.3896 + vm_exit_during_initialization("-Xrun library failed to init", agent->name()); 1.3897 + } 1.3898 + } else { 1.3899 + vm_exit_during_initialization("Could not find JVM_OnLoad function in -Xrun library", agent->name()); 1.3900 + } 1.3901 + } 1.3902 +} 1.3903 + 1.3904 +// Last thread running calls java.lang.Shutdown.shutdown() 1.3905 +void JavaThread::invoke_shutdown_hooks() { 1.3906 + HandleMark hm(this); 1.3907 + 1.3908 + // We could get here with a pending exception, if so clear it now. 1.3909 + if (this->has_pending_exception()) { 1.3910 + this->clear_pending_exception(); 1.3911 + } 1.3912 + 1.3913 + EXCEPTION_MARK; 1.3914 + Klass* k = 1.3915 + SystemDictionary::resolve_or_null(vmSymbols::java_lang_Shutdown(), 1.3916 + THREAD); 1.3917 + if (k != NULL) { 1.3918 + // SystemDictionary::resolve_or_null will return null if there was 1.3919 + // an exception. If we cannot load the Shutdown class, just don't 1.3920 + // call Shutdown.shutdown() at all. This will mean the shutdown hooks 1.3921 + // and finalizers (if runFinalizersOnExit is set) won't be run. 1.3922 + // Note that if a shutdown hook was registered or runFinalizersOnExit 1.3923 + // was called, the Shutdown class would have already been loaded 1.3924 + // (Runtime.addShutdownHook and runFinalizersOnExit will load it). 1.3925 + instanceKlassHandle shutdown_klass (THREAD, k); 1.3926 + JavaValue result(T_VOID); 1.3927 + JavaCalls::call_static(&result, 1.3928 + shutdown_klass, 1.3929 + vmSymbols::shutdown_method_name(), 1.3930 + vmSymbols::void_method_signature(), 1.3931 + THREAD); 1.3932 + } 1.3933 + CLEAR_PENDING_EXCEPTION; 1.3934 +} 1.3935 + 1.3936 +// Threads::destroy_vm() is normally called from jni_DestroyJavaVM() when 1.3937 +// the program falls off the end of main(). Another VM exit path is through 1.3938 +// vm_exit() when the program calls System.exit() to return a value or when 1.3939 +// there is a serious error in VM. The two shutdown paths are not exactly 1.3940 +// the same, but they share Shutdown.shutdown() at Java level and before_exit() 1.3941 +// and VM_Exit op at VM level. 1.3942 +// 1.3943 +// Shutdown sequence: 1.3944 +// + Shutdown native memory tracking if it is on 1.3945 +// + Wait until we are the last non-daemon thread to execute 1.3946 +// <-- every thing is still working at this moment --> 1.3947 +// + Call java.lang.Shutdown.shutdown(), which will invoke Java level 1.3948 +// shutdown hooks, run finalizers if finalization-on-exit 1.3949 +// + Call before_exit(), prepare for VM exit 1.3950 +// > run VM level shutdown hooks (they are registered through JVM_OnExit(), 1.3951 +// currently the only user of this mechanism is File.deleteOnExit()) 1.3952 +// > stop flat profiler, StatSampler, watcher thread, CMS threads, 1.3953 +// post thread end and vm death events to JVMTI, 1.3954 +// stop signal thread 1.3955 +// + Call JavaThread::exit(), it will: 1.3956 +// > release JNI handle blocks, remove stack guard pages 1.3957 +// > remove this thread from Threads list 1.3958 +// <-- no more Java code from this thread after this point --> 1.3959 +// + Stop VM thread, it will bring the remaining VM to a safepoint and stop 1.3960 +// the compiler threads at safepoint 1.3961 +// <-- do not use anything that could get blocked by Safepoint --> 1.3962 +// + Disable tracing at JNI/JVM barriers 1.3963 +// + Set _vm_exited flag for threads that are still running native code 1.3964 +// + Delete this thread 1.3965 +// + Call exit_globals() 1.3966 +// > deletes tty 1.3967 +// > deletes PerfMemory resources 1.3968 +// + Return to caller 1.3969 + 1.3970 +bool Threads::destroy_vm() { 1.3971 + JavaThread* thread = JavaThread::current(); 1.3972 + 1.3973 +#ifdef ASSERT 1.3974 + _vm_complete = false; 1.3975 +#endif 1.3976 + // Wait until we are the last non-daemon thread to execute 1.3977 + { MutexLocker nu(Threads_lock); 1.3978 + while (Threads::number_of_non_daemon_threads() > 1 ) 1.3979 + // This wait should make safepoint checks, wait without a timeout, 1.3980 + // and wait as a suspend-equivalent condition. 1.3981 + // 1.3982 + // Note: If the FlatProfiler is running and this thread is waiting 1.3983 + // for another non-daemon thread to finish, then the FlatProfiler 1.3984 + // is waiting for the external suspend request on this thread to 1.3985 + // complete. wait_for_ext_suspend_completion() will eventually 1.3986 + // timeout, but that takes time. Making this wait a suspend- 1.3987 + // equivalent condition solves that timeout problem. 1.3988 + // 1.3989 + Threads_lock->wait(!Mutex::_no_safepoint_check_flag, 0, 1.3990 + Mutex::_as_suspend_equivalent_flag); 1.3991 + } 1.3992 + 1.3993 + // Hang forever on exit if we are reporting an error. 1.3994 + if (ShowMessageBoxOnError && is_error_reported()) { 1.3995 + os::infinite_sleep(); 1.3996 + } 1.3997 + os::wait_for_keypress_at_exit(); 1.3998 + 1.3999 + if (JDK_Version::is_jdk12x_version()) { 1.4000 + // We are the last thread running, so check if finalizers should be run. 1.4001 + // For 1.3 or later this is done in thread->invoke_shutdown_hooks() 1.4002 + HandleMark rm(thread); 1.4003 + Universe::run_finalizers_on_exit(); 1.4004 + } else { 1.4005 + // run Java level shutdown hooks 1.4006 + thread->invoke_shutdown_hooks(); 1.4007 + } 1.4008 + 1.4009 + before_exit(thread); 1.4010 + 1.4011 + thread->exit(true); 1.4012 + 1.4013 + // Stop VM thread. 1.4014 + { 1.4015 + // 4945125 The vm thread comes to a safepoint during exit. 1.4016 + // GC vm_operations can get caught at the safepoint, and the 1.4017 + // heap is unparseable if they are caught. Grab the Heap_lock 1.4018 + // to prevent this. The GC vm_operations will not be able to 1.4019 + // queue until after the vm thread is dead. After this point, 1.4020 + // we'll never emerge out of the safepoint before the VM exits. 1.4021 + 1.4022 + MutexLocker ml(Heap_lock); 1.4023 + 1.4024 + VMThread::wait_for_vm_thread_exit(); 1.4025 + assert(SafepointSynchronize::is_at_safepoint(), "VM thread should exit at Safepoint"); 1.4026 + VMThread::destroy(); 1.4027 + } 1.4028 + 1.4029 + // clean up ideal graph printers 1.4030 +#if defined(COMPILER2) && !defined(PRODUCT) 1.4031 + IdealGraphPrinter::clean_up(); 1.4032 +#endif 1.4033 + 1.4034 + // Now, all Java threads are gone except daemon threads. Daemon threads 1.4035 + // running Java code or in VM are stopped by the Safepoint. However, 1.4036 + // daemon threads executing native code are still running. But they 1.4037 + // will be stopped at native=>Java/VM barriers. Note that we can't 1.4038 + // simply kill or suspend them, as it is inherently deadlock-prone. 1.4039 + 1.4040 +#ifndef PRODUCT 1.4041 + // disable function tracing at JNI/JVM barriers 1.4042 + TraceJNICalls = false; 1.4043 + TraceJVMCalls = false; 1.4044 + TraceRuntimeCalls = false; 1.4045 +#endif 1.4046 + 1.4047 + VM_Exit::set_vm_exited(); 1.4048 + 1.4049 + notify_vm_shutdown(); 1.4050 + 1.4051 + delete thread; 1.4052 + 1.4053 + // exit_globals() will delete tty 1.4054 + exit_globals(); 1.4055 + 1.4056 + return true; 1.4057 +} 1.4058 + 1.4059 + 1.4060 +jboolean Threads::is_supported_jni_version_including_1_1(jint version) { 1.4061 + if (version == JNI_VERSION_1_1) return JNI_TRUE; 1.4062 + return is_supported_jni_version(version); 1.4063 +} 1.4064 + 1.4065 + 1.4066 +jboolean Threads::is_supported_jni_version(jint version) { 1.4067 + if (version == JNI_VERSION_1_2) return JNI_TRUE; 1.4068 + if (version == JNI_VERSION_1_4) return JNI_TRUE; 1.4069 + if (version == JNI_VERSION_1_6) return JNI_TRUE; 1.4070 + if (version == JNI_VERSION_1_8) return JNI_TRUE; 1.4071 + return JNI_FALSE; 1.4072 +} 1.4073 + 1.4074 + 1.4075 +void Threads::add(JavaThread* p, bool force_daemon) { 1.4076 + // The threads lock must be owned at this point 1.4077 + assert_locked_or_safepoint(Threads_lock); 1.4078 + 1.4079 + // See the comment for this method in thread.hpp for its purpose and 1.4080 + // why it is called here. 1.4081 + p->initialize_queues(); 1.4082 + p->set_next(_thread_list); 1.4083 + _thread_list = p; 1.4084 + _number_of_threads++; 1.4085 + oop threadObj = p->threadObj(); 1.4086 + bool daemon = true; 1.4087 + // Bootstrapping problem: threadObj can be null for initial 1.4088 + // JavaThread (or for threads attached via JNI) 1.4089 + if ((!force_daemon) && (threadObj == NULL || !java_lang_Thread::is_daemon(threadObj))) { 1.4090 + _number_of_non_daemon_threads++; 1.4091 + daemon = false; 1.4092 + } 1.4093 + 1.4094 + p->set_safepoint_visible(true); 1.4095 + 1.4096 + ThreadService::add_thread(p, daemon); 1.4097 + 1.4098 + // Possible GC point. 1.4099 + Events::log(p, "Thread added: " INTPTR_FORMAT, p); 1.4100 +} 1.4101 + 1.4102 +void Threads::remove(JavaThread* p) { 1.4103 + // Extra scope needed for Thread_lock, so we can check 1.4104 + // that we do not remove thread without safepoint code notice 1.4105 + { MutexLocker ml(Threads_lock); 1.4106 + 1.4107 + assert(includes(p), "p must be present"); 1.4108 + 1.4109 + JavaThread* current = _thread_list; 1.4110 + JavaThread* prev = NULL; 1.4111 + 1.4112 + while (current != p) { 1.4113 + prev = current; 1.4114 + current = current->next(); 1.4115 + } 1.4116 + 1.4117 + if (prev) { 1.4118 + prev->set_next(current->next()); 1.4119 + } else { 1.4120 + _thread_list = p->next(); 1.4121 + } 1.4122 + _number_of_threads--; 1.4123 + oop threadObj = p->threadObj(); 1.4124 + bool daemon = true; 1.4125 + if (threadObj == NULL || !java_lang_Thread::is_daemon(threadObj)) { 1.4126 + _number_of_non_daemon_threads--; 1.4127 + daemon = false; 1.4128 + 1.4129 + // Only one thread left, do a notify on the Threads_lock so a thread waiting 1.4130 + // on destroy_vm will wake up. 1.4131 + if (number_of_non_daemon_threads() == 1) 1.4132 + Threads_lock->notify_all(); 1.4133 + } 1.4134 + ThreadService::remove_thread(p, daemon); 1.4135 + 1.4136 + // Make sure that safepoint code disregard this thread. This is needed since 1.4137 + // the thread might mess around with locks after this point. This can cause it 1.4138 + // to do callbacks into the safepoint code. However, the safepoint code is not aware 1.4139 + // of this thread since it is removed from the queue. 1.4140 + p->set_terminated_value(); 1.4141 + 1.4142 + // Now, this thread is not visible to safepoint 1.4143 + p->set_safepoint_visible(false); 1.4144 + // once the thread becomes safepoint invisible, we can not use its per-thread 1.4145 + // recorder. And Threads::do_threads() no longer walks this thread, so we have 1.4146 + // to release its per-thread recorder here. 1.4147 + MemTracker::thread_exiting(p); 1.4148 + } // unlock Threads_lock 1.4149 + 1.4150 + // Since Events::log uses a lock, we grab it outside the Threads_lock 1.4151 + Events::log(p, "Thread exited: " INTPTR_FORMAT, p); 1.4152 +} 1.4153 + 1.4154 +// Threads_lock must be held when this is called (or must be called during a safepoint) 1.4155 +bool Threads::includes(JavaThread* p) { 1.4156 + assert(Threads_lock->is_locked(), "sanity check"); 1.4157 + ALL_JAVA_THREADS(q) { 1.4158 + if (q == p ) { 1.4159 + return true; 1.4160 + } 1.4161 + } 1.4162 + return false; 1.4163 +} 1.4164 + 1.4165 +// Operations on the Threads list for GC. These are not explicitly locked, 1.4166 +// but the garbage collector must provide a safe context for them to run. 1.4167 +// In particular, these things should never be called when the Threads_lock 1.4168 +// is held by some other thread. (Note: the Safepoint abstraction also 1.4169 +// uses the Threads_lock to gurantee this property. It also makes sure that 1.4170 +// all threads gets blocked when exiting or starting). 1.4171 + 1.4172 +void Threads::oops_do(OopClosure* f, CLDToOopClosure* cld_f, CodeBlobClosure* cf) { 1.4173 + ALL_JAVA_THREADS(p) { 1.4174 + p->oops_do(f, cld_f, cf); 1.4175 + } 1.4176 + VMThread::vm_thread()->oops_do(f, cld_f, cf); 1.4177 +} 1.4178 + 1.4179 +void Threads::possibly_parallel_oops_do(OopClosure* f, CLDToOopClosure* cld_f, CodeBlobClosure* cf) { 1.4180 + // Introduce a mechanism allowing parallel threads to claim threads as 1.4181 + // root groups. Overhead should be small enough to use all the time, 1.4182 + // even in sequential code. 1.4183 + SharedHeap* sh = SharedHeap::heap(); 1.4184 + // Cannot yet substitute active_workers for n_par_threads 1.4185 + // because of G1CollectedHeap::verify() use of 1.4186 + // SharedHeap::process_strong_roots(). n_par_threads == 0 will 1.4187 + // turn off parallelism in process_strong_roots while active_workers 1.4188 + // is being used for parallelism elsewhere. 1.4189 + bool is_par = sh->n_par_threads() > 0; 1.4190 + assert(!is_par || 1.4191 + (SharedHeap::heap()->n_par_threads() == 1.4192 + SharedHeap::heap()->workers()->active_workers()), "Mismatch"); 1.4193 + int cp = SharedHeap::heap()->strong_roots_parity(); 1.4194 + ALL_JAVA_THREADS(p) { 1.4195 + if (p->claim_oops_do(is_par, cp)) { 1.4196 + p->oops_do(f, cld_f, cf); 1.4197 + } 1.4198 + } 1.4199 + VMThread* vmt = VMThread::vm_thread(); 1.4200 + if (vmt->claim_oops_do(is_par, cp)) { 1.4201 + vmt->oops_do(f, cld_f, cf); 1.4202 + } 1.4203 +} 1.4204 + 1.4205 +#if INCLUDE_ALL_GCS 1.4206 +// Used by ParallelScavenge 1.4207 +void Threads::create_thread_roots_tasks(GCTaskQueue* q) { 1.4208 + ALL_JAVA_THREADS(p) { 1.4209 + q->enqueue(new ThreadRootsTask(p)); 1.4210 + } 1.4211 + q->enqueue(new ThreadRootsTask(VMThread::vm_thread())); 1.4212 +} 1.4213 + 1.4214 +// Used by Parallel Old 1.4215 +void Threads::create_thread_roots_marking_tasks(GCTaskQueue* q) { 1.4216 + ALL_JAVA_THREADS(p) { 1.4217 + q->enqueue(new ThreadRootsMarkingTask(p)); 1.4218 + } 1.4219 + q->enqueue(new ThreadRootsMarkingTask(VMThread::vm_thread())); 1.4220 +} 1.4221 +#endif // INCLUDE_ALL_GCS 1.4222 + 1.4223 +void Threads::nmethods_do(CodeBlobClosure* cf) { 1.4224 + ALL_JAVA_THREADS(p) { 1.4225 + p->nmethods_do(cf); 1.4226 + } 1.4227 + VMThread::vm_thread()->nmethods_do(cf); 1.4228 +} 1.4229 + 1.4230 +void Threads::metadata_do(void f(Metadata*)) { 1.4231 + ALL_JAVA_THREADS(p) { 1.4232 + p->metadata_do(f); 1.4233 + } 1.4234 +} 1.4235 + 1.4236 +void Threads::gc_epilogue() { 1.4237 + ALL_JAVA_THREADS(p) { 1.4238 + p->gc_epilogue(); 1.4239 + } 1.4240 +} 1.4241 + 1.4242 +void Threads::gc_prologue() { 1.4243 + ALL_JAVA_THREADS(p) { 1.4244 + p->gc_prologue(); 1.4245 + } 1.4246 +} 1.4247 + 1.4248 +void Threads::deoptimized_wrt_marked_nmethods() { 1.4249 + ALL_JAVA_THREADS(p) { 1.4250 + p->deoptimized_wrt_marked_nmethods(); 1.4251 + } 1.4252 +} 1.4253 + 1.4254 + 1.4255 +// Get count Java threads that are waiting to enter the specified monitor. 1.4256 +GrowableArray<JavaThread*>* Threads::get_pending_threads(int count, 1.4257 + address monitor, bool doLock) { 1.4258 + assert(doLock || SafepointSynchronize::is_at_safepoint(), 1.4259 + "must grab Threads_lock or be at safepoint"); 1.4260 + GrowableArray<JavaThread*>* result = new GrowableArray<JavaThread*>(count); 1.4261 + 1.4262 + int i = 0; 1.4263 + { 1.4264 + MutexLockerEx ml(doLock ? Threads_lock : NULL); 1.4265 + ALL_JAVA_THREADS(p) { 1.4266 + if (p->is_Compiler_thread()) continue; 1.4267 + 1.4268 + address pending = (address)p->current_pending_monitor(); 1.4269 + if (pending == monitor) { // found a match 1.4270 + if (i < count) result->append(p); // save the first count matches 1.4271 + i++; 1.4272 + } 1.4273 + } 1.4274 + } 1.4275 + return result; 1.4276 +} 1.4277 + 1.4278 + 1.4279 +JavaThread *Threads::owning_thread_from_monitor_owner(address owner, bool doLock) { 1.4280 + assert(doLock || 1.4281 + Threads_lock->owned_by_self() || 1.4282 + SafepointSynchronize::is_at_safepoint(), 1.4283 + "must grab Threads_lock or be at safepoint"); 1.4284 + 1.4285 + // NULL owner means not locked so we can skip the search 1.4286 + if (owner == NULL) return NULL; 1.4287 + 1.4288 + { 1.4289 + MutexLockerEx ml(doLock ? Threads_lock : NULL); 1.4290 + ALL_JAVA_THREADS(p) { 1.4291 + // first, see if owner is the address of a Java thread 1.4292 + if (owner == (address)p) return p; 1.4293 + } 1.4294 + } 1.4295 + // Cannot assert on lack of success here since this function may be 1.4296 + // used by code that is trying to report useful problem information 1.4297 + // like deadlock detection. 1.4298 + if (UseHeavyMonitors) return NULL; 1.4299 + 1.4300 + // 1.4301 + // If we didn't find a matching Java thread and we didn't force use of 1.4302 + // heavyweight monitors, then the owner is the stack address of the 1.4303 + // Lock Word in the owning Java thread's stack. 1.4304 + // 1.4305 + JavaThread* the_owner = NULL; 1.4306 + { 1.4307 + MutexLockerEx ml(doLock ? Threads_lock : NULL); 1.4308 + ALL_JAVA_THREADS(q) { 1.4309 + if (q->is_lock_owned(owner)) { 1.4310 + the_owner = q; 1.4311 + break; 1.4312 + } 1.4313 + } 1.4314 + } 1.4315 + // cannot assert on lack of success here; see above comment 1.4316 + return the_owner; 1.4317 +} 1.4318 + 1.4319 +// Threads::print_on() is called at safepoint by VM_PrintThreads operation. 1.4320 +void Threads::print_on(outputStream* st, bool print_stacks, bool internal_format, bool print_concurrent_locks) { 1.4321 + char buf[32]; 1.4322 + st->print_cr("%s", os::local_time_string(buf, sizeof(buf))); 1.4323 + 1.4324 + st->print_cr("Full thread dump %s (%s %s):", 1.4325 + Abstract_VM_Version::vm_name(), 1.4326 + Abstract_VM_Version::vm_release(), 1.4327 + Abstract_VM_Version::vm_info_string() 1.4328 + ); 1.4329 + st->cr(); 1.4330 + 1.4331 +#if INCLUDE_ALL_GCS 1.4332 + // Dump concurrent locks 1.4333 + ConcurrentLocksDump concurrent_locks; 1.4334 + if (print_concurrent_locks) { 1.4335 + concurrent_locks.dump_at_safepoint(); 1.4336 + } 1.4337 +#endif // INCLUDE_ALL_GCS 1.4338 + 1.4339 + ALL_JAVA_THREADS(p) { 1.4340 + ResourceMark rm; 1.4341 + p->print_on(st); 1.4342 + if (print_stacks) { 1.4343 + if (internal_format) { 1.4344 + p->trace_stack(); 1.4345 + } else { 1.4346 + p->print_stack_on(st); 1.4347 + } 1.4348 + } 1.4349 + st->cr(); 1.4350 +#if INCLUDE_ALL_GCS 1.4351 + if (print_concurrent_locks) { 1.4352 + concurrent_locks.print_locks_on(p, st); 1.4353 + } 1.4354 +#endif // INCLUDE_ALL_GCS 1.4355 + } 1.4356 + 1.4357 + VMThread::vm_thread()->print_on(st); 1.4358 + st->cr(); 1.4359 + Universe::heap()->print_gc_threads_on(st); 1.4360 + WatcherThread* wt = WatcherThread::watcher_thread(); 1.4361 + if (wt != NULL) { 1.4362 + wt->print_on(st); 1.4363 + st->cr(); 1.4364 + } 1.4365 + CompileBroker::print_compiler_threads_on(st); 1.4366 + st->flush(); 1.4367 +} 1.4368 + 1.4369 +// Threads::print_on_error() is called by fatal error handler. It's possible 1.4370 +// that VM is not at safepoint and/or current thread is inside signal handler. 1.4371 +// Don't print stack trace, as the stack may not be walkable. Don't allocate 1.4372 +// memory (even in resource area), it might deadlock the error handler. 1.4373 +void Threads::print_on_error(outputStream* st, Thread* current, char* buf, int buflen) { 1.4374 + bool found_current = false; 1.4375 + st->print_cr("Java Threads: ( => current thread )"); 1.4376 + ALL_JAVA_THREADS(thread) { 1.4377 + bool is_current = (current == thread); 1.4378 + found_current = found_current || is_current; 1.4379 + 1.4380 + st->print("%s", is_current ? "=>" : " "); 1.4381 + 1.4382 + st->print(PTR_FORMAT, thread); 1.4383 + st->print(" "); 1.4384 + thread->print_on_error(st, buf, buflen); 1.4385 + st->cr(); 1.4386 + } 1.4387 + st->cr(); 1.4388 + 1.4389 + st->print_cr("Other Threads:"); 1.4390 + if (VMThread::vm_thread()) { 1.4391 + bool is_current = (current == VMThread::vm_thread()); 1.4392 + found_current = found_current || is_current; 1.4393 + st->print("%s", current == VMThread::vm_thread() ? "=>" : " "); 1.4394 + 1.4395 + st->print(PTR_FORMAT, VMThread::vm_thread()); 1.4396 + st->print(" "); 1.4397 + VMThread::vm_thread()->print_on_error(st, buf, buflen); 1.4398 + st->cr(); 1.4399 + } 1.4400 + WatcherThread* wt = WatcherThread::watcher_thread(); 1.4401 + if (wt != NULL) { 1.4402 + bool is_current = (current == wt); 1.4403 + found_current = found_current || is_current; 1.4404 + st->print("%s", is_current ? "=>" : " "); 1.4405 + 1.4406 + st->print(PTR_FORMAT, wt); 1.4407 + st->print(" "); 1.4408 + wt->print_on_error(st, buf, buflen); 1.4409 + st->cr(); 1.4410 + } 1.4411 + if (!found_current) { 1.4412 + st->cr(); 1.4413 + st->print("=>" PTR_FORMAT " (exited) ", current); 1.4414 + current->print_on_error(st, buf, buflen); 1.4415 + st->cr(); 1.4416 + } 1.4417 +} 1.4418 + 1.4419 +// Internal SpinLock and Mutex 1.4420 +// Based on ParkEvent 1.4421 + 1.4422 +// Ad-hoc mutual exclusion primitives: SpinLock and Mux 1.4423 +// 1.4424 +// We employ SpinLocks _only for low-contention, fixed-length 1.4425 +// short-duration critical sections where we're concerned 1.4426 +// about native mutex_t or HotSpot Mutex:: latency. 1.4427 +// The mux construct provides a spin-then-block mutual exclusion 1.4428 +// mechanism. 1.4429 +// 1.4430 +// Testing has shown that contention on the ListLock guarding gFreeList 1.4431 +// is common. If we implement ListLock as a simple SpinLock it's common 1.4432 +// for the JVM to devolve to yielding with little progress. This is true 1.4433 +// despite the fact that the critical sections protected by ListLock are 1.4434 +// extremely short. 1.4435 +// 1.4436 +// TODO-FIXME: ListLock should be of type SpinLock. 1.4437 +// We should make this a 1st-class type, integrated into the lock 1.4438 +// hierarchy as leaf-locks. Critically, the SpinLock structure 1.4439 +// should have sufficient padding to avoid false-sharing and excessive 1.4440 +// cache-coherency traffic. 1.4441 + 1.4442 + 1.4443 +typedef volatile int SpinLockT ; 1.4444 + 1.4445 +void Thread::SpinAcquire (volatile int * adr, const char * LockName) { 1.4446 + if (Atomic::cmpxchg (1, adr, 0) == 0) { 1.4447 + return ; // normal fast-path return 1.4448 + } 1.4449 + 1.4450 + // Slow-path : We've encountered contention -- Spin/Yield/Block strategy. 1.4451 + TEVENT (SpinAcquire - ctx) ; 1.4452 + int ctr = 0 ; 1.4453 + int Yields = 0 ; 1.4454 + for (;;) { 1.4455 + while (*adr != 0) { 1.4456 + ++ctr ; 1.4457 + if ((ctr & 0xFFF) == 0 || !os::is_MP()) { 1.4458 + if (Yields > 5) { 1.4459 + os::naked_short_sleep(1); 1.4460 + } else { 1.4461 + os::NakedYield() ; 1.4462 + ++Yields ; 1.4463 + } 1.4464 + } else { 1.4465 + SpinPause() ; 1.4466 + } 1.4467 + } 1.4468 + if (Atomic::cmpxchg (1, adr, 0) == 0) return ; 1.4469 + } 1.4470 +} 1.4471 + 1.4472 +void Thread::SpinRelease (volatile int * adr) { 1.4473 + assert (*adr != 0, "invariant") ; 1.4474 + OrderAccess::fence() ; // guarantee at least release consistency. 1.4475 + // Roach-motel semantics. 1.4476 + // It's safe if subsequent LDs and STs float "up" into the critical section, 1.4477 + // but prior LDs and STs within the critical section can't be allowed 1.4478 + // to reorder or float past the ST that releases the lock. 1.4479 + *adr = 0 ; 1.4480 +} 1.4481 + 1.4482 +// muxAcquire and muxRelease: 1.4483 +// 1.4484 +// * muxAcquire and muxRelease support a single-word lock-word construct. 1.4485 +// The LSB of the word is set IFF the lock is held. 1.4486 +// The remainder of the word points to the head of a singly-linked list 1.4487 +// of threads blocked on the lock. 1.4488 +// 1.4489 +// * The current implementation of muxAcquire-muxRelease uses its own 1.4490 +// dedicated Thread._MuxEvent instance. If we're interested in 1.4491 +// minimizing the peak number of extant ParkEvent instances then 1.4492 +// we could eliminate _MuxEvent and "borrow" _ParkEvent as long 1.4493 +// as certain invariants were satisfied. Specifically, care would need 1.4494 +// to be taken with regards to consuming unpark() "permits". 1.4495 +// A safe rule of thumb is that a thread would never call muxAcquire() 1.4496 +// if it's enqueued (cxq, EntryList, WaitList, etc) and will subsequently 1.4497 +// park(). Otherwise the _ParkEvent park() operation in muxAcquire() could 1.4498 +// consume an unpark() permit intended for monitorenter, for instance. 1.4499 +// One way around this would be to widen the restricted-range semaphore 1.4500 +// implemented in park(). Another alternative would be to provide 1.4501 +// multiple instances of the PlatformEvent() for each thread. One 1.4502 +// instance would be dedicated to muxAcquire-muxRelease, for instance. 1.4503 +// 1.4504 +// * Usage: 1.4505 +// -- Only as leaf locks 1.4506 +// -- for short-term locking only as muxAcquire does not perform 1.4507 +// thread state transitions. 1.4508 +// 1.4509 +// Alternatives: 1.4510 +// * We could implement muxAcquire and muxRelease with MCS or CLH locks 1.4511 +// but with parking or spin-then-park instead of pure spinning. 1.4512 +// * Use Taura-Oyama-Yonenzawa locks. 1.4513 +// * It's possible to construct a 1-0 lock if we encode the lockword as 1.4514 +// (List,LockByte). Acquire will CAS the full lockword while Release 1.4515 +// will STB 0 into the LockByte. The 1-0 scheme admits stranding, so 1.4516 +// acquiring threads use timers (ParkTimed) to detect and recover from 1.4517 +// the stranding window. Thread/Node structures must be aligned on 256-byte 1.4518 +// boundaries by using placement-new. 1.4519 +// * Augment MCS with advisory back-link fields maintained with CAS(). 1.4520 +// Pictorially: LockWord -> T1 <-> T2 <-> T3 <-> ... <-> Tn <-> Owner. 1.4521 +// The validity of the backlinks must be ratified before we trust the value. 1.4522 +// If the backlinks are invalid the exiting thread must back-track through the 1.4523 +// the forward links, which are always trustworthy. 1.4524 +// * Add a successor indication. The LockWord is currently encoded as 1.4525 +// (List, LOCKBIT:1). We could also add a SUCCBIT or an explicit _succ variable 1.4526 +// to provide the usual futile-wakeup optimization. 1.4527 +// See RTStt for details. 1.4528 +// * Consider schedctl.sc_nopreempt to cover the critical section. 1.4529 +// 1.4530 + 1.4531 + 1.4532 +typedef volatile intptr_t MutexT ; // Mux Lock-word 1.4533 +enum MuxBits { LOCKBIT = 1 } ; 1.4534 + 1.4535 +void Thread::muxAcquire (volatile intptr_t * Lock, const char * LockName) { 1.4536 + intptr_t w = Atomic::cmpxchg_ptr (LOCKBIT, Lock, 0) ; 1.4537 + if (w == 0) return ; 1.4538 + if ((w & LOCKBIT) == 0 && Atomic::cmpxchg_ptr (w|LOCKBIT, Lock, w) == w) { 1.4539 + return ; 1.4540 + } 1.4541 + 1.4542 + TEVENT (muxAcquire - Contention) ; 1.4543 + ParkEvent * const Self = Thread::current()->_MuxEvent ; 1.4544 + assert ((intptr_t(Self) & LOCKBIT) == 0, "invariant") ; 1.4545 + for (;;) { 1.4546 + int its = (os::is_MP() ? 100 : 0) + 1 ; 1.4547 + 1.4548 + // Optional spin phase: spin-then-park strategy 1.4549 + while (--its >= 0) { 1.4550 + w = *Lock ; 1.4551 + if ((w & LOCKBIT) == 0 && Atomic::cmpxchg_ptr (w|LOCKBIT, Lock, w) == w) { 1.4552 + return ; 1.4553 + } 1.4554 + } 1.4555 + 1.4556 + Self->reset() ; 1.4557 + Self->OnList = intptr_t(Lock) ; 1.4558 + // The following fence() isn't _strictly necessary as the subsequent 1.4559 + // CAS() both serializes execution and ratifies the fetched *Lock value. 1.4560 + OrderAccess::fence(); 1.4561 + for (;;) { 1.4562 + w = *Lock ; 1.4563 + if ((w & LOCKBIT) == 0) { 1.4564 + if (Atomic::cmpxchg_ptr (w|LOCKBIT, Lock, w) == w) { 1.4565 + Self->OnList = 0 ; // hygiene - allows stronger asserts 1.4566 + return ; 1.4567 + } 1.4568 + continue ; // Interference -- *Lock changed -- Just retry 1.4569 + } 1.4570 + assert (w & LOCKBIT, "invariant") ; 1.4571 + Self->ListNext = (ParkEvent *) (w & ~LOCKBIT ); 1.4572 + if (Atomic::cmpxchg_ptr (intptr_t(Self)|LOCKBIT, Lock, w) == w) break ; 1.4573 + } 1.4574 + 1.4575 + while (Self->OnList != 0) { 1.4576 + Self->park() ; 1.4577 + } 1.4578 + } 1.4579 +} 1.4580 + 1.4581 +void Thread::muxAcquireW (volatile intptr_t * Lock, ParkEvent * ev) { 1.4582 + intptr_t w = Atomic::cmpxchg_ptr (LOCKBIT, Lock, 0) ; 1.4583 + if (w == 0) return ; 1.4584 + if ((w & LOCKBIT) == 0 && Atomic::cmpxchg_ptr (w|LOCKBIT, Lock, w) == w) { 1.4585 + return ; 1.4586 + } 1.4587 + 1.4588 + TEVENT (muxAcquire - Contention) ; 1.4589 + ParkEvent * ReleaseAfter = NULL ; 1.4590 + if (ev == NULL) { 1.4591 + ev = ReleaseAfter = ParkEvent::Allocate (NULL) ; 1.4592 + } 1.4593 + assert ((intptr_t(ev) & LOCKBIT) == 0, "invariant") ; 1.4594 + for (;;) { 1.4595 + guarantee (ev->OnList == 0, "invariant") ; 1.4596 + int its = (os::is_MP() ? 100 : 0) + 1 ; 1.4597 + 1.4598 + // Optional spin phase: spin-then-park strategy 1.4599 + while (--its >= 0) { 1.4600 + w = *Lock ; 1.4601 + if ((w & LOCKBIT) == 0 && Atomic::cmpxchg_ptr (w|LOCKBIT, Lock, w) == w) { 1.4602 + if (ReleaseAfter != NULL) { 1.4603 + ParkEvent::Release (ReleaseAfter) ; 1.4604 + } 1.4605 + return ; 1.4606 + } 1.4607 + } 1.4608 + 1.4609 + ev->reset() ; 1.4610 + ev->OnList = intptr_t(Lock) ; 1.4611 + // The following fence() isn't _strictly necessary as the subsequent 1.4612 + // CAS() both serializes execution and ratifies the fetched *Lock value. 1.4613 + OrderAccess::fence(); 1.4614 + for (;;) { 1.4615 + w = *Lock ; 1.4616 + if ((w & LOCKBIT) == 0) { 1.4617 + if (Atomic::cmpxchg_ptr (w|LOCKBIT, Lock, w) == w) { 1.4618 + ev->OnList = 0 ; 1.4619 + // We call ::Release while holding the outer lock, thus 1.4620 + // artificially lengthening the critical section. 1.4621 + // Consider deferring the ::Release() until the subsequent unlock(), 1.4622 + // after we've dropped the outer lock. 1.4623 + if (ReleaseAfter != NULL) { 1.4624 + ParkEvent::Release (ReleaseAfter) ; 1.4625 + } 1.4626 + return ; 1.4627 + } 1.4628 + continue ; // Interference -- *Lock changed -- Just retry 1.4629 + } 1.4630 + assert (w & LOCKBIT, "invariant") ; 1.4631 + ev->ListNext = (ParkEvent *) (w & ~LOCKBIT ); 1.4632 + if (Atomic::cmpxchg_ptr (intptr_t(ev)|LOCKBIT, Lock, w) == w) break ; 1.4633 + } 1.4634 + 1.4635 + while (ev->OnList != 0) { 1.4636 + ev->park() ; 1.4637 + } 1.4638 + } 1.4639 +} 1.4640 + 1.4641 +// Release() must extract a successor from the list and then wake that thread. 1.4642 +// It can "pop" the front of the list or use a detach-modify-reattach (DMR) scheme 1.4643 +// similar to that used by ParkEvent::Allocate() and ::Release(). DMR-based 1.4644 +// Release() would : 1.4645 +// (A) CAS() or swap() null to *Lock, releasing the lock and detaching the list. 1.4646 +// (B) Extract a successor from the private list "in-hand" 1.4647 +// (C) attempt to CAS() the residual back into *Lock over null. 1.4648 +// If there were any newly arrived threads and the CAS() would fail. 1.4649 +// In that case Release() would detach the RATs, re-merge the list in-hand 1.4650 +// with the RATs and repeat as needed. Alternately, Release() might 1.4651 +// detach and extract a successor, but then pass the residual list to the wakee. 1.4652 +// The wakee would be responsible for reattaching and remerging before it 1.4653 +// competed for the lock. 1.4654 +// 1.4655 +// Both "pop" and DMR are immune from ABA corruption -- there can be 1.4656 +// multiple concurrent pushers, but only one popper or detacher. 1.4657 +// This implementation pops from the head of the list. This is unfair, 1.4658 +// but tends to provide excellent throughput as hot threads remain hot. 1.4659 +// (We wake recently run threads first). 1.4660 + 1.4661 +void Thread::muxRelease (volatile intptr_t * Lock) { 1.4662 + for (;;) { 1.4663 + const intptr_t w = Atomic::cmpxchg_ptr (0, Lock, LOCKBIT) ; 1.4664 + assert (w & LOCKBIT, "invariant") ; 1.4665 + if (w == LOCKBIT) return ; 1.4666 + ParkEvent * List = (ParkEvent *) (w & ~LOCKBIT) ; 1.4667 + assert (List != NULL, "invariant") ; 1.4668 + assert (List->OnList == intptr_t(Lock), "invariant") ; 1.4669 + ParkEvent * nxt = List->ListNext ; 1.4670 + 1.4671 + // The following CAS() releases the lock and pops the head element. 1.4672 + if (Atomic::cmpxchg_ptr (intptr_t(nxt), Lock, w) != w) { 1.4673 + continue ; 1.4674 + } 1.4675 + List->OnList = 0 ; 1.4676 + OrderAccess::fence() ; 1.4677 + List->unpark () ; 1.4678 + return ; 1.4679 + } 1.4680 +} 1.4681 + 1.4682 + 1.4683 +void Threads::verify() { 1.4684 + ALL_JAVA_THREADS(p) { 1.4685 + p->verify(); 1.4686 + } 1.4687 + VMThread* thread = VMThread::vm_thread(); 1.4688 + if (thread != NULL) thread->verify(); 1.4689 +}