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