1 /* 2 * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. 8 * 9 * This code is distributed in the hope that it will be useful, but WITHOUT 10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 12 * version 2 for more details (a copy is included in the LICENSE file that 13 * accompanied this code). 14 * 15 * You should have received a copy of the GNU General Public License version 16 * 2 along with this work; if not, write to the Free Software Foundation, 17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 18 * 19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 20 * or visit www.oracle.com if you need additional information or have any 21 * questions. 22 * 23 */ 24 25 #include "precompiled.hpp" 26 #include "jvm.h" 27 #include "classfile/classLoader.hpp" 28 #include "classfile/javaClasses.hpp" 29 #include "classfile/moduleEntry.hpp" 30 #include "classfile/systemDictionary.hpp" 31 #include "classfile/vmSymbols.hpp" 32 #include "code/codeCache.hpp" 33 #include "code/scopeDesc.hpp" 34 #include "compiler/compileBroker.hpp" 35 #include "compiler/compileTask.hpp" 36 #include "gc/shared/barrierSet.hpp" 37 #include "gc/shared/gcId.hpp" 38 #include "gc/shared/gcLocker.inline.hpp" 39 #include "gc/shared/workgroup.hpp" 40 #include "interpreter/interpreter.hpp" 41 #include "interpreter/linkResolver.hpp" 42 #include "interpreter/oopMapCache.hpp" 43 #include "jfr/jfrEvents.hpp" 44 #include "jfr/support/jfrThreadId.hpp" 45 #include "jvmtifiles/jvmtiEnv.hpp" 46 #include "logging/log.hpp" 47 #include "logging/logConfiguration.hpp" 48 #include "logging/logStream.hpp" 49 #include "memory/allocation.inline.hpp" 50 #include "memory/metaspaceShared.hpp" 51 #include "memory/oopFactory.hpp" 52 #include "memory/resourceArea.hpp" 53 #include "memory/universe.hpp" 54 #include "oops/access.inline.hpp" 55 #include "oops/instanceKlass.hpp" 56 #include "oops/objArrayOop.hpp" 57 #include "oops/oop.inline.hpp" 58 #include "oops/symbol.hpp" 59 #include "oops/typeArrayOop.inline.hpp" 60 #include "oops/verifyOopClosure.hpp" 61 #include "prims/jvm_misc.hpp" 62 #include "prims/jvmtiExport.hpp" 63 #include "prims/jvmtiThreadState.hpp" 64 #include "prims/privilegedStack.hpp" 65 #include "runtime/arguments.hpp" 66 #include "runtime/atomic.hpp" 67 #include "runtime/biasedLocking.hpp" 68 #include "runtime/flags/jvmFlagConstraintList.hpp" 69 #include "runtime/flags/jvmFlagRangeList.hpp" 70 #include "runtime/flags/jvmFlagWriteableList.hpp" 71 #include "runtime/deoptimization.hpp" 72 #include "runtime/frame.inline.hpp" 73 #include "runtime/handshake.hpp" 74 #include "runtime/init.hpp" 75 #include "runtime/interfaceSupport.inline.hpp" 76 #include "runtime/java.hpp" 77 #include "runtime/javaCalls.hpp" 78 #include "runtime/jniHandles.inline.hpp" 79 #include "runtime/jniPeriodicChecker.hpp" 80 #include "runtime/memprofiler.hpp" 81 #include "runtime/mutexLocker.hpp" 82 #include "runtime/objectMonitor.hpp" 83 #include "runtime/orderAccess.hpp" 84 #include "runtime/osThread.hpp" 85 #include "runtime/prefetch.inline.hpp" 86 #include "runtime/safepoint.hpp" 87 #include "runtime/safepointMechanism.inline.hpp" 88 #include "runtime/sharedRuntime.hpp" 89 #include "runtime/statSampler.hpp" 90 #include "runtime/stubRoutines.hpp" 91 #include "runtime/sweeper.hpp" 92 #include "runtime/task.hpp" 93 #include "runtime/thread.inline.hpp" 94 #include "runtime/threadCritical.hpp" 95 #include "runtime/threadSMR.inline.hpp" 96 #include "runtime/threadStatisticalInfo.hpp" 97 #include "runtime/timer.hpp" 98 #include "runtime/timerTrace.hpp" 99 #include "runtime/vframe.inline.hpp" 100 #include "runtime/vframeArray.hpp" 101 #include "runtime/vframe_hp.hpp" 102 #include "runtime/vmThread.hpp" 103 #include "runtime/vm_operations.hpp" 104 #include "runtime/vm_version.hpp" 105 #include "services/attachListener.hpp" 106 #include "services/management.hpp" 107 #include "services/memTracker.hpp" 108 #include "services/threadService.hpp" 109 #include "utilities/align.hpp" 110 #include "utilities/copy.hpp" 111 #include "utilities/defaultStream.hpp" 112 #include "utilities/dtrace.hpp" 113 #include "utilities/events.hpp" 114 #include "utilities/macros.hpp" 115 #include "utilities/preserveException.hpp" 116 #include "utilities/vmError.hpp" 117 #if INCLUDE_JVMCI 118 #include "jvmci/jvmciCompiler.hpp" 119 #include "jvmci/jvmciRuntime.hpp" 120 #include "logging/logHandle.hpp" 121 #endif 122 #ifdef COMPILER1 123 #include "c1/c1_Compiler.hpp" 124 #endif 125 #ifdef COMPILER2 126 #include "opto/c2compiler.hpp" 127 #include "opto/idealGraphPrinter.hpp" 128 #endif 129 #if INCLUDE_RTM_OPT 130 #include "runtime/rtmLocking.hpp" 131 #endif 132 #if INCLUDE_JFR 133 #include "jfr/jfr.hpp" 134 #endif 135 136 // Initialization after module runtime initialization 137 void universe_post_module_init(); // must happen after call_initPhase2 138 139 #ifdef DTRACE_ENABLED 140 141 // Only bother with this argument setup if dtrace is available 142 143 #define HOTSPOT_THREAD_PROBE_start HOTSPOT_THREAD_START 144 #define HOTSPOT_THREAD_PROBE_stop HOTSPOT_THREAD_STOP 145 146 #define DTRACE_THREAD_PROBE(probe, javathread) \ 147 { \ 148 ResourceMark rm(this); \ 149 int len = 0; \ 150 const char* name = (javathread)->get_thread_name(); \ 151 len = strlen(name); \ 152 HOTSPOT_THREAD_PROBE_##probe(/* probe = start, stop */ \ 153 (char *) name, len, \ 154 java_lang_Thread::thread_id((javathread)->threadObj()), \ 155 (uintptr_t) (javathread)->osthread()->thread_id(), \ 156 java_lang_Thread::is_daemon((javathread)->threadObj())); \ 157 } 158 159 #else // ndef DTRACE_ENABLED 160 161 #define DTRACE_THREAD_PROBE(probe, javathread) 162 163 #endif // ndef DTRACE_ENABLED 164 165 #ifndef USE_LIBRARY_BASED_TLS_ONLY 166 // Current thread is maintained as a thread-local variable 167 THREAD_LOCAL_DECL Thread* Thread::_thr_current = NULL; 168 #endif 169 // Class hierarchy 170 // - Thread 171 // - VMThread 172 // - WatcherThread 173 // - ConcurrentMarkSweepThread 174 // - JavaThread 175 // - CompilerThread 176 177 // ======= Thread ======== 178 // Support for forcing alignment of thread objects for biased locking 179 void* Thread::allocate(size_t size, bool throw_excpt, MEMFLAGS flags) { 180 if (UseBiasedLocking) { 181 const int alignment = markOopDesc::biased_lock_alignment; 182 size_t aligned_size = size + (alignment - sizeof(intptr_t)); 183 void* real_malloc_addr = throw_excpt? AllocateHeap(aligned_size, flags, CURRENT_PC) 184 : AllocateHeap(aligned_size, flags, CURRENT_PC, 185 AllocFailStrategy::RETURN_NULL); 186 void* aligned_addr = align_up(real_malloc_addr, alignment); 187 assert(((uintptr_t) aligned_addr + (uintptr_t) size) <= 188 ((uintptr_t) real_malloc_addr + (uintptr_t) aligned_size), 189 "JavaThread alignment code overflowed allocated storage"); 190 if (aligned_addr != real_malloc_addr) { 191 log_info(biasedlocking)("Aligned thread " INTPTR_FORMAT " to " INTPTR_FORMAT, 192 p2i(real_malloc_addr), 193 p2i(aligned_addr)); 194 } 195 ((Thread*) aligned_addr)->_real_malloc_address = real_malloc_addr; 196 return aligned_addr; 197 } else { 198 return throw_excpt? AllocateHeap(size, flags, CURRENT_PC) 199 : AllocateHeap(size, flags, CURRENT_PC, AllocFailStrategy::RETURN_NULL); 200 } 201 } 202 203 void Thread::operator delete(void* p) { 204 if (UseBiasedLocking) { 205 FreeHeap(((Thread*) p)->_real_malloc_address); 206 } else { 207 FreeHeap(p); 208 } 209 } 210 211 void JavaThread::smr_delete() { 212 if (_on_thread_list) { 213 ThreadsSMRSupport::smr_delete(this); 214 } else { 215 delete this; 216 } 217 } 218 219 // Base class for all threads: VMThread, WatcherThread, ConcurrentMarkSweepThread, 220 // JavaThread 221 222 223 Thread::Thread() { 224 // stack and get_thread 225 set_stack_base(NULL); 226 set_stack_size(0); 227 set_self_raw_id(0); 228 set_lgrp_id(-1); 229 DEBUG_ONLY(clear_suspendible_thread();) 230 231 // allocated data structures 232 set_osthread(NULL); 233 set_resource_area(new (mtThread)ResourceArea()); 234 DEBUG_ONLY(_current_resource_mark = NULL;) 235 set_handle_area(new (mtThread) HandleArea(NULL)); 236 set_metadata_handles(new (ResourceObj::C_HEAP, mtClass) GrowableArray<Metadata*>(30, true)); 237 set_active_handles(NULL); 238 set_free_handle_block(NULL); 239 set_last_handle_mark(NULL); 240 241 // This initial value ==> never claimed. 242 _oops_do_parity = 0; 243 _threads_hazard_ptr = NULL; 244 _threads_list_ptr = NULL; 245 _nested_threads_hazard_ptr_cnt = 0; 246 _rcu_counter = 0; 247 248 // the handle mark links itself to last_handle_mark 249 new HandleMark(this); 250 251 // plain initialization 252 debug_only(_owned_locks = NULL;) 253 debug_only(_allow_allocation_count = 0;) 254 NOT_PRODUCT(_allow_safepoint_count = 0;) 255 NOT_PRODUCT(_skip_gcalot = false;) 256 _jvmti_env_iteration_count = 0; 257 set_allocated_bytes(0); 258 _vm_operation_started_count = 0; 259 _vm_operation_completed_count = 0; 260 _current_pending_monitor = NULL; 261 _current_pending_monitor_is_from_java = true; 262 _current_waiting_monitor = NULL; 263 _num_nested_signal = 0; 264 omFreeList = NULL; 265 omFreeCount = 0; 266 omFreeProvision = 32; 267 omInUseList = NULL; 268 omInUseCount = 0; 269 270 #ifdef ASSERT 271 _visited_for_critical_count = false; 272 #endif 273 274 _SR_lock = new Monitor(Mutex::suspend_resume, "SR_lock", true, 275 Monitor::_safepoint_check_sometimes); 276 _suspend_flags = 0; 277 278 // thread-specific hashCode stream generator state - Marsaglia shift-xor form 279 _hashStateX = os::random(); 280 _hashStateY = 842502087; 281 _hashStateZ = 0x8767; // (int)(3579807591LL & 0xffff) ; 282 _hashStateW = 273326509; 283 284 _OnTrap = 0; 285 _schedctl = NULL; 286 _Stalled = 0; 287 _TypeTag = 0x2BAD; 288 289 // Many of the following fields are effectively final - immutable 290 // Note that nascent threads can't use the Native Monitor-Mutex 291 // construct until the _MutexEvent is initialized ... 292 // CONSIDER: instead of using a fixed set of purpose-dedicated ParkEvents 293 // we might instead use a stack of ParkEvents that we could provision on-demand. 294 // The stack would act as a cache to avoid calls to ParkEvent::Allocate() 295 // and ::Release() 296 _ParkEvent = ParkEvent::Allocate(this); 297 _SleepEvent = ParkEvent::Allocate(this); 298 _MutexEvent = ParkEvent::Allocate(this); 299 _MuxEvent = ParkEvent::Allocate(this); 300 301 #ifdef CHECK_UNHANDLED_OOPS 302 if (CheckUnhandledOops) { 303 _unhandled_oops = new UnhandledOops(this); 304 } 305 #endif // CHECK_UNHANDLED_OOPS 306 #ifdef ASSERT 307 if (UseBiasedLocking) { 308 assert((((uintptr_t) this) & (markOopDesc::biased_lock_alignment - 1)) == 0, "forced alignment of thread object failed"); 309 assert(this == _real_malloc_address || 310 this == align_up(_real_malloc_address, (int)markOopDesc::biased_lock_alignment), 311 "bug in forced alignment of thread objects"); 312 } 313 #endif // ASSERT 314 315 // Notify the barrier set that a thread is being created. Note that the 316 // main thread is created before a barrier set is available. The call to 317 // BarrierSet::on_thread_create() for the main thread is therefore deferred 318 // until it calls BarrierSet::set_barrier_set(). 319 BarrierSet* const barrier_set = BarrierSet::barrier_set(); 320 if (barrier_set != NULL) { 321 barrier_set->on_thread_create(this); 322 } 323 } 324 325 void Thread::initialize_thread_current() { 326 #ifndef USE_LIBRARY_BASED_TLS_ONLY 327 assert(_thr_current == NULL, "Thread::current already initialized"); 328 _thr_current = this; 329 #endif 330 assert(ThreadLocalStorage::thread() == NULL, "ThreadLocalStorage::thread already initialized"); 331 ThreadLocalStorage::set_thread(this); 332 assert(Thread::current() == ThreadLocalStorage::thread(), "TLS mismatch!"); 333 } 334 335 void Thread::clear_thread_current() { 336 assert(Thread::current() == ThreadLocalStorage::thread(), "TLS mismatch!"); 337 #ifndef USE_LIBRARY_BASED_TLS_ONLY 338 _thr_current = NULL; 339 #endif 340 ThreadLocalStorage::set_thread(NULL); 341 } 342 343 void Thread::record_stack_base_and_size() { 344 set_stack_base(os::current_stack_base()); 345 set_stack_size(os::current_stack_size()); 346 // CR 7190089: on Solaris, primordial thread's stack is adjusted 347 // in initialize_thread(). Without the adjustment, stack size is 348 // incorrect if stack is set to unlimited (ulimit -s unlimited). 349 // So far, only Solaris has real implementation of initialize_thread(). 350 // 351 // set up any platform-specific state. 352 os::initialize_thread(this); 353 354 // Set stack limits after thread is initialized. 355 if (is_Java_thread()) { 356 ((JavaThread*) this)->set_stack_overflow_limit(); 357 ((JavaThread*) this)->set_reserved_stack_activation(stack_base()); 358 } 359 #if INCLUDE_NMT 360 // record thread's native stack, stack grows downward 361 MemTracker::record_thread_stack(stack_end(), stack_size()); 362 #endif // INCLUDE_NMT 363 log_debug(os, thread)("Thread " UINTX_FORMAT " stack dimensions: " 364 PTR_FORMAT "-" PTR_FORMAT " (" SIZE_FORMAT "k).", 365 os::current_thread_id(), p2i(stack_base() - stack_size()), 366 p2i(stack_base()), stack_size()/1024); 367 } 368 369 370 Thread::~Thread() { 371 JFR_ONLY(Jfr::on_thread_destruct(this);) 372 373 // Notify the barrier set that a thread is being destroyed. Note that a barrier 374 // set might not be available if we encountered errors during bootstrapping. 375 BarrierSet* const barrier_set = BarrierSet::barrier_set(); 376 if (barrier_set != NULL) { 377 barrier_set->on_thread_destroy(this); 378 } 379 380 381 // stack_base can be NULL if the thread is never started or exited before 382 // record_stack_base_and_size called. Although, we would like to ensure 383 // that all started threads do call record_stack_base_and_size(), there is 384 // not proper way to enforce that. 385 #if INCLUDE_NMT 386 if (_stack_base != NULL) { 387 MemTracker::release_thread_stack(stack_end(), stack_size()); 388 #ifdef ASSERT 389 set_stack_base(NULL); 390 #endif 391 } 392 #endif // INCLUDE_NMT 393 394 // deallocate data structures 395 delete resource_area(); 396 // since the handle marks are using the handle area, we have to deallocated the root 397 // handle mark before deallocating the thread's handle area, 398 assert(last_handle_mark() != NULL, "check we have an element"); 399 delete last_handle_mark(); 400 assert(last_handle_mark() == NULL, "check we have reached the end"); 401 402 // It's possible we can encounter a null _ParkEvent, etc., in stillborn threads. 403 // We NULL out the fields for good hygiene. 404 ParkEvent::Release(_ParkEvent); _ParkEvent = NULL; 405 ParkEvent::Release(_SleepEvent); _SleepEvent = NULL; 406 ParkEvent::Release(_MutexEvent); _MutexEvent = NULL; 407 ParkEvent::Release(_MuxEvent); _MuxEvent = NULL; 408 409 delete handle_area(); 410 delete metadata_handles(); 411 412 // SR_handler uses this as a termination indicator - 413 // needs to happen before os::free_thread() 414 delete _SR_lock; 415 _SR_lock = NULL; 416 417 // osthread() can be NULL, if creation of thread failed. 418 if (osthread() != NULL) os::free_thread(osthread()); 419 420 // clear Thread::current if thread is deleting itself. 421 // Needed to ensure JNI correctly detects non-attached threads. 422 if (this == Thread::current()) { 423 clear_thread_current(); 424 } 425 426 CHECK_UNHANDLED_OOPS_ONLY(if (CheckUnhandledOops) delete unhandled_oops();) 427 } 428 429 // NOTE: dummy function for assertion purpose. 430 void Thread::run() { 431 ShouldNotReachHere(); 432 } 433 434 #ifdef ASSERT 435 // A JavaThread is considered "dangling" if it is not the current 436 // thread, has been added the Threads list, the system is not at a 437 // safepoint and the Thread is not "protected". 438 // 439 void Thread::check_for_dangling_thread_pointer(Thread *thread) { 440 assert(!thread->is_Java_thread() || Thread::current() == thread || 441 !((JavaThread *) thread)->on_thread_list() || 442 SafepointSynchronize::is_at_safepoint() || 443 ThreadsSMRSupport::is_a_protected_JavaThread_with_lock((JavaThread *) thread), 444 "possibility of dangling Thread pointer"); 445 } 446 #endif 447 448 ThreadPriority Thread::get_priority(const Thread* const thread) { 449 ThreadPriority priority; 450 // Can return an error! 451 (void)os::get_priority(thread, priority); 452 assert(MinPriority <= priority && priority <= MaxPriority, "non-Java priority found"); 453 return priority; 454 } 455 456 void Thread::set_priority(Thread* thread, ThreadPriority priority) { 457 debug_only(check_for_dangling_thread_pointer(thread);) 458 // Can return an error! 459 (void)os::set_priority(thread, priority); 460 } 461 462 463 void Thread::start(Thread* thread) { 464 // Start is different from resume in that its safety is guaranteed by context or 465 // being called from a Java method synchronized on the Thread object. 466 if (!DisableStartThread) { 467 if (thread->is_Java_thread()) { 468 // Initialize the thread state to RUNNABLE before starting this thread. 469 // Can not set it after the thread started because we do not know the 470 // exact thread state at that time. It could be in MONITOR_WAIT or 471 // in SLEEPING or some other state. 472 java_lang_Thread::set_thread_status(((JavaThread*)thread)->threadObj(), 473 java_lang_Thread::RUNNABLE); 474 } 475 os::start_thread(thread); 476 } 477 } 478 479 // Enqueue a VM_Operation to do the job for us - sometime later 480 void Thread::send_async_exception(oop java_thread, oop java_throwable) { 481 VM_ThreadStop* vm_stop = new VM_ThreadStop(java_thread, java_throwable); 482 VMThread::execute(vm_stop); 483 } 484 485 486 // Check if an external suspend request has completed (or has been 487 // cancelled). Returns true if the thread is externally suspended and 488 // false otherwise. 489 // 490 // The bits parameter returns information about the code path through 491 // the routine. Useful for debugging: 492 // 493 // set in is_ext_suspend_completed(): 494 // 0x00000001 - routine was entered 495 // 0x00000010 - routine return false at end 496 // 0x00000100 - thread exited (return false) 497 // 0x00000200 - suspend request cancelled (return false) 498 // 0x00000400 - thread suspended (return true) 499 // 0x00001000 - thread is in a suspend equivalent state (return true) 500 // 0x00002000 - thread is native and walkable (return true) 501 // 0x00004000 - thread is native_trans and walkable (needed retry) 502 // 503 // set in wait_for_ext_suspend_completion(): 504 // 0x00010000 - routine was entered 505 // 0x00020000 - suspend request cancelled before loop (return false) 506 // 0x00040000 - thread suspended before loop (return true) 507 // 0x00080000 - suspend request cancelled in loop (return false) 508 // 0x00100000 - thread suspended in loop (return true) 509 // 0x00200000 - suspend not completed during retry loop (return false) 510 511 // Helper class for tracing suspend wait debug bits. 512 // 513 // 0x00000100 indicates that the target thread exited before it could 514 // self-suspend which is not a wait failure. 0x00000200, 0x00020000 and 515 // 0x00080000 each indicate a cancelled suspend request so they don't 516 // count as wait failures either. 517 #define DEBUG_FALSE_BITS (0x00000010 | 0x00200000) 518 519 class TraceSuspendDebugBits : public StackObj { 520 private: 521 JavaThread * jt; 522 bool is_wait; 523 bool called_by_wait; // meaningful when !is_wait 524 uint32_t * bits; 525 526 public: 527 TraceSuspendDebugBits(JavaThread *_jt, bool _is_wait, bool _called_by_wait, 528 uint32_t *_bits) { 529 jt = _jt; 530 is_wait = _is_wait; 531 called_by_wait = _called_by_wait; 532 bits = _bits; 533 } 534 535 ~TraceSuspendDebugBits() { 536 if (!is_wait) { 537 #if 1 538 // By default, don't trace bits for is_ext_suspend_completed() calls. 539 // That trace is very chatty. 540 return; 541 #else 542 if (!called_by_wait) { 543 // If tracing for is_ext_suspend_completed() is enabled, then only 544 // trace calls to it from wait_for_ext_suspend_completion() 545 return; 546 } 547 #endif 548 } 549 550 if (AssertOnSuspendWaitFailure || TraceSuspendWaitFailures) { 551 if (bits != NULL && (*bits & DEBUG_FALSE_BITS) != 0) { 552 MutexLocker ml(Threads_lock); // needed for get_thread_name() 553 ResourceMark rm; 554 555 tty->print_cr( 556 "Failed wait_for_ext_suspend_completion(thread=%s, debug_bits=%x)", 557 jt->get_thread_name(), *bits); 558 559 guarantee(!AssertOnSuspendWaitFailure, "external suspend wait failed"); 560 } 561 } 562 } 563 }; 564 #undef DEBUG_FALSE_BITS 565 566 567 bool JavaThread::is_ext_suspend_completed(bool called_by_wait, int delay, 568 uint32_t *bits) { 569 TraceSuspendDebugBits tsdb(this, false /* !is_wait */, called_by_wait, bits); 570 571 bool did_trans_retry = false; // only do thread_in_native_trans retry once 572 bool do_trans_retry; // flag to force the retry 573 574 *bits |= 0x00000001; 575 576 do { 577 do_trans_retry = false; 578 579 if (is_exiting()) { 580 // Thread is in the process of exiting. This is always checked 581 // first to reduce the risk of dereferencing a freed JavaThread. 582 *bits |= 0x00000100; 583 return false; 584 } 585 586 if (!is_external_suspend()) { 587 // Suspend request is cancelled. This is always checked before 588 // is_ext_suspended() to reduce the risk of a rogue resume 589 // confusing the thread that made the suspend request. 590 *bits |= 0x00000200; 591 return false; 592 } 593 594 if (is_ext_suspended()) { 595 // thread is suspended 596 *bits |= 0x00000400; 597 return true; 598 } 599 600 // Now that we no longer do hard suspends of threads running 601 // native code, the target thread can be changing thread state 602 // while we are in this routine: 603 // 604 // _thread_in_native -> _thread_in_native_trans -> _thread_blocked 605 // 606 // We save a copy of the thread state as observed at this moment 607 // and make our decision about suspend completeness based on the 608 // copy. This closes the race where the thread state is seen as 609 // _thread_in_native_trans in the if-thread_blocked check, but is 610 // seen as _thread_blocked in if-thread_in_native_trans check. 611 JavaThreadState save_state = thread_state(); 612 613 if (save_state == _thread_blocked && is_suspend_equivalent()) { 614 // If the thread's state is _thread_blocked and this blocking 615 // condition is known to be equivalent to a suspend, then we can 616 // consider the thread to be externally suspended. This means that 617 // the code that sets _thread_blocked has been modified to do 618 // self-suspension if the blocking condition releases. We also 619 // used to check for CONDVAR_WAIT here, but that is now covered by 620 // the _thread_blocked with self-suspension check. 621 // 622 // Return true since we wouldn't be here unless there was still an 623 // external suspend request. 624 *bits |= 0x00001000; 625 return true; 626 } else if (save_state == _thread_in_native && frame_anchor()->walkable()) { 627 // Threads running native code will self-suspend on native==>VM/Java 628 // transitions. If its stack is walkable (should always be the case 629 // unless this function is called before the actual java_suspend() 630 // call), then the wait is done. 631 *bits |= 0x00002000; 632 return true; 633 } else if (!called_by_wait && !did_trans_retry && 634 save_state == _thread_in_native_trans && 635 frame_anchor()->walkable()) { 636 // The thread is transitioning from thread_in_native to another 637 // thread state. check_safepoint_and_suspend_for_native_trans() 638 // will force the thread to self-suspend. If it hasn't gotten 639 // there yet we may have caught the thread in-between the native 640 // code check above and the self-suspend. Lucky us. If we were 641 // called by wait_for_ext_suspend_completion(), then it 642 // will be doing the retries so we don't have to. 643 // 644 // Since we use the saved thread state in the if-statement above, 645 // there is a chance that the thread has already transitioned to 646 // _thread_blocked by the time we get here. In that case, we will 647 // make a single unnecessary pass through the logic below. This 648 // doesn't hurt anything since we still do the trans retry. 649 650 *bits |= 0x00004000; 651 652 // Once the thread leaves thread_in_native_trans for another 653 // thread state, we break out of this retry loop. We shouldn't 654 // need this flag to prevent us from getting back here, but 655 // sometimes paranoia is good. 656 did_trans_retry = true; 657 658 // We wait for the thread to transition to a more usable state. 659 for (int i = 1; i <= SuspendRetryCount; i++) { 660 // We used to do an "os::yield_all(i)" call here with the intention 661 // that yielding would increase on each retry. However, the parameter 662 // is ignored on Linux which means the yield didn't scale up. Waiting 663 // on the SR_lock below provides a much more predictable scale up for 664 // the delay. It also provides a simple/direct point to check for any 665 // safepoint requests from the VMThread 666 667 // temporarily drops SR_lock while doing wait with safepoint check 668 // (if we're a JavaThread - the WatcherThread can also call this) 669 // and increase delay with each retry 670 SR_lock()->wait(!Thread::current()->is_Java_thread(), i * delay); 671 672 // check the actual thread state instead of what we saved above 673 if (thread_state() != _thread_in_native_trans) { 674 // the thread has transitioned to another thread state so 675 // try all the checks (except this one) one more time. 676 do_trans_retry = true; 677 break; 678 } 679 } // end retry loop 680 681 682 } 683 } while (do_trans_retry); 684 685 *bits |= 0x00000010; 686 return false; 687 } 688 689 // Wait for an external suspend request to complete (or be cancelled). 690 // Returns true if the thread is externally suspended and false otherwise. 691 // 692 bool JavaThread::wait_for_ext_suspend_completion(int retries, int delay, 693 uint32_t *bits) { 694 TraceSuspendDebugBits tsdb(this, true /* is_wait */, 695 false /* !called_by_wait */, bits); 696 697 // local flag copies to minimize SR_lock hold time 698 bool is_suspended; 699 bool pending; 700 uint32_t reset_bits; 701 702 // set a marker so is_ext_suspend_completed() knows we are the caller 703 *bits |= 0x00010000; 704 705 // We use reset_bits to reinitialize the bits value at the top of 706 // each retry loop. This allows the caller to make use of any 707 // unused bits for their own marking purposes. 708 reset_bits = *bits; 709 710 { 711 MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag); 712 is_suspended = is_ext_suspend_completed(true /* called_by_wait */, 713 delay, bits); 714 pending = is_external_suspend(); 715 } 716 // must release SR_lock to allow suspension to complete 717 718 if (!pending) { 719 // A cancelled suspend request is the only false return from 720 // is_ext_suspend_completed() that keeps us from entering the 721 // retry loop. 722 *bits |= 0x00020000; 723 return false; 724 } 725 726 if (is_suspended) { 727 *bits |= 0x00040000; 728 return true; 729 } 730 731 for (int i = 1; i <= retries; i++) { 732 *bits = reset_bits; // reinit to only track last retry 733 734 // We used to do an "os::yield_all(i)" call here with the intention 735 // that yielding would increase on each retry. However, the parameter 736 // is ignored on Linux which means the yield didn't scale up. Waiting 737 // on the SR_lock below provides a much more predictable scale up for 738 // the delay. It also provides a simple/direct point to check for any 739 // safepoint requests from the VMThread 740 741 { 742 MutexLocker ml(SR_lock()); 743 // wait with safepoint check (if we're a JavaThread - the WatcherThread 744 // can also call this) and increase delay with each retry 745 SR_lock()->wait(!Thread::current()->is_Java_thread(), i * delay); 746 747 is_suspended = is_ext_suspend_completed(true /* called_by_wait */, 748 delay, bits); 749 750 // It is possible for the external suspend request to be cancelled 751 // (by a resume) before the actual suspend operation is completed. 752 // Refresh our local copy to see if we still need to wait. 753 pending = is_external_suspend(); 754 } 755 756 if (!pending) { 757 // A cancelled suspend request is the only false return from 758 // is_ext_suspend_completed() that keeps us from staying in the 759 // retry loop. 760 *bits |= 0x00080000; 761 return false; 762 } 763 764 if (is_suspended) { 765 *bits |= 0x00100000; 766 return true; 767 } 768 } // end retry loop 769 770 // thread did not suspend after all our retries 771 *bits |= 0x00200000; 772 return false; 773 } 774 775 // Called from API entry points which perform stack walking. If the 776 // associated JavaThread is the current thread, then wait_for_suspend 777 // is not used. Otherwise, it determines if we should wait for the 778 // "other" thread to complete external suspension. (NOTE: in future 779 // releases the suspension mechanism should be reimplemented so this 780 // is not necessary.) 781 // 782 bool 783 JavaThread::is_thread_fully_suspended(bool wait_for_suspend, uint32_t *bits) { 784 if (this != JavaThread::current()) { 785 // "other" threads require special handling. 786 if (wait_for_suspend) { 787 // We are allowed to wait for the external suspend to complete 788 // so give the other thread a chance to get suspended. 789 if (!wait_for_ext_suspend_completion(SuspendRetryCount, 790 SuspendRetryDelay, bits)) { 791 // Didn't make it so let the caller know. 792 return false; 793 } 794 } 795 // We aren't allowed to wait for the external suspend to complete 796 // so if the other thread isn't externally suspended we need to 797 // let the caller know. 798 else if (!is_ext_suspend_completed_with_lock(bits)) { 799 return false; 800 } 801 } 802 803 return true; 804 } 805 806 #ifndef PRODUCT 807 void JavaThread::record_jump(address target, address instr, const char* file, 808 int line) { 809 810 // This should not need to be atomic as the only way for simultaneous 811 // updates is via interrupts. Even then this should be rare or non-existent 812 // and we don't care that much anyway. 813 814 int index = _jmp_ring_index; 815 _jmp_ring_index = (index + 1) & (jump_ring_buffer_size - 1); 816 _jmp_ring[index]._target = (intptr_t) target; 817 _jmp_ring[index]._instruction = (intptr_t) instr; 818 _jmp_ring[index]._file = file; 819 _jmp_ring[index]._line = line; 820 } 821 #endif // PRODUCT 822 823 void Thread::interrupt(Thread* thread) { 824 debug_only(check_for_dangling_thread_pointer(thread);) 825 os::interrupt(thread); 826 } 827 828 bool Thread::is_interrupted(Thread* thread, bool clear_interrupted) { 829 debug_only(check_for_dangling_thread_pointer(thread);) 830 // Note: If clear_interrupted==false, this simply fetches and 831 // returns the value of the field osthread()->interrupted(). 832 return os::is_interrupted(thread, clear_interrupted); 833 } 834 835 836 // GC Support 837 bool Thread::claim_oops_do_par_case(int strong_roots_parity) { 838 int thread_parity = _oops_do_parity; 839 if (thread_parity != strong_roots_parity) { 840 jint res = Atomic::cmpxchg(strong_roots_parity, &_oops_do_parity, thread_parity); 841 if (res == thread_parity) { 842 return true; 843 } else { 844 guarantee(res == strong_roots_parity, "Or else what?"); 845 return false; 846 } 847 } 848 return false; 849 } 850 851 void Thread::oops_do(OopClosure* f, CodeBlobClosure* cf) { 852 active_handles()->oops_do(f); 853 // Do oop for ThreadShadow 854 f->do_oop((oop*)&_pending_exception); 855 handle_area()->oops_do(f); 856 857 if (MonitorInUseLists) { 858 // When using thread local monitor lists, we scan them here, 859 // and the remaining global monitors in ObjectSynchronizer::oops_do(). 860 ObjectSynchronizer::thread_local_used_oops_do(this, f); 861 } 862 } 863 864 void Thread::metadata_handles_do(void f(Metadata*)) { 865 // Only walk the Handles in Thread. 866 if (metadata_handles() != NULL) { 867 for (int i = 0; i< metadata_handles()->length(); i++) { 868 f(metadata_handles()->at(i)); 869 } 870 } 871 } 872 873 void Thread::print_on(outputStream* st, bool print_extended_info) const { 874 // get_priority assumes osthread initialized 875 if (osthread() != NULL) { 876 int os_prio; 877 if (os::get_native_priority(this, &os_prio) == OS_OK) { 878 st->print("os_prio=%d ", os_prio); 879 } 880 881 st->print("cpu=%.2fms ", 882 os::thread_cpu_time(const_cast<Thread*>(this), true) / 1000000.0 883 ); 884 st->print("elapsed=%.2fs ", 885 _statistical_info.getElapsedTime() / 1000.0 886 ); 887 if (is_Java_thread() && (PrintExtendedThreadInfo || print_extended_info)) { 888 size_t allocated_bytes = (size_t) const_cast<Thread*>(this)->cooked_allocated_bytes(); 889 st->print("allocated=" SIZE_FORMAT "%s ", 890 byte_size_in_proper_unit(allocated_bytes), 891 proper_unit_for_byte_size(allocated_bytes) 892 ); 893 st->print("defined_classes=" INT64_FORMAT " ", _statistical_info.getDefineClassCount()); 894 } 895 896 st->print("tid=" INTPTR_FORMAT " ", p2i(this)); 897 osthread()->print_on(st); 898 } 899 ThreadsSMRSupport::print_info_on(this, st); 900 st->print(" "); 901 debug_only(if (WizardMode) print_owned_locks_on(st);) 902 } 903 904 // Thread::print_on_error() is called by fatal error handler. Don't use 905 // any lock or allocate memory. 906 void Thread::print_on_error(outputStream* st, char* buf, int buflen) const { 907 assert(!(is_Compiler_thread() || is_Java_thread()), "Can't call name() here if it allocates"); 908 909 if (is_VM_thread()) { st->print("VMThread"); } 910 else if (is_GC_task_thread()) { st->print("GCTaskThread"); } 911 else if (is_Watcher_thread()) { st->print("WatcherThread"); } 912 else if (is_ConcurrentGC_thread()) { st->print("ConcurrentGCThread"); } 913 else { st->print("Thread"); } 914 915 if (is_Named_thread()) { 916 st->print(" \"%s\"", name()); 917 } 918 919 st->print(" [stack: " PTR_FORMAT "," PTR_FORMAT "]", 920 p2i(stack_end()), p2i(stack_base())); 921 922 if (osthread()) { 923 st->print(" [id=%d]", osthread()->thread_id()); 924 } 925 926 ThreadsSMRSupport::print_info_on(this, st); 927 } 928 929 void Thread::print_value_on(outputStream* st) const { 930 if (is_Named_thread()) { 931 st->print(" \"%s\" ", name()); 932 } 933 st->print(INTPTR_FORMAT, p2i(this)); // print address 934 } 935 936 #ifdef ASSERT 937 void Thread::print_owned_locks_on(outputStream* st) const { 938 Monitor *cur = _owned_locks; 939 if (cur == NULL) { 940 st->print(" (no locks) "); 941 } else { 942 st->print_cr(" Locks owned:"); 943 while (cur) { 944 cur->print_on(st); 945 cur = cur->next(); 946 } 947 } 948 } 949 950 static int ref_use_count = 0; 951 952 bool Thread::owns_locks_but_compiled_lock() const { 953 for (Monitor *cur = _owned_locks; cur; cur = cur->next()) { 954 if (cur != Compile_lock) return true; 955 } 956 return false; 957 } 958 959 960 #endif 961 962 #ifndef PRODUCT 963 964 // The flag: potential_vm_operation notifies if this particular safepoint state could potentially 965 // invoke the vm-thread (e.g., an oop allocation). In that case, we also have to make sure that 966 // no threads which allow_vm_block's are held 967 void Thread::check_for_valid_safepoint_state(bool potential_vm_operation) { 968 // Check if current thread is allowed to block at a safepoint 969 if (!(_allow_safepoint_count == 0)) { 970 fatal("Possible safepoint reached by thread that does not allow it"); 971 } 972 if (is_Java_thread() && ((JavaThread*)this)->thread_state() != _thread_in_vm) { 973 fatal("LEAF method calling lock?"); 974 } 975 976 #ifdef ASSERT 977 if (potential_vm_operation && is_Java_thread() 978 && !Universe::is_bootstrapping()) { 979 // Make sure we do not hold any locks that the VM thread also uses. 980 // This could potentially lead to deadlocks 981 for (Monitor *cur = _owned_locks; cur; cur = cur->next()) { 982 // Threads_lock is special, since the safepoint synchronization will not start before this is 983 // acquired. Hence, a JavaThread cannot be holding it at a safepoint. So is VMOperationRequest_lock, 984 // since it is used to transfer control between JavaThreads and the VMThread 985 // Do not *exclude* any locks unless you are absolutely sure it is correct. Ask someone else first! 986 if ((cur->allow_vm_block() && 987 cur != Threads_lock && 988 cur != Compile_lock && // Temporary: should not be necessary when we get separate compilation 989 cur != VMOperationRequest_lock && 990 cur != VMOperationQueue_lock) || 991 cur->rank() == Mutex::special) { 992 fatal("Thread holding lock at safepoint that vm can block on: %s", cur->name()); 993 } 994 } 995 } 996 997 if (GCALotAtAllSafepoints) { 998 // We could enter a safepoint here and thus have a gc 999 InterfaceSupport::check_gc_alot(); 1000 } 1001 #endif 1002 } 1003 #endif 1004 1005 bool Thread::is_in_stack(address adr) const { 1006 assert(Thread::current() == this, "is_in_stack can only be called from current thread"); 1007 address end = os::current_stack_pointer(); 1008 // Allow non Java threads to call this without stack_base 1009 if (_stack_base == NULL) return true; 1010 if (stack_base() >= adr && adr >= end) return true; 1011 1012 return false; 1013 } 1014 1015 bool Thread::is_in_usable_stack(address adr) const { 1016 size_t stack_guard_size = os::uses_stack_guard_pages() ? JavaThread::stack_guard_zone_size() : 0; 1017 size_t usable_stack_size = _stack_size - stack_guard_size; 1018 1019 return ((adr < stack_base()) && (adr >= stack_base() - usable_stack_size)); 1020 } 1021 1022 1023 // We had to move these methods here, because vm threads get into ObjectSynchronizer::enter 1024 // However, there is a note in JavaThread::is_lock_owned() about the VM threads not being 1025 // used for compilation in the future. If that change is made, the need for these methods 1026 // should be revisited, and they should be removed if possible. 1027 1028 bool Thread::is_lock_owned(address adr) const { 1029 return on_local_stack(adr); 1030 } 1031 1032 bool Thread::set_as_starting_thread() { 1033 // NOTE: this must be called inside the main thread. 1034 return os::create_main_thread((JavaThread*)this); 1035 } 1036 1037 static void initialize_class(Symbol* class_name, TRAPS) { 1038 Klass* klass = SystemDictionary::resolve_or_fail(class_name, true, CHECK); 1039 InstanceKlass::cast(klass)->initialize(CHECK); 1040 } 1041 1042 1043 // Creates the initial ThreadGroup 1044 static Handle create_initial_thread_group(TRAPS) { 1045 Handle system_instance = JavaCalls::construct_new_instance( 1046 SystemDictionary::ThreadGroup_klass(), 1047 vmSymbols::void_method_signature(), 1048 CHECK_NH); 1049 Universe::set_system_thread_group(system_instance()); 1050 1051 Handle string = java_lang_String::create_from_str("main", CHECK_NH); 1052 Handle main_instance = JavaCalls::construct_new_instance( 1053 SystemDictionary::ThreadGroup_klass(), 1054 vmSymbols::threadgroup_string_void_signature(), 1055 system_instance, 1056 string, 1057 CHECK_NH); 1058 return main_instance; 1059 } 1060 1061 // Creates the initial Thread 1062 static oop create_initial_thread(Handle thread_group, JavaThread* thread, 1063 TRAPS) { 1064 InstanceKlass* ik = SystemDictionary::Thread_klass(); 1065 assert(ik->is_initialized(), "must be"); 1066 instanceHandle thread_oop = ik->allocate_instance_handle(CHECK_NULL); 1067 1068 // Cannot use JavaCalls::construct_new_instance because the java.lang.Thread 1069 // constructor calls Thread.current(), which must be set here for the 1070 // initial thread. 1071 java_lang_Thread::set_thread(thread_oop(), thread); 1072 java_lang_Thread::set_priority(thread_oop(), NormPriority); 1073 thread->set_threadObj(thread_oop()); 1074 1075 Handle string = java_lang_String::create_from_str("main", CHECK_NULL); 1076 1077 JavaValue result(T_VOID); 1078 JavaCalls::call_special(&result, thread_oop, 1079 ik, 1080 vmSymbols::object_initializer_name(), 1081 vmSymbols::threadgroup_string_void_signature(), 1082 thread_group, 1083 string, 1084 CHECK_NULL); 1085 return thread_oop(); 1086 } 1087 1088 char java_runtime_name[128] = ""; 1089 char java_runtime_version[128] = ""; 1090 1091 // extract the JRE name from java.lang.VersionProps.java_runtime_name 1092 static const char* get_java_runtime_name(TRAPS) { 1093 Klass* k = SystemDictionary::find(vmSymbols::java_lang_VersionProps(), 1094 Handle(), Handle(), CHECK_AND_CLEAR_NULL); 1095 fieldDescriptor fd; 1096 bool found = k != NULL && 1097 InstanceKlass::cast(k)->find_local_field(vmSymbols::java_runtime_name_name(), 1098 vmSymbols::string_signature(), &fd); 1099 if (found) { 1100 oop name_oop = k->java_mirror()->obj_field(fd.offset()); 1101 if (name_oop == NULL) { 1102 return NULL; 1103 } 1104 const char* name = java_lang_String::as_utf8_string(name_oop, 1105 java_runtime_name, 1106 sizeof(java_runtime_name)); 1107 return name; 1108 } else { 1109 return NULL; 1110 } 1111 } 1112 1113 // extract the JRE version from java.lang.VersionProps.java_runtime_version 1114 static const char* get_java_runtime_version(TRAPS) { 1115 Klass* k = SystemDictionary::find(vmSymbols::java_lang_VersionProps(), 1116 Handle(), Handle(), CHECK_AND_CLEAR_NULL); 1117 fieldDescriptor fd; 1118 bool found = k != NULL && 1119 InstanceKlass::cast(k)->find_local_field(vmSymbols::java_runtime_version_name(), 1120 vmSymbols::string_signature(), &fd); 1121 if (found) { 1122 oop name_oop = k->java_mirror()->obj_field(fd.offset()); 1123 if (name_oop == NULL) { 1124 return NULL; 1125 } 1126 const char* name = java_lang_String::as_utf8_string(name_oop, 1127 java_runtime_version, 1128 sizeof(java_runtime_version)); 1129 return name; 1130 } else { 1131 return NULL; 1132 } 1133 } 1134 1135 // General purpose hook into Java code, run once when the VM is initialized. 1136 // The Java library method itself may be changed independently from the VM. 1137 static void call_postVMInitHook(TRAPS) { 1138 Klass* klass = SystemDictionary::resolve_or_null(vmSymbols::jdk_internal_vm_PostVMInitHook(), THREAD); 1139 if (klass != NULL) { 1140 JavaValue result(T_VOID); 1141 JavaCalls::call_static(&result, klass, vmSymbols::run_method_name(), 1142 vmSymbols::void_method_signature(), 1143 CHECK); 1144 } 1145 } 1146 1147 void JavaThread::allocate_threadObj(Handle thread_group, const char* thread_name, 1148 bool daemon, TRAPS) { 1149 assert(thread_group.not_null(), "thread group should be specified"); 1150 assert(threadObj() == NULL, "should only create Java thread object once"); 1151 1152 InstanceKlass* ik = SystemDictionary::Thread_klass(); 1153 assert(ik->is_initialized(), "must be"); 1154 instanceHandle thread_oop = ik->allocate_instance_handle(CHECK); 1155 1156 // We are called from jni_AttachCurrentThread/jni_AttachCurrentThreadAsDaemon. 1157 // We cannot use JavaCalls::construct_new_instance because the java.lang.Thread 1158 // constructor calls Thread.current(), which must be set here. 1159 java_lang_Thread::set_thread(thread_oop(), this); 1160 java_lang_Thread::set_priority(thread_oop(), NormPriority); 1161 set_threadObj(thread_oop()); 1162 1163 JavaValue result(T_VOID); 1164 if (thread_name != NULL) { 1165 Handle name = java_lang_String::create_from_str(thread_name, CHECK); 1166 // Thread gets assigned specified name and null target 1167 JavaCalls::call_special(&result, 1168 thread_oop, 1169 ik, 1170 vmSymbols::object_initializer_name(), 1171 vmSymbols::threadgroup_string_void_signature(), 1172 thread_group, 1173 name, 1174 THREAD); 1175 } else { 1176 // Thread gets assigned name "Thread-nnn" and null target 1177 // (java.lang.Thread doesn't have a constructor taking only a ThreadGroup argument) 1178 JavaCalls::call_special(&result, 1179 thread_oop, 1180 ik, 1181 vmSymbols::object_initializer_name(), 1182 vmSymbols::threadgroup_runnable_void_signature(), 1183 thread_group, 1184 Handle(), 1185 THREAD); 1186 } 1187 1188 1189 if (daemon) { 1190 java_lang_Thread::set_daemon(thread_oop()); 1191 } 1192 1193 if (HAS_PENDING_EXCEPTION) { 1194 return; 1195 } 1196 1197 Klass* group = SystemDictionary::ThreadGroup_klass(); 1198 Handle threadObj(THREAD, this->threadObj()); 1199 1200 JavaCalls::call_special(&result, 1201 thread_group, 1202 group, 1203 vmSymbols::add_method_name(), 1204 vmSymbols::thread_void_signature(), 1205 threadObj, // Arg 1 1206 THREAD); 1207 } 1208 1209 // NamedThread -- non-JavaThread subclasses with multiple 1210 // uniquely named instances should derive from this. 1211 NamedThread::NamedThread() : Thread() { 1212 _name = NULL; 1213 _processed_thread = NULL; 1214 _gc_id = GCId::undefined(); 1215 } 1216 1217 NamedThread::~NamedThread() { 1218 if (_name != NULL) { 1219 FREE_C_HEAP_ARRAY(char, _name); 1220 _name = NULL; 1221 } 1222 } 1223 1224 void NamedThread::set_name(const char* format, ...) { 1225 guarantee(_name == NULL, "Only get to set name once."); 1226 _name = NEW_C_HEAP_ARRAY(char, max_name_len, mtThread); 1227 guarantee(_name != NULL, "alloc failure"); 1228 va_list ap; 1229 va_start(ap, format); 1230 jio_vsnprintf(_name, max_name_len, format, ap); 1231 va_end(ap); 1232 } 1233 1234 void NamedThread::initialize_named_thread() { 1235 set_native_thread_name(name()); 1236 } 1237 1238 void NamedThread::print_on(outputStream* st) const { 1239 st->print("\"%s\" ", name()); 1240 Thread::print_on(st); 1241 st->cr(); 1242 } 1243 1244 1245 // ======= WatcherThread ======== 1246 1247 // The watcher thread exists to simulate timer interrupts. It should 1248 // be replaced by an abstraction over whatever native support for 1249 // timer interrupts exists on the platform. 1250 1251 WatcherThread* WatcherThread::_watcher_thread = NULL; 1252 bool WatcherThread::_startable = false; 1253 volatile bool WatcherThread::_should_terminate = false; 1254 1255 WatcherThread::WatcherThread() : Thread() { 1256 assert(watcher_thread() == NULL, "we can only allocate one WatcherThread"); 1257 if (os::create_thread(this, os::watcher_thread)) { 1258 _watcher_thread = this; 1259 1260 // Set the watcher thread to the highest OS priority which should not be 1261 // used, unless a Java thread with priority java.lang.Thread.MAX_PRIORITY 1262 // is created. The only normal thread using this priority is the reference 1263 // handler thread, which runs for very short intervals only. 1264 // If the VMThread's priority is not lower than the WatcherThread profiling 1265 // will be inaccurate. 1266 os::set_priority(this, MaxPriority); 1267 if (!DisableStartThread) { 1268 os::start_thread(this); 1269 } 1270 } 1271 } 1272 1273 int WatcherThread::sleep() const { 1274 // The WatcherThread does not participate in the safepoint protocol 1275 // for the PeriodicTask_lock because it is not a JavaThread. 1276 MutexLockerEx ml(PeriodicTask_lock, Mutex::_no_safepoint_check_flag); 1277 1278 if (_should_terminate) { 1279 // check for termination before we do any housekeeping or wait 1280 return 0; // we did not sleep. 1281 } 1282 1283 // remaining will be zero if there are no tasks, 1284 // causing the WatcherThread to sleep until a task is 1285 // enrolled 1286 int remaining = PeriodicTask::time_to_wait(); 1287 int time_slept = 0; 1288 1289 // we expect this to timeout - we only ever get unparked when 1290 // we should terminate or when a new task has been enrolled 1291 OSThreadWaitState osts(this->osthread(), false /* not Object.wait() */); 1292 1293 jlong time_before_loop = os::javaTimeNanos(); 1294 1295 while (true) { 1296 bool timedout = PeriodicTask_lock->wait(Mutex::_no_safepoint_check_flag, 1297 remaining); 1298 jlong now = os::javaTimeNanos(); 1299 1300 if (remaining == 0) { 1301 // if we didn't have any tasks we could have waited for a long time 1302 // consider the time_slept zero and reset time_before_loop 1303 time_slept = 0; 1304 time_before_loop = now; 1305 } else { 1306 // need to recalculate since we might have new tasks in _tasks 1307 time_slept = (int) ((now - time_before_loop) / 1000000); 1308 } 1309 1310 // Change to task list or spurious wakeup of some kind 1311 if (timedout || _should_terminate) { 1312 break; 1313 } 1314 1315 remaining = PeriodicTask::time_to_wait(); 1316 if (remaining == 0) { 1317 // Last task was just disenrolled so loop around and wait until 1318 // another task gets enrolled 1319 continue; 1320 } 1321 1322 remaining -= time_slept; 1323 if (remaining <= 0) { 1324 break; 1325 } 1326 } 1327 1328 return time_slept; 1329 } 1330 1331 void WatcherThread::run() { 1332 assert(this == watcher_thread(), "just checking"); 1333 1334 this->record_stack_base_and_size(); 1335 this->set_native_thread_name(this->name()); 1336 this->set_active_handles(JNIHandleBlock::allocate_block()); 1337 while (true) { 1338 assert(watcher_thread() == Thread::current(), "thread consistency check"); 1339 assert(watcher_thread() == this, "thread consistency check"); 1340 1341 // Calculate how long it'll be until the next PeriodicTask work 1342 // should be done, and sleep that amount of time. 1343 int time_waited = sleep(); 1344 1345 if (VMError::is_error_reported()) { 1346 // A fatal error has happened, the error handler(VMError::report_and_die) 1347 // should abort JVM after creating an error log file. However in some 1348 // rare cases, the error handler itself might deadlock. Here periodically 1349 // check for error reporting timeouts, and if it happens, just proceed to 1350 // abort the VM. 1351 1352 // This code is in WatcherThread because WatcherThread wakes up 1353 // periodically so the fatal error handler doesn't need to do anything; 1354 // also because the WatcherThread is less likely to crash than other 1355 // threads. 1356 1357 for (;;) { 1358 // Note: we use naked sleep in this loop because we want to avoid using 1359 // any kind of VM infrastructure which may be broken at this point. 1360 if (VMError::check_timeout()) { 1361 // We hit error reporting timeout. Error reporting was interrupted and 1362 // will be wrapping things up now (closing files etc). Give it some more 1363 // time, then quit the VM. 1364 os::naked_short_sleep(200); 1365 // Print a message to stderr. 1366 fdStream err(defaultStream::output_fd()); 1367 err.print_raw_cr("# [ timer expired, abort... ]"); 1368 // skip atexit/vm_exit/vm_abort hooks 1369 os::die(); 1370 } 1371 1372 // Wait a second, then recheck for timeout. 1373 os::naked_short_sleep(999); 1374 } 1375 } 1376 1377 if (_should_terminate) { 1378 // check for termination before posting the next tick 1379 break; 1380 } 1381 1382 PeriodicTask::real_time_tick(time_waited); 1383 } 1384 1385 // Signal that it is terminated 1386 { 1387 MutexLockerEx mu(Terminator_lock, Mutex::_no_safepoint_check_flag); 1388 _watcher_thread = NULL; 1389 Terminator_lock->notify(); 1390 } 1391 } 1392 1393 void WatcherThread::start() { 1394 assert(PeriodicTask_lock->owned_by_self(), "PeriodicTask_lock required"); 1395 1396 if (watcher_thread() == NULL && _startable) { 1397 _should_terminate = false; 1398 // Create the single instance of WatcherThread 1399 new WatcherThread(); 1400 } 1401 } 1402 1403 void WatcherThread::make_startable() { 1404 assert(PeriodicTask_lock->owned_by_self(), "PeriodicTask_lock required"); 1405 _startable = true; 1406 } 1407 1408 void WatcherThread::stop() { 1409 { 1410 // Follow normal safepoint aware lock enter protocol since the 1411 // WatcherThread is stopped by another JavaThread. 1412 MutexLocker ml(PeriodicTask_lock); 1413 _should_terminate = true; 1414 1415 WatcherThread* watcher = watcher_thread(); 1416 if (watcher != NULL) { 1417 // unpark the WatcherThread so it can see that it should terminate 1418 watcher->unpark(); 1419 } 1420 } 1421 1422 MutexLocker mu(Terminator_lock); 1423 1424 while (watcher_thread() != NULL) { 1425 // This wait should make safepoint checks, wait without a timeout, 1426 // and wait as a suspend-equivalent condition. 1427 Terminator_lock->wait(!Mutex::_no_safepoint_check_flag, 0, 1428 Mutex::_as_suspend_equivalent_flag); 1429 } 1430 } 1431 1432 void WatcherThread::unpark() { 1433 assert(PeriodicTask_lock->owned_by_self(), "PeriodicTask_lock required"); 1434 PeriodicTask_lock->notify(); 1435 } 1436 1437 void WatcherThread::print_on(outputStream* st) const { 1438 st->print("\"%s\" ", name()); 1439 Thread::print_on(st); 1440 st->cr(); 1441 } 1442 1443 // ======= JavaThread ======== 1444 1445 #if INCLUDE_JVMCI 1446 1447 jlong* JavaThread::_jvmci_old_thread_counters; 1448 1449 bool jvmci_counters_include(JavaThread* thread) { 1450 return !JVMCICountersExcludeCompiler || !thread->is_Compiler_thread(); 1451 } 1452 1453 void JavaThread::collect_counters(typeArrayOop array) { 1454 if (JVMCICounterSize > 0) { 1455 JavaThreadIteratorWithHandle jtiwh; 1456 for (int i = 0; i < array->length(); i++) { 1457 array->long_at_put(i, _jvmci_old_thread_counters[i]); 1458 } 1459 for (; JavaThread *tp = jtiwh.next(); ) { 1460 if (jvmci_counters_include(tp)) { 1461 for (int i = 0; i < array->length(); i++) { 1462 array->long_at_put(i, array->long_at(i) + tp->_jvmci_counters[i]); 1463 } 1464 } 1465 } 1466 } 1467 } 1468 1469 #endif // INCLUDE_JVMCI 1470 1471 // A JavaThread is a normal Java thread 1472 1473 void JavaThread::initialize() { 1474 // Initialize fields 1475 1476 set_saved_exception_pc(NULL); 1477 set_threadObj(NULL); 1478 _anchor.clear(); 1479 set_entry_point(NULL); 1480 set_jni_functions(jni_functions()); 1481 set_callee_target(NULL); 1482 set_vm_result(NULL); 1483 set_vm_result_2(NULL); 1484 set_vframe_array_head(NULL); 1485 set_vframe_array_last(NULL); 1486 set_deferred_locals(NULL); 1487 set_deopt_mark(NULL); 1488 set_deopt_compiled_method(NULL); 1489 clear_must_deopt_id(); 1490 set_monitor_chunks(NULL); 1491 set_next(NULL); 1492 _on_thread_list = false; 1493 set_thread_state(_thread_new); 1494 _terminated = _not_terminated; 1495 _privileged_stack_top = NULL; 1496 _array_for_gc = NULL; 1497 _suspend_equivalent = false; 1498 _in_deopt_handler = 0; 1499 _doing_unsafe_access = false; 1500 _stack_guard_state = stack_guard_unused; 1501 #if INCLUDE_JVMCI 1502 _pending_monitorenter = false; 1503 _pending_deoptimization = -1; 1504 _pending_failed_speculation = 0; 1505 _pending_transfer_to_interpreter = false; 1506 _adjusting_comp_level = false; 1507 _jvmci._alternate_call_target = NULL; 1508 assert(_jvmci._implicit_exception_pc == NULL, "must be"); 1509 if (JVMCICounterSize > 0) { 1510 _jvmci_counters = NEW_C_HEAP_ARRAY(jlong, JVMCICounterSize, mtInternal); 1511 memset(_jvmci_counters, 0, sizeof(jlong) * JVMCICounterSize); 1512 } else { 1513 _jvmci_counters = NULL; 1514 } 1515 #endif // INCLUDE_JVMCI 1516 _reserved_stack_activation = NULL; // stack base not known yet 1517 (void)const_cast<oop&>(_exception_oop = oop(NULL)); 1518 _exception_pc = 0; 1519 _exception_handler_pc = 0; 1520 _is_method_handle_return = 0; 1521 _jvmti_thread_state= NULL; 1522 _should_post_on_exceptions_flag = JNI_FALSE; 1523 _jvmti_get_loaded_classes_closure = NULL; 1524 _interp_only_mode = 0; 1525 _special_runtime_exit_condition = _no_async_condition; 1526 _pending_async_exception = NULL; 1527 _thread_stat = NULL; 1528 _thread_stat = new ThreadStatistics(); 1529 _blocked_on_compilation = false; 1530 _jni_active_critical = 0; 1531 _pending_jni_exception_check_fn = NULL; 1532 _do_not_unlock_if_synchronized = false; 1533 _cached_monitor_info = NULL; 1534 _parker = Parker::Allocate(this); 1535 1536 #ifndef PRODUCT 1537 _jmp_ring_index = 0; 1538 for (int ji = 0; ji < jump_ring_buffer_size; ji++) { 1539 record_jump(NULL, NULL, NULL, 0); 1540 } 1541 #endif // PRODUCT 1542 1543 // Setup safepoint state info for this thread 1544 ThreadSafepointState::create(this); 1545 1546 debug_only(_java_call_counter = 0); 1547 1548 // JVMTI PopFrame support 1549 _popframe_condition = popframe_inactive; 1550 _popframe_preserved_args = NULL; 1551 _popframe_preserved_args_size = 0; 1552 _frames_to_pop_failed_realloc = 0; 1553 1554 if (SafepointMechanism::uses_thread_local_poll()) { 1555 SafepointMechanism::initialize_header(this); 1556 } 1557 1558 pd_initialize(); 1559 } 1560 1561 JavaThread::JavaThread(bool is_attaching_via_jni) : 1562 Thread() { 1563 initialize(); 1564 if (is_attaching_via_jni) { 1565 _jni_attach_state = _attaching_via_jni; 1566 } else { 1567 _jni_attach_state = _not_attaching_via_jni; 1568 } 1569 assert(deferred_card_mark().is_empty(), "Default MemRegion ctor"); 1570 } 1571 1572 bool JavaThread::reguard_stack(address cur_sp) { 1573 if (_stack_guard_state != stack_guard_yellow_reserved_disabled 1574 && _stack_guard_state != stack_guard_reserved_disabled) { 1575 return true; // Stack already guarded or guard pages not needed. 1576 } 1577 1578 if (register_stack_overflow()) { 1579 // For those architectures which have separate register and 1580 // memory stacks, we must check the register stack to see if 1581 // it has overflowed. 1582 return false; 1583 } 1584 1585 // Java code never executes within the yellow zone: the latter is only 1586 // there to provoke an exception during stack banging. If java code 1587 // is executing there, either StackShadowPages should be larger, or 1588 // some exception code in c1, c2 or the interpreter isn't unwinding 1589 // when it should. 1590 guarantee(cur_sp > stack_reserved_zone_base(), 1591 "not enough space to reguard - increase StackShadowPages"); 1592 if (_stack_guard_state == stack_guard_yellow_reserved_disabled) { 1593 enable_stack_yellow_reserved_zone(); 1594 if (reserved_stack_activation() != stack_base()) { 1595 set_reserved_stack_activation(stack_base()); 1596 } 1597 } else if (_stack_guard_state == stack_guard_reserved_disabled) { 1598 set_reserved_stack_activation(stack_base()); 1599 enable_stack_reserved_zone(); 1600 } 1601 return true; 1602 } 1603 1604 bool JavaThread::reguard_stack(void) { 1605 return reguard_stack(os::current_stack_pointer()); 1606 } 1607 1608 1609 void JavaThread::block_if_vm_exited() { 1610 if (_terminated == _vm_exited) { 1611 // _vm_exited is set at safepoint, and Threads_lock is never released 1612 // we will block here forever 1613 Threads_lock->lock_without_safepoint_check(); 1614 ShouldNotReachHere(); 1615 } 1616 } 1617 1618 1619 // Remove this ifdef when C1 is ported to the compiler interface. 1620 static void compiler_thread_entry(JavaThread* thread, TRAPS); 1621 static void sweeper_thread_entry(JavaThread* thread, TRAPS); 1622 1623 JavaThread::JavaThread(ThreadFunction entry_point, size_t stack_sz) : 1624 Thread() { 1625 initialize(); 1626 _jni_attach_state = _not_attaching_via_jni; 1627 set_entry_point(entry_point); 1628 // Create the native thread itself. 1629 // %note runtime_23 1630 os::ThreadType thr_type = os::java_thread; 1631 thr_type = entry_point == &compiler_thread_entry ? os::compiler_thread : 1632 os::java_thread; 1633 os::create_thread(this, thr_type, stack_sz); 1634 // The _osthread may be NULL here because we ran out of memory (too many threads active). 1635 // We need to throw and OutOfMemoryError - however we cannot do this here because the caller 1636 // may hold a lock and all locks must be unlocked before throwing the exception (throwing 1637 // the exception consists of creating the exception object & initializing it, initialization 1638 // will leave the VM via a JavaCall and then all locks must be unlocked). 1639 // 1640 // The thread is still suspended when we reach here. Thread must be explicit started 1641 // by creator! Furthermore, the thread must also explicitly be added to the Threads list 1642 // by calling Threads:add. The reason why this is not done here, is because the thread 1643 // object must be fully initialized (take a look at JVM_Start) 1644 } 1645 1646 JavaThread::~JavaThread() { 1647 1648 // JSR166 -- return the parker to the free list 1649 Parker::Release(_parker); 1650 _parker = NULL; 1651 1652 // Free any remaining previous UnrollBlock 1653 vframeArray* old_array = vframe_array_last(); 1654 1655 if (old_array != NULL) { 1656 Deoptimization::UnrollBlock* old_info = old_array->unroll_block(); 1657 old_array->set_unroll_block(NULL); 1658 delete old_info; 1659 delete old_array; 1660 } 1661 1662 GrowableArray<jvmtiDeferredLocalVariableSet*>* deferred = deferred_locals(); 1663 if (deferred != NULL) { 1664 // This can only happen if thread is destroyed before deoptimization occurs. 1665 assert(deferred->length() != 0, "empty array!"); 1666 do { 1667 jvmtiDeferredLocalVariableSet* dlv = deferred->at(0); 1668 deferred->remove_at(0); 1669 // individual jvmtiDeferredLocalVariableSet are CHeapObj's 1670 delete dlv; 1671 } while (deferred->length() != 0); 1672 delete deferred; 1673 } 1674 1675 // All Java related clean up happens in exit 1676 ThreadSafepointState::destroy(this); 1677 if (_thread_stat != NULL) delete _thread_stat; 1678 1679 #if INCLUDE_JVMCI 1680 if (JVMCICounterSize > 0) { 1681 if (jvmci_counters_include(this)) { 1682 for (int i = 0; i < JVMCICounterSize; i++) { 1683 _jvmci_old_thread_counters[i] += _jvmci_counters[i]; 1684 } 1685 } 1686 FREE_C_HEAP_ARRAY(jlong, _jvmci_counters); 1687 } 1688 #endif // INCLUDE_JVMCI 1689 } 1690 1691 1692 // The first routine called by a new Java thread 1693 void JavaThread::run() { 1694 // initialize thread-local alloc buffer related fields 1695 this->initialize_tlab(); 1696 1697 // used to test validity of stack trace backs 1698 this->record_base_of_stack_pointer(); 1699 1700 // Record real stack base and size. 1701 this->record_stack_base_and_size(); 1702 1703 this->create_stack_guard_pages(); 1704 1705 this->cache_global_variables(); 1706 1707 // Thread is now sufficient initialized to be handled by the safepoint code as being 1708 // in the VM. Change thread state from _thread_new to _thread_in_vm 1709 ThreadStateTransition::transition_and_fence(this, _thread_new, _thread_in_vm); 1710 1711 assert(JavaThread::current() == this, "sanity check"); 1712 assert(!Thread::current()->owns_locks(), "sanity check"); 1713 1714 DTRACE_THREAD_PROBE(start, this); 1715 1716 // This operation might block. We call that after all safepoint checks for a new thread has 1717 // been completed. 1718 this->set_active_handles(JNIHandleBlock::allocate_block()); 1719 1720 if (JvmtiExport::should_post_thread_life()) { 1721 JvmtiExport::post_thread_start(this); 1722 } 1723 1724 EventThreadStart event; 1725 if (event.should_commit()) { 1726 event.set_thread(JFR_THREAD_ID(this)); 1727 event.commit(); 1728 } 1729 1730 // We call another function to do the rest so we are sure that the stack addresses used 1731 // from there will be lower than the stack base just computed 1732 thread_main_inner(); 1733 1734 // Note, thread is no longer valid at this point! 1735 } 1736 1737 1738 void JavaThread::thread_main_inner() { 1739 assert(JavaThread::current() == this, "sanity check"); 1740 assert(this->threadObj() != NULL, "just checking"); 1741 1742 // Execute thread entry point unless this thread has a pending exception 1743 // or has been stopped before starting. 1744 // Note: Due to JVM_StopThread we can have pending exceptions already! 1745 if (!this->has_pending_exception() && 1746 !java_lang_Thread::is_stillborn(this->threadObj())) { 1747 { 1748 ResourceMark rm(this); 1749 this->set_native_thread_name(this->get_thread_name()); 1750 } 1751 HandleMark hm(this); 1752 this->entry_point()(this, this); 1753 } 1754 1755 DTRACE_THREAD_PROBE(stop, this); 1756 1757 this->exit(false); 1758 this->smr_delete(); 1759 } 1760 1761 1762 static void ensure_join(JavaThread* thread) { 1763 // We do not need to grab the Threads_lock, since we are operating on ourself. 1764 Handle threadObj(thread, thread->threadObj()); 1765 assert(threadObj.not_null(), "java thread object must exist"); 1766 ObjectLocker lock(threadObj, thread); 1767 // Ignore pending exception (ThreadDeath), since we are exiting anyway 1768 thread->clear_pending_exception(); 1769 // Thread is exiting. So set thread_status field in java.lang.Thread class to TERMINATED. 1770 java_lang_Thread::set_thread_status(threadObj(), java_lang_Thread::TERMINATED); 1771 // Clear the native thread instance - this makes isAlive return false and allows the join() 1772 // to complete once we've done the notify_all below 1773 java_lang_Thread::set_thread(threadObj(), NULL); 1774 lock.notify_all(thread); 1775 // Ignore pending exception (ThreadDeath), since we are exiting anyway 1776 thread->clear_pending_exception(); 1777 } 1778 1779 1780 // For any new cleanup additions, please check to see if they need to be applied to 1781 // cleanup_failed_attach_current_thread as well. 1782 void JavaThread::exit(bool destroy_vm, ExitType exit_type) { 1783 assert(this == JavaThread::current(), "thread consistency check"); 1784 1785 elapsedTimer _timer_exit_phase1; 1786 elapsedTimer _timer_exit_phase2; 1787 elapsedTimer _timer_exit_phase3; 1788 elapsedTimer _timer_exit_phase4; 1789 1790 if (log_is_enabled(Debug, os, thread, timer)) { 1791 _timer_exit_phase1.start(); 1792 } 1793 1794 HandleMark hm(this); 1795 Handle uncaught_exception(this, this->pending_exception()); 1796 this->clear_pending_exception(); 1797 Handle threadObj(this, this->threadObj()); 1798 assert(threadObj.not_null(), "Java thread object should be created"); 1799 1800 // FIXIT: This code should be moved into else part, when reliable 1.2/1.3 check is in place 1801 { 1802 EXCEPTION_MARK; 1803 1804 CLEAR_PENDING_EXCEPTION; 1805 } 1806 if (!destroy_vm) { 1807 if (uncaught_exception.not_null()) { 1808 EXCEPTION_MARK; 1809 // Call method Thread.dispatchUncaughtException(). 1810 Klass* thread_klass = SystemDictionary::Thread_klass(); 1811 JavaValue result(T_VOID); 1812 JavaCalls::call_virtual(&result, 1813 threadObj, thread_klass, 1814 vmSymbols::dispatchUncaughtException_name(), 1815 vmSymbols::throwable_void_signature(), 1816 uncaught_exception, 1817 THREAD); 1818 if (HAS_PENDING_EXCEPTION) { 1819 ResourceMark rm(this); 1820 jio_fprintf(defaultStream::error_stream(), 1821 "\nException: %s thrown from the UncaughtExceptionHandler" 1822 " in thread \"%s\"\n", 1823 pending_exception()->klass()->external_name(), 1824 get_thread_name()); 1825 CLEAR_PENDING_EXCEPTION; 1826 } 1827 } 1828 1829 // Called before the java thread exit since we want to read info 1830 // from java_lang_Thread object 1831 EventThreadEnd event; 1832 if (event.should_commit()) { 1833 event.set_thread(JFR_THREAD_ID(this)); 1834 event.commit(); 1835 } 1836 1837 // Call after last event on thread 1838 JFR_ONLY(Jfr::on_thread_exit(this);) 1839 1840 // Call Thread.exit(). We try 3 times in case we got another Thread.stop during 1841 // the execution of the method. If that is not enough, then we don't really care. Thread.stop 1842 // is deprecated anyhow. 1843 if (!is_Compiler_thread()) { 1844 int count = 3; 1845 while (java_lang_Thread::threadGroup(threadObj()) != NULL && (count-- > 0)) { 1846 EXCEPTION_MARK; 1847 JavaValue result(T_VOID); 1848 Klass* thread_klass = SystemDictionary::Thread_klass(); 1849 JavaCalls::call_virtual(&result, 1850 threadObj, thread_klass, 1851 vmSymbols::exit_method_name(), 1852 vmSymbols::void_method_signature(), 1853 THREAD); 1854 CLEAR_PENDING_EXCEPTION; 1855 } 1856 } 1857 // notify JVMTI 1858 if (JvmtiExport::should_post_thread_life()) { 1859 JvmtiExport::post_thread_end(this); 1860 } 1861 1862 // We have notified the agents that we are exiting, before we go on, 1863 // we must check for a pending external suspend request and honor it 1864 // in order to not surprise the thread that made the suspend request. 1865 while (true) { 1866 { 1867 MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag); 1868 if (!is_external_suspend()) { 1869 set_terminated(_thread_exiting); 1870 ThreadService::current_thread_exiting(this); 1871 break; 1872 } 1873 // Implied else: 1874 // Things get a little tricky here. We have a pending external 1875 // suspend request, but we are holding the SR_lock so we 1876 // can't just self-suspend. So we temporarily drop the lock 1877 // and then self-suspend. 1878 } 1879 1880 ThreadBlockInVM tbivm(this); 1881 java_suspend_self(); 1882 1883 // We're done with this suspend request, but we have to loop around 1884 // and check again. Eventually we will get SR_lock without a pending 1885 // external suspend request and will be able to mark ourselves as 1886 // exiting. 1887 } 1888 // no more external suspends are allowed at this point 1889 } else { 1890 // before_exit() has already posted JVMTI THREAD_END events 1891 } 1892 1893 if (log_is_enabled(Debug, os, thread, timer)) { 1894 _timer_exit_phase1.stop(); 1895 _timer_exit_phase2.start(); 1896 } 1897 // Notify waiters on thread object. This has to be done after exit() is called 1898 // on the thread (if the thread is the last thread in a daemon ThreadGroup the 1899 // group should have the destroyed bit set before waiters are notified). 1900 ensure_join(this); 1901 assert(!this->has_pending_exception(), "ensure_join should have cleared"); 1902 1903 if (log_is_enabled(Debug, os, thread, timer)) { 1904 _timer_exit_phase2.stop(); 1905 _timer_exit_phase3.start(); 1906 } 1907 // 6282335 JNI DetachCurrentThread spec states that all Java monitors 1908 // held by this thread must be released. The spec does not distinguish 1909 // between JNI-acquired and regular Java monitors. We can only see 1910 // regular Java monitors here if monitor enter-exit matching is broken. 1911 // 1912 // Optionally release any monitors for regular JavaThread exits. This 1913 // is provided as a work around for any bugs in monitor enter-exit 1914 // matching. This can be expensive so it is not enabled by default. 1915 // 1916 // ensure_join() ignores IllegalThreadStateExceptions, and so does 1917 // ObjectSynchronizer::release_monitors_owned_by_thread(). 1918 if (exit_type == jni_detach || ObjectMonitor::Knob_ExitRelease) { 1919 // Sanity check even though JNI DetachCurrentThread() would have 1920 // returned JNI_ERR if there was a Java frame. JavaThread exit 1921 // should be done executing Java code by the time we get here. 1922 assert(!this->has_last_Java_frame(), 1923 "should not have a Java frame when detaching or exiting"); 1924 ObjectSynchronizer::release_monitors_owned_by_thread(this); 1925 assert(!this->has_pending_exception(), "release_monitors should have cleared"); 1926 } 1927 1928 // These things needs to be done while we are still a Java Thread. Make sure that thread 1929 // is in a consistent state, in case GC happens 1930 assert(_privileged_stack_top == NULL, "must be NULL when we get here"); 1931 1932 if (active_handles() != NULL) { 1933 JNIHandleBlock* block = active_handles(); 1934 set_active_handles(NULL); 1935 JNIHandleBlock::release_block(block); 1936 } 1937 1938 if (free_handle_block() != NULL) { 1939 JNIHandleBlock* block = free_handle_block(); 1940 set_free_handle_block(NULL); 1941 JNIHandleBlock::release_block(block); 1942 } 1943 1944 // These have to be removed while this is still a valid thread. 1945 remove_stack_guard_pages(); 1946 1947 if (UseTLAB) { 1948 tlab().make_parsable(true); // retire TLAB 1949 } 1950 1951 if (JvmtiEnv::environments_might_exist()) { 1952 JvmtiExport::cleanup_thread(this); 1953 } 1954 1955 // We must flush any deferred card marks and other various GC barrier 1956 // related buffers (e.g. G1 SATB buffer and G1 dirty card queue buffer) 1957 // before removing a thread from the list of active threads. 1958 BarrierSet::barrier_set()->on_thread_detach(this); 1959 1960 log_info(os, thread)("JavaThread %s (tid: " UINTX_FORMAT ").", 1961 exit_type == JavaThread::normal_exit ? "exiting" : "detaching", 1962 os::current_thread_id()); 1963 1964 if (log_is_enabled(Debug, os, thread, timer)) { 1965 _timer_exit_phase3.stop(); 1966 _timer_exit_phase4.start(); 1967 } 1968 // Remove from list of active threads list, and notify VM thread if we are the last non-daemon thread 1969 Threads::remove(this); 1970 1971 if (log_is_enabled(Debug, os, thread, timer)) { 1972 _timer_exit_phase4.stop(); 1973 ResourceMark rm(this); 1974 log_debug(os, thread, timer)("name='%s'" 1975 ", exit-phase1=" JLONG_FORMAT 1976 ", exit-phase2=" JLONG_FORMAT 1977 ", exit-phase3=" JLONG_FORMAT 1978 ", exit-phase4=" JLONG_FORMAT, 1979 get_thread_name(), 1980 _timer_exit_phase1.milliseconds(), 1981 _timer_exit_phase2.milliseconds(), 1982 _timer_exit_phase3.milliseconds(), 1983 _timer_exit_phase4.milliseconds()); 1984 } 1985 } 1986 1987 void JavaThread::cleanup_failed_attach_current_thread() { 1988 if (active_handles() != NULL) { 1989 JNIHandleBlock* block = active_handles(); 1990 set_active_handles(NULL); 1991 JNIHandleBlock::release_block(block); 1992 } 1993 1994 if (free_handle_block() != NULL) { 1995 JNIHandleBlock* block = free_handle_block(); 1996 set_free_handle_block(NULL); 1997 JNIHandleBlock::release_block(block); 1998 } 1999 2000 // These have to be removed while this is still a valid thread. 2001 remove_stack_guard_pages(); 2002 2003 if (UseTLAB) { 2004 tlab().make_parsable(true); // retire TLAB, if any 2005 } 2006 2007 BarrierSet::barrier_set()->on_thread_detach(this); 2008 2009 Threads::remove(this); 2010 this->smr_delete(); 2011 } 2012 2013 JavaThread* JavaThread::active() { 2014 Thread* thread = Thread::current(); 2015 if (thread->is_Java_thread()) { 2016 return (JavaThread*) thread; 2017 } else { 2018 assert(thread->is_VM_thread(), "this must be a vm thread"); 2019 VM_Operation* op = ((VMThread*) thread)->vm_operation(); 2020 JavaThread *ret=op == NULL ? NULL : (JavaThread *)op->calling_thread(); 2021 assert(ret->is_Java_thread(), "must be a Java thread"); 2022 return ret; 2023 } 2024 } 2025 2026 bool JavaThread::is_lock_owned(address adr) const { 2027 if (Thread::is_lock_owned(adr)) return true; 2028 2029 for (MonitorChunk* chunk = monitor_chunks(); chunk != NULL; chunk = chunk->next()) { 2030 if (chunk->contains(adr)) return true; 2031 } 2032 2033 return false; 2034 } 2035 2036 2037 void JavaThread::add_monitor_chunk(MonitorChunk* chunk) { 2038 chunk->set_next(monitor_chunks()); 2039 set_monitor_chunks(chunk); 2040 } 2041 2042 void JavaThread::remove_monitor_chunk(MonitorChunk* chunk) { 2043 guarantee(monitor_chunks() != NULL, "must be non empty"); 2044 if (monitor_chunks() == chunk) { 2045 set_monitor_chunks(chunk->next()); 2046 } else { 2047 MonitorChunk* prev = monitor_chunks(); 2048 while (prev->next() != chunk) prev = prev->next(); 2049 prev->set_next(chunk->next()); 2050 } 2051 } 2052 2053 // JVM support. 2054 2055 // Note: this function shouldn't block if it's called in 2056 // _thread_in_native_trans state (such as from 2057 // check_special_condition_for_native_trans()). 2058 void JavaThread::check_and_handle_async_exceptions(bool check_unsafe_error) { 2059 2060 if (has_last_Java_frame() && has_async_condition()) { 2061 // If we are at a polling page safepoint (not a poll return) 2062 // then we must defer async exception because live registers 2063 // will be clobbered by the exception path. Poll return is 2064 // ok because the call we a returning from already collides 2065 // with exception handling registers and so there is no issue. 2066 // (The exception handling path kills call result registers but 2067 // this is ok since the exception kills the result anyway). 2068 2069 if (is_at_poll_safepoint()) { 2070 // if the code we are returning to has deoptimized we must defer 2071 // the exception otherwise live registers get clobbered on the 2072 // exception path before deoptimization is able to retrieve them. 2073 // 2074 RegisterMap map(this, false); 2075 frame caller_fr = last_frame().sender(&map); 2076 assert(caller_fr.is_compiled_frame(), "what?"); 2077 if (caller_fr.is_deoptimized_frame()) { 2078 log_info(exceptions)("deferred async exception at compiled safepoint"); 2079 return; 2080 } 2081 } 2082 } 2083 2084 JavaThread::AsyncRequests condition = clear_special_runtime_exit_condition(); 2085 if (condition == _no_async_condition) { 2086 // Conditions have changed since has_special_runtime_exit_condition() 2087 // was called: 2088 // - if we were here only because of an external suspend request, 2089 // then that was taken care of above (or cancelled) so we are done 2090 // - if we were here because of another async request, then it has 2091 // been cleared between the has_special_runtime_exit_condition() 2092 // and now so again we are done 2093 return; 2094 } 2095 2096 // Check for pending async. exception 2097 if (_pending_async_exception != NULL) { 2098 // Only overwrite an already pending exception, if it is not a threadDeath. 2099 if (!has_pending_exception() || !pending_exception()->is_a(SystemDictionary::ThreadDeath_klass())) { 2100 2101 // We cannot call Exceptions::_throw(...) here because we cannot block 2102 set_pending_exception(_pending_async_exception, __FILE__, __LINE__); 2103 2104 LogTarget(Info, exceptions) lt; 2105 if (lt.is_enabled()) { 2106 ResourceMark rm; 2107 LogStream ls(lt); 2108 ls.print("Async. exception installed at runtime exit (" INTPTR_FORMAT ")", p2i(this)); 2109 if (has_last_Java_frame()) { 2110 frame f = last_frame(); 2111 ls.print(" (pc: " INTPTR_FORMAT " sp: " INTPTR_FORMAT " )", p2i(f.pc()), p2i(f.sp())); 2112 } 2113 ls.print_cr(" of type: %s", _pending_async_exception->klass()->external_name()); 2114 } 2115 _pending_async_exception = NULL; 2116 clear_has_async_exception(); 2117 } 2118 } 2119 2120 if (check_unsafe_error && 2121 condition == _async_unsafe_access_error && !has_pending_exception()) { 2122 condition = _no_async_condition; // done 2123 switch (thread_state()) { 2124 case _thread_in_vm: { 2125 JavaThread* THREAD = this; 2126 THROW_MSG(vmSymbols::java_lang_InternalError(), "a fault occurred in an unsafe memory access operation"); 2127 } 2128 case _thread_in_native: { 2129 ThreadInVMfromNative tiv(this); 2130 JavaThread* THREAD = this; 2131 THROW_MSG(vmSymbols::java_lang_InternalError(), "a fault occurred in an unsafe memory access operation"); 2132 } 2133 case _thread_in_Java: { 2134 ThreadInVMfromJava tiv(this); 2135 JavaThread* THREAD = this; 2136 THROW_MSG(vmSymbols::java_lang_InternalError(), "a fault occurred in a recent unsafe memory access operation in compiled Java code"); 2137 } 2138 default: 2139 ShouldNotReachHere(); 2140 } 2141 } 2142 2143 assert(condition == _no_async_condition || has_pending_exception() || 2144 (!check_unsafe_error && condition == _async_unsafe_access_error), 2145 "must have handled the async condition, if no exception"); 2146 } 2147 2148 void JavaThread::handle_special_runtime_exit_condition(bool check_asyncs) { 2149 // 2150 // Check for pending external suspend. Internal suspend requests do 2151 // not use handle_special_runtime_exit_condition(). 2152 // If JNIEnv proxies are allowed, don't self-suspend if the target 2153 // thread is not the current thread. In older versions of jdbx, jdbx 2154 // threads could call into the VM with another thread's JNIEnv so we 2155 // can be here operating on behalf of a suspended thread (4432884). 2156 bool do_self_suspend = is_external_suspend_with_lock(); 2157 if (do_self_suspend && (!AllowJNIEnvProxy || this == JavaThread::current())) { 2158 // 2159 // Because thread is external suspended the safepoint code will count 2160 // thread as at a safepoint. This can be odd because we can be here 2161 // as _thread_in_Java which would normally transition to _thread_blocked 2162 // at a safepoint. We would like to mark the thread as _thread_blocked 2163 // before calling java_suspend_self like all other callers of it but 2164 // we must then observe proper safepoint protocol. (We can't leave 2165 // _thread_blocked with a safepoint in progress). However we can be 2166 // here as _thread_in_native_trans so we can't use a normal transition 2167 // constructor/destructor pair because they assert on that type of 2168 // transition. We could do something like: 2169 // 2170 // JavaThreadState state = thread_state(); 2171 // set_thread_state(_thread_in_vm); 2172 // { 2173 // ThreadBlockInVM tbivm(this); 2174 // java_suspend_self() 2175 // } 2176 // set_thread_state(_thread_in_vm_trans); 2177 // if (safepoint) block; 2178 // set_thread_state(state); 2179 // 2180 // but that is pretty messy. Instead we just go with the way the 2181 // code has worked before and note that this is the only path to 2182 // java_suspend_self that doesn't put the thread in _thread_blocked 2183 // mode. 2184 2185 frame_anchor()->make_walkable(this); 2186 java_suspend_self(); 2187 2188 // We might be here for reasons in addition to the self-suspend request 2189 // so check for other async requests. 2190 } 2191 2192 if (check_asyncs) { 2193 check_and_handle_async_exceptions(); 2194 } 2195 2196 JFR_ONLY(SUSPEND_THREAD_CONDITIONAL(this);) 2197 } 2198 2199 void JavaThread::send_thread_stop(oop java_throwable) { 2200 assert(Thread::current()->is_VM_thread(), "should be in the vm thread"); 2201 assert(Threads_lock->is_locked(), "Threads_lock should be locked by safepoint code"); 2202 assert(SafepointSynchronize::is_at_safepoint(), "all threads are stopped"); 2203 2204 // Do not throw asynchronous exceptions against the compiler thread 2205 // (the compiler thread should not be a Java thread -- fix in 1.4.2) 2206 if (!can_call_java()) return; 2207 2208 { 2209 // Actually throw the Throwable against the target Thread - however 2210 // only if there is no thread death exception installed already. 2211 if (_pending_async_exception == NULL || !_pending_async_exception->is_a(SystemDictionary::ThreadDeath_klass())) { 2212 // If the topmost frame is a runtime stub, then we are calling into 2213 // OptoRuntime from compiled code. Some runtime stubs (new, monitor_exit..) 2214 // must deoptimize the caller before continuing, as the compiled exception handler table 2215 // may not be valid 2216 if (has_last_Java_frame()) { 2217 frame f = last_frame(); 2218 if (f.is_runtime_frame() || f.is_safepoint_blob_frame()) { 2219 // BiasedLocking needs an updated RegisterMap for the revoke monitors pass 2220 RegisterMap reg_map(this, UseBiasedLocking); 2221 frame compiled_frame = f.sender(®_map); 2222 if (!StressCompiledExceptionHandlers && compiled_frame.can_be_deoptimized()) { 2223 Deoptimization::deoptimize(this, compiled_frame, ®_map); 2224 } 2225 } 2226 } 2227 2228 // Set async. pending exception in thread. 2229 set_pending_async_exception(java_throwable); 2230 2231 if (log_is_enabled(Info, exceptions)) { 2232 ResourceMark rm; 2233 log_info(exceptions)("Pending Async. exception installed of type: %s", 2234 InstanceKlass::cast(_pending_async_exception->klass())->external_name()); 2235 } 2236 // for AbortVMOnException flag 2237 Exceptions::debug_check_abort(_pending_async_exception->klass()->external_name()); 2238 } 2239 } 2240 2241 2242 // Interrupt thread so it will wake up from a potential wait() 2243 Thread::interrupt(this); 2244 } 2245 2246 // External suspension mechanism. 2247 // 2248 // Tell the VM to suspend a thread when ever it knows that it does not hold on 2249 // to any VM_locks and it is at a transition 2250 // Self-suspension will happen on the transition out of the vm. 2251 // Catch "this" coming in from JNIEnv pointers when the thread has been freed 2252 // 2253 // Guarantees on return: 2254 // + Target thread will not execute any new bytecode (that's why we need to 2255 // force a safepoint) 2256 // + Target thread will not enter any new monitors 2257 // 2258 void JavaThread::java_suspend() { 2259 ThreadsListHandle tlh; 2260 if (!tlh.includes(this) || threadObj() == NULL || is_exiting()) { 2261 return; 2262 } 2263 2264 { MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag); 2265 if (!is_external_suspend()) { 2266 // a racing resume has cancelled us; bail out now 2267 return; 2268 } 2269 2270 // suspend is done 2271 uint32_t debug_bits = 0; 2272 // Warning: is_ext_suspend_completed() may temporarily drop the 2273 // SR_lock to allow the thread to reach a stable thread state if 2274 // it is currently in a transient thread state. 2275 if (is_ext_suspend_completed(false /* !called_by_wait */, 2276 SuspendRetryDelay, &debug_bits)) { 2277 return; 2278 } 2279 } 2280 2281 VM_ThreadSuspend vm_suspend; 2282 VMThread::execute(&vm_suspend); 2283 } 2284 2285 // Part II of external suspension. 2286 // A JavaThread self suspends when it detects a pending external suspend 2287 // request. This is usually on transitions. It is also done in places 2288 // where continuing to the next transition would surprise the caller, 2289 // e.g., monitor entry. 2290 // 2291 // Returns the number of times that the thread self-suspended. 2292 // 2293 // Note: DO NOT call java_suspend_self() when you just want to block current 2294 // thread. java_suspend_self() is the second stage of cooperative 2295 // suspension for external suspend requests and should only be used 2296 // to complete an external suspend request. 2297 // 2298 int JavaThread::java_suspend_self() { 2299 int ret = 0; 2300 2301 // we are in the process of exiting so don't suspend 2302 if (is_exiting()) { 2303 clear_external_suspend(); 2304 return ret; 2305 } 2306 2307 assert(_anchor.walkable() || 2308 (is_Java_thread() && !((JavaThread*)this)->has_last_Java_frame()), 2309 "must have walkable stack"); 2310 2311 MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag); 2312 2313 assert(!this->is_ext_suspended(), 2314 "a thread trying to self-suspend should not already be suspended"); 2315 2316 if (this->is_suspend_equivalent()) { 2317 // If we are self-suspending as a result of the lifting of a 2318 // suspend equivalent condition, then the suspend_equivalent 2319 // flag is not cleared until we set the ext_suspended flag so 2320 // that wait_for_ext_suspend_completion() returns consistent 2321 // results. 2322 this->clear_suspend_equivalent(); 2323 } 2324 2325 // A racing resume may have cancelled us before we grabbed SR_lock 2326 // above. Or another external suspend request could be waiting for us 2327 // by the time we return from SR_lock()->wait(). The thread 2328 // that requested the suspension may already be trying to walk our 2329 // stack and if we return now, we can change the stack out from under 2330 // it. This would be a "bad thing (TM)" and cause the stack walker 2331 // to crash. We stay self-suspended until there are no more pending 2332 // external suspend requests. 2333 while (is_external_suspend()) { 2334 ret++; 2335 this->set_ext_suspended(); 2336 2337 // _ext_suspended flag is cleared by java_resume() 2338 while (is_ext_suspended()) { 2339 this->SR_lock()->wait(Mutex::_no_safepoint_check_flag); 2340 } 2341 } 2342 2343 return ret; 2344 } 2345 2346 #ifdef ASSERT 2347 // Verify the JavaThread has not yet been published in the Threads::list, and 2348 // hence doesn't need protection from concurrent access at this stage. 2349 void JavaThread::verify_not_published() { 2350 // Cannot create a ThreadsListHandle here and check !tlh.includes(this) 2351 // since an unpublished JavaThread doesn't participate in the 2352 // Thread-SMR protocol for keeping a ThreadsList alive. 2353 assert(!on_thread_list(), "JavaThread shouldn't have been published yet!"); 2354 } 2355 #endif 2356 2357 // Slow path when the native==>VM/Java barriers detect a safepoint is in 2358 // progress or when _suspend_flags is non-zero. 2359 // Current thread needs to self-suspend if there is a suspend request and/or 2360 // block if a safepoint is in progress. 2361 // Async exception ISN'T checked. 2362 // Note only the ThreadInVMfromNative transition can call this function 2363 // directly and when thread state is _thread_in_native_trans 2364 void JavaThread::check_safepoint_and_suspend_for_native_trans(JavaThread *thread) { 2365 assert(thread->thread_state() == _thread_in_native_trans, "wrong state"); 2366 2367 JavaThread *curJT = JavaThread::current(); 2368 bool do_self_suspend = thread->is_external_suspend(); 2369 2370 assert(!curJT->has_last_Java_frame() || curJT->frame_anchor()->walkable(), "Unwalkable stack in native->vm transition"); 2371 2372 // If JNIEnv proxies are allowed, don't self-suspend if the target 2373 // thread is not the current thread. In older versions of jdbx, jdbx 2374 // threads could call into the VM with another thread's JNIEnv so we 2375 // can be here operating on behalf of a suspended thread (4432884). 2376 if (do_self_suspend && (!AllowJNIEnvProxy || curJT == thread)) { 2377 JavaThreadState state = thread->thread_state(); 2378 2379 // We mark this thread_blocked state as a suspend-equivalent so 2380 // that a caller to is_ext_suspend_completed() won't be confused. 2381 // The suspend-equivalent state is cleared by java_suspend_self(). 2382 thread->set_suspend_equivalent(); 2383 2384 // If the safepoint code sees the _thread_in_native_trans state, it will 2385 // wait until the thread changes to other thread state. There is no 2386 // guarantee on how soon we can obtain the SR_lock and complete the 2387 // self-suspend request. It would be a bad idea to let safepoint wait for 2388 // too long. Temporarily change the state to _thread_blocked to 2389 // let the VM thread know that this thread is ready for GC. The problem 2390 // of changing thread state is that safepoint could happen just after 2391 // java_suspend_self() returns after being resumed, and VM thread will 2392 // see the _thread_blocked state. We must check for safepoint 2393 // after restoring the state and make sure we won't leave while a safepoint 2394 // is in progress. 2395 thread->set_thread_state(_thread_blocked); 2396 thread->java_suspend_self(); 2397 thread->set_thread_state(state); 2398 2399 InterfaceSupport::serialize_thread_state_with_handler(thread); 2400 } 2401 2402 SafepointMechanism::block_if_requested(curJT); 2403 2404 if (thread->is_deopt_suspend()) { 2405 thread->clear_deopt_suspend(); 2406 RegisterMap map(thread, false); 2407 frame f = thread->last_frame(); 2408 while (f.id() != thread->must_deopt_id() && ! f.is_first_frame()) { 2409 f = f.sender(&map); 2410 } 2411 if (f.id() == thread->must_deopt_id()) { 2412 thread->clear_must_deopt_id(); 2413 f.deoptimize(thread); 2414 } else { 2415 fatal("missed deoptimization!"); 2416 } 2417 } 2418 2419 JFR_ONLY(SUSPEND_THREAD_CONDITIONAL(thread);) 2420 } 2421 2422 // Slow path when the native==>VM/Java barriers detect a safepoint is in 2423 // progress or when _suspend_flags is non-zero. 2424 // Current thread needs to self-suspend if there is a suspend request and/or 2425 // block if a safepoint is in progress. 2426 // Also check for pending async exception (not including unsafe access error). 2427 // Note only the native==>VM/Java barriers can call this function and when 2428 // thread state is _thread_in_native_trans. 2429 void JavaThread::check_special_condition_for_native_trans(JavaThread *thread) { 2430 check_safepoint_and_suspend_for_native_trans(thread); 2431 2432 if (thread->has_async_exception()) { 2433 // We are in _thread_in_native_trans state, don't handle unsafe 2434 // access error since that may block. 2435 thread->check_and_handle_async_exceptions(false); 2436 } 2437 } 2438 2439 // This is a variant of the normal 2440 // check_special_condition_for_native_trans with slightly different 2441 // semantics for use by critical native wrappers. It does all the 2442 // normal checks but also performs the transition back into 2443 // thread_in_Java state. This is required so that critical natives 2444 // can potentially block and perform a GC if they are the last thread 2445 // exiting the GCLocker. 2446 void JavaThread::check_special_condition_for_native_trans_and_transition(JavaThread *thread) { 2447 check_special_condition_for_native_trans(thread); 2448 2449 // Finish the transition 2450 thread->set_thread_state(_thread_in_Java); 2451 2452 if (thread->do_critical_native_unlock()) { 2453 ThreadInVMfromJavaNoAsyncException tiv(thread); 2454 GCLocker::unlock_critical(thread); 2455 thread->clear_critical_native_unlock(); 2456 } 2457 } 2458 2459 // We need to guarantee the Threads_lock here, since resumes are not 2460 // allowed during safepoint synchronization 2461 // Can only resume from an external suspension 2462 void JavaThread::java_resume() { 2463 assert_locked_or_safepoint(Threads_lock); 2464 2465 // Sanity check: thread is gone, has started exiting or the thread 2466 // was not externally suspended. 2467 ThreadsListHandle tlh; 2468 if (!tlh.includes(this) || is_exiting() || !is_external_suspend()) { 2469 return; 2470 } 2471 2472 MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag); 2473 2474 clear_external_suspend(); 2475 2476 if (is_ext_suspended()) { 2477 clear_ext_suspended(); 2478 SR_lock()->notify_all(); 2479 } 2480 } 2481 2482 size_t JavaThread::_stack_red_zone_size = 0; 2483 size_t JavaThread::_stack_yellow_zone_size = 0; 2484 size_t JavaThread::_stack_reserved_zone_size = 0; 2485 size_t JavaThread::_stack_shadow_zone_size = 0; 2486 2487 void JavaThread::create_stack_guard_pages() { 2488 if (!os::uses_stack_guard_pages() || 2489 _stack_guard_state != stack_guard_unused || 2490 (DisablePrimordialThreadGuardPages && os::is_primordial_thread())) { 2491 log_info(os, thread)("Stack guard page creation for thread " 2492 UINTX_FORMAT " disabled", os::current_thread_id()); 2493 return; 2494 } 2495 address low_addr = stack_end(); 2496 size_t len = stack_guard_zone_size(); 2497 2498 assert(is_aligned(low_addr, os::vm_page_size()), "Stack base should be the start of a page"); 2499 assert(is_aligned(len, os::vm_page_size()), "Stack size should be a multiple of page size"); 2500 2501 int must_commit = os::must_commit_stack_guard_pages(); 2502 // warning("Guarding at " PTR_FORMAT " for len " SIZE_FORMAT "\n", low_addr, len); 2503 2504 if (must_commit && !os::create_stack_guard_pages((char *) low_addr, len)) { 2505 log_warning(os, thread)("Attempt to allocate stack guard pages failed."); 2506 return; 2507 } 2508 2509 if (os::guard_memory((char *) low_addr, len)) { 2510 _stack_guard_state = stack_guard_enabled; 2511 } else { 2512 log_warning(os, thread)("Attempt to protect stack guard pages failed (" 2513 PTR_FORMAT "-" PTR_FORMAT ").", p2i(low_addr), p2i(low_addr + len)); 2514 if (os::uncommit_memory((char *) low_addr, len)) { 2515 log_warning(os, thread)("Attempt to deallocate stack guard pages failed."); 2516 } 2517 return; 2518 } 2519 2520 log_debug(os, thread)("Thread " UINTX_FORMAT " stack guard pages activated: " 2521 PTR_FORMAT "-" PTR_FORMAT ".", 2522 os::current_thread_id(), p2i(low_addr), p2i(low_addr + len)); 2523 } 2524 2525 void JavaThread::remove_stack_guard_pages() { 2526 assert(Thread::current() == this, "from different thread"); 2527 if (_stack_guard_state == stack_guard_unused) return; 2528 address low_addr = stack_end(); 2529 size_t len = stack_guard_zone_size(); 2530 2531 if (os::must_commit_stack_guard_pages()) { 2532 if (os::remove_stack_guard_pages((char *) low_addr, len)) { 2533 _stack_guard_state = stack_guard_unused; 2534 } else { 2535 log_warning(os, thread)("Attempt to deallocate stack guard pages failed (" 2536 PTR_FORMAT "-" PTR_FORMAT ").", p2i(low_addr), p2i(low_addr + len)); 2537 return; 2538 } 2539 } else { 2540 if (_stack_guard_state == stack_guard_unused) return; 2541 if (os::unguard_memory((char *) low_addr, len)) { 2542 _stack_guard_state = stack_guard_unused; 2543 } else { 2544 log_warning(os, thread)("Attempt to unprotect stack guard pages failed (" 2545 PTR_FORMAT "-" PTR_FORMAT ").", p2i(low_addr), p2i(low_addr + len)); 2546 return; 2547 } 2548 } 2549 2550 log_debug(os, thread)("Thread " UINTX_FORMAT " stack guard pages removed: " 2551 PTR_FORMAT "-" PTR_FORMAT ".", 2552 os::current_thread_id(), p2i(low_addr), p2i(low_addr + len)); 2553 } 2554 2555 void JavaThread::enable_stack_reserved_zone() { 2556 assert(_stack_guard_state != stack_guard_unused, "must be using guard pages."); 2557 assert(_stack_guard_state != stack_guard_enabled, "already enabled"); 2558 2559 // The base notation is from the stack's point of view, growing downward. 2560 // We need to adjust it to work correctly with guard_memory() 2561 address base = stack_reserved_zone_base() - stack_reserved_zone_size(); 2562 2563 guarantee(base < stack_base(),"Error calculating stack reserved zone"); 2564 guarantee(base < os::current_stack_pointer(),"Error calculating stack reserved zone"); 2565 2566 if (os::guard_memory((char *) base, stack_reserved_zone_size())) { 2567 _stack_guard_state = stack_guard_enabled; 2568 } else { 2569 warning("Attempt to guard stack reserved zone failed."); 2570 } 2571 enable_register_stack_guard(); 2572 } 2573 2574 void JavaThread::disable_stack_reserved_zone() { 2575 assert(_stack_guard_state != stack_guard_unused, "must be using guard pages."); 2576 assert(_stack_guard_state != stack_guard_reserved_disabled, "already disabled"); 2577 2578 // Simply return if called for a thread that does not use guard pages. 2579 if (_stack_guard_state == stack_guard_unused) return; 2580 2581 // The base notation is from the stack's point of view, growing downward. 2582 // We need to adjust it to work correctly with guard_memory() 2583 address base = stack_reserved_zone_base() - stack_reserved_zone_size(); 2584 2585 if (os::unguard_memory((char *)base, stack_reserved_zone_size())) { 2586 _stack_guard_state = stack_guard_reserved_disabled; 2587 } else { 2588 warning("Attempt to unguard stack reserved zone failed."); 2589 } 2590 disable_register_stack_guard(); 2591 } 2592 2593 void JavaThread::enable_stack_yellow_reserved_zone() { 2594 assert(_stack_guard_state != stack_guard_unused, "must be using guard pages."); 2595 assert(_stack_guard_state != stack_guard_enabled, "already enabled"); 2596 2597 // The base notation is from the stacks point of view, growing downward. 2598 // We need to adjust it to work correctly with guard_memory() 2599 address base = stack_red_zone_base(); 2600 2601 guarantee(base < stack_base(), "Error calculating stack yellow zone"); 2602 guarantee(base < os::current_stack_pointer(), "Error calculating stack yellow zone"); 2603 2604 if (os::guard_memory((char *) base, stack_yellow_reserved_zone_size())) { 2605 _stack_guard_state = stack_guard_enabled; 2606 } else { 2607 warning("Attempt to guard stack yellow zone failed."); 2608 } 2609 enable_register_stack_guard(); 2610 } 2611 2612 void JavaThread::disable_stack_yellow_reserved_zone() { 2613 assert(_stack_guard_state != stack_guard_unused, "must be using guard pages."); 2614 assert(_stack_guard_state != stack_guard_yellow_reserved_disabled, "already disabled"); 2615 2616 // Simply return if called for a thread that does not use guard pages. 2617 if (_stack_guard_state == stack_guard_unused) return; 2618 2619 // The base notation is from the stacks point of view, growing downward. 2620 // We need to adjust it to work correctly with guard_memory() 2621 address base = stack_red_zone_base(); 2622 2623 if (os::unguard_memory((char *)base, stack_yellow_reserved_zone_size())) { 2624 _stack_guard_state = stack_guard_yellow_reserved_disabled; 2625 } else { 2626 warning("Attempt to unguard stack yellow zone failed."); 2627 } 2628 disable_register_stack_guard(); 2629 } 2630 2631 void JavaThread::enable_stack_red_zone() { 2632 // The base notation is from the stacks point of view, growing downward. 2633 // We need to adjust it to work correctly with guard_memory() 2634 assert(_stack_guard_state != stack_guard_unused, "must be using guard pages."); 2635 address base = stack_red_zone_base() - stack_red_zone_size(); 2636 2637 guarantee(base < stack_base(), "Error calculating stack red zone"); 2638 guarantee(base < os::current_stack_pointer(), "Error calculating stack red zone"); 2639 2640 if (!os::guard_memory((char *) base, stack_red_zone_size())) { 2641 warning("Attempt to guard stack red zone failed."); 2642 } 2643 } 2644 2645 void JavaThread::disable_stack_red_zone() { 2646 // The base notation is from the stacks point of view, growing downward. 2647 // We need to adjust it to work correctly with guard_memory() 2648 assert(_stack_guard_state != stack_guard_unused, "must be using guard pages."); 2649 address base = stack_red_zone_base() - stack_red_zone_size(); 2650 if (!os::unguard_memory((char *)base, stack_red_zone_size())) { 2651 warning("Attempt to unguard stack red zone failed."); 2652 } 2653 } 2654 2655 void JavaThread::frames_do(void f(frame*, const RegisterMap* map)) { 2656 // ignore is there is no stack 2657 if (!has_last_Java_frame()) return; 2658 // traverse the stack frames. Starts from top frame. 2659 for (StackFrameStream fst(this); !fst.is_done(); fst.next()) { 2660 frame* fr = fst.current(); 2661 f(fr, fst.register_map()); 2662 } 2663 } 2664 2665 2666 #ifndef PRODUCT 2667 // Deoptimization 2668 // Function for testing deoptimization 2669 void JavaThread::deoptimize() { 2670 // BiasedLocking needs an updated RegisterMap for the revoke monitors pass 2671 StackFrameStream fst(this, UseBiasedLocking); 2672 bool deopt = false; // Dump stack only if a deopt actually happens. 2673 bool only_at = strlen(DeoptimizeOnlyAt) > 0; 2674 // Iterate over all frames in the thread and deoptimize 2675 for (; !fst.is_done(); fst.next()) { 2676 if (fst.current()->can_be_deoptimized()) { 2677 2678 if (only_at) { 2679 // Deoptimize only at particular bcis. DeoptimizeOnlyAt 2680 // consists of comma or carriage return separated numbers so 2681 // search for the current bci in that string. 2682 address pc = fst.current()->pc(); 2683 nmethod* nm = (nmethod*) fst.current()->cb(); 2684 ScopeDesc* sd = nm->scope_desc_at(pc); 2685 char buffer[8]; 2686 jio_snprintf(buffer, sizeof(buffer), "%d", sd->bci()); 2687 size_t len = strlen(buffer); 2688 const char * found = strstr(DeoptimizeOnlyAt, buffer); 2689 while (found != NULL) { 2690 if ((found[len] == ',' || found[len] == '\n' || found[len] == '\0') && 2691 (found == DeoptimizeOnlyAt || found[-1] == ',' || found[-1] == '\n')) { 2692 // Check that the bci found is bracketed by terminators. 2693 break; 2694 } 2695 found = strstr(found + 1, buffer); 2696 } 2697 if (!found) { 2698 continue; 2699 } 2700 } 2701 2702 if (DebugDeoptimization && !deopt) { 2703 deopt = true; // One-time only print before deopt 2704 tty->print_cr("[BEFORE Deoptimization]"); 2705 trace_frames(); 2706 trace_stack(); 2707 } 2708 Deoptimization::deoptimize(this, *fst.current(), fst.register_map()); 2709 } 2710 } 2711 2712 if (DebugDeoptimization && deopt) { 2713 tty->print_cr("[AFTER Deoptimization]"); 2714 trace_frames(); 2715 } 2716 } 2717 2718 2719 // Make zombies 2720 void JavaThread::make_zombies() { 2721 for (StackFrameStream fst(this); !fst.is_done(); fst.next()) { 2722 if (fst.current()->can_be_deoptimized()) { 2723 // it is a Java nmethod 2724 nmethod* nm = CodeCache::find_nmethod(fst.current()->pc()); 2725 nm->make_not_entrant(); 2726 } 2727 } 2728 } 2729 #endif // PRODUCT 2730 2731 2732 void JavaThread::deoptimized_wrt_marked_nmethods() { 2733 if (!has_last_Java_frame()) return; 2734 // BiasedLocking needs an updated RegisterMap for the revoke monitors pass 2735 StackFrameStream fst(this, UseBiasedLocking); 2736 for (; !fst.is_done(); fst.next()) { 2737 if (fst.current()->should_be_deoptimized()) { 2738 Deoptimization::deoptimize(this, *fst.current(), fst.register_map()); 2739 } 2740 } 2741 } 2742 2743 2744 // If the caller is a NamedThread, then remember, in the current scope, 2745 // the given JavaThread in its _processed_thread field. 2746 class RememberProcessedThread: public StackObj { 2747 NamedThread* _cur_thr; 2748 public: 2749 RememberProcessedThread(JavaThread* jthr) { 2750 Thread* thread = Thread::current(); 2751 if (thread->is_Named_thread()) { 2752 _cur_thr = (NamedThread *)thread; 2753 _cur_thr->set_processed_thread(jthr); 2754 } else { 2755 _cur_thr = NULL; 2756 } 2757 } 2758 2759 ~RememberProcessedThread() { 2760 if (_cur_thr) { 2761 _cur_thr->set_processed_thread(NULL); 2762 } 2763 } 2764 }; 2765 2766 void JavaThread::oops_do(OopClosure* f, CodeBlobClosure* cf) { 2767 // Verify that the deferred card marks have been flushed. 2768 assert(deferred_card_mark().is_empty(), "Should be empty during GC"); 2769 2770 // Traverse the GCHandles 2771 Thread::oops_do(f, cf); 2772 2773 assert((!has_last_Java_frame() && java_call_counter() == 0) || 2774 (has_last_Java_frame() && java_call_counter() > 0), "wrong java_sp info!"); 2775 2776 if (has_last_Java_frame()) { 2777 // Record JavaThread to GC thread 2778 RememberProcessedThread rpt(this); 2779 2780 // Traverse the privileged stack 2781 if (_privileged_stack_top != NULL) { 2782 _privileged_stack_top->oops_do(f); 2783 } 2784 2785 // traverse the registered growable array 2786 if (_array_for_gc != NULL) { 2787 for (int index = 0; index < _array_for_gc->length(); index++) { 2788 f->do_oop(_array_for_gc->adr_at(index)); 2789 } 2790 } 2791 2792 // Traverse the monitor chunks 2793 for (MonitorChunk* chunk = monitor_chunks(); chunk != NULL; chunk = chunk->next()) { 2794 chunk->oops_do(f); 2795 } 2796 2797 // Traverse the execution stack 2798 for (StackFrameStream fst(this); !fst.is_done(); fst.next()) { 2799 fst.current()->oops_do(f, cf, fst.register_map()); 2800 } 2801 } 2802 2803 // callee_target is never live across a gc point so NULL it here should 2804 // it still contain a methdOop. 2805 2806 set_callee_target(NULL); 2807 2808 assert(vframe_array_head() == NULL, "deopt in progress at a safepoint!"); 2809 // If we have deferred set_locals there might be oops waiting to be 2810 // written 2811 GrowableArray<jvmtiDeferredLocalVariableSet*>* list = deferred_locals(); 2812 if (list != NULL) { 2813 for (int i = 0; i < list->length(); i++) { 2814 list->at(i)->oops_do(f); 2815 } 2816 } 2817 2818 // Traverse instance variables at the end since the GC may be moving things 2819 // around using this function 2820 f->do_oop((oop*) &_threadObj); 2821 f->do_oop((oop*) &_vm_result); 2822 f->do_oop((oop*) &_exception_oop); 2823 f->do_oop((oop*) &_pending_async_exception); 2824 2825 if (jvmti_thread_state() != NULL) { 2826 jvmti_thread_state()->oops_do(f); 2827 } 2828 } 2829 2830 void JavaThread::nmethods_do(CodeBlobClosure* cf) { 2831 assert((!has_last_Java_frame() && java_call_counter() == 0) || 2832 (has_last_Java_frame() && java_call_counter() > 0), "wrong java_sp info!"); 2833 2834 if (has_last_Java_frame()) { 2835 // Traverse the execution stack 2836 for (StackFrameStream fst(this); !fst.is_done(); fst.next()) { 2837 fst.current()->nmethods_do(cf); 2838 } 2839 } 2840 } 2841 2842 void JavaThread::metadata_do(void f(Metadata*)) { 2843 if (has_last_Java_frame()) { 2844 // Traverse the execution stack to call f() on the methods in the stack 2845 for (StackFrameStream fst(this); !fst.is_done(); fst.next()) { 2846 fst.current()->metadata_do(f); 2847 } 2848 } else if (is_Compiler_thread()) { 2849 // need to walk ciMetadata in current compile tasks to keep alive. 2850 CompilerThread* ct = (CompilerThread*)this; 2851 if (ct->env() != NULL) { 2852 ct->env()->metadata_do(f); 2853 } 2854 CompileTask* task = ct->task(); 2855 if (task != NULL) { 2856 task->metadata_do(f); 2857 } 2858 } 2859 } 2860 2861 // Printing 2862 const char* _get_thread_state_name(JavaThreadState _thread_state) { 2863 switch (_thread_state) { 2864 case _thread_uninitialized: return "_thread_uninitialized"; 2865 case _thread_new: return "_thread_new"; 2866 case _thread_new_trans: return "_thread_new_trans"; 2867 case _thread_in_native: return "_thread_in_native"; 2868 case _thread_in_native_trans: return "_thread_in_native_trans"; 2869 case _thread_in_vm: return "_thread_in_vm"; 2870 case _thread_in_vm_trans: return "_thread_in_vm_trans"; 2871 case _thread_in_Java: return "_thread_in_Java"; 2872 case _thread_in_Java_trans: return "_thread_in_Java_trans"; 2873 case _thread_blocked: return "_thread_blocked"; 2874 case _thread_blocked_trans: return "_thread_blocked_trans"; 2875 default: return "unknown thread state"; 2876 } 2877 } 2878 2879 #ifndef PRODUCT 2880 void JavaThread::print_thread_state_on(outputStream *st) const { 2881 st->print_cr(" JavaThread state: %s", _get_thread_state_name(_thread_state)); 2882 }; 2883 void JavaThread::print_thread_state() const { 2884 print_thread_state_on(tty); 2885 } 2886 #endif // PRODUCT 2887 2888 // Called by Threads::print() for VM_PrintThreads operation 2889 void JavaThread::print_on(outputStream *st, bool print_extended_info) const { 2890 st->print_raw("\""); 2891 st->print_raw(get_thread_name()); 2892 st->print_raw("\" "); 2893 oop thread_oop = threadObj(); 2894 if (thread_oop != NULL) { 2895 st->print("#" INT64_FORMAT " ", (int64_t)java_lang_Thread::thread_id(thread_oop)); 2896 if (java_lang_Thread::is_daemon(thread_oop)) st->print("daemon "); 2897 st->print("prio=%d ", java_lang_Thread::priority(thread_oop)); 2898 } 2899 Thread::print_on(st, print_extended_info); 2900 // print guess for valid stack memory region (assume 4K pages); helps lock debugging 2901 st->print_cr("[" INTPTR_FORMAT "]", (intptr_t)last_Java_sp() & ~right_n_bits(12)); 2902 if (thread_oop != NULL) { 2903 st->print_cr(" java.lang.Thread.State: %s", java_lang_Thread::thread_status_name(thread_oop)); 2904 } 2905 #ifndef PRODUCT 2906 print_thread_state_on(st); 2907 _safepoint_state->print_on(st); 2908 #endif // PRODUCT 2909 if (is_Compiler_thread()) { 2910 CompileTask *task = ((CompilerThread*)this)->task(); 2911 if (task != NULL) { 2912 st->print(" Compiling: "); 2913 task->print(st, NULL, true, false); 2914 } else { 2915 st->print(" No compile task"); 2916 } 2917 st->cr(); 2918 } 2919 } 2920 2921 void JavaThread::print_name_on_error(outputStream* st, char *buf, int buflen) const { 2922 st->print("%s", get_thread_name_string(buf, buflen)); 2923 } 2924 2925 // Called by fatal error handler. The difference between this and 2926 // JavaThread::print() is that we can't grab lock or allocate memory. 2927 void JavaThread::print_on_error(outputStream* st, char *buf, int buflen) const { 2928 st->print("JavaThread \"%s\"", get_thread_name_string(buf, buflen)); 2929 oop thread_obj = threadObj(); 2930 if (thread_obj != NULL) { 2931 if (java_lang_Thread::is_daemon(thread_obj)) st->print(" daemon"); 2932 } 2933 st->print(" ["); 2934 st->print("%s", _get_thread_state_name(_thread_state)); 2935 if (osthread()) { 2936 st->print(", id=%d", osthread()->thread_id()); 2937 } 2938 st->print(", stack(" PTR_FORMAT "," PTR_FORMAT ")", 2939 p2i(stack_end()), p2i(stack_base())); 2940 st->print("]"); 2941 2942 ThreadsSMRSupport::print_info_on(this, st); 2943 return; 2944 } 2945 2946 // Verification 2947 2948 static void frame_verify(frame* f, const RegisterMap *map) { f->verify(map); } 2949 2950 void JavaThread::verify() { 2951 // Verify oops in the thread. 2952 oops_do(&VerifyOopClosure::verify_oop, NULL); 2953 2954 // Verify the stack frames. 2955 frames_do(frame_verify); 2956 } 2957 2958 // CR 6300358 (sub-CR 2137150) 2959 // Most callers of this method assume that it can't return NULL but a 2960 // thread may not have a name whilst it is in the process of attaching to 2961 // the VM - see CR 6412693, and there are places where a JavaThread can be 2962 // seen prior to having it's threadObj set (eg JNI attaching threads and 2963 // if vm exit occurs during initialization). These cases can all be accounted 2964 // for such that this method never returns NULL. 2965 const char* JavaThread::get_thread_name() const { 2966 #ifdef ASSERT 2967 // early safepoints can hit while current thread does not yet have TLS 2968 if (!SafepointSynchronize::is_at_safepoint()) { 2969 Thread *cur = Thread::current(); 2970 if (!(cur->is_Java_thread() && cur == this)) { 2971 // Current JavaThreads are allowed to get their own name without 2972 // the Threads_lock. 2973 assert_locked_or_safepoint(Threads_lock); 2974 } 2975 } 2976 #endif // ASSERT 2977 return get_thread_name_string(); 2978 } 2979 2980 // Returns a non-NULL representation of this thread's name, or a suitable 2981 // descriptive string if there is no set name 2982 const char* JavaThread::get_thread_name_string(char* buf, int buflen) const { 2983 const char* name_str; 2984 oop thread_obj = threadObj(); 2985 if (thread_obj != NULL) { 2986 oop name = java_lang_Thread::name(thread_obj); 2987 if (name != NULL) { 2988 if (buf == NULL) { 2989 name_str = java_lang_String::as_utf8_string(name); 2990 } else { 2991 name_str = java_lang_String::as_utf8_string(name, buf, buflen); 2992 } 2993 } else if (is_attaching_via_jni()) { // workaround for 6412693 - see 6404306 2994 name_str = "<no-name - thread is attaching>"; 2995 } else { 2996 name_str = Thread::name(); 2997 } 2998 } else { 2999 name_str = Thread::name(); 3000 } 3001 assert(name_str != NULL, "unexpected NULL thread name"); 3002 return name_str; 3003 } 3004 3005 3006 const char* JavaThread::get_threadgroup_name() const { 3007 debug_only(if (JavaThread::current() != this) assert_locked_or_safepoint(Threads_lock);) 3008 oop thread_obj = threadObj(); 3009 if (thread_obj != NULL) { 3010 oop thread_group = java_lang_Thread::threadGroup(thread_obj); 3011 if (thread_group != NULL) { 3012 // ThreadGroup.name can be null 3013 return java_lang_ThreadGroup::name(thread_group); 3014 } 3015 } 3016 return NULL; 3017 } 3018 3019 const char* JavaThread::get_parent_name() const { 3020 debug_only(if (JavaThread::current() != this) assert_locked_or_safepoint(Threads_lock);) 3021 oop thread_obj = threadObj(); 3022 if (thread_obj != NULL) { 3023 oop thread_group = java_lang_Thread::threadGroup(thread_obj); 3024 if (thread_group != NULL) { 3025 oop parent = java_lang_ThreadGroup::parent(thread_group); 3026 if (parent != NULL) { 3027 // ThreadGroup.name can be null 3028 return java_lang_ThreadGroup::name(parent); 3029 } 3030 } 3031 } 3032 return NULL; 3033 } 3034 3035 ThreadPriority JavaThread::java_priority() const { 3036 oop thr_oop = threadObj(); 3037 if (thr_oop == NULL) return NormPriority; // Bootstrapping 3038 ThreadPriority priority = java_lang_Thread::priority(thr_oop); 3039 assert(MinPriority <= priority && priority <= MaxPriority, "sanity check"); 3040 return priority; 3041 } 3042 3043 void JavaThread::prepare(jobject jni_thread, ThreadPriority prio) { 3044 3045 assert(Threads_lock->owner() == Thread::current(), "must have threads lock"); 3046 // Link Java Thread object <-> C++ Thread 3047 3048 // Get the C++ thread object (an oop) from the JNI handle (a jthread) 3049 // and put it into a new Handle. The Handle "thread_oop" can then 3050 // be used to pass the C++ thread object to other methods. 3051 3052 // Set the Java level thread object (jthread) field of the 3053 // new thread (a JavaThread *) to C++ thread object using the 3054 // "thread_oop" handle. 3055 3056 // Set the thread field (a JavaThread *) of the 3057 // oop representing the java_lang_Thread to the new thread (a JavaThread *). 3058 3059 Handle thread_oop(Thread::current(), 3060 JNIHandles::resolve_non_null(jni_thread)); 3061 assert(InstanceKlass::cast(thread_oop->klass())->is_linked(), 3062 "must be initialized"); 3063 set_threadObj(thread_oop()); 3064 java_lang_Thread::set_thread(thread_oop(), this); 3065 3066 if (prio == NoPriority) { 3067 prio = java_lang_Thread::priority(thread_oop()); 3068 assert(prio != NoPriority, "A valid priority should be present"); 3069 } 3070 3071 // Push the Java priority down to the native thread; needs Threads_lock 3072 Thread::set_priority(this, prio); 3073 3074 // Add the new thread to the Threads list and set it in motion. 3075 // We must have threads lock in order to call Threads::add. 3076 // It is crucial that we do not block before the thread is 3077 // added to the Threads list for if a GC happens, then the java_thread oop 3078 // will not be visited by GC. 3079 Threads::add(this); 3080 } 3081 3082 oop JavaThread::current_park_blocker() { 3083 // Support for JSR-166 locks 3084 oop thread_oop = threadObj(); 3085 if (thread_oop != NULL && 3086 JDK_Version::current().supports_thread_park_blocker()) { 3087 return java_lang_Thread::park_blocker(thread_oop); 3088 } 3089 return NULL; 3090 } 3091 3092 3093 void JavaThread::print_stack_on(outputStream* st) { 3094 if (!has_last_Java_frame()) return; 3095 ResourceMark rm; 3096 HandleMark hm; 3097 3098 RegisterMap reg_map(this); 3099 vframe* start_vf = last_java_vframe(®_map); 3100 int count = 0; 3101 for (vframe* f = start_vf; f != NULL; f = f->sender()) { 3102 if (f->is_java_frame()) { 3103 javaVFrame* jvf = javaVFrame::cast(f); 3104 java_lang_Throwable::print_stack_element(st, jvf->method(), jvf->bci()); 3105 3106 // Print out lock information 3107 if (JavaMonitorsInStackTrace) { 3108 jvf->print_lock_info_on(st, count); 3109 } 3110 } else { 3111 // Ignore non-Java frames 3112 } 3113 3114 // Bail-out case for too deep stacks if MaxJavaStackTraceDepth > 0 3115 count++; 3116 if (MaxJavaStackTraceDepth > 0 && MaxJavaStackTraceDepth == count) return; 3117 } 3118 } 3119 3120 3121 // JVMTI PopFrame support 3122 void JavaThread::popframe_preserve_args(ByteSize size_in_bytes, void* start) { 3123 assert(_popframe_preserved_args == NULL, "should not wipe out old PopFrame preserved arguments"); 3124 if (in_bytes(size_in_bytes) != 0) { 3125 _popframe_preserved_args = NEW_C_HEAP_ARRAY(char, in_bytes(size_in_bytes), mtThread); 3126 _popframe_preserved_args_size = in_bytes(size_in_bytes); 3127 Copy::conjoint_jbytes(start, _popframe_preserved_args, _popframe_preserved_args_size); 3128 } 3129 } 3130 3131 void* JavaThread::popframe_preserved_args() { 3132 return _popframe_preserved_args; 3133 } 3134 3135 ByteSize JavaThread::popframe_preserved_args_size() { 3136 return in_ByteSize(_popframe_preserved_args_size); 3137 } 3138 3139 WordSize JavaThread::popframe_preserved_args_size_in_words() { 3140 int sz = in_bytes(popframe_preserved_args_size()); 3141 assert(sz % wordSize == 0, "argument size must be multiple of wordSize"); 3142 return in_WordSize(sz / wordSize); 3143 } 3144 3145 void JavaThread::popframe_free_preserved_args() { 3146 assert(_popframe_preserved_args != NULL, "should not free PopFrame preserved arguments twice"); 3147 FREE_C_HEAP_ARRAY(char, (char*) _popframe_preserved_args); 3148 _popframe_preserved_args = NULL; 3149 _popframe_preserved_args_size = 0; 3150 } 3151 3152 #ifndef PRODUCT 3153 3154 void JavaThread::trace_frames() { 3155 tty->print_cr("[Describe stack]"); 3156 int frame_no = 1; 3157 for (StackFrameStream fst(this); !fst.is_done(); fst.next()) { 3158 tty->print(" %d. ", frame_no++); 3159 fst.current()->print_value_on(tty, this); 3160 tty->cr(); 3161 } 3162 } 3163 3164 class PrintAndVerifyOopClosure: public OopClosure { 3165 protected: 3166 template <class T> inline void do_oop_work(T* p) { 3167 oop obj = RawAccess<>::oop_load(p); 3168 if (obj == NULL) return; 3169 tty->print(INTPTR_FORMAT ": ", p2i(p)); 3170 if (oopDesc::is_oop_or_null(obj)) { 3171 if (obj->is_objArray()) { 3172 tty->print_cr("valid objArray: " INTPTR_FORMAT, p2i(obj)); 3173 } else { 3174 obj->print(); 3175 } 3176 } else { 3177 tty->print_cr("invalid oop: " INTPTR_FORMAT, p2i(obj)); 3178 } 3179 tty->cr(); 3180 } 3181 public: 3182 virtual void do_oop(oop* p) { do_oop_work(p); } 3183 virtual void do_oop(narrowOop* p) { do_oop_work(p); } 3184 }; 3185 3186 3187 static void oops_print(frame* f, const RegisterMap *map) { 3188 PrintAndVerifyOopClosure print; 3189 f->print_value(); 3190 f->oops_do(&print, NULL, (RegisterMap*)map); 3191 } 3192 3193 // Print our all the locations that contain oops and whether they are 3194 // valid or not. This useful when trying to find the oldest frame 3195 // where an oop has gone bad since the frame walk is from youngest to 3196 // oldest. 3197 void JavaThread::trace_oops() { 3198 tty->print_cr("[Trace oops]"); 3199 frames_do(oops_print); 3200 } 3201 3202 3203 #ifdef ASSERT 3204 // Print or validate the layout of stack frames 3205 void JavaThread::print_frame_layout(int depth, bool validate_only) { 3206 ResourceMark rm; 3207 PRESERVE_EXCEPTION_MARK; 3208 FrameValues values; 3209 int frame_no = 0; 3210 for (StackFrameStream fst(this, false); !fst.is_done(); fst.next()) { 3211 fst.current()->describe(values, ++frame_no); 3212 if (depth == frame_no) break; 3213 } 3214 if (validate_only) { 3215 values.validate(); 3216 } else { 3217 tty->print_cr("[Describe stack layout]"); 3218 values.print(this); 3219 } 3220 } 3221 #endif 3222 3223 void JavaThread::trace_stack_from(vframe* start_vf) { 3224 ResourceMark rm; 3225 int vframe_no = 1; 3226 for (vframe* f = start_vf; f; f = f->sender()) { 3227 if (f->is_java_frame()) { 3228 javaVFrame::cast(f)->print_activation(vframe_no++); 3229 } else { 3230 f->print(); 3231 } 3232 if (vframe_no > StackPrintLimit) { 3233 tty->print_cr("...<more frames>..."); 3234 return; 3235 } 3236 } 3237 } 3238 3239 3240 void JavaThread::trace_stack() { 3241 if (!has_last_Java_frame()) return; 3242 ResourceMark rm; 3243 HandleMark hm; 3244 RegisterMap reg_map(this); 3245 trace_stack_from(last_java_vframe(®_map)); 3246 } 3247 3248 3249 #endif // PRODUCT 3250 3251 3252 javaVFrame* JavaThread::last_java_vframe(RegisterMap *reg_map) { 3253 assert(reg_map != NULL, "a map must be given"); 3254 frame f = last_frame(); 3255 for (vframe* vf = vframe::new_vframe(&f, reg_map, this); vf; vf = vf->sender()) { 3256 if (vf->is_java_frame()) return javaVFrame::cast(vf); 3257 } 3258 return NULL; 3259 } 3260 3261 3262 Klass* JavaThread::security_get_caller_class(int depth) { 3263 vframeStream vfst(this); 3264 vfst.security_get_caller_frame(depth); 3265 if (!vfst.at_end()) { 3266 return vfst.method()->method_holder(); 3267 } 3268 return NULL; 3269 } 3270 3271 static void compiler_thread_entry(JavaThread* thread, TRAPS) { 3272 assert(thread->is_Compiler_thread(), "must be compiler thread"); 3273 CompileBroker::compiler_thread_loop(); 3274 } 3275 3276 static void sweeper_thread_entry(JavaThread* thread, TRAPS) { 3277 NMethodSweeper::sweeper_loop(); 3278 } 3279 3280 // Create a CompilerThread 3281 CompilerThread::CompilerThread(CompileQueue* queue, 3282 CompilerCounters* counters) 3283 : JavaThread(&compiler_thread_entry) { 3284 _env = NULL; 3285 _log = NULL; 3286 _task = NULL; 3287 _queue = queue; 3288 _counters = counters; 3289 _buffer_blob = NULL; 3290 _compiler = NULL; 3291 3292 // Compiler uses resource area for compilation, let's bias it to mtCompiler 3293 resource_area()->bias_to(mtCompiler); 3294 3295 #ifndef PRODUCT 3296 _ideal_graph_printer = NULL; 3297 #endif 3298 } 3299 3300 CompilerThread::~CompilerThread() { 3301 // Free buffer blob, if allocated 3302 if (get_buffer_blob() != NULL) { 3303 MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag); 3304 CodeCache::free(get_buffer_blob()); 3305 } 3306 // Delete objects which were allocated on heap. 3307 delete _counters; 3308 } 3309 3310 bool CompilerThread::can_call_java() const { 3311 return _compiler != NULL && _compiler->is_jvmci(); 3312 } 3313 3314 // Create sweeper thread 3315 CodeCacheSweeperThread::CodeCacheSweeperThread() 3316 : JavaThread(&sweeper_thread_entry) { 3317 _scanned_compiled_method = NULL; 3318 } 3319 3320 void CodeCacheSweeperThread::oops_do(OopClosure* f, CodeBlobClosure* cf) { 3321 JavaThread::oops_do(f, cf); 3322 if (_scanned_compiled_method != NULL && cf != NULL) { 3323 // Safepoints can occur when the sweeper is scanning an nmethod so 3324 // process it here to make sure it isn't unloaded in the middle of 3325 // a scan. 3326 cf->do_code_blob(_scanned_compiled_method); 3327 } 3328 } 3329 3330 void CodeCacheSweeperThread::nmethods_do(CodeBlobClosure* cf) { 3331 JavaThread::nmethods_do(cf); 3332 if (_scanned_compiled_method != NULL && cf != NULL) { 3333 // Safepoints can occur when the sweeper is scanning an nmethod so 3334 // process it here to make sure it isn't unloaded in the middle of 3335 // a scan. 3336 cf->do_code_blob(_scanned_compiled_method); 3337 } 3338 } 3339 3340 3341 // ======= Threads ======== 3342 3343 // The Threads class links together all active threads, and provides 3344 // operations over all threads. It is protected by the Threads_lock, 3345 // which is also used in other global contexts like safepointing. 3346 // ThreadsListHandles are used to safely perform operations on one 3347 // or more threads without the risk of the thread exiting during the 3348 // operation. 3349 // 3350 // Note: The Threads_lock is currently more widely used than we 3351 // would like. We are actively migrating Threads_lock uses to other 3352 // mechanisms in order to reduce Threads_lock contention. 3353 3354 JavaThread* Threads::_thread_list = NULL; 3355 int Threads::_number_of_threads = 0; 3356 int Threads::_number_of_non_daemon_threads = 0; 3357 int Threads::_return_code = 0; 3358 int Threads::_thread_claim_parity = 0; 3359 size_t JavaThread::_stack_size_at_create = 0; 3360 3361 #ifdef ASSERT 3362 bool Threads::_vm_complete = false; 3363 #endif 3364 3365 static inline void *prefetch_and_load_ptr(void **addr, intx prefetch_interval) { 3366 Prefetch::read((void*)addr, prefetch_interval); 3367 return *addr; 3368 } 3369 3370 // Possibly the ugliest for loop the world has seen. C++ does not allow 3371 // multiple types in the declaration section of the for loop. In this case 3372 // we are only dealing with pointers and hence can cast them. It looks ugly 3373 // but macros are ugly and therefore it's fine to make things absurdly ugly. 3374 #define DO_JAVA_THREADS(LIST, X) \ 3375 for (JavaThread *MACRO_scan_interval = (JavaThread*)(uintptr_t)PrefetchScanIntervalInBytes, \ 3376 *MACRO_list = (JavaThread*)(LIST), \ 3377 **MACRO_end = ((JavaThread**)((ThreadsList*)MACRO_list)->threads()) + ((ThreadsList*)MACRO_list)->length(), \ 3378 **MACRO_current_p = (JavaThread**)((ThreadsList*)MACRO_list)->threads(), \ 3379 *X = (JavaThread*)prefetch_and_load_ptr((void**)MACRO_current_p, (intx)MACRO_scan_interval); \ 3380 MACRO_current_p != MACRO_end; \ 3381 MACRO_current_p++, \ 3382 X = (JavaThread*)prefetch_and_load_ptr((void**)MACRO_current_p, (intx)MACRO_scan_interval)) 3383 3384 // All JavaThreads 3385 #define ALL_JAVA_THREADS(X) DO_JAVA_THREADS(ThreadsSMRSupport::get_java_thread_list(), X) 3386 3387 // All non-JavaThreads (i.e., every non-JavaThread in the system). 3388 void Threads::non_java_threads_do(ThreadClosure* tc) { 3389 // Someday we could have a table or list of all non-JavaThreads. 3390 // For now, just manually iterate through them. 3391 tc->do_thread(VMThread::vm_thread()); 3392 if (Universe::heap() != NULL) { 3393 Universe::heap()->gc_threads_do(tc); 3394 } 3395 WatcherThread *wt = WatcherThread::watcher_thread(); 3396 // Strictly speaking, the following NULL check isn't sufficient to make sure 3397 // the data for WatcherThread is still valid upon being examined. However, 3398 // considering that WatchThread terminates when the VM is on the way to 3399 // exit at safepoint, the chance of the above is extremely small. The right 3400 // way to prevent termination of WatcherThread would be to acquire 3401 // Terminator_lock, but we can't do that without violating the lock rank 3402 // checking in some cases. 3403 if (wt != NULL) { 3404 tc->do_thread(wt); 3405 } 3406 3407 #if INCLUDE_JFR 3408 Thread* sampler_thread = Jfr::sampler_thread(); 3409 if (sampler_thread != NULL) { 3410 tc->do_thread(sampler_thread); 3411 } 3412 3413 #endif 3414 3415 // If CompilerThreads ever become non-JavaThreads, add them here 3416 } 3417 3418 // All JavaThreads 3419 void Threads::java_threads_do(ThreadClosure* tc) { 3420 assert_locked_or_safepoint(Threads_lock); 3421 // ALL_JAVA_THREADS iterates through all JavaThreads. 3422 ALL_JAVA_THREADS(p) { 3423 tc->do_thread(p); 3424 } 3425 } 3426 3427 void Threads::java_threads_and_vm_thread_do(ThreadClosure* tc) { 3428 assert_locked_or_safepoint(Threads_lock); 3429 java_threads_do(tc); 3430 tc->do_thread(VMThread::vm_thread()); 3431 } 3432 3433 // All JavaThreads + all non-JavaThreads (i.e., every thread in the system). 3434 void Threads::threads_do(ThreadClosure* tc) { 3435 assert_locked_or_safepoint(Threads_lock); 3436 java_threads_do(tc); 3437 non_java_threads_do(tc); 3438 } 3439 3440 void Threads::possibly_parallel_threads_do(bool is_par, ThreadClosure* tc) { 3441 int cp = Threads::thread_claim_parity(); 3442 ALL_JAVA_THREADS(p) { 3443 if (p->claim_oops_do(is_par, cp)) { 3444 tc->do_thread(p); 3445 } 3446 } 3447 VMThread* vmt = VMThread::vm_thread(); 3448 if (vmt->claim_oops_do(is_par, cp)) { 3449 tc->do_thread(vmt); 3450 } 3451 } 3452 3453 // The system initialization in the library has three phases. 3454 // 3455 // Phase 1: java.lang.System class initialization 3456 // java.lang.System is a primordial class loaded and initialized 3457 // by the VM early during startup. java.lang.System.<clinit> 3458 // only does registerNatives and keeps the rest of the class 3459 // initialization work later until thread initialization completes. 3460 // 3461 // System.initPhase1 initializes the system properties, the static 3462 // fields in, out, and err. Set up java signal handlers, OS-specific 3463 // system settings, and thread group of the main thread. 3464 static void call_initPhase1(TRAPS) { 3465 Klass* klass = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_System(), true, CHECK); 3466 JavaValue result(T_VOID); 3467 JavaCalls::call_static(&result, klass, vmSymbols::initPhase1_name(), 3468 vmSymbols::void_method_signature(), CHECK); 3469 } 3470 3471 // Phase 2. Module system initialization 3472 // This will initialize the module system. Only java.base classes 3473 // can be loaded until phase 2 completes. 3474 // 3475 // Call System.initPhase2 after the compiler initialization and jsr292 3476 // classes get initialized because module initialization runs a lot of java 3477 // code, that for performance reasons, should be compiled. Also, this will 3478 // enable the startup code to use lambda and other language features in this 3479 // phase and onward. 3480 // 3481 // After phase 2, The VM will begin search classes from -Xbootclasspath/a. 3482 static void call_initPhase2(TRAPS) { 3483 TraceTime timer("Initialize module system", TRACETIME_LOG(Info, startuptime)); 3484 3485 Klass* klass = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_System(), true, CHECK); 3486 3487 JavaValue result(T_INT); 3488 JavaCallArguments args; 3489 args.push_int(DisplayVMOutputToStderr); 3490 args.push_int(log_is_enabled(Debug, init)); // print stack trace if exception thrown 3491 JavaCalls::call_static(&result, klass, vmSymbols::initPhase2_name(), 3492 vmSymbols::boolean_boolean_int_signature(), &args, CHECK); 3493 if (result.get_jint() != JNI_OK) { 3494 vm_exit_during_initialization(); // no message or exception 3495 } 3496 3497 universe_post_module_init(); 3498 } 3499 3500 // Phase 3. final setup - set security manager, system class loader and TCCL 3501 // 3502 // This will instantiate and set the security manager, set the system class 3503 // loader as well as the thread context class loader. The security manager 3504 // and system class loader may be a custom class loaded from -Xbootclasspath/a, 3505 // other modules or the application's classpath. 3506 static void call_initPhase3(TRAPS) { 3507 Klass* klass = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_System(), true, CHECK); 3508 JavaValue result(T_VOID); 3509 JavaCalls::call_static(&result, klass, vmSymbols::initPhase3_name(), 3510 vmSymbols::void_method_signature(), CHECK); 3511 } 3512 3513 void Threads::initialize_java_lang_classes(JavaThread* main_thread, TRAPS) { 3514 TraceTime timer("Initialize java.lang classes", TRACETIME_LOG(Info, startuptime)); 3515 3516 if (EagerXrunInit && Arguments::init_libraries_at_startup()) { 3517 create_vm_init_libraries(); 3518 } 3519 3520 initialize_class(vmSymbols::java_lang_String(), CHECK); 3521 3522 // Inject CompactStrings value after the static initializers for String ran. 3523 java_lang_String::set_compact_strings(CompactStrings); 3524 3525 // Initialize java_lang.System (needed before creating the thread) 3526 initialize_class(vmSymbols::java_lang_System(), CHECK); 3527 // The VM creates & returns objects of this class. Make sure it's initialized. 3528 initialize_class(vmSymbols::java_lang_Class(), CHECK); 3529 initialize_class(vmSymbols::java_lang_ThreadGroup(), CHECK); 3530 Handle thread_group = create_initial_thread_group(CHECK); 3531 Universe::set_main_thread_group(thread_group()); 3532 initialize_class(vmSymbols::java_lang_Thread(), CHECK); 3533 oop thread_object = create_initial_thread(thread_group, main_thread, CHECK); 3534 main_thread->set_threadObj(thread_object); 3535 // Set thread status to running since main thread has 3536 // been started and running. 3537 java_lang_Thread::set_thread_status(thread_object, 3538 java_lang_Thread::RUNNABLE); 3539 3540 // The VM creates objects of this class. 3541 initialize_class(vmSymbols::java_lang_Module(), CHECK); 3542 3543 // The VM preresolves methods to these classes. Make sure that they get initialized 3544 initialize_class(vmSymbols::java_lang_reflect_Method(), CHECK); 3545 initialize_class(vmSymbols::java_lang_ref_Finalizer(), CHECK); 3546 3547 // Phase 1 of the system initialization in the library, java.lang.System class initialization 3548 call_initPhase1(CHECK); 3549 3550 // get the Java runtime name after java.lang.System is initialized 3551 JDK_Version::set_runtime_name(get_java_runtime_name(THREAD)); 3552 JDK_Version::set_runtime_version(get_java_runtime_version(THREAD)); 3553 3554 // an instance of OutOfMemory exception has been allocated earlier 3555 initialize_class(vmSymbols::java_lang_OutOfMemoryError(), CHECK); 3556 initialize_class(vmSymbols::java_lang_NullPointerException(), CHECK); 3557 initialize_class(vmSymbols::java_lang_ClassCastException(), CHECK); 3558 initialize_class(vmSymbols::java_lang_ArrayStoreException(), CHECK); 3559 initialize_class(vmSymbols::java_lang_ArithmeticException(), CHECK); 3560 initialize_class(vmSymbols::java_lang_StackOverflowError(), CHECK); 3561 initialize_class(vmSymbols::java_lang_IllegalMonitorStateException(), CHECK); 3562 initialize_class(vmSymbols::java_lang_IllegalArgumentException(), CHECK); 3563 } 3564 3565 void Threads::initialize_jsr292_core_classes(TRAPS) { 3566 TraceTime timer("Initialize java.lang.invoke classes", TRACETIME_LOG(Info, startuptime)); 3567 3568 initialize_class(vmSymbols::java_lang_invoke_MethodHandle(), CHECK); 3569 initialize_class(vmSymbols::java_lang_invoke_ResolvedMethodName(), CHECK); 3570 initialize_class(vmSymbols::java_lang_invoke_MemberName(), CHECK); 3571 initialize_class(vmSymbols::java_lang_invoke_MethodHandleNatives(), CHECK); 3572 } 3573 3574 jint Threads::create_vm(JavaVMInitArgs* args, bool* canTryAgain) { 3575 extern void JDK_Version_init(); 3576 3577 // Preinitialize version info. 3578 VM_Version::early_initialize(); 3579 3580 // Check version 3581 if (!is_supported_jni_version(args->version)) return JNI_EVERSION; 3582 3583 // Initialize library-based TLS 3584 ThreadLocalStorage::init(); 3585 3586 // Initialize the output stream module 3587 ostream_init(); 3588 3589 // Process java launcher properties. 3590 Arguments::process_sun_java_launcher_properties(args); 3591 3592 // Initialize the os module 3593 os::init(); 3594 3595 // Record VM creation timing statistics 3596 TraceVmCreationTime create_vm_timer; 3597 create_vm_timer.start(); 3598 3599 // Initialize system properties. 3600 Arguments::init_system_properties(); 3601 3602 // So that JDK version can be used as a discriminator when parsing arguments 3603 JDK_Version_init(); 3604 3605 // Update/Initialize System properties after JDK version number is known 3606 Arguments::init_version_specific_system_properties(); 3607 3608 // Make sure to initialize log configuration *before* parsing arguments 3609 LogConfiguration::initialize(create_vm_timer.begin_time()); 3610 3611 // Parse arguments 3612 // Note: this internally calls os::init_container_support() 3613 jint parse_result = Arguments::parse(args); 3614 if (parse_result != JNI_OK) return parse_result; 3615 3616 os::init_before_ergo(); 3617 3618 jint ergo_result = Arguments::apply_ergo(); 3619 if (ergo_result != JNI_OK) return ergo_result; 3620 3621 // Final check of all ranges after ergonomics which may change values. 3622 if (!JVMFlagRangeList::check_ranges()) { 3623 return JNI_EINVAL; 3624 } 3625 3626 // Final check of all 'AfterErgo' constraints after ergonomics which may change values. 3627 bool constraint_result = JVMFlagConstraintList::check_constraints(JVMFlagConstraint::AfterErgo); 3628 if (!constraint_result) { 3629 return JNI_EINVAL; 3630 } 3631 3632 JVMFlagWriteableList::mark_startup(); 3633 3634 if (PauseAtStartup) { 3635 os::pause(); 3636 } 3637 3638 HOTSPOT_VM_INIT_BEGIN(); 3639 3640 // Timing (must come after argument parsing) 3641 TraceTime timer("Create VM", TRACETIME_LOG(Info, startuptime)); 3642 3643 #ifdef CAN_SHOW_REGISTERS_ON_ASSERT 3644 // Initialize assert poison page mechanism. 3645 if (ShowRegistersOnAssert) { 3646 initialize_assert_poison(); 3647 } 3648 #endif // CAN_SHOW_REGISTERS_ON_ASSERT 3649 3650 // Initialize the os module after parsing the args 3651 jint os_init_2_result = os::init_2(); 3652 if (os_init_2_result != JNI_OK) return os_init_2_result; 3653 3654 SafepointMechanism::initialize(); 3655 3656 jint adjust_after_os_result = Arguments::adjust_after_os(); 3657 if (adjust_after_os_result != JNI_OK) return adjust_after_os_result; 3658 3659 // Initialize output stream logging 3660 ostream_init_log(); 3661 3662 // Convert -Xrun to -agentlib: if there is no JVM_OnLoad 3663 // Must be before create_vm_init_agents() 3664 if (Arguments::init_libraries_at_startup()) { 3665 convert_vm_init_libraries_to_agents(); 3666 } 3667 3668 // Launch -agentlib/-agentpath and converted -Xrun agents 3669 if (Arguments::init_agents_at_startup()) { 3670 create_vm_init_agents(); 3671 } 3672 3673 // Initialize Threads state 3674 _thread_list = NULL; 3675 _number_of_threads = 0; 3676 _number_of_non_daemon_threads = 0; 3677 3678 // Initialize global data structures and create system classes in heap 3679 vm_init_globals(); 3680 3681 #if INCLUDE_JVMCI 3682 if (JVMCICounterSize > 0) { 3683 JavaThread::_jvmci_old_thread_counters = NEW_C_HEAP_ARRAY(jlong, JVMCICounterSize, mtInternal); 3684 memset(JavaThread::_jvmci_old_thread_counters, 0, sizeof(jlong) * JVMCICounterSize); 3685 } else { 3686 JavaThread::_jvmci_old_thread_counters = NULL; 3687 } 3688 #endif // INCLUDE_JVMCI 3689 3690 // Attach the main thread to this os thread 3691 JavaThread* main_thread = new JavaThread(); 3692 main_thread->set_thread_state(_thread_in_vm); 3693 main_thread->initialize_thread_current(); 3694 // must do this before set_active_handles 3695 main_thread->record_stack_base_and_size(); 3696 main_thread->set_active_handles(JNIHandleBlock::allocate_block()); 3697 3698 if (!main_thread->set_as_starting_thread()) { 3699 vm_shutdown_during_initialization( 3700 "Failed necessary internal allocation. Out of swap space"); 3701 main_thread->smr_delete(); 3702 *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again 3703 return JNI_ENOMEM; 3704 } 3705 3706 // Enable guard page *after* os::create_main_thread(), otherwise it would 3707 // crash Linux VM, see notes in os_linux.cpp. 3708 main_thread->create_stack_guard_pages(); 3709 3710 // Initialize Java-Level synchronization subsystem 3711 ObjectMonitor::Initialize(); 3712 3713 // Initialize global modules 3714 jint status = init_globals(); 3715 if (status != JNI_OK) { 3716 main_thread->smr_delete(); 3717 *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again 3718 return status; 3719 } 3720 3721 JFR_ONLY(Jfr::on_vm_init();) 3722 3723 // Should be done after the heap is fully created 3724 main_thread->cache_global_variables(); 3725 3726 HandleMark hm; 3727 3728 { MutexLocker mu(Threads_lock); 3729 Threads::add(main_thread); 3730 } 3731 3732 // Any JVMTI raw monitors entered in onload will transition into 3733 // real raw monitor. VM is setup enough here for raw monitor enter. 3734 JvmtiExport::transition_pending_onload_raw_monitors(); 3735 3736 // Create the VMThread 3737 { TraceTime timer("Start VMThread", TRACETIME_LOG(Info, startuptime)); 3738 3739 VMThread::create(); 3740 Thread* vmthread = VMThread::vm_thread(); 3741 3742 if (!os::create_thread(vmthread, os::vm_thread)) { 3743 vm_exit_during_initialization("Cannot create VM thread. " 3744 "Out of system resources."); 3745 } 3746 3747 // Wait for the VM thread to become ready, and VMThread::run to initialize 3748 // Monitors can have spurious returns, must always check another state flag 3749 { 3750 MutexLocker ml(Notify_lock); 3751 os::start_thread(vmthread); 3752 while (vmthread->active_handles() == NULL) { 3753 Notify_lock->wait(); 3754 } 3755 } 3756 } 3757 3758 assert(Universe::is_fully_initialized(), "not initialized"); 3759 if (VerifyDuringStartup) { 3760 // Make sure we're starting with a clean slate. 3761 VM_Verify verify_op; 3762 VMThread::execute(&verify_op); 3763 } 3764 3765 // We need this to update the java.vm.info property in case any flags used 3766 // to initially define it have been changed. This is needed for both CDS and 3767 // AOT, since UseSharedSpaces and UseAOT may be changed after java.vm.info 3768 // is initially computed. See Abstract_VM_Version::vm_info_string(). 3769 // This update must happen before we initialize the java classes, but 3770 // after any initialization logic that might modify the flags. 3771 Arguments::update_vm_info_property(VM_Version::vm_info_string()); 3772 3773 Thread* THREAD = Thread::current(); 3774 3775 // Always call even when there are not JVMTI environments yet, since environments 3776 // may be attached late and JVMTI must track phases of VM execution 3777 JvmtiExport::enter_early_start_phase(); 3778 3779 // Notify JVMTI agents that VM has started (JNI is up) - nop if no agents. 3780 JvmtiExport::post_early_vm_start(); 3781 3782 initialize_java_lang_classes(main_thread, CHECK_JNI_ERR); 3783 3784 quicken_jni_functions(); 3785 3786 // No more stub generation allowed after that point. 3787 StubCodeDesc::freeze(); 3788 3789 // Set flag that basic initialization has completed. Used by exceptions and various 3790 // debug stuff, that does not work until all basic classes have been initialized. 3791 set_init_completed(); 3792 3793 LogConfiguration::post_initialize(); 3794 Metaspace::post_initialize(); 3795 3796 HOTSPOT_VM_INIT_END(); 3797 3798 // record VM initialization completion time 3799 #if INCLUDE_MANAGEMENT 3800 Management::record_vm_init_completed(); 3801 #endif // INCLUDE_MANAGEMENT 3802 3803 // Signal Dispatcher needs to be started before VMInit event is posted 3804 os::initialize_jdk_signal_support(CHECK_JNI_ERR); 3805 3806 // Start Attach Listener if +StartAttachListener or it can't be started lazily 3807 if (!DisableAttachMechanism) { 3808 AttachListener::vm_start(); 3809 if (StartAttachListener || AttachListener::init_at_startup()) { 3810 AttachListener::init(); 3811 } 3812 } 3813 3814 // Launch -Xrun agents 3815 // Must be done in the JVMTI live phase so that for backward compatibility the JDWP 3816 // back-end can launch with -Xdebug -Xrunjdwp. 3817 if (!EagerXrunInit && Arguments::init_libraries_at_startup()) { 3818 create_vm_init_libraries(); 3819 } 3820 3821 if (CleanChunkPoolAsync) { 3822 Chunk::start_chunk_pool_cleaner_task(); 3823 } 3824 3825 // initialize compiler(s) 3826 #if defined(COMPILER1) || COMPILER2_OR_JVMCI 3827 #if INCLUDE_JVMCI 3828 bool force_JVMCI_intialization = false; 3829 if (EnableJVMCI) { 3830 // Initialize JVMCI eagerly when it is explicitly requested. 3831 // Or when JVMCIPrintProperties is enabled. 3832 // The JVMCI Java initialization code will read this flag and 3833 // do the printing if it's set. 3834 force_JVMCI_intialization = EagerJVMCI || JVMCIPrintProperties; 3835 3836 if (!force_JVMCI_intialization) { 3837 // 8145270: Force initialization of JVMCI runtime otherwise requests for blocking 3838 // compilations via JVMCI will not actually block until JVMCI is initialized. 3839 force_JVMCI_intialization = UseJVMCICompiler && (!UseInterpreter || !BackgroundCompilation); 3840 } 3841 } 3842 #endif 3843 CompileBroker::compilation_init_phase1(CHECK_JNI_ERR); 3844 // Postpone completion of compiler initialization to after JVMCI 3845 // is initialized to avoid timeouts of blocking compilations. 3846 if (JVMCI_ONLY(!force_JVMCI_intialization) NOT_JVMCI(true)) { 3847 CompileBroker::compilation_init_phase2(); 3848 } 3849 #endif 3850 3851 // Pre-initialize some JSR292 core classes to avoid deadlock during class loading. 3852 // It is done after compilers are initialized, because otherwise compilations of 3853 // signature polymorphic MH intrinsics can be missed 3854 // (see SystemDictionary::find_method_handle_intrinsic). 3855 initialize_jsr292_core_classes(CHECK_JNI_ERR); 3856 3857 // This will initialize the module system. Only java.base classes can be 3858 // loaded until phase 2 completes 3859 call_initPhase2(CHECK_JNI_ERR); 3860 3861 // Always call even when there are not JVMTI environments yet, since environments 3862 // may be attached late and JVMTI must track phases of VM execution 3863 JvmtiExport::enter_start_phase(); 3864 3865 // Notify JVMTI agents that VM has started (JNI is up) - nop if no agents. 3866 JvmtiExport::post_vm_start(); 3867 3868 // Final system initialization including security manager and system class loader 3869 call_initPhase3(CHECK_JNI_ERR); 3870 3871 // cache the system and platform class loaders 3872 SystemDictionary::compute_java_loaders(CHECK_JNI_ERR); 3873 3874 #if INCLUDE_CDS 3875 if (DumpSharedSpaces) { 3876 // capture the module path info from the ModuleEntryTable 3877 ClassLoader::initialize_module_path(THREAD); 3878 } 3879 #endif 3880 3881 #if INCLUDE_JVMCI 3882 if (force_JVMCI_intialization) { 3883 JVMCIRuntime::force_initialization(CHECK_JNI_ERR); 3884 CompileBroker::compilation_init_phase2(); 3885 } 3886 #endif 3887 3888 // Always call even when there are not JVMTI environments yet, since environments 3889 // may be attached late and JVMTI must track phases of VM execution 3890 JvmtiExport::enter_live_phase(); 3891 3892 // Notify JVMTI agents that VM initialization is complete - nop if no agents. 3893 JvmtiExport::post_vm_initialized(); 3894 3895 JFR_ONLY(Jfr::on_vm_start();) 3896 3897 #if INCLUDE_MANAGEMENT 3898 Management::initialize(THREAD); 3899 3900 if (HAS_PENDING_EXCEPTION) { 3901 // management agent fails to start possibly due to 3902 // configuration problem and is responsible for printing 3903 // stack trace if appropriate. Simply exit VM. 3904 vm_exit(1); 3905 } 3906 #endif // INCLUDE_MANAGEMENT 3907 3908 if (MemProfiling) MemProfiler::engage(); 3909 StatSampler::engage(); 3910 if (CheckJNICalls) JniPeriodicChecker::engage(); 3911 3912 BiasedLocking::init(); 3913 3914 #if INCLUDE_RTM_OPT 3915 RTMLockingCounters::init(); 3916 #endif 3917 3918 if (JDK_Version::current().post_vm_init_hook_enabled()) { 3919 call_postVMInitHook(THREAD); 3920 // The Java side of PostVMInitHook.run must deal with all 3921 // exceptions and provide means of diagnosis. 3922 if (HAS_PENDING_EXCEPTION) { 3923 CLEAR_PENDING_EXCEPTION; 3924 } 3925 } 3926 3927 { 3928 MutexLocker ml(PeriodicTask_lock); 3929 // Make sure the WatcherThread can be started by WatcherThread::start() 3930 // or by dynamic enrollment. 3931 WatcherThread::make_startable(); 3932 // Start up the WatcherThread if there are any periodic tasks 3933 // NOTE: All PeriodicTasks should be registered by now. If they 3934 // aren't, late joiners might appear to start slowly (we might 3935 // take a while to process their first tick). 3936 if (PeriodicTask::num_tasks() > 0) { 3937 WatcherThread::start(); 3938 } 3939 } 3940 3941 create_vm_timer.end(); 3942 #ifdef ASSERT 3943 _vm_complete = true; 3944 #endif 3945 3946 if (DumpSharedSpaces) { 3947 MetaspaceShared::preload_and_dump(CHECK_JNI_ERR); 3948 ShouldNotReachHere(); 3949 } 3950 3951 return JNI_OK; 3952 } 3953 3954 // type for the Agent_OnLoad and JVM_OnLoad entry points 3955 extern "C" { 3956 typedef jint (JNICALL *OnLoadEntry_t)(JavaVM *, char *, void *); 3957 } 3958 // Find a command line agent library and return its entry point for 3959 // -agentlib: -agentpath: -Xrun 3960 // num_symbol_entries must be passed-in since only the caller knows the number of symbols in the array. 3961 static OnLoadEntry_t lookup_on_load(AgentLibrary* agent, 3962 const char *on_load_symbols[], 3963 size_t num_symbol_entries) { 3964 OnLoadEntry_t on_load_entry = NULL; 3965 void *library = NULL; 3966 3967 if (!agent->valid()) { 3968 char buffer[JVM_MAXPATHLEN]; 3969 char ebuf[1024] = ""; 3970 const char *name = agent->name(); 3971 const char *msg = "Could not find agent library "; 3972 3973 // First check to see if agent is statically linked into executable 3974 if (os::find_builtin_agent(agent, on_load_symbols, num_symbol_entries)) { 3975 library = agent->os_lib(); 3976 } else if (agent->is_absolute_path()) { 3977 library = os::dll_load(name, ebuf, sizeof ebuf); 3978 if (library == NULL) { 3979 const char *sub_msg = " in absolute path, with error: "; 3980 size_t len = strlen(msg) + strlen(name) + strlen(sub_msg) + strlen(ebuf) + 1; 3981 char *buf = NEW_C_HEAP_ARRAY(char, len, mtThread); 3982 jio_snprintf(buf, len, "%s%s%s%s", msg, name, sub_msg, ebuf); 3983 // If we can't find the agent, exit. 3984 vm_exit_during_initialization(buf, NULL); 3985 FREE_C_HEAP_ARRAY(char, buf); 3986 } 3987 } else { 3988 // Try to load the agent from the standard dll directory 3989 if (os::dll_locate_lib(buffer, sizeof(buffer), Arguments::get_dll_dir(), 3990 name)) { 3991 library = os::dll_load(buffer, ebuf, sizeof ebuf); 3992 } 3993 if (library == NULL) { // Try the library path directory. 3994 if (os::dll_build_name(buffer, sizeof(buffer), name)) { 3995 library = os::dll_load(buffer, ebuf, sizeof ebuf); 3996 } 3997 if (library == NULL) { 3998 const char *sub_msg = " on the library path, with error: "; 3999 const char *sub_msg2 = "\nModule java.instrument may be missing from runtime image."; 4000 4001 size_t len = strlen(msg) + strlen(name) + strlen(sub_msg) + 4002 strlen(ebuf) + strlen(sub_msg2) + 1; 4003 char *buf = NEW_C_HEAP_ARRAY(char, len, mtThread); 4004 if (!agent->is_instrument_lib()) { 4005 jio_snprintf(buf, len, "%s%s%s%s", msg, name, sub_msg, ebuf); 4006 } else { 4007 jio_snprintf(buf, len, "%s%s%s%s%s", msg, name, sub_msg, ebuf, sub_msg2); 4008 } 4009 // If we can't find the agent, exit. 4010 vm_exit_during_initialization(buf, NULL); 4011 FREE_C_HEAP_ARRAY(char, buf); 4012 } 4013 } 4014 } 4015 agent->set_os_lib(library); 4016 agent->set_valid(); 4017 } 4018 4019 // Find the OnLoad function. 4020 on_load_entry = 4021 CAST_TO_FN_PTR(OnLoadEntry_t, os::find_agent_function(agent, 4022 false, 4023 on_load_symbols, 4024 num_symbol_entries)); 4025 return on_load_entry; 4026 } 4027 4028 // Find the JVM_OnLoad entry point 4029 static OnLoadEntry_t lookup_jvm_on_load(AgentLibrary* agent) { 4030 const char *on_load_symbols[] = JVM_ONLOAD_SYMBOLS; 4031 return lookup_on_load(agent, on_load_symbols, sizeof(on_load_symbols) / sizeof(char*)); 4032 } 4033 4034 // Find the Agent_OnLoad entry point 4035 static OnLoadEntry_t lookup_agent_on_load(AgentLibrary* agent) { 4036 const char *on_load_symbols[] = AGENT_ONLOAD_SYMBOLS; 4037 return lookup_on_load(agent, on_load_symbols, sizeof(on_load_symbols) / sizeof(char*)); 4038 } 4039 4040 // For backwards compatibility with -Xrun 4041 // Convert libraries with no JVM_OnLoad, but which have Agent_OnLoad to be 4042 // treated like -agentpath: 4043 // Must be called before agent libraries are created 4044 void Threads::convert_vm_init_libraries_to_agents() { 4045 AgentLibrary* agent; 4046 AgentLibrary* next; 4047 4048 for (agent = Arguments::libraries(); agent != NULL; agent = next) { 4049 next = agent->next(); // cache the next agent now as this agent may get moved off this list 4050 OnLoadEntry_t on_load_entry = lookup_jvm_on_load(agent); 4051 4052 // If there is an JVM_OnLoad function it will get called later, 4053 // otherwise see if there is an Agent_OnLoad 4054 if (on_load_entry == NULL) { 4055 on_load_entry = lookup_agent_on_load(agent); 4056 if (on_load_entry != NULL) { 4057 // switch it to the agent list -- so that Agent_OnLoad will be called, 4058 // JVM_OnLoad won't be attempted and Agent_OnUnload will 4059 Arguments::convert_library_to_agent(agent); 4060 } else { 4061 vm_exit_during_initialization("Could not find JVM_OnLoad or Agent_OnLoad function in the library", agent->name()); 4062 } 4063 } 4064 } 4065 } 4066 4067 // Create agents for -agentlib: -agentpath: and converted -Xrun 4068 // Invokes Agent_OnLoad 4069 // Called very early -- before JavaThreads exist 4070 void Threads::create_vm_init_agents() { 4071 extern struct JavaVM_ main_vm; 4072 AgentLibrary* agent; 4073 4074 JvmtiExport::enter_onload_phase(); 4075 4076 for (agent = Arguments::agents(); agent != NULL; agent = agent->next()) { 4077 OnLoadEntry_t on_load_entry = lookup_agent_on_load(agent); 4078 4079 if (on_load_entry != NULL) { 4080 // Invoke the Agent_OnLoad function 4081 jint err = (*on_load_entry)(&main_vm, agent->options(), NULL); 4082 if (err != JNI_OK) { 4083 vm_exit_during_initialization("agent library failed to init", agent->name()); 4084 } 4085 } else { 4086 vm_exit_during_initialization("Could not find Agent_OnLoad function in the agent library", agent->name()); 4087 } 4088 } 4089 JvmtiExport::enter_primordial_phase(); 4090 } 4091 4092 extern "C" { 4093 typedef void (JNICALL *Agent_OnUnload_t)(JavaVM *); 4094 } 4095 4096 void Threads::shutdown_vm_agents() { 4097 // Send any Agent_OnUnload notifications 4098 const char *on_unload_symbols[] = AGENT_ONUNLOAD_SYMBOLS; 4099 size_t num_symbol_entries = ARRAY_SIZE(on_unload_symbols); 4100 extern struct JavaVM_ main_vm; 4101 for (AgentLibrary* agent = Arguments::agents(); agent != NULL; agent = agent->next()) { 4102 4103 // Find the Agent_OnUnload function. 4104 Agent_OnUnload_t unload_entry = CAST_TO_FN_PTR(Agent_OnUnload_t, 4105 os::find_agent_function(agent, 4106 false, 4107 on_unload_symbols, 4108 num_symbol_entries)); 4109 4110 // Invoke the Agent_OnUnload function 4111 if (unload_entry != NULL) { 4112 JavaThread* thread = JavaThread::current(); 4113 ThreadToNativeFromVM ttn(thread); 4114 HandleMark hm(thread); 4115 (*unload_entry)(&main_vm); 4116 } 4117 } 4118 } 4119 4120 // Called for after the VM is initialized for -Xrun libraries which have not been converted to agent libraries 4121 // Invokes JVM_OnLoad 4122 void Threads::create_vm_init_libraries() { 4123 extern struct JavaVM_ main_vm; 4124 AgentLibrary* agent; 4125 4126 for (agent = Arguments::libraries(); agent != NULL; agent = agent->next()) { 4127 OnLoadEntry_t on_load_entry = lookup_jvm_on_load(agent); 4128 4129 if (on_load_entry != NULL) { 4130 // Invoke the JVM_OnLoad function 4131 JavaThread* thread = JavaThread::current(); 4132 ThreadToNativeFromVM ttn(thread); 4133 HandleMark hm(thread); 4134 jint err = (*on_load_entry)(&main_vm, agent->options(), NULL); 4135 if (err != JNI_OK) { 4136 vm_exit_during_initialization("-Xrun library failed to init", agent->name()); 4137 } 4138 } else { 4139 vm_exit_during_initialization("Could not find JVM_OnLoad function in -Xrun library", agent->name()); 4140 } 4141 } 4142 } 4143 4144 4145 // Last thread running calls java.lang.Shutdown.shutdown() 4146 void JavaThread::invoke_shutdown_hooks() { 4147 HandleMark hm(this); 4148 4149 // We could get here with a pending exception, if so clear it now. 4150 if (this->has_pending_exception()) { 4151 this->clear_pending_exception(); 4152 } 4153 4154 EXCEPTION_MARK; 4155 Klass* shutdown_klass = 4156 SystemDictionary::resolve_or_null(vmSymbols::java_lang_Shutdown(), 4157 THREAD); 4158 if (shutdown_klass != NULL) { 4159 // SystemDictionary::resolve_or_null will return null if there was 4160 // an exception. If we cannot load the Shutdown class, just don't 4161 // call Shutdown.shutdown() at all. This will mean the shutdown hooks 4162 // won't be run. Note that if a shutdown hook was registered, 4163 // the Shutdown class would have already been loaded 4164 // (Runtime.addShutdownHook will load it). 4165 JavaValue result(T_VOID); 4166 JavaCalls::call_static(&result, 4167 shutdown_klass, 4168 vmSymbols::shutdown_method_name(), 4169 vmSymbols::void_method_signature(), 4170 THREAD); 4171 } 4172 CLEAR_PENDING_EXCEPTION; 4173 } 4174 4175 // Threads::destroy_vm() is normally called from jni_DestroyJavaVM() when 4176 // the program falls off the end of main(). Another VM exit path is through 4177 // vm_exit() when the program calls System.exit() to return a value or when 4178 // there is a serious error in VM. The two shutdown paths are not exactly 4179 // the same, but they share Shutdown.shutdown() at Java level and before_exit() 4180 // and VM_Exit op at VM level. 4181 // 4182 // Shutdown sequence: 4183 // + Shutdown native memory tracking if it is on 4184 // + Wait until we are the last non-daemon thread to execute 4185 // <-- every thing is still working at this moment --> 4186 // + Call java.lang.Shutdown.shutdown(), which will invoke Java level 4187 // shutdown hooks 4188 // + Call before_exit(), prepare for VM exit 4189 // > run VM level shutdown hooks (they are registered through JVM_OnExit(), 4190 // currently the only user of this mechanism is File.deleteOnExit()) 4191 // > stop StatSampler, watcher thread, CMS threads, 4192 // post thread end and vm death events to JVMTI, 4193 // stop signal thread 4194 // + Call JavaThread::exit(), it will: 4195 // > release JNI handle blocks, remove stack guard pages 4196 // > remove this thread from Threads list 4197 // <-- no more Java code from this thread after this point --> 4198 // + Stop VM thread, it will bring the remaining VM to a safepoint and stop 4199 // the compiler threads at safepoint 4200 // <-- do not use anything that could get blocked by Safepoint --> 4201 // + Disable tracing at JNI/JVM barriers 4202 // + Set _vm_exited flag for threads that are still running native code 4203 // + Delete this thread 4204 // + Call exit_globals() 4205 // > deletes tty 4206 // > deletes PerfMemory resources 4207 // + Return to caller 4208 4209 bool Threads::destroy_vm() { 4210 JavaThread* thread = JavaThread::current(); 4211 4212 #ifdef ASSERT 4213 _vm_complete = false; 4214 #endif 4215 // Wait until we are the last non-daemon thread to execute 4216 { MutexLocker nu(Threads_lock); 4217 while (Threads::number_of_non_daemon_threads() > 1) 4218 // This wait should make safepoint checks, wait without a timeout, 4219 // and wait as a suspend-equivalent condition. 4220 Threads_lock->wait(!Mutex::_no_safepoint_check_flag, 0, 4221 Mutex::_as_suspend_equivalent_flag); 4222 } 4223 4224 EventShutdown e; 4225 if (e.should_commit()) { 4226 e.set_reason("No remaining non-daemon Java threads"); 4227 e.commit(); 4228 } 4229 4230 // Hang forever on exit if we are reporting an error. 4231 if (ShowMessageBoxOnError && VMError::is_error_reported()) { 4232 os::infinite_sleep(); 4233 } 4234 os::wait_for_keypress_at_exit(); 4235 4236 // run Java level shutdown hooks 4237 thread->invoke_shutdown_hooks(); 4238 4239 before_exit(thread); 4240 4241 thread->exit(true); 4242 // thread will never call smr_delete, instead of implicit cancel 4243 // in wait_for_vm_thread_exit we do it explicit. 4244 thread->cancel_handshake(); 4245 4246 // Stop VM thread. 4247 { 4248 // 4945125 The vm thread comes to a safepoint during exit. 4249 // GC vm_operations can get caught at the safepoint, and the 4250 // heap is unparseable if they are caught. Grab the Heap_lock 4251 // to prevent this. The GC vm_operations will not be able to 4252 // queue until after the vm thread is dead. After this point, 4253 // we'll never emerge out of the safepoint before the VM exits. 4254 4255 MutexLocker ml(Heap_lock); 4256 4257 VMThread::wait_for_vm_thread_exit(); 4258 assert(SafepointSynchronize::is_at_safepoint(), "VM thread should exit at Safepoint"); 4259 VMThread::destroy(); 4260 } 4261 4262 // Now, all Java threads are gone except daemon threads. Daemon threads 4263 // running Java code or in VM are stopped by the Safepoint. However, 4264 // daemon threads executing native code are still running. But they 4265 // will be stopped at native=>Java/VM barriers. Note that we can't 4266 // simply kill or suspend them, as it is inherently deadlock-prone. 4267 4268 VM_Exit::set_vm_exited(); 4269 4270 // Clean up ideal graph printers after the VMThread has started 4271 // the final safepoint which will block all the Compiler threads. 4272 // Note that this Thread has already logically exited so the 4273 // clean_up() function's use of a JavaThreadIteratorWithHandle 4274 // would be a problem except set_vm_exited() has remembered the 4275 // shutdown thread which is granted a policy exception. 4276 #if defined(COMPILER2) && !defined(PRODUCT) 4277 IdealGraphPrinter::clean_up(); 4278 #endif 4279 4280 notify_vm_shutdown(); 4281 4282 // We are after VM_Exit::set_vm_exited() so we can't call 4283 // thread->smr_delete() or we will block on the Threads_lock. 4284 // Deleting the shutdown thread here is safe because another 4285 // JavaThread cannot have an active ThreadsListHandle for 4286 // this JavaThread. 4287 delete thread; 4288 4289 #if INCLUDE_JVMCI 4290 if (JVMCICounterSize > 0) { 4291 FREE_C_HEAP_ARRAY(jlong, JavaThread::_jvmci_old_thread_counters); 4292 } 4293 #endif 4294 4295 // exit_globals() will delete tty 4296 exit_globals(); 4297 4298 LogConfiguration::finalize(); 4299 4300 return true; 4301 } 4302 4303 4304 jboolean Threads::is_supported_jni_version_including_1_1(jint version) { 4305 if (version == JNI_VERSION_1_1) return JNI_TRUE; 4306 return is_supported_jni_version(version); 4307 } 4308 4309 4310 jboolean Threads::is_supported_jni_version(jint version) { 4311 if (version == JNI_VERSION_1_2) return JNI_TRUE; 4312 if (version == JNI_VERSION_1_4) return JNI_TRUE; 4313 if (version == JNI_VERSION_1_6) return JNI_TRUE; 4314 if (version == JNI_VERSION_1_8) return JNI_TRUE; 4315 if (version == JNI_VERSION_9) return JNI_TRUE; 4316 if (version == JNI_VERSION_10) return JNI_TRUE; 4317 return JNI_FALSE; 4318 } 4319 4320 4321 void Threads::add(JavaThread* p, bool force_daemon) { 4322 // The threads lock must be owned at this point 4323 assert_locked_or_safepoint(Threads_lock); 4324 4325 BarrierSet::barrier_set()->on_thread_attach(p); 4326 4327 p->set_next(_thread_list); 4328 _thread_list = p; 4329 4330 // Once a JavaThread is added to the Threads list, smr_delete() has 4331 // to be used to delete it. Otherwise we can just delete it directly. 4332 p->set_on_thread_list(); 4333 4334 _number_of_threads++; 4335 oop threadObj = p->threadObj(); 4336 bool daemon = true; 4337 // Bootstrapping problem: threadObj can be null for initial 4338 // JavaThread (or for threads attached via JNI) 4339 if ((!force_daemon) && (threadObj == NULL || !java_lang_Thread::is_daemon(threadObj))) { 4340 _number_of_non_daemon_threads++; 4341 daemon = false; 4342 } 4343 4344 ThreadService::add_thread(p, daemon); 4345 4346 // Maintain fast thread list 4347 ThreadsSMRSupport::add_thread(p); 4348 4349 // Possible GC point. 4350 Events::log(p, "Thread added: " INTPTR_FORMAT, p2i(p)); 4351 } 4352 4353 void Threads::remove(JavaThread* p) { 4354 4355 // Reclaim the objectmonitors from the omInUseList and omFreeList of the moribund thread. 4356 ObjectSynchronizer::omFlush(p); 4357 4358 // Extra scope needed for Thread_lock, so we can check 4359 // that we do not remove thread without safepoint code notice 4360 { MutexLocker ml(Threads_lock); 4361 4362 assert(ThreadsSMRSupport::get_java_thread_list()->includes(p), "p must be present"); 4363 4364 // Maintain fast thread list 4365 ThreadsSMRSupport::remove_thread(p); 4366 4367 JavaThread* current = _thread_list; 4368 JavaThread* prev = NULL; 4369 4370 while (current != p) { 4371 prev = current; 4372 current = current->next(); 4373 } 4374 4375 if (prev) { 4376 prev->set_next(current->next()); 4377 } else { 4378 _thread_list = p->next(); 4379 } 4380 4381 _number_of_threads--; 4382 oop threadObj = p->threadObj(); 4383 bool daemon = true; 4384 if (threadObj == NULL || !java_lang_Thread::is_daemon(threadObj)) { 4385 _number_of_non_daemon_threads--; 4386 daemon = false; 4387 4388 // Only one thread left, do a notify on the Threads_lock so a thread waiting 4389 // on destroy_vm will wake up. 4390 if (number_of_non_daemon_threads() == 1) { 4391 Threads_lock->notify_all(); 4392 } 4393 } 4394 ThreadService::remove_thread(p, daemon); 4395 4396 // Make sure that safepoint code disregard this thread. This is needed since 4397 // the thread might mess around with locks after this point. This can cause it 4398 // to do callbacks into the safepoint code. However, the safepoint code is not aware 4399 // of this thread since it is removed from the queue. 4400 p->set_terminated_value(); 4401 } // unlock Threads_lock 4402 4403 // Since Events::log uses a lock, we grab it outside the Threads_lock 4404 Events::log(p, "Thread exited: " INTPTR_FORMAT, p2i(p)); 4405 } 4406 4407 // Operations on the Threads list for GC. These are not explicitly locked, 4408 // but the garbage collector must provide a safe context for them to run. 4409 // In particular, these things should never be called when the Threads_lock 4410 // is held by some other thread. (Note: the Safepoint abstraction also 4411 // uses the Threads_lock to guarantee this property. It also makes sure that 4412 // all threads gets blocked when exiting or starting). 4413 4414 void Threads::oops_do(OopClosure* f, CodeBlobClosure* cf) { 4415 ALL_JAVA_THREADS(p) { 4416 p->oops_do(f, cf); 4417 } 4418 VMThread::vm_thread()->oops_do(f, cf); 4419 } 4420 4421 void Threads::change_thread_claim_parity() { 4422 // Set the new claim parity. 4423 assert(_thread_claim_parity >= 0 && _thread_claim_parity <= 2, 4424 "Not in range."); 4425 _thread_claim_parity++; 4426 if (_thread_claim_parity == 3) _thread_claim_parity = 1; 4427 assert(_thread_claim_parity >= 1 && _thread_claim_parity <= 2, 4428 "Not in range."); 4429 } 4430 4431 #ifdef ASSERT 4432 void Threads::assert_all_threads_claimed() { 4433 ALL_JAVA_THREADS(p) { 4434 const int thread_parity = p->oops_do_parity(); 4435 assert((thread_parity == _thread_claim_parity), 4436 "Thread " PTR_FORMAT " has incorrect parity %d != %d", p2i(p), thread_parity, _thread_claim_parity); 4437 } 4438 VMThread* vmt = VMThread::vm_thread(); 4439 const int thread_parity = vmt->oops_do_parity(); 4440 assert((thread_parity == _thread_claim_parity), 4441 "VMThread " PTR_FORMAT " has incorrect parity %d != %d", p2i(vmt), thread_parity, _thread_claim_parity); 4442 } 4443 #endif // ASSERT 4444 4445 class ParallelOopsDoThreadClosure : public ThreadClosure { 4446 private: 4447 OopClosure* _f; 4448 CodeBlobClosure* _cf; 4449 public: 4450 ParallelOopsDoThreadClosure(OopClosure* f, CodeBlobClosure* cf) : _f(f), _cf(cf) {} 4451 void do_thread(Thread* t) { 4452 t->oops_do(_f, _cf); 4453 } 4454 }; 4455 4456 void Threads::possibly_parallel_oops_do(bool is_par, OopClosure* f, CodeBlobClosure* cf) { 4457 ParallelOopsDoThreadClosure tc(f, cf); 4458 possibly_parallel_threads_do(is_par, &tc); 4459 } 4460 4461 void Threads::nmethods_do(CodeBlobClosure* cf) { 4462 ALL_JAVA_THREADS(p) { 4463 // This is used by the code cache sweeper to mark nmethods that are active 4464 // on the stack of a Java thread. Ignore the sweeper thread itself to avoid 4465 // marking CodeCacheSweeperThread::_scanned_compiled_method as active. 4466 if(!p->is_Code_cache_sweeper_thread()) { 4467 p->nmethods_do(cf); 4468 } 4469 } 4470 } 4471 4472 void Threads::metadata_do(void f(Metadata*)) { 4473 ALL_JAVA_THREADS(p) { 4474 p->metadata_do(f); 4475 } 4476 } 4477 4478 class ThreadHandlesClosure : public ThreadClosure { 4479 void (*_f)(Metadata*); 4480 public: 4481 ThreadHandlesClosure(void f(Metadata*)) : _f(f) {} 4482 virtual void do_thread(Thread* thread) { 4483 thread->metadata_handles_do(_f); 4484 } 4485 }; 4486 4487 void Threads::metadata_handles_do(void f(Metadata*)) { 4488 // Only walk the Handles in Thread. 4489 ThreadHandlesClosure handles_closure(f); 4490 threads_do(&handles_closure); 4491 } 4492 4493 void Threads::deoptimized_wrt_marked_nmethods() { 4494 ALL_JAVA_THREADS(p) { 4495 p->deoptimized_wrt_marked_nmethods(); 4496 } 4497 } 4498 4499 4500 // Get count Java threads that are waiting to enter the specified monitor. 4501 GrowableArray<JavaThread*>* Threads::get_pending_threads(ThreadsList * t_list, 4502 int count, 4503 address monitor) { 4504 GrowableArray<JavaThread*>* result = new GrowableArray<JavaThread*>(count); 4505 4506 int i = 0; 4507 DO_JAVA_THREADS(t_list, p) { 4508 if (!p->can_call_java()) continue; 4509 4510 address pending = (address)p->current_pending_monitor(); 4511 if (pending == monitor) { // found a match 4512 if (i < count) result->append(p); // save the first count matches 4513 i++; 4514 } 4515 } 4516 4517 return result; 4518 } 4519 4520 4521 JavaThread *Threads::owning_thread_from_monitor_owner(ThreadsList * t_list, 4522 address owner) { 4523 // NULL owner means not locked so we can skip the search 4524 if (owner == NULL) return NULL; 4525 4526 DO_JAVA_THREADS(t_list, p) { 4527 // first, see if owner is the address of a Java thread 4528 if (owner == (address)p) return p; 4529 } 4530 4531 // Cannot assert on lack of success here since this function may be 4532 // used by code that is trying to report useful problem information 4533 // like deadlock detection. 4534 if (UseHeavyMonitors) return NULL; 4535 4536 // If we didn't find a matching Java thread and we didn't force use of 4537 // heavyweight monitors, then the owner is the stack address of the 4538 // Lock Word in the owning Java thread's stack. 4539 // 4540 JavaThread* the_owner = NULL; 4541 DO_JAVA_THREADS(t_list, q) { 4542 if (q->is_lock_owned(owner)) { 4543 the_owner = q; 4544 break; 4545 } 4546 } 4547 4548 // cannot assert on lack of success here; see above comment 4549 return the_owner; 4550 } 4551 4552 // Threads::print_on() is called at safepoint by VM_PrintThreads operation. 4553 void Threads::print_on(outputStream* st, bool print_stacks, 4554 bool internal_format, bool print_concurrent_locks, 4555 bool print_extended_info) { 4556 char buf[32]; 4557 st->print_raw_cr(os::local_time_string(buf, sizeof(buf))); 4558 4559 st->print_cr("Full thread dump %s (%s %s):", 4560 Abstract_VM_Version::vm_name(), 4561 Abstract_VM_Version::vm_release(), 4562 Abstract_VM_Version::vm_info_string()); 4563 st->cr(); 4564 4565 #if INCLUDE_SERVICES 4566 // Dump concurrent locks 4567 ConcurrentLocksDump concurrent_locks; 4568 if (print_concurrent_locks) { 4569 concurrent_locks.dump_at_safepoint(); 4570 } 4571 #endif // INCLUDE_SERVICES 4572 4573 ThreadsSMRSupport::print_info_on(st); 4574 st->cr(); 4575 4576 ALL_JAVA_THREADS(p) { 4577 ResourceMark rm; 4578 p->print_on(st, print_extended_info); 4579 if (print_stacks) { 4580 if (internal_format) { 4581 p->trace_stack(); 4582 } else { 4583 p->print_stack_on(st); 4584 } 4585 } 4586 st->cr(); 4587 #if INCLUDE_SERVICES 4588 if (print_concurrent_locks) { 4589 concurrent_locks.print_locks_on(p, st); 4590 } 4591 #endif // INCLUDE_SERVICES 4592 } 4593 4594 VMThread::vm_thread()->print_on(st); 4595 st->cr(); 4596 Universe::heap()->print_gc_threads_on(st); 4597 WatcherThread* wt = WatcherThread::watcher_thread(); 4598 if (wt != NULL) { 4599 wt->print_on(st); 4600 st->cr(); 4601 } 4602 4603 st->flush(); 4604 } 4605 4606 void Threads::print_on_error(Thread* this_thread, outputStream* st, Thread* current, char* buf, 4607 int buflen, bool* found_current) { 4608 if (this_thread != NULL) { 4609 bool is_current = (current == this_thread); 4610 *found_current = *found_current || is_current; 4611 st->print("%s", is_current ? "=>" : " "); 4612 4613 st->print(PTR_FORMAT, p2i(this_thread)); 4614 st->print(" "); 4615 this_thread->print_on_error(st, buf, buflen); 4616 st->cr(); 4617 } 4618 } 4619 4620 class PrintOnErrorClosure : public ThreadClosure { 4621 outputStream* _st; 4622 Thread* _current; 4623 char* _buf; 4624 int _buflen; 4625 bool* _found_current; 4626 public: 4627 PrintOnErrorClosure(outputStream* st, Thread* current, char* buf, 4628 int buflen, bool* found_current) : 4629 _st(st), _current(current), _buf(buf), _buflen(buflen), _found_current(found_current) {} 4630 4631 virtual void do_thread(Thread* thread) { 4632 Threads::print_on_error(thread, _st, _current, _buf, _buflen, _found_current); 4633 } 4634 }; 4635 4636 // Threads::print_on_error() is called by fatal error handler. It's possible 4637 // that VM is not at safepoint and/or current thread is inside signal handler. 4638 // Don't print stack trace, as the stack may not be walkable. Don't allocate 4639 // memory (even in resource area), it might deadlock the error handler. 4640 void Threads::print_on_error(outputStream* st, Thread* current, char* buf, 4641 int buflen) { 4642 ThreadsSMRSupport::print_info_on(st); 4643 st->cr(); 4644 4645 bool found_current = false; 4646 st->print_cr("Java Threads: ( => current thread )"); 4647 ALL_JAVA_THREADS(thread) { 4648 print_on_error(thread, st, current, buf, buflen, &found_current); 4649 } 4650 st->cr(); 4651 4652 st->print_cr("Other Threads:"); 4653 print_on_error(VMThread::vm_thread(), st, current, buf, buflen, &found_current); 4654 print_on_error(WatcherThread::watcher_thread(), st, current, buf, buflen, &found_current); 4655 4656 PrintOnErrorClosure print_closure(st, current, buf, buflen, &found_current); 4657 Universe::heap()->gc_threads_do(&print_closure); 4658 4659 if (!found_current) { 4660 st->cr(); 4661 st->print("=>" PTR_FORMAT " (exited) ", p2i(current)); 4662 current->print_on_error(st, buf, buflen); 4663 st->cr(); 4664 } 4665 st->cr(); 4666 4667 st->print_cr("Threads with active compile tasks:"); 4668 print_threads_compiling(st, buf, buflen); 4669 } 4670 4671 void Threads::print_threads_compiling(outputStream* st, char* buf, int buflen) { 4672 ALL_JAVA_THREADS(thread) { 4673 if (thread->is_Compiler_thread()) { 4674 CompilerThread* ct = (CompilerThread*) thread; 4675 4676 // Keep task in local variable for NULL check. 4677 // ct->_task might be set to NULL by concurring compiler thread 4678 // because it completed the compilation. The task is never freed, 4679 // though, just returned to a free list. 4680 CompileTask* task = ct->task(); 4681 if (task != NULL) { 4682 thread->print_name_on_error(st, buf, buflen); 4683 task->print(st, NULL, true, true); 4684 } 4685 } 4686 } 4687 } 4688 4689 4690 // Internal SpinLock and Mutex 4691 // Based on ParkEvent 4692 4693 // Ad-hoc mutual exclusion primitives: SpinLock and Mux 4694 // 4695 // We employ SpinLocks _only for low-contention, fixed-length 4696 // short-duration critical sections where we're concerned 4697 // about native mutex_t or HotSpot Mutex:: latency. 4698 // The mux construct provides a spin-then-block mutual exclusion 4699 // mechanism. 4700 // 4701 // Testing has shown that contention on the ListLock guarding gFreeList 4702 // is common. If we implement ListLock as a simple SpinLock it's common 4703 // for the JVM to devolve to yielding with little progress. This is true 4704 // despite the fact that the critical sections protected by ListLock are 4705 // extremely short. 4706 // 4707 // TODO-FIXME: ListLock should be of type SpinLock. 4708 // We should make this a 1st-class type, integrated into the lock 4709 // hierarchy as leaf-locks. Critically, the SpinLock structure 4710 // should have sufficient padding to avoid false-sharing and excessive 4711 // cache-coherency traffic. 4712 4713 4714 typedef volatile int SpinLockT; 4715 4716 void Thread::SpinAcquire(volatile int * adr, const char * LockName) { 4717 if (Atomic::cmpxchg (1, adr, 0) == 0) { 4718 return; // normal fast-path return 4719 } 4720 4721 // Slow-path : We've encountered contention -- Spin/Yield/Block strategy. 4722 TEVENT(SpinAcquire - ctx); 4723 int ctr = 0; 4724 int Yields = 0; 4725 for (;;) { 4726 while (*adr != 0) { 4727 ++ctr; 4728 if ((ctr & 0xFFF) == 0 || !os::is_MP()) { 4729 if (Yields > 5) { 4730 os::naked_short_sleep(1); 4731 } else { 4732 os::naked_yield(); 4733 ++Yields; 4734 } 4735 } else { 4736 SpinPause(); 4737 } 4738 } 4739 if (Atomic::cmpxchg(1, adr, 0) == 0) return; 4740 } 4741 } 4742 4743 void Thread::SpinRelease(volatile int * adr) { 4744 assert(*adr != 0, "invariant"); 4745 OrderAccess::fence(); // guarantee at least release consistency. 4746 // Roach-motel semantics. 4747 // It's safe if subsequent LDs and STs float "up" into the critical section, 4748 // but prior LDs and STs within the critical section can't be allowed 4749 // to reorder or float past the ST that releases the lock. 4750 // Loads and stores in the critical section - which appear in program 4751 // order before the store that releases the lock - must also appear 4752 // before the store that releases the lock in memory visibility order. 4753 // Conceptually we need a #loadstore|#storestore "release" MEMBAR before 4754 // the ST of 0 into the lock-word which releases the lock, so fence 4755 // more than covers this on all platforms. 4756 *adr = 0; 4757 } 4758 4759 // muxAcquire and muxRelease: 4760 // 4761 // * muxAcquire and muxRelease support a single-word lock-word construct. 4762 // The LSB of the word is set IFF the lock is held. 4763 // The remainder of the word points to the head of a singly-linked list 4764 // of threads blocked on the lock. 4765 // 4766 // * The current implementation of muxAcquire-muxRelease uses its own 4767 // dedicated Thread._MuxEvent instance. If we're interested in 4768 // minimizing the peak number of extant ParkEvent instances then 4769 // we could eliminate _MuxEvent and "borrow" _ParkEvent as long 4770 // as certain invariants were satisfied. Specifically, care would need 4771 // to be taken with regards to consuming unpark() "permits". 4772 // A safe rule of thumb is that a thread would never call muxAcquire() 4773 // if it's enqueued (cxq, EntryList, WaitList, etc) and will subsequently 4774 // park(). Otherwise the _ParkEvent park() operation in muxAcquire() could 4775 // consume an unpark() permit intended for monitorenter, for instance. 4776 // One way around this would be to widen the restricted-range semaphore 4777 // implemented in park(). Another alternative would be to provide 4778 // multiple instances of the PlatformEvent() for each thread. One 4779 // instance would be dedicated to muxAcquire-muxRelease, for instance. 4780 // 4781 // * Usage: 4782 // -- Only as leaf locks 4783 // -- for short-term locking only as muxAcquire does not perform 4784 // thread state transitions. 4785 // 4786 // Alternatives: 4787 // * We could implement muxAcquire and muxRelease with MCS or CLH locks 4788 // but with parking or spin-then-park instead of pure spinning. 4789 // * Use Taura-Oyama-Yonenzawa locks. 4790 // * It's possible to construct a 1-0 lock if we encode the lockword as 4791 // (List,LockByte). Acquire will CAS the full lockword while Release 4792 // will STB 0 into the LockByte. The 1-0 scheme admits stranding, so 4793 // acquiring threads use timers (ParkTimed) to detect and recover from 4794 // the stranding window. Thread/Node structures must be aligned on 256-byte 4795 // boundaries by using placement-new. 4796 // * Augment MCS with advisory back-link fields maintained with CAS(). 4797 // Pictorially: LockWord -> T1 <-> T2 <-> T3 <-> ... <-> Tn <-> Owner. 4798 // The validity of the backlinks must be ratified before we trust the value. 4799 // If the backlinks are invalid the exiting thread must back-track through the 4800 // the forward links, which are always trustworthy. 4801 // * Add a successor indication. The LockWord is currently encoded as 4802 // (List, LOCKBIT:1). We could also add a SUCCBIT or an explicit _succ variable 4803 // to provide the usual futile-wakeup optimization. 4804 // See RTStt for details. 4805 // * Consider schedctl.sc_nopreempt to cover the critical section. 4806 // 4807 4808 4809 const intptr_t LOCKBIT = 1; 4810 4811 void Thread::muxAcquire(volatile intptr_t * Lock, const char * LockName) { 4812 intptr_t w = Atomic::cmpxchg(LOCKBIT, Lock, (intptr_t)0); 4813 if (w == 0) return; 4814 if ((w & LOCKBIT) == 0 && Atomic::cmpxchg(w|LOCKBIT, Lock, w) == w) { 4815 return; 4816 } 4817 4818 TEVENT(muxAcquire - Contention); 4819 ParkEvent * const Self = Thread::current()->_MuxEvent; 4820 assert((intptr_t(Self) & LOCKBIT) == 0, "invariant"); 4821 for (;;) { 4822 int its = (os::is_MP() ? 100 : 0) + 1; 4823 4824 // Optional spin phase: spin-then-park strategy 4825 while (--its >= 0) { 4826 w = *Lock; 4827 if ((w & LOCKBIT) == 0 && Atomic::cmpxchg(w|LOCKBIT, Lock, w) == w) { 4828 return; 4829 } 4830 } 4831 4832 Self->reset(); 4833 Self->OnList = intptr_t(Lock); 4834 // The following fence() isn't _strictly necessary as the subsequent 4835 // CAS() both serializes execution and ratifies the fetched *Lock value. 4836 OrderAccess::fence(); 4837 for (;;) { 4838 w = *Lock; 4839 if ((w & LOCKBIT) == 0) { 4840 if (Atomic::cmpxchg(w|LOCKBIT, Lock, w) == w) { 4841 Self->OnList = 0; // hygiene - allows stronger asserts 4842 return; 4843 } 4844 continue; // Interference -- *Lock changed -- Just retry 4845 } 4846 assert(w & LOCKBIT, "invariant"); 4847 Self->ListNext = (ParkEvent *) (w & ~LOCKBIT); 4848 if (Atomic::cmpxchg(intptr_t(Self)|LOCKBIT, Lock, w) == w) break; 4849 } 4850 4851 while (Self->OnList != 0) { 4852 Self->park(); 4853 } 4854 } 4855 } 4856 4857 void Thread::muxAcquireW(volatile intptr_t * Lock, ParkEvent * ev) { 4858 intptr_t w = Atomic::cmpxchg(LOCKBIT, Lock, (intptr_t)0); 4859 if (w == 0) return; 4860 if ((w & LOCKBIT) == 0 && Atomic::cmpxchg(w|LOCKBIT, Lock, w) == w) { 4861 return; 4862 } 4863 4864 TEVENT(muxAcquire - Contention); 4865 ParkEvent * ReleaseAfter = NULL; 4866 if (ev == NULL) { 4867 ev = ReleaseAfter = ParkEvent::Allocate(NULL); 4868 } 4869 assert((intptr_t(ev) & LOCKBIT) == 0, "invariant"); 4870 for (;;) { 4871 guarantee(ev->OnList == 0, "invariant"); 4872 int its = (os::is_MP() ? 100 : 0) + 1; 4873 4874 // Optional spin phase: spin-then-park strategy 4875 while (--its >= 0) { 4876 w = *Lock; 4877 if ((w & LOCKBIT) == 0 && Atomic::cmpxchg(w|LOCKBIT, Lock, w) == w) { 4878 if (ReleaseAfter != NULL) { 4879 ParkEvent::Release(ReleaseAfter); 4880 } 4881 return; 4882 } 4883 } 4884 4885 ev->reset(); 4886 ev->OnList = intptr_t(Lock); 4887 // The following fence() isn't _strictly necessary as the subsequent 4888 // CAS() both serializes execution and ratifies the fetched *Lock value. 4889 OrderAccess::fence(); 4890 for (;;) { 4891 w = *Lock; 4892 if ((w & LOCKBIT) == 0) { 4893 if (Atomic::cmpxchg(w|LOCKBIT, Lock, w) == w) { 4894 ev->OnList = 0; 4895 // We call ::Release while holding the outer lock, thus 4896 // artificially lengthening the critical section. 4897 // Consider deferring the ::Release() until the subsequent unlock(), 4898 // after we've dropped the outer lock. 4899 if (ReleaseAfter != NULL) { 4900 ParkEvent::Release(ReleaseAfter); 4901 } 4902 return; 4903 } 4904 continue; // Interference -- *Lock changed -- Just retry 4905 } 4906 assert(w & LOCKBIT, "invariant"); 4907 ev->ListNext = (ParkEvent *) (w & ~LOCKBIT); 4908 if (Atomic::cmpxchg(intptr_t(ev)|LOCKBIT, Lock, w) == w) break; 4909 } 4910 4911 while (ev->OnList != 0) { 4912 ev->park(); 4913 } 4914 } 4915 } 4916 4917 // Release() must extract a successor from the list and then wake that thread. 4918 // It can "pop" the front of the list or use a detach-modify-reattach (DMR) scheme 4919 // similar to that used by ParkEvent::Allocate() and ::Release(). DMR-based 4920 // Release() would : 4921 // (A) CAS() or swap() null to *Lock, releasing the lock and detaching the list. 4922 // (B) Extract a successor from the private list "in-hand" 4923 // (C) attempt to CAS() the residual back into *Lock over null. 4924 // If there were any newly arrived threads and the CAS() would fail. 4925 // In that case Release() would detach the RATs, re-merge the list in-hand 4926 // with the RATs and repeat as needed. Alternately, Release() might 4927 // detach and extract a successor, but then pass the residual list to the wakee. 4928 // The wakee would be responsible for reattaching and remerging before it 4929 // competed for the lock. 4930 // 4931 // Both "pop" and DMR are immune from ABA corruption -- there can be 4932 // multiple concurrent pushers, but only one popper or detacher. 4933 // This implementation pops from the head of the list. This is unfair, 4934 // but tends to provide excellent throughput as hot threads remain hot. 4935 // (We wake recently run threads first). 4936 // 4937 // All paths through muxRelease() will execute a CAS. 4938 // Release consistency -- We depend on the CAS in muxRelease() to provide full 4939 // bidirectional fence/MEMBAR semantics, ensuring that all prior memory operations 4940 // executed within the critical section are complete and globally visible before the 4941 // store (CAS) to the lock-word that releases the lock becomes globally visible. 4942 void Thread::muxRelease(volatile intptr_t * Lock) { 4943 for (;;) { 4944 const intptr_t w = Atomic::cmpxchg((intptr_t)0, Lock, LOCKBIT); 4945 assert(w & LOCKBIT, "invariant"); 4946 if (w == LOCKBIT) return; 4947 ParkEvent * const List = (ParkEvent *) (w & ~LOCKBIT); 4948 assert(List != NULL, "invariant"); 4949 assert(List->OnList == intptr_t(Lock), "invariant"); 4950 ParkEvent * const nxt = List->ListNext; 4951 guarantee((intptr_t(nxt) & LOCKBIT) == 0, "invariant"); 4952 4953 // The following CAS() releases the lock and pops the head element. 4954 // The CAS() also ratifies the previously fetched lock-word value. 4955 if (Atomic::cmpxchg(intptr_t(nxt), Lock, w) != w) { 4956 continue; 4957 } 4958 List->OnList = 0; 4959 OrderAccess::fence(); 4960 List->unpark(); 4961 return; 4962 } 4963 } 4964 4965 4966 void Threads::verify() { 4967 ALL_JAVA_THREADS(p) { 4968 p->verify(); 4969 } 4970 VMThread* thread = VMThread::vm_thread(); 4971 if (thread != NULL) thread->verify(); 4972 }