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