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