1 /* 2 * Copyright (c) 1997, 2019, 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/flags/jvmFlagWriteableList.hpp" 72 #include "runtime/deoptimization.hpp" 73 #include "runtime/frame.inline.hpp" 74 #include "runtime/handles.inline.hpp" 75 #include "runtime/handshake.hpp" 76 #include "runtime/init.hpp" 77 #include "runtime/interfaceSupport.inline.hpp" 78 #include "runtime/java.hpp" 79 #include "runtime/javaCalls.hpp" 80 #include "runtime/jniHandles.inline.hpp" 81 #include "runtime/jniPeriodicChecker.hpp" 82 #include "runtime/memprofiler.hpp" 83 #include "runtime/mutexLocker.hpp" 84 #include "runtime/objectMonitor.hpp" 85 #include "runtime/orderAccess.hpp" 86 #include "runtime/osThread.hpp" 87 #include "runtime/prefetch.inline.hpp" 88 #include "runtime/safepoint.hpp" 89 #include "runtime/safepointMechanism.inline.hpp" 90 #include "runtime/safepointVerifiers.hpp" 91 #include "runtime/serviceThread.hpp" 92 #include "runtime/sharedRuntime.hpp" 93 #include "runtime/statSampler.hpp" 94 #include "runtime/stubRoutines.hpp" 95 #include "runtime/sweeper.hpp" 96 #include "runtime/task.hpp" 97 #include "runtime/thread.inline.hpp" 98 #include "runtime/threadCritical.hpp" 99 #include "runtime/threadSMR.inline.hpp" 100 #include "runtime/threadStatisticalInfo.hpp" 101 #include "runtime/timer.hpp" 102 #include "runtime/timerTrace.hpp" 103 #include "runtime/vframe.inline.hpp" 104 #include "runtime/vframeArray.hpp" 105 #include "runtime/vframe_hp.hpp" 106 #include "runtime/vmThread.hpp" 107 #include "runtime/vmOperations.hpp" 108 #include "runtime/vm_version.hpp" 109 #include "services/attachListener.hpp" 110 #include "services/management.hpp" 111 #include "services/memTracker.hpp" 112 #include "services/threadService.hpp" 113 #include "utilities/align.hpp" 114 #include "utilities/copy.hpp" 115 #include "utilities/defaultStream.hpp" 116 #include "utilities/dtrace.hpp" 117 #include "utilities/events.hpp" 118 #include "utilities/macros.hpp" 119 #include "utilities/preserveException.hpp" 120 #include "utilities/singleWriterSynchronizer.hpp" 121 #include "utilities/vmError.hpp" 122 #if INCLUDE_JVMCI 123 #include "jvmci/jvmci.hpp" 124 #include "jvmci/jvmciEnv.hpp" 125 #endif 126 #ifdef COMPILER1 127 #include "c1/c1_Compiler.hpp" 128 #endif 129 #ifdef COMPILER2 130 #include "opto/c2compiler.hpp" 131 #include "opto/idealGraphPrinter.hpp" 132 #endif 133 #if INCLUDE_RTM_OPT 134 #include "runtime/rtmLocking.hpp" 135 #endif 136 #if INCLUDE_JFR 137 #include "jfr/jfr.hpp" 138 #endif 139 140 // Initialization after module runtime initialization 141 void universe_post_module_init(); // must happen after call_initPhase2 142 143 #ifdef DTRACE_ENABLED 144 145 // Only bother with this argument setup if dtrace is available 146 147 #define HOTSPOT_THREAD_PROBE_start HOTSPOT_THREAD_START 148 #define HOTSPOT_THREAD_PROBE_stop HOTSPOT_THREAD_STOP 149 150 #define DTRACE_THREAD_PROBE(probe, javathread) \ 151 { \ 152 ResourceMark rm(this); \ 153 int len = 0; \ 154 const char* name = (javathread)->get_thread_name(); \ 155 len = strlen(name); \ 156 HOTSPOT_THREAD_PROBE_##probe(/* probe = start, stop */ \ 157 (char *) name, len, \ 158 java_lang_Thread::thread_id((javathread)->threadObj()), \ 159 (uintptr_t) (javathread)->osthread()->thread_id(), \ 160 java_lang_Thread::is_daemon((javathread)->threadObj())); \ 161 } 162 163 #else // ndef DTRACE_ENABLED 164 165 #define DTRACE_THREAD_PROBE(probe, javathread) 166 167 #endif // ndef DTRACE_ENABLED 168 169 #ifndef USE_LIBRARY_BASED_TLS_ONLY 170 // Current thread is maintained as a thread-local variable 171 THREAD_LOCAL Thread* Thread::_thr_current = NULL; 172 #endif 173 174 // ======= Thread ======== 175 // Support for forcing alignment of thread objects for biased locking 176 void* Thread::allocate(size_t size, bool throw_excpt, MEMFLAGS flags) { 177 if (UseBiasedLocking) { 178 const size_t alignment = markWord::biased_lock_alignment; 179 size_t aligned_size = size + (alignment - sizeof(intptr_t)); 180 void* real_malloc_addr = throw_excpt? AllocateHeap(aligned_size, flags, CURRENT_PC) 181 : AllocateHeap(aligned_size, flags, CURRENT_PC, 182 AllocFailStrategy::RETURN_NULL); 183 void* aligned_addr = align_up(real_malloc_addr, alignment); 184 assert(((uintptr_t) aligned_addr + (uintptr_t) size) <= 185 ((uintptr_t) real_malloc_addr + (uintptr_t) aligned_size), 186 "JavaThread alignment code overflowed allocated storage"); 187 if (aligned_addr != real_malloc_addr) { 188 log_info(biasedlocking)("Aligned thread " INTPTR_FORMAT " to " INTPTR_FORMAT, 189 p2i(real_malloc_addr), 190 p2i(aligned_addr)); 191 } 192 ((Thread*) aligned_addr)->_real_malloc_address = real_malloc_addr; 193 return aligned_addr; 194 } else { 195 return throw_excpt? AllocateHeap(size, flags, CURRENT_PC) 196 : AllocateHeap(size, flags, CURRENT_PC, AllocFailStrategy::RETURN_NULL); 197 } 198 } 199 200 void Thread::operator delete(void* p) { 201 if (UseBiasedLocking) { 202 FreeHeap(((Thread*) p)->_real_malloc_address); 203 } else { 204 FreeHeap(p); 205 } 206 } 207 208 void JavaThread::smr_delete() { 209 if (_on_thread_list) { 210 ThreadsSMRSupport::smr_delete(this); 211 } else { 212 delete this; 213 } 214 } 215 216 // Base class for all threads: VMThread, WatcherThread, ConcurrentMarkSweepThread, 217 // JavaThread 218 219 DEBUG_ONLY(Thread* Thread::_starting_thread = NULL;) 220 221 Thread::Thread() { 222 223 DEBUG_ONLY(_run_state = PRE_CALL_RUN;) 224 225 // stack and get_thread 226 set_stack_base(NULL); 227 set_stack_size(0); 228 set_lgrp_id(-1); 229 DEBUG_ONLY(clear_suspendible_thread();) 230 231 // allocated data structures 232 set_osthread(NULL); 233 set_resource_area(new (mtThread)ResourceArea()); 234 DEBUG_ONLY(_current_resource_mark = NULL;) 235 set_handle_area(new (mtThread) HandleArea(NULL)); 236 set_metadata_handles(new (ResourceObj::C_HEAP, mtClass) GrowableArray<Metadata*>(30, true)); 237 set_active_handles(NULL); 238 set_free_handle_block(NULL); 239 set_last_handle_mark(NULL); 240 DEBUG_ONLY(_missed_ic_stub_refill_verifier = NULL); 241 242 // Initial value of zero ==> never claimed. 243 _threads_do_token = 0; 244 _threads_hazard_ptr = NULL; 245 _threads_list_ptr = NULL; 246 _nested_threads_hazard_ptr_cnt = 0; 247 _rcu_counter = 0; 248 249 // the handle mark links itself to last_handle_mark 250 new HandleMark(this); 251 252 // plain initialization 253 debug_only(_owned_locks = NULL;) 254 NOT_PRODUCT(_no_safepoint_count = 0;) 255 NOT_PRODUCT(_skip_gcalot = false;) 256 _jvmti_env_iteration_count = 0; 257 set_allocated_bytes(0); 258 _vm_operation_started_count = 0; 259 _vm_operation_completed_count = 0; 260 _current_pending_monitor = NULL; 261 _current_pending_monitor_is_from_java = true; 262 _current_waiting_monitor = NULL; 263 _current_pending_raw_monitor = NULL; 264 _num_nested_signal = 0; 265 om_free_list = NULL; 266 om_free_count = 0; 267 om_free_provision = 32; 268 om_in_use_list = NULL; 269 om_in_use_count = 0; 270 271 #ifdef ASSERT 272 _visited_for_critical_count = false; 273 #endif 274 275 _SR_lock = new Monitor(Mutex::suspend_resume, "SR_lock", true, 276 Monitor::_safepoint_check_sometimes); 277 _suspend_flags = 0; 278 279 // thread-specific hashCode stream generator state - Marsaglia shift-xor form 280 _hashStateX = os::random(); 281 _hashStateY = 842502087; 282 _hashStateZ = 0x8767; // (int)(3579807591LL & 0xffff) ; 283 _hashStateW = 273326509; 284 285 _OnTrap = 0; 286 _Stalled = 0; 287 _TypeTag = 0x2BAD; 288 289 // Many of the following fields are effectively final - immutable 290 // Note that nascent threads can't use the Native Monitor-Mutex 291 // construct until the _MutexEvent is initialized ... 292 // CONSIDER: instead of using a fixed set of purpose-dedicated ParkEvents 293 // we might instead use a stack of ParkEvents that we could provision on-demand. 294 // The stack would act as a cache to avoid calls to ParkEvent::Allocate() 295 // and ::Release() 296 _ParkEvent = ParkEvent::Allocate(this); 297 _MuxEvent = ParkEvent::Allocate(this); 298 299 #ifdef CHECK_UNHANDLED_OOPS 300 if (CheckUnhandledOops) { 301 _unhandled_oops = new UnhandledOops(this); 302 } 303 #endif // CHECK_UNHANDLED_OOPS 304 #ifdef ASSERT 305 if (UseBiasedLocking) { 306 assert(is_aligned(this, markWord::biased_lock_alignment), "forced alignment of thread object failed"); 307 assert(this == _real_malloc_address || 308 this == align_up(_real_malloc_address, markWord::biased_lock_alignment), 309 "bug in forced alignment of thread objects"); 310 } 311 #endif // ASSERT 312 313 // Notify the barrier set that a thread is being created. The initial 314 // thread is created before the barrier set is available. The call to 315 // BarrierSet::on_thread_create() for this thread is therefore deferred 316 // to BarrierSet::set_barrier_set(). 317 BarrierSet* const barrier_set = BarrierSet::barrier_set(); 318 if (barrier_set != NULL) { 319 barrier_set->on_thread_create(this); 320 } else { 321 // Only the main thread should be created before the barrier set 322 // and that happens just before Thread::current is set. No other thread 323 // can attach as the VM is not created yet, so they can't execute this code. 324 // If the main thread creates other threads before the barrier set that is an error. 325 assert(Thread::current_or_null() == NULL, "creating thread before barrier set"); 326 } 327 } 328 329 void Thread::initialize_thread_current() { 330 #ifndef USE_LIBRARY_BASED_TLS_ONLY 331 assert(_thr_current == NULL, "Thread::current already initialized"); 332 _thr_current = this; 333 #endif 334 assert(ThreadLocalStorage::thread() == NULL, "ThreadLocalStorage::thread already initialized"); 335 ThreadLocalStorage::set_thread(this); 336 assert(Thread::current() == ThreadLocalStorage::thread(), "TLS mismatch!"); 337 } 338 339 void Thread::clear_thread_current() { 340 assert(Thread::current() == ThreadLocalStorage::thread(), "TLS mismatch!"); 341 #ifndef USE_LIBRARY_BASED_TLS_ONLY 342 _thr_current = NULL; 343 #endif 344 ThreadLocalStorage::set_thread(NULL); 345 } 346 347 void Thread::record_stack_base_and_size() { 348 // Note: at this point, Thread object is not yet initialized. Do not rely on 349 // any members being initialized. Do not rely on Thread::current() being set. 350 // If possible, refrain from doing anything which may crash or assert since 351 // quite probably those crash dumps will be useless. 352 set_stack_base(os::current_stack_base()); 353 set_stack_size(os::current_stack_size()); 354 355 #ifdef SOLARIS 356 if (os::is_primordial_thread()) { 357 os::Solaris::correct_stack_boundaries_for_primordial_thread(this); 358 } 359 #endif 360 361 // Set stack limits after thread is initialized. 362 if (is_Java_thread()) { 363 ((JavaThread*) this)->set_stack_overflow_limit(); 364 ((JavaThread*) this)->set_reserved_stack_activation(stack_base()); 365 } 366 } 367 368 #if INCLUDE_NMT 369 void Thread::register_thread_stack_with_NMT() { 370 MemTracker::record_thread_stack(stack_end(), stack_size()); 371 } 372 #endif // INCLUDE_NMT 373 374 void Thread::call_run() { 375 DEBUG_ONLY(_run_state = CALL_RUN;) 376 377 // At this point, Thread object should be fully initialized and 378 // Thread::current() should be set. 379 380 assert(Thread::current_or_null() != NULL, "current thread is unset"); 381 assert(Thread::current_or_null() == this, "current thread is wrong"); 382 383 // Perform common initialization actions 384 385 register_thread_stack_with_NMT(); 386 387 JFR_ONLY(Jfr::on_thread_start(this);) 388 389 log_debug(os, thread)("Thread " UINTX_FORMAT " stack dimensions: " 390 PTR_FORMAT "-" PTR_FORMAT " (" SIZE_FORMAT "k).", 391 os::current_thread_id(), p2i(stack_base() - stack_size()), 392 p2i(stack_base()), stack_size()/1024); 393 394 // Perform <ChildClass> initialization actions 395 DEBUG_ONLY(_run_state = PRE_RUN;) 396 this->pre_run(); 397 398 // Invoke <ChildClass>::run() 399 DEBUG_ONLY(_run_state = RUN;) 400 this->run(); 401 // Returned from <ChildClass>::run(). Thread finished. 402 403 // Perform common tear-down actions 404 405 assert(Thread::current_or_null() != NULL, "current thread is unset"); 406 assert(Thread::current_or_null() == this, "current thread is wrong"); 407 408 // Perform <ChildClass> tear-down actions 409 DEBUG_ONLY(_run_state = POST_RUN;) 410 this->post_run(); 411 412 // Note: at this point the thread object may already have deleted itself, 413 // so from here on do not dereference *this*. Not all thread types currently 414 // delete themselves when they terminate. But no thread should ever be deleted 415 // asynchronously with respect to its termination - that is what _run_state can 416 // be used to check. 417 418 assert(Thread::current_or_null() == NULL, "current thread still present"); 419 } 420 421 Thread::~Thread() { 422 423 // Attached threads will remain in PRE_CALL_RUN, as will threads that don't actually 424 // get started due to errors etc. Any active thread should at least reach post_run 425 // before it is deleted (usually in post_run()). 426 assert(_run_state == PRE_CALL_RUN || 427 _run_state == POST_RUN, "Active Thread deleted before post_run(): " 428 "_run_state=%d", (int)_run_state); 429 430 // Notify the barrier set that a thread is being destroyed. Note that a barrier 431 // set might not be available if we encountered errors during bootstrapping. 432 BarrierSet* const barrier_set = BarrierSet::barrier_set(); 433 if (barrier_set != NULL) { 434 barrier_set->on_thread_destroy(this); 435 } 436 437 // stack_base can be NULL if the thread is never started or exited before 438 // record_stack_base_and_size called. Although, we would like to ensure 439 // that all started threads do call record_stack_base_and_size(), there is 440 // not proper way to enforce that. 441 #if INCLUDE_NMT 442 if (_stack_base != NULL) { 443 MemTracker::release_thread_stack(stack_end(), stack_size()); 444 #ifdef ASSERT 445 set_stack_base(NULL); 446 #endif 447 } 448 #endif // INCLUDE_NMT 449 450 // deallocate data structures 451 delete resource_area(); 452 // since the handle marks are using the handle area, we have to deallocated the root 453 // handle mark before deallocating the thread's handle area, 454 assert(last_handle_mark() != NULL, "check we have an element"); 455 delete last_handle_mark(); 456 assert(last_handle_mark() == NULL, "check we have reached the end"); 457 458 // It's possible we can encounter a null _ParkEvent, etc., in stillborn threads. 459 // We NULL out the fields for good hygiene. 460 ParkEvent::Release(_ParkEvent); _ParkEvent = NULL; 461 ParkEvent::Release(_MuxEvent); _MuxEvent = NULL; 462 463 delete handle_area(); 464 delete metadata_handles(); 465 466 // SR_handler uses this as a termination indicator - 467 // needs to happen before os::free_thread() 468 delete _SR_lock; 469 _SR_lock = NULL; 470 471 // osthread() can be NULL, if creation of thread failed. 472 if (osthread() != NULL) os::free_thread(osthread()); 473 474 // Clear Thread::current if thread is deleting itself and it has not 475 // already been done. This must be done before the memory is deallocated. 476 // Needed to ensure JNI correctly detects non-attached threads. 477 if (this == Thread::current_or_null()) { 478 Thread::clear_thread_current(); 479 } 480 481 CHECK_UNHANDLED_OOPS_ONLY(if (CheckUnhandledOops) delete unhandled_oops();) 482 } 483 484 #ifdef ASSERT 485 // A JavaThread is considered "dangling" if it is not the current 486 // thread, has been added the Threads list, the system is not at a 487 // safepoint and the Thread is not "protected". 488 // 489 void Thread::check_for_dangling_thread_pointer(Thread *thread) { 490 assert(!thread->is_Java_thread() || Thread::current() == thread || 491 !((JavaThread *) thread)->on_thread_list() || 492 SafepointSynchronize::is_at_safepoint() || 493 ThreadsSMRSupport::is_a_protected_JavaThread_with_lock((JavaThread *) thread), 494 "possibility of dangling Thread pointer"); 495 } 496 #endif 497 498 ThreadPriority Thread::get_priority(const Thread* const thread) { 499 ThreadPriority priority; 500 // Can return an error! 501 (void)os::get_priority(thread, priority); 502 assert(MinPriority <= priority && priority <= MaxPriority, "non-Java priority found"); 503 return priority; 504 } 505 506 void Thread::set_priority(Thread* thread, ThreadPriority priority) { 507 debug_only(check_for_dangling_thread_pointer(thread);) 508 // Can return an error! 509 (void)os::set_priority(thread, priority); 510 } 511 512 513 void Thread::start(Thread* thread) { 514 // Start is different from resume in that its safety is guaranteed by context or 515 // being called from a Java method synchronized on the Thread object. 516 if (!DisableStartThread) { 517 if (thread->is_Java_thread()) { 518 // Initialize the thread state to RUNNABLE before starting this thread. 519 // Can not set it after the thread started because we do not know the 520 // exact thread state at that time. It could be in MONITOR_WAIT or 521 // in SLEEPING or some other state. 522 java_lang_Thread::set_thread_status(((JavaThread*)thread)->threadObj(), 523 java_lang_Thread::RUNNABLE); 524 } 525 os::start_thread(thread); 526 } 527 } 528 529 class InstallAsyncExceptionClosure : public HandshakeClosure { 530 Handle _throwable; // The Throwable thrown at the target Thread 531 public: 532 InstallAsyncExceptionClosure(Handle throwable) : HandshakeClosure("InstallAsyncException"), _throwable(throwable) {} 533 534 void do_thread(Thread* thr) { 535 JavaThread* target = (JavaThread*)thr; 536 // Note that this now allows multiple ThreadDeath exceptions to be 537 // thrown at a thread. 538 // The target thread has run and has not exited yet. 539 target->send_thread_stop(_throwable()); 540 } 541 }; 542 543 void Thread::send_async_exception(oop java_thread, oop java_throwable) { 544 Handle throwable(Thread::current(), java_throwable); 545 JavaThread* target = java_lang_Thread::thread(java_thread); 546 InstallAsyncExceptionClosure vm_stop(throwable); 547 Handshake::execute(&vm_stop, target); 548 } 549 550 551 // Check if an external suspend request has completed (or has been 552 // cancelled). Returns true if the thread is externally suspended and 553 // false otherwise. 554 // 555 // The bits parameter returns information about the code path through 556 // the routine. Useful for debugging: 557 // 558 // set in is_ext_suspend_completed(): 559 // 0x00000001 - routine was entered 560 // 0x00000010 - routine return false at end 561 // 0x00000100 - thread exited (return false) 562 // 0x00000200 - suspend request cancelled (return false) 563 // 0x00000400 - thread suspended (return true) 564 // 0x00001000 - thread is in a suspend equivalent state (return true) 565 // 0x00002000 - thread is native and walkable (return true) 566 // 0x00004000 - thread is native_trans and walkable (needed retry) 567 // 568 // set in wait_for_ext_suspend_completion(): 569 // 0x00010000 - routine was entered 570 // 0x00020000 - suspend request cancelled before loop (return false) 571 // 0x00040000 - thread suspended before loop (return true) 572 // 0x00080000 - suspend request cancelled in loop (return false) 573 // 0x00100000 - thread suspended in loop (return true) 574 // 0x00200000 - suspend not completed during retry loop (return false) 575 576 // Helper class for tracing suspend wait debug bits. 577 // 578 // 0x00000100 indicates that the target thread exited before it could 579 // self-suspend which is not a wait failure. 0x00000200, 0x00020000 and 580 // 0x00080000 each indicate a cancelled suspend request so they don't 581 // count as wait failures either. 582 #define DEBUG_FALSE_BITS (0x00000010 | 0x00200000) 583 584 class TraceSuspendDebugBits : public StackObj { 585 private: 586 JavaThread * jt; 587 bool is_wait; 588 bool called_by_wait; // meaningful when !is_wait 589 uint32_t * bits; 590 591 public: 592 TraceSuspendDebugBits(JavaThread *_jt, bool _is_wait, bool _called_by_wait, 593 uint32_t *_bits) { 594 jt = _jt; 595 is_wait = _is_wait; 596 called_by_wait = _called_by_wait; 597 bits = _bits; 598 } 599 600 ~TraceSuspendDebugBits() { 601 if (!is_wait) { 602 #if 1 603 // By default, don't trace bits for is_ext_suspend_completed() calls. 604 // That trace is very chatty. 605 return; 606 #else 607 if (!called_by_wait) { 608 // If tracing for is_ext_suspend_completed() is enabled, then only 609 // trace calls to it from wait_for_ext_suspend_completion() 610 return; 611 } 612 #endif 613 } 614 615 if (AssertOnSuspendWaitFailure || TraceSuspendWaitFailures) { 616 if (bits != NULL && (*bits & DEBUG_FALSE_BITS) != 0) { 617 MutexLocker ml(Threads_lock); // needed for get_thread_name() 618 ResourceMark rm; 619 620 tty->print_cr( 621 "Failed wait_for_ext_suspend_completion(thread=%s, debug_bits=%x)", 622 jt->get_thread_name(), *bits); 623 624 guarantee(!AssertOnSuspendWaitFailure, "external suspend wait failed"); 625 } 626 } 627 } 628 }; 629 #undef DEBUG_FALSE_BITS 630 631 632 bool JavaThread::is_ext_suspend_completed(bool called_by_wait, int delay, 633 uint32_t *bits) { 634 TraceSuspendDebugBits tsdb(this, false /* !is_wait */, called_by_wait, bits); 635 636 bool did_trans_retry = false; // only do thread_in_native_trans retry once 637 bool do_trans_retry; // flag to force the retry 638 639 *bits |= 0x00000001; 640 641 do { 642 do_trans_retry = false; 643 644 if (is_exiting()) { 645 // Thread is in the process of exiting. This is always checked 646 // first to reduce the risk of dereferencing a freed JavaThread. 647 *bits |= 0x00000100; 648 return false; 649 } 650 651 if (!is_external_suspend()) { 652 // Suspend request is cancelled. This is always checked before 653 // is_ext_suspended() to reduce the risk of a rogue resume 654 // confusing the thread that made the suspend request. 655 *bits |= 0x00000200; 656 return false; 657 } 658 659 if (is_ext_suspended()) { 660 // thread is suspended 661 *bits |= 0x00000400; 662 return true; 663 } 664 665 // Now that we no longer do hard suspends of threads running 666 // native code, the target thread can be changing thread state 667 // while we are in this routine: 668 // 669 // _thread_in_native -> _thread_in_native_trans -> _thread_blocked 670 // 671 // We save a copy of the thread state as observed at this moment 672 // and make our decision about suspend completeness based on the 673 // copy. This closes the race where the thread state is seen as 674 // _thread_in_native_trans in the if-thread_blocked check, but is 675 // seen as _thread_blocked in if-thread_in_native_trans check. 676 JavaThreadState save_state = thread_state(); 677 678 if (save_state == _thread_blocked && is_suspend_equivalent()) { 679 // If the thread's state is _thread_blocked and this blocking 680 // condition is known to be equivalent to a suspend, then we can 681 // consider the thread to be externally suspended. This means that 682 // the code that sets _thread_blocked has been modified to do 683 // self-suspension if the blocking condition releases. We also 684 // used to check for CONDVAR_WAIT here, but that is now covered by 685 // the _thread_blocked with self-suspension check. 686 // 687 // Return true since we wouldn't be here unless there was still an 688 // external suspend request. 689 *bits |= 0x00001000; 690 return true; 691 } else if (save_state == _thread_in_native && frame_anchor()->walkable()) { 692 // Threads running native code will self-suspend on native==>VM/Java 693 // transitions. If its stack is walkable (should always be the case 694 // unless this function is called before the actual java_suspend() 695 // call), then the wait is done. 696 *bits |= 0x00002000; 697 return true; 698 } else if (!called_by_wait && !did_trans_retry && 699 save_state == _thread_in_native_trans && 700 frame_anchor()->walkable()) { 701 // The thread is transitioning from thread_in_native to another 702 // thread state. check_safepoint_and_suspend_for_native_trans() 703 // will force the thread to self-suspend. If it hasn't gotten 704 // there yet we may have caught the thread in-between the native 705 // code check above and the self-suspend. Lucky us. If we were 706 // called by wait_for_ext_suspend_completion(), then it 707 // will be doing the retries so we don't have to. 708 // 709 // Since we use the saved thread state in the if-statement above, 710 // there is a chance that the thread has already transitioned to 711 // _thread_blocked by the time we get here. In that case, we will 712 // make a single unnecessary pass through the logic below. This 713 // doesn't hurt anything since we still do the trans retry. 714 715 *bits |= 0x00004000; 716 717 // Once the thread leaves thread_in_native_trans for another 718 // thread state, we break out of this retry loop. We shouldn't 719 // need this flag to prevent us from getting back here, but 720 // sometimes paranoia is good. 721 did_trans_retry = true; 722 723 // We wait for the thread to transition to a more usable state. 724 for (int i = 1; i <= SuspendRetryCount; i++) { 725 // We used to do an "os::yield_all(i)" call here with the intention 726 // that yielding would increase on each retry. However, the parameter 727 // is ignored on Linux which means the yield didn't scale up. Waiting 728 // on the SR_lock below provides a much more predictable scale up for 729 // the delay. It also provides a simple/direct point to check for any 730 // safepoint requests from the VMThread 731 732 // temporarily drops SR_lock while doing wait with safepoint check 733 // (if we're a JavaThread - the WatcherThread can also call this) 734 // and increase delay with each retry 735 if (Thread::current()->is_Java_thread()) { 736 SR_lock()->wait(i * delay); 737 } else { 738 SR_lock()->wait_without_safepoint_check(i * delay); 739 } 740 741 // check the actual thread state instead of what we saved above 742 if (thread_state() != _thread_in_native_trans) { 743 // the thread has transitioned to another thread state so 744 // try all the checks (except this one) one more time. 745 do_trans_retry = true; 746 break; 747 } 748 } // end retry loop 749 750 751 } 752 } while (do_trans_retry); 753 754 *bits |= 0x00000010; 755 return false; 756 } 757 758 // Wait for an external suspend request to complete (or be cancelled). 759 // Returns true if the thread is externally suspended and false otherwise. 760 // 761 bool JavaThread::wait_for_ext_suspend_completion(int retries, int delay, 762 uint32_t *bits) { 763 TraceSuspendDebugBits tsdb(this, true /* is_wait */, 764 false /* !called_by_wait */, bits); 765 766 // local flag copies to minimize SR_lock hold time 767 bool is_suspended; 768 bool pending; 769 uint32_t reset_bits; 770 771 // set a marker so is_ext_suspend_completed() knows we are the caller 772 *bits |= 0x00010000; 773 774 // We use reset_bits to reinitialize the bits value at the top of 775 // each retry loop. This allows the caller to make use of any 776 // unused bits for their own marking purposes. 777 reset_bits = *bits; 778 779 { 780 MutexLocker ml(SR_lock(), Mutex::_no_safepoint_check_flag); 781 is_suspended = is_ext_suspend_completed(true /* called_by_wait */, 782 delay, bits); 783 pending = is_external_suspend(); 784 } 785 // must release SR_lock to allow suspension to complete 786 787 if (!pending) { 788 // A cancelled suspend request is the only false return from 789 // is_ext_suspend_completed() that keeps us from entering the 790 // retry loop. 791 *bits |= 0x00020000; 792 return false; 793 } 794 795 if (is_suspended) { 796 *bits |= 0x00040000; 797 return true; 798 } 799 800 for (int i = 1; i <= retries; i++) { 801 *bits = reset_bits; // reinit to only track last retry 802 803 // We used to do an "os::yield_all(i)" call here with the intention 804 // that yielding would increase on each retry. However, the parameter 805 // is ignored on Linux which means the yield didn't scale up. Waiting 806 // on the SR_lock below provides a much more predictable scale up for 807 // the delay. It also provides a simple/direct point to check for any 808 // safepoint requests from the VMThread 809 810 { 811 Thread* t = Thread::current(); 812 MonitorLocker ml(SR_lock(), 813 t->is_Java_thread() ? Mutex::_safepoint_check_flag : Mutex::_no_safepoint_check_flag); 814 // wait with safepoint check (if we're a JavaThread - the WatcherThread 815 // can also call this) and increase delay with each retry 816 ml.wait(i * delay); 817 818 is_suspended = is_ext_suspend_completed(true /* called_by_wait */, 819 delay, bits); 820 821 // It is possible for the external suspend request to be cancelled 822 // (by a resume) before the actual suspend operation is completed. 823 // Refresh our local copy to see if we still need to wait. 824 pending = is_external_suspend(); 825 } 826 827 if (!pending) { 828 // A cancelled suspend request is the only false return from 829 // is_ext_suspend_completed() that keeps us from staying in the 830 // retry loop. 831 *bits |= 0x00080000; 832 return false; 833 } 834 835 if (is_suspended) { 836 *bits |= 0x00100000; 837 return true; 838 } 839 } // end retry loop 840 841 // thread did not suspend after all our retries 842 *bits |= 0x00200000; 843 return false; 844 } 845 846 // Called from API entry points which perform stack walking. If the 847 // associated JavaThread is the current thread, then wait_for_suspend 848 // is not used. Otherwise, it determines if we should wait for the 849 // "other" thread to complete external suspension. (NOTE: in future 850 // releases the suspension mechanism should be reimplemented so this 851 // is not necessary.) 852 // 853 bool 854 JavaThread::is_thread_fully_suspended(bool wait_for_suspend, uint32_t *bits) { 855 if (this != JavaThread::current()) { 856 // "other" threads require special handling. 857 if (wait_for_suspend) { 858 // We are allowed to wait for the external suspend to complete 859 // so give the other thread a chance to get suspended. 860 if (!wait_for_ext_suspend_completion(SuspendRetryCount, 861 SuspendRetryDelay, bits)) { 862 // Didn't make it so let the caller know. 863 return false; 864 } 865 } 866 // We aren't allowed to wait for the external suspend to complete 867 // so if the other thread isn't externally suspended we need to 868 // let the caller know. 869 else if (!is_ext_suspend_completed_with_lock(bits)) { 870 return false; 871 } 872 } 873 874 return true; 875 } 876 877 // GC Support 878 bool Thread::claim_par_threads_do(uintx claim_token) { 879 uintx token = _threads_do_token; 880 if (token != claim_token) { 881 uintx res = Atomic::cmpxchg(&_threads_do_token, token, claim_token); 882 if (res == token) { 883 return true; 884 } 885 guarantee(res == claim_token, "invariant"); 886 } 887 return false; 888 } 889 890 void Thread::oops_do(OopClosure* f, CodeBlobClosure* cf) { 891 active_handles()->oops_do(f); 892 // Do oop for ThreadShadow 893 f->do_oop((oop*)&_pending_exception); 894 handle_area()->oops_do(f); 895 896 // We scan thread local monitor lists here, and the remaining global 897 // monitors in ObjectSynchronizer::oops_do(). 898 ObjectSynchronizer::thread_local_used_oops_do(this, f); 899 } 900 901 void Thread::metadata_handles_do(void f(Metadata*)) { 902 // Only walk the Handles in Thread. 903 if (metadata_handles() != NULL) { 904 for (int i = 0; i< metadata_handles()->length(); i++) { 905 f(metadata_handles()->at(i)); 906 } 907 } 908 } 909 910 void Thread::print_on(outputStream* st, bool print_extended_info) const { 911 // get_priority assumes osthread initialized 912 if (osthread() != NULL) { 913 int os_prio; 914 if (os::get_native_priority(this, &os_prio) == OS_OK) { 915 st->print("os_prio=%d ", os_prio); 916 } 917 918 st->print("cpu=%.2fms ", 919 os::thread_cpu_time(const_cast<Thread*>(this), true) / 1000000.0 920 ); 921 st->print("elapsed=%.2fs ", 922 _statistical_info.getElapsedTime() / 1000.0 923 ); 924 if (is_Java_thread() && (PrintExtendedThreadInfo || print_extended_info)) { 925 size_t allocated_bytes = (size_t) const_cast<Thread*>(this)->cooked_allocated_bytes(); 926 st->print("allocated=" SIZE_FORMAT "%s ", 927 byte_size_in_proper_unit(allocated_bytes), 928 proper_unit_for_byte_size(allocated_bytes) 929 ); 930 st->print("defined_classes=" INT64_FORMAT " ", _statistical_info.getDefineClassCount()); 931 } 932 933 st->print("tid=" INTPTR_FORMAT " ", p2i(this)); 934 osthread()->print_on(st); 935 } 936 ThreadsSMRSupport::print_info_on(this, st); 937 st->print(" "); 938 debug_only(if (WizardMode) print_owned_locks_on(st);) 939 } 940 941 void Thread::print() const { print_on(tty); } 942 943 // Thread::print_on_error() is called by fatal error handler. Don't use 944 // any lock or allocate memory. 945 void Thread::print_on_error(outputStream* st, char* buf, int buflen) const { 946 assert(!(is_Compiler_thread() || is_Java_thread()), "Can't call name() here if it allocates"); 947 948 if (is_VM_thread()) { st->print("VMThread"); } 949 else if (is_GC_task_thread()) { st->print("GCTaskThread"); } 950 else if (is_Watcher_thread()) { st->print("WatcherThread"); } 951 else if (is_ConcurrentGC_thread()) { st->print("ConcurrentGCThread"); } 952 else { st->print("Thread"); } 953 954 if (is_Named_thread()) { 955 st->print(" \"%s\"", name()); 956 } 957 958 st->print(" [stack: " PTR_FORMAT "," PTR_FORMAT "]", 959 p2i(stack_end()), p2i(stack_base())); 960 961 if (osthread()) { 962 st->print(" [id=%d]", osthread()->thread_id()); 963 } 964 965 ThreadsSMRSupport::print_info_on(this, st); 966 } 967 968 void Thread::print_value_on(outputStream* st) const { 969 if (is_Named_thread()) { 970 st->print(" \"%s\" ", name()); 971 } 972 st->print(INTPTR_FORMAT, p2i(this)); // print address 973 } 974 975 #ifdef ASSERT 976 void Thread::print_owned_locks_on(outputStream* st) const { 977 Mutex* cur = _owned_locks; 978 if (cur == NULL) { 979 st->print(" (no locks) "); 980 } else { 981 st->print_cr(" Locks owned:"); 982 while (cur) { 983 cur->print_on(st); 984 cur = cur->next(); 985 } 986 } 987 } 988 989 // Checks safepoint allowed and clears unhandled oops at potential safepoints. 990 void Thread::check_possible_safepoint() { 991 if (!is_Java_thread()) return; 992 993 if (_no_safepoint_count > 0) { 994 print_owned_locks(); 995 fatal("Possible safepoint reached by thread that does not allow it"); 996 } 997 #ifdef CHECK_UNHANDLED_OOPS 998 // Clear unhandled oops in JavaThreads so we get a crash right away. 999 clear_unhandled_oops(); 1000 #endif // CHECK_UNHANDLED_OOPS 1001 } 1002 1003 void Thread::check_for_valid_safepoint_state() { 1004 if (!is_Java_thread()) return; 1005 1006 // Check NoSafepointVerifier, which is implied by locks taken that can be 1007 // shared with the VM thread. This makes sure that no locks with allow_vm_block 1008 // are held. 1009 check_possible_safepoint(); 1010 1011 if (((JavaThread*)this)->thread_state() != _thread_in_vm) { 1012 fatal("LEAF method calling lock?"); 1013 } 1014 1015 if (GCALotAtAllSafepoints) { 1016 // We could enter a safepoint here and thus have a gc 1017 InterfaceSupport::check_gc_alot(); 1018 } 1019 } 1020 #endif // ASSERT 1021 1022 bool Thread::is_in_stack(address adr) const { 1023 assert(Thread::current() == this, "is_in_stack can only be called from current thread"); 1024 address end = os::current_stack_pointer(); 1025 // Allow non Java threads to call this without stack_base 1026 if (_stack_base == NULL) return true; 1027 if (stack_base() > adr && adr >= end) return true; 1028 1029 return false; 1030 } 1031 1032 bool Thread::is_in_usable_stack(address adr) const { 1033 size_t stack_guard_size = os::uses_stack_guard_pages() ? JavaThread::stack_guard_zone_size() : 0; 1034 size_t usable_stack_size = _stack_size - stack_guard_size; 1035 1036 return ((adr < stack_base()) && (adr >= stack_base() - usable_stack_size)); 1037 } 1038 1039 1040 // We had to move these methods here, because vm threads get into ObjectSynchronizer::enter 1041 // However, there is a note in JavaThread::is_lock_owned() about the VM threads not being 1042 // used for compilation in the future. If that change is made, the need for these methods 1043 // should be revisited, and they should be removed if possible. 1044 1045 bool Thread::is_lock_owned(address adr) const { 1046 return on_local_stack(adr); 1047 } 1048 1049 bool Thread::set_as_starting_thread() { 1050 assert(_starting_thread == NULL, "already initialized: " 1051 "_starting_thread=" INTPTR_FORMAT, p2i(_starting_thread)); 1052 // NOTE: this must be called inside the main thread. 1053 DEBUG_ONLY(_starting_thread = this;) 1054 return os::create_main_thread((JavaThread*)this); 1055 } 1056 1057 static void initialize_class(Symbol* class_name, TRAPS) { 1058 Klass* klass = SystemDictionary::resolve_or_fail(class_name, true, CHECK); 1059 InstanceKlass::cast(klass)->initialize(CHECK); 1060 } 1061 1062 1063 // Creates the initial ThreadGroup 1064 static Handle create_initial_thread_group(TRAPS) { 1065 Handle system_instance = JavaCalls::construct_new_instance( 1066 SystemDictionary::ThreadGroup_klass(), 1067 vmSymbols::void_method_signature(), 1068 CHECK_NH); 1069 Universe::set_system_thread_group(system_instance()); 1070 1071 Handle string = java_lang_String::create_from_str("main", CHECK_NH); 1072 Handle main_instance = JavaCalls::construct_new_instance( 1073 SystemDictionary::ThreadGroup_klass(), 1074 vmSymbols::threadgroup_string_void_signature(), 1075 system_instance, 1076 string, 1077 CHECK_NH); 1078 return main_instance; 1079 } 1080 1081 // Creates the initial Thread 1082 static oop create_initial_thread(Handle thread_group, JavaThread* thread, 1083 TRAPS) { 1084 InstanceKlass* ik = SystemDictionary::Thread_klass(); 1085 assert(ik->is_initialized(), "must be"); 1086 instanceHandle thread_oop = ik->allocate_instance_handle(CHECK_NULL); 1087 1088 // Cannot use JavaCalls::construct_new_instance because the java.lang.Thread 1089 // constructor calls Thread.current(), which must be set here for the 1090 // initial thread. 1091 java_lang_Thread::set_thread(thread_oop(), thread); 1092 java_lang_Thread::set_priority(thread_oop(), NormPriority); 1093 thread->set_threadObj(thread_oop()); 1094 1095 Handle string = java_lang_String::create_from_str("main", CHECK_NULL); 1096 1097 JavaValue result(T_VOID); 1098 JavaCalls::call_special(&result, thread_oop, 1099 ik, 1100 vmSymbols::object_initializer_name(), 1101 vmSymbols::threadgroup_string_void_signature(), 1102 thread_group, 1103 string, 1104 CHECK_NULL); 1105 return thread_oop(); 1106 } 1107 1108 char java_runtime_name[128] = ""; 1109 char java_runtime_version[128] = ""; 1110 char java_runtime_vendor_version[128] = ""; 1111 char java_runtime_vendor_vm_bug_url[128] = ""; 1112 1113 // extract the JRE name from java.lang.VersionProps.java_runtime_name 1114 static const char* get_java_runtime_name(TRAPS) { 1115 Klass* k = SystemDictionary::find(vmSymbols::java_lang_VersionProps(), 1116 Handle(), Handle(), CHECK_AND_CLEAR_NULL); 1117 fieldDescriptor fd; 1118 bool found = k != NULL && 1119 InstanceKlass::cast(k)->find_local_field(vmSymbols::java_runtime_name_name(), 1120 vmSymbols::string_signature(), &fd); 1121 if (found) { 1122 oop name_oop = k->java_mirror()->obj_field(fd.offset()); 1123 if (name_oop == NULL) { 1124 return NULL; 1125 } 1126 const char* name = java_lang_String::as_utf8_string(name_oop, 1127 java_runtime_name, 1128 sizeof(java_runtime_name)); 1129 return name; 1130 } else { 1131 return NULL; 1132 } 1133 } 1134 1135 // extract the JRE version from java.lang.VersionProps.java_runtime_version 1136 static const char* get_java_runtime_version(TRAPS) { 1137 Klass* k = SystemDictionary::find(vmSymbols::java_lang_VersionProps(), 1138 Handle(), Handle(), CHECK_AND_CLEAR_NULL); 1139 fieldDescriptor fd; 1140 bool found = k != NULL && 1141 InstanceKlass::cast(k)->find_local_field(vmSymbols::java_runtime_version_name(), 1142 vmSymbols::string_signature(), &fd); 1143 if (found) { 1144 oop name_oop = k->java_mirror()->obj_field(fd.offset()); 1145 if (name_oop == NULL) { 1146 return NULL; 1147 } 1148 const char* name = java_lang_String::as_utf8_string(name_oop, 1149 java_runtime_version, 1150 sizeof(java_runtime_version)); 1151 return name; 1152 } else { 1153 return NULL; 1154 } 1155 } 1156 1157 // extract the JRE vendor version from java.lang.VersionProps.VENDOR_VERSION 1158 static const char* get_java_runtime_vendor_version(TRAPS) { 1159 Klass* k = SystemDictionary::find(vmSymbols::java_lang_VersionProps(), 1160 Handle(), Handle(), CHECK_AND_CLEAR_NULL); 1161 fieldDescriptor fd; 1162 bool found = k != NULL && 1163 InstanceKlass::cast(k)->find_local_field(vmSymbols::java_runtime_vendor_version_name(), 1164 vmSymbols::string_signature(), &fd); 1165 if (found) { 1166 oop name_oop = k->java_mirror()->obj_field(fd.offset()); 1167 if (name_oop == NULL) { 1168 return NULL; 1169 } 1170 const char* name = java_lang_String::as_utf8_string(name_oop, 1171 java_runtime_vendor_version, 1172 sizeof(java_runtime_vendor_version)); 1173 return name; 1174 } else { 1175 return NULL; 1176 } 1177 } 1178 1179 // extract the JRE vendor VM bug URL from java.lang.VersionProps.VENDOR_URL_VM_BUG 1180 static const char* get_java_runtime_vendor_vm_bug_url(TRAPS) { 1181 Klass* k = SystemDictionary::find(vmSymbols::java_lang_VersionProps(), 1182 Handle(), Handle(), CHECK_AND_CLEAR_NULL); 1183 fieldDescriptor fd; 1184 bool found = k != NULL && 1185 InstanceKlass::cast(k)->find_local_field(vmSymbols::java_runtime_vendor_vm_bug_url_name(), 1186 vmSymbols::string_signature(), &fd); 1187 if (found) { 1188 oop name_oop = k->java_mirror()->obj_field(fd.offset()); 1189 if (name_oop == NULL) { 1190 return NULL; 1191 } 1192 const char* name = java_lang_String::as_utf8_string(name_oop, 1193 java_runtime_vendor_vm_bug_url, 1194 sizeof(java_runtime_vendor_vm_bug_url)); 1195 return name; 1196 } else { 1197 return NULL; 1198 } 1199 } 1200 1201 // General purpose hook into Java code, run once when the VM is initialized. 1202 // The Java library method itself may be changed independently from the VM. 1203 static void call_postVMInitHook(TRAPS) { 1204 Klass* klass = SystemDictionary::resolve_or_null(vmSymbols::jdk_internal_vm_PostVMInitHook(), THREAD); 1205 if (klass != NULL) { 1206 JavaValue result(T_VOID); 1207 JavaCalls::call_static(&result, klass, vmSymbols::run_method_name(), 1208 vmSymbols::void_method_signature(), 1209 CHECK); 1210 } 1211 } 1212 1213 void JavaThread::allocate_threadObj(Handle thread_group, const char* thread_name, 1214 bool daemon, TRAPS) { 1215 assert(thread_group.not_null(), "thread group should be specified"); 1216 assert(threadObj() == NULL, "should only create Java thread object once"); 1217 1218 InstanceKlass* ik = SystemDictionary::Thread_klass(); 1219 assert(ik->is_initialized(), "must be"); 1220 instanceHandle thread_oop = ik->allocate_instance_handle(CHECK); 1221 1222 // We are called from jni_AttachCurrentThread/jni_AttachCurrentThreadAsDaemon. 1223 // We cannot use JavaCalls::construct_new_instance because the java.lang.Thread 1224 // constructor calls Thread.current(), which must be set here. 1225 java_lang_Thread::set_thread(thread_oop(), this); 1226 java_lang_Thread::set_priority(thread_oop(), NormPriority); 1227 set_threadObj(thread_oop()); 1228 1229 JavaValue result(T_VOID); 1230 if (thread_name != NULL) { 1231 Handle name = java_lang_String::create_from_str(thread_name, CHECK); 1232 // Thread gets assigned specified name and null target 1233 JavaCalls::call_special(&result, 1234 thread_oop, 1235 ik, 1236 vmSymbols::object_initializer_name(), 1237 vmSymbols::threadgroup_string_void_signature(), 1238 thread_group, 1239 name, 1240 THREAD); 1241 } else { 1242 // Thread gets assigned name "Thread-nnn" and null target 1243 // (java.lang.Thread doesn't have a constructor taking only a ThreadGroup argument) 1244 JavaCalls::call_special(&result, 1245 thread_oop, 1246 ik, 1247 vmSymbols::object_initializer_name(), 1248 vmSymbols::threadgroup_runnable_void_signature(), 1249 thread_group, 1250 Handle(), 1251 THREAD); 1252 } 1253 1254 1255 if (daemon) { 1256 java_lang_Thread::set_daemon(thread_oop()); 1257 } 1258 1259 if (HAS_PENDING_EXCEPTION) { 1260 return; 1261 } 1262 1263 Klass* group = SystemDictionary::ThreadGroup_klass(); 1264 Handle threadObj(THREAD, this->threadObj()); 1265 1266 JavaCalls::call_special(&result, 1267 thread_group, 1268 group, 1269 vmSymbols::add_method_name(), 1270 vmSymbols::thread_void_signature(), 1271 threadObj, // Arg 1 1272 THREAD); 1273 } 1274 1275 // List of all NonJavaThreads and safe iteration over that list. 1276 1277 class NonJavaThread::List { 1278 public: 1279 NonJavaThread* volatile _head; 1280 SingleWriterSynchronizer _protect; 1281 1282 List() : _head(NULL), _protect() {} 1283 }; 1284 1285 NonJavaThread::List NonJavaThread::_the_list; 1286 1287 NonJavaThread::Iterator::Iterator() : 1288 _protect_enter(_the_list._protect.enter()), 1289 _current(Atomic::load_acquire(&_the_list._head)) 1290 {} 1291 1292 NonJavaThread::Iterator::~Iterator() { 1293 _the_list._protect.exit(_protect_enter); 1294 } 1295 1296 void NonJavaThread::Iterator::step() { 1297 assert(!end(), "precondition"); 1298 _current = Atomic::load_acquire(&_current->_next); 1299 } 1300 1301 NonJavaThread::NonJavaThread() : Thread(), _next(NULL) { 1302 assert(BarrierSet::barrier_set() != NULL, "NonJavaThread created too soon!"); 1303 } 1304 1305 NonJavaThread::~NonJavaThread() { } 1306 1307 void NonJavaThread::add_to_the_list() { 1308 MutexLocker ml(NonJavaThreadsList_lock, Mutex::_no_safepoint_check_flag); 1309 // Initialize BarrierSet-related data before adding to list. 1310 BarrierSet::barrier_set()->on_thread_attach(this); 1311 Atomic::release_store(&_next, _the_list._head); 1312 Atomic::release_store(&_the_list._head, this); 1313 } 1314 1315 void NonJavaThread::remove_from_the_list() { 1316 { 1317 MutexLocker ml(NonJavaThreadsList_lock, Mutex::_no_safepoint_check_flag); 1318 // Cleanup BarrierSet-related data before removing from list. 1319 BarrierSet::barrier_set()->on_thread_detach(this); 1320 NonJavaThread* volatile* p = &_the_list._head; 1321 for (NonJavaThread* t = *p; t != NULL; p = &t->_next, t = *p) { 1322 if (t == this) { 1323 *p = _next; 1324 break; 1325 } 1326 } 1327 } 1328 // Wait for any in-progress iterators. Concurrent synchronize is not 1329 // allowed, so do it while holding a dedicated lock. Outside and distinct 1330 // from NJTList_lock in case an iteration attempts to lock it. 1331 MutexLocker ml(NonJavaThreadsListSync_lock, Mutex::_no_safepoint_check_flag); 1332 _the_list._protect.synchronize(); 1333 _next = NULL; // Safe to drop the link now. 1334 } 1335 1336 void NonJavaThread::pre_run() { 1337 add_to_the_list(); 1338 1339 // This is slightly odd in that NamedThread is a subclass, but 1340 // in fact name() is defined in Thread 1341 assert(this->name() != NULL, "thread name was not set before it was started"); 1342 this->set_native_thread_name(this->name()); 1343 } 1344 1345 void NonJavaThread::post_run() { 1346 JFR_ONLY(Jfr::on_thread_exit(this);) 1347 remove_from_the_list(); 1348 // Ensure thread-local-storage is cleared before termination. 1349 Thread::clear_thread_current(); 1350 } 1351 1352 // NamedThread -- non-JavaThread subclasses with multiple 1353 // uniquely named instances should derive from this. 1354 NamedThread::NamedThread() : 1355 NonJavaThread(), 1356 _name(NULL), 1357 _processed_thread(NULL), 1358 _gc_id(GCId::undefined()) 1359 {} 1360 1361 NamedThread::~NamedThread() { 1362 FREE_C_HEAP_ARRAY(char, _name); 1363 } 1364 1365 void NamedThread::set_name(const char* format, ...) { 1366 guarantee(_name == NULL, "Only get to set name once."); 1367 _name = NEW_C_HEAP_ARRAY(char, max_name_len, mtThread); 1368 va_list ap; 1369 va_start(ap, format); 1370 jio_vsnprintf(_name, max_name_len, format, ap); 1371 va_end(ap); 1372 } 1373 1374 void NamedThread::print_on(outputStream* st) const { 1375 st->print("\"%s\" ", name()); 1376 Thread::print_on(st); 1377 st->cr(); 1378 } 1379 1380 1381 // ======= WatcherThread ======== 1382 1383 // The watcher thread exists to simulate timer interrupts. It should 1384 // be replaced by an abstraction over whatever native support for 1385 // timer interrupts exists on the platform. 1386 1387 WatcherThread* WatcherThread::_watcher_thread = NULL; 1388 bool WatcherThread::_startable = false; 1389 volatile bool WatcherThread::_should_terminate = false; 1390 1391 WatcherThread::WatcherThread() : NonJavaThread() { 1392 assert(watcher_thread() == NULL, "we can only allocate one WatcherThread"); 1393 if (os::create_thread(this, os::watcher_thread)) { 1394 _watcher_thread = this; 1395 1396 // Set the watcher thread to the highest OS priority which should not be 1397 // used, unless a Java thread with priority java.lang.Thread.MAX_PRIORITY 1398 // is created. The only normal thread using this priority is the reference 1399 // handler thread, which runs for very short intervals only. 1400 // If the VMThread's priority is not lower than the WatcherThread profiling 1401 // will be inaccurate. 1402 os::set_priority(this, MaxPriority); 1403 if (!DisableStartThread) { 1404 os::start_thread(this); 1405 } 1406 } 1407 } 1408 1409 int WatcherThread::sleep() const { 1410 // The WatcherThread does not participate in the safepoint protocol 1411 // for the PeriodicTask_lock because it is not a JavaThread. 1412 MonitorLocker ml(PeriodicTask_lock, Mutex::_no_safepoint_check_flag); 1413 1414 if (_should_terminate) { 1415 // check for termination before we do any housekeeping or wait 1416 return 0; // we did not sleep. 1417 } 1418 1419 // remaining will be zero if there are no tasks, 1420 // causing the WatcherThread to sleep until a task is 1421 // enrolled 1422 int remaining = PeriodicTask::time_to_wait(); 1423 int time_slept = 0; 1424 1425 // we expect this to timeout - we only ever get unparked when 1426 // we should terminate or when a new task has been enrolled 1427 OSThreadWaitState osts(this->osthread(), false /* not Object.wait() */); 1428 1429 jlong time_before_loop = os::javaTimeNanos(); 1430 1431 while (true) { 1432 bool timedout = ml.wait(remaining); 1433 jlong now = os::javaTimeNanos(); 1434 1435 if (remaining == 0) { 1436 // if we didn't have any tasks we could have waited for a long time 1437 // consider the time_slept zero and reset time_before_loop 1438 time_slept = 0; 1439 time_before_loop = now; 1440 } else { 1441 // need to recalculate since we might have new tasks in _tasks 1442 time_slept = (int) ((now - time_before_loop) / 1000000); 1443 } 1444 1445 // Change to task list or spurious wakeup of some kind 1446 if (timedout || _should_terminate) { 1447 break; 1448 } 1449 1450 remaining = PeriodicTask::time_to_wait(); 1451 if (remaining == 0) { 1452 // Last task was just disenrolled so loop around and wait until 1453 // another task gets enrolled 1454 continue; 1455 } 1456 1457 remaining -= time_slept; 1458 if (remaining <= 0) { 1459 break; 1460 } 1461 } 1462 1463 return time_slept; 1464 } 1465 1466 void WatcherThread::run() { 1467 assert(this == watcher_thread(), "just checking"); 1468 1469 this->set_active_handles(JNIHandleBlock::allocate_block()); 1470 while (true) { 1471 assert(watcher_thread() == Thread::current(), "thread consistency check"); 1472 assert(watcher_thread() == this, "thread consistency check"); 1473 1474 // Calculate how long it'll be until the next PeriodicTask work 1475 // should be done, and sleep that amount of time. 1476 int time_waited = sleep(); 1477 1478 if (VMError::is_error_reported()) { 1479 // A fatal error has happened, the error handler(VMError::report_and_die) 1480 // should abort JVM after creating an error log file. However in some 1481 // rare cases, the error handler itself might deadlock. Here periodically 1482 // check for error reporting timeouts, and if it happens, just proceed to 1483 // abort the VM. 1484 1485 // This code is in WatcherThread because WatcherThread wakes up 1486 // periodically so the fatal error handler doesn't need to do anything; 1487 // also because the WatcherThread is less likely to crash than other 1488 // threads. 1489 1490 for (;;) { 1491 // Note: we use naked sleep in this loop because we want to avoid using 1492 // any kind of VM infrastructure which may be broken at this point. 1493 if (VMError::check_timeout()) { 1494 // We hit error reporting timeout. Error reporting was interrupted and 1495 // will be wrapping things up now (closing files etc). Give it some more 1496 // time, then quit the VM. 1497 os::naked_short_sleep(200); 1498 // Print a message to stderr. 1499 fdStream err(defaultStream::output_fd()); 1500 err.print_raw_cr("# [ timer expired, abort... ]"); 1501 // skip atexit/vm_exit/vm_abort hooks 1502 os::die(); 1503 } 1504 1505 // Wait a second, then recheck for timeout. 1506 os::naked_short_sleep(999); 1507 } 1508 } 1509 1510 if (_should_terminate) { 1511 // check for termination before posting the next tick 1512 break; 1513 } 1514 1515 PeriodicTask::real_time_tick(time_waited); 1516 } 1517 1518 // Signal that it is terminated 1519 { 1520 MutexLocker mu(Terminator_lock, Mutex::_no_safepoint_check_flag); 1521 _watcher_thread = NULL; 1522 Terminator_lock->notify_all(); 1523 } 1524 } 1525 1526 void WatcherThread::start() { 1527 assert(PeriodicTask_lock->owned_by_self(), "PeriodicTask_lock required"); 1528 1529 if (watcher_thread() == NULL && _startable) { 1530 _should_terminate = false; 1531 // Create the single instance of WatcherThread 1532 new WatcherThread(); 1533 } 1534 } 1535 1536 void WatcherThread::make_startable() { 1537 assert(PeriodicTask_lock->owned_by_self(), "PeriodicTask_lock required"); 1538 _startable = true; 1539 } 1540 1541 void WatcherThread::stop() { 1542 { 1543 // Follow normal safepoint aware lock enter protocol since the 1544 // WatcherThread is stopped by another JavaThread. 1545 MutexLocker ml(PeriodicTask_lock); 1546 _should_terminate = true; 1547 1548 WatcherThread* watcher = watcher_thread(); 1549 if (watcher != NULL) { 1550 // unpark the WatcherThread so it can see that it should terminate 1551 watcher->unpark(); 1552 } 1553 } 1554 1555 MonitorLocker mu(Terminator_lock); 1556 1557 while (watcher_thread() != NULL) { 1558 // This wait should make safepoint checks, wait without a timeout, 1559 // and wait as a suspend-equivalent condition. 1560 mu.wait(0, Mutex::_as_suspend_equivalent_flag); 1561 } 1562 } 1563 1564 void WatcherThread::unpark() { 1565 assert(PeriodicTask_lock->owned_by_self(), "PeriodicTask_lock required"); 1566 PeriodicTask_lock->notify(); 1567 } 1568 1569 void WatcherThread::print_on(outputStream* st) const { 1570 st->print("\"%s\" ", name()); 1571 Thread::print_on(st); 1572 st->cr(); 1573 } 1574 1575 // ======= JavaThread ======== 1576 1577 #if INCLUDE_JVMCI 1578 1579 jlong* JavaThread::_jvmci_old_thread_counters; 1580 1581 bool jvmci_counters_include(JavaThread* thread) { 1582 return !JVMCICountersExcludeCompiler || !thread->is_Compiler_thread(); 1583 } 1584 1585 void JavaThread::collect_counters(jlong* array, int length) { 1586 assert(length == JVMCICounterSize, "wrong value"); 1587 for (int i = 0; i < length; i++) { 1588 array[i] = _jvmci_old_thread_counters[i]; 1589 } 1590 for (JavaThreadIteratorWithHandle jtiwh; JavaThread *tp = jtiwh.next(); ) { 1591 if (jvmci_counters_include(tp)) { 1592 for (int i = 0; i < length; i++) { 1593 array[i] += tp->_jvmci_counters[i]; 1594 } 1595 } 1596 } 1597 } 1598 1599 // Attempt to enlarge the array for per thread counters. 1600 jlong* resize_counters_array(jlong* old_counters, int current_size, int new_size) { 1601 jlong* new_counters = NEW_C_HEAP_ARRAY(jlong, new_size, mtJVMCI); 1602 if (old_counters == NULL) { 1603 old_counters = new_counters; 1604 memset(old_counters, 0, sizeof(jlong) * new_size); 1605 } else { 1606 for (int i = 0; i < MIN2((int) current_size, new_size); i++) { 1607 new_counters[i] = old_counters[i]; 1608 } 1609 if (new_size > current_size) { 1610 memset(new_counters + current_size, 0, sizeof(jlong) * (new_size - current_size)); 1611 } 1612 FREE_C_HEAP_ARRAY(jlong, old_counters); 1613 } 1614 return new_counters; 1615 } 1616 1617 // Attempt to enlarge the array for per thread counters. 1618 void JavaThread::resize_counters(int current_size, int new_size) { 1619 _jvmci_counters = resize_counters_array(_jvmci_counters, current_size, new_size); 1620 } 1621 1622 class VM_JVMCIResizeCounters : public VM_Operation { 1623 private: 1624 int _new_size; 1625 1626 public: 1627 VM_JVMCIResizeCounters(int new_size) : _new_size(new_size) { } 1628 VMOp_Type type() const { return VMOp_JVMCIResizeCounters; } 1629 bool allow_nested_vm_operations() const { return true; } 1630 void doit() { 1631 // Resize the old thread counters array 1632 jlong* new_counters = resize_counters_array(JavaThread::_jvmci_old_thread_counters, JVMCICounterSize, _new_size); 1633 JavaThread::_jvmci_old_thread_counters = new_counters; 1634 1635 // Now resize each threads array 1636 for (JavaThreadIteratorWithHandle jtiwh; JavaThread *tp = jtiwh.next(); ) { 1637 tp->resize_counters(JVMCICounterSize, _new_size); 1638 } 1639 JVMCICounterSize = _new_size; 1640 } 1641 }; 1642 1643 void JavaThread::resize_all_jvmci_counters(int new_size) { 1644 VM_JVMCIResizeCounters op(new_size); 1645 VMThread::execute(&op); 1646 } 1647 1648 #endif // INCLUDE_JVMCI 1649 1650 // A JavaThread is a normal Java thread 1651 1652 void JavaThread::initialize() { 1653 // Initialize fields 1654 1655 set_saved_exception_pc(NULL); 1656 set_threadObj(NULL); 1657 _anchor.clear(); 1658 set_entry_point(NULL); 1659 set_jni_functions(jni_functions()); 1660 set_callee_target(NULL); 1661 set_vm_result(NULL); 1662 set_vm_result_2(NULL); 1663 set_vframe_array_head(NULL); 1664 set_vframe_array_last(NULL); 1665 set_deferred_locals(NULL); 1666 set_deopt_mark(NULL); 1667 set_deopt_compiled_method(NULL); 1668 set_monitor_chunks(NULL); 1669 _on_thread_list = false; 1670 _thread_state = _thread_new; 1671 _terminated = _not_terminated; 1672 _array_for_gc = NULL; 1673 _suspend_equivalent = false; 1674 _in_deopt_handler = 0; 1675 _doing_unsafe_access = false; 1676 _stack_guard_state = stack_guard_unused; 1677 #if INCLUDE_JVMCI 1678 _pending_monitorenter = false; 1679 _pending_deoptimization = -1; 1680 _pending_failed_speculation = 0; 1681 _pending_transfer_to_interpreter = false; 1682 _in_retryable_allocation = false; 1683 _jvmci._alternate_call_target = NULL; 1684 assert(_jvmci._implicit_exception_pc == NULL, "must be"); 1685 _jvmci_counters = NULL; 1686 if (JVMCICounterSize > 0) { 1687 resize_counters(0, (int) JVMCICounterSize); 1688 } 1689 #endif // INCLUDE_JVMCI 1690 _reserved_stack_activation = NULL; // stack base not known yet 1691 (void)const_cast<oop&>(_exception_oop = oop(NULL)); 1692 _exception_pc = 0; 1693 _exception_handler_pc = 0; 1694 _is_method_handle_return = 0; 1695 _jvmti_thread_state= NULL; 1696 _should_post_on_exceptions_flag = JNI_FALSE; 1697 _interp_only_mode = 0; 1698 _special_runtime_exit_condition = _no_async_condition; 1699 _pending_async_exception = NULL; 1700 _thread_stat = NULL; 1701 _thread_stat = new ThreadStatistics(); 1702 _jni_active_critical = 0; 1703 _pending_jni_exception_check_fn = NULL; 1704 _do_not_unlock_if_synchronized = false; 1705 _cached_monitor_info = NULL; 1706 _parker = Parker::Allocate(this); 1707 _SleepEvent = ParkEvent::Allocate(this); 1708 // Setup safepoint state info for this thread 1709 ThreadSafepointState::create(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 JVMFlagWriteableList::mark_startup(); 3822 3823 if (PauseAtStartup) { 3824 os::pause(); 3825 } 3826 3827 HOTSPOT_VM_INIT_BEGIN(); 3828 3829 // Timing (must come after argument parsing) 3830 TraceTime timer("Create VM", TRACETIME_LOG(Info, startuptime)); 3831 3832 // Initialize the os module after parsing the args 3833 jint os_init_2_result = os::init_2(); 3834 if (os_init_2_result != JNI_OK) return os_init_2_result; 3835 3836 #ifdef CAN_SHOW_REGISTERS_ON_ASSERT 3837 // Initialize assert poison page mechanism. 3838 if (ShowRegistersOnAssert) { 3839 initialize_assert_poison(); 3840 } 3841 #endif // CAN_SHOW_REGISTERS_ON_ASSERT 3842 3843 SafepointMechanism::initialize(); 3844 3845 jint adjust_after_os_result = Arguments::adjust_after_os(); 3846 if (adjust_after_os_result != JNI_OK) return adjust_after_os_result; 3847 3848 // Initialize output stream logging 3849 ostream_init_log(); 3850 3851 // Convert -Xrun to -agentlib: if there is no JVM_OnLoad 3852 // Must be before create_vm_init_agents() 3853 if (Arguments::init_libraries_at_startup()) { 3854 convert_vm_init_libraries_to_agents(); 3855 } 3856 3857 // Launch -agentlib/-agentpath and converted -Xrun agents 3858 if (Arguments::init_agents_at_startup()) { 3859 create_vm_init_agents(); 3860 } 3861 3862 // Initialize Threads state 3863 _number_of_threads = 0; 3864 _number_of_non_daemon_threads = 0; 3865 3866 // Initialize global data structures and create system classes in heap 3867 vm_init_globals(); 3868 3869 #if INCLUDE_JVMCI 3870 if (JVMCICounterSize > 0) { 3871 JavaThread::_jvmci_old_thread_counters = NEW_C_HEAP_ARRAY(jlong, JVMCICounterSize, mtJVMCI); 3872 memset(JavaThread::_jvmci_old_thread_counters, 0, sizeof(jlong) * JVMCICounterSize); 3873 } else { 3874 JavaThread::_jvmci_old_thread_counters = NULL; 3875 } 3876 #endif // INCLUDE_JVMCI 3877 3878 // Attach the main thread to this os thread 3879 JavaThread* main_thread = new JavaThread(); 3880 main_thread->set_thread_state(_thread_in_vm); 3881 main_thread->initialize_thread_current(); 3882 // must do this before set_active_handles 3883 main_thread->record_stack_base_and_size(); 3884 main_thread->register_thread_stack_with_NMT(); 3885 main_thread->set_active_handles(JNIHandleBlock::allocate_block()); 3886 3887 if (!main_thread->set_as_starting_thread()) { 3888 vm_shutdown_during_initialization( 3889 "Failed necessary internal allocation. Out of swap space"); 3890 main_thread->smr_delete(); 3891 *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again 3892 return JNI_ENOMEM; 3893 } 3894 3895 // Enable guard page *after* os::create_main_thread(), otherwise it would 3896 // crash Linux VM, see notes in os_linux.cpp. 3897 main_thread->create_stack_guard_pages(); 3898 3899 // Initialize Java-Level synchronization subsystem 3900 ObjectMonitor::Initialize(); 3901 3902 // Initialize global modules 3903 jint status = init_globals(); 3904 if (status != JNI_OK) { 3905 main_thread->smr_delete(); 3906 *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again 3907 return status; 3908 } 3909 3910 JFR_ONLY(Jfr::on_create_vm_1();) 3911 3912 // Should be done after the heap is fully created 3913 main_thread->cache_global_variables(); 3914 3915 HandleMark hm; 3916 3917 { MutexLocker mu(Threads_lock); 3918 Threads::add(main_thread); 3919 } 3920 3921 // Any JVMTI raw monitors entered in onload will transition into 3922 // real raw monitor. VM is setup enough here for raw monitor enter. 3923 JvmtiExport::transition_pending_onload_raw_monitors(); 3924 3925 // Create the VMThread 3926 { TraceTime timer("Start VMThread", TRACETIME_LOG(Info, startuptime)); 3927 3928 VMThread::create(); 3929 Thread* vmthread = VMThread::vm_thread(); 3930 3931 if (!os::create_thread(vmthread, os::vm_thread)) { 3932 vm_exit_during_initialization("Cannot create VM thread. " 3933 "Out of system resources."); 3934 } 3935 3936 // Wait for the VM thread to become ready, and VMThread::run to initialize 3937 // Monitors can have spurious returns, must always check another state flag 3938 { 3939 MonitorLocker ml(Notify_lock); 3940 os::start_thread(vmthread); 3941 while (vmthread->active_handles() == NULL) { 3942 ml.wait(); 3943 } 3944 } 3945 } 3946 3947 assert(Universe::is_fully_initialized(), "not initialized"); 3948 if (VerifyDuringStartup) { 3949 // Make sure we're starting with a clean slate. 3950 VM_Verify verify_op; 3951 VMThread::execute(&verify_op); 3952 } 3953 3954 // We need this to update the java.vm.info property in case any flags used 3955 // to initially define it have been changed. This is needed for both CDS and 3956 // AOT, since UseSharedSpaces and UseAOT may be changed after java.vm.info 3957 // is initially computed. See Abstract_VM_Version::vm_info_string(). 3958 // This update must happen before we initialize the java classes, but 3959 // after any initialization logic that might modify the flags. 3960 Arguments::update_vm_info_property(VM_Version::vm_info_string()); 3961 3962 Thread* THREAD = Thread::current(); 3963 3964 // Always call even when there are not JVMTI environments yet, since environments 3965 // may be attached late and JVMTI must track phases of VM execution 3966 JvmtiExport::enter_early_start_phase(); 3967 3968 // Notify JVMTI agents that VM has started (JNI is up) - nop if no agents. 3969 JvmtiExport::post_early_vm_start(); 3970 3971 initialize_java_lang_classes(main_thread, CHECK_JNI_ERR); 3972 3973 quicken_jni_functions(); 3974 3975 // No more stub generation allowed after that point. 3976 StubCodeDesc::freeze(); 3977 3978 // Set flag that basic initialization has completed. Used by exceptions and various 3979 // debug stuff, that does not work until all basic classes have been initialized. 3980 set_init_completed(); 3981 3982 LogConfiguration::post_initialize(); 3983 Metaspace::post_initialize(); 3984 3985 HOTSPOT_VM_INIT_END(); 3986 3987 // record VM initialization completion time 3988 #if INCLUDE_MANAGEMENT 3989 Management::record_vm_init_completed(); 3990 #endif // INCLUDE_MANAGEMENT 3991 3992 // Signal Dispatcher needs to be started before VMInit event is posted 3993 os::initialize_jdk_signal_support(CHECK_JNI_ERR); 3994 3995 // Start Attach Listener if +StartAttachListener or it can't be started lazily 3996 if (!DisableAttachMechanism) { 3997 AttachListener::vm_start(); 3998 if (StartAttachListener || AttachListener::init_at_startup()) { 3999 AttachListener::init(); 4000 } 4001 } 4002 4003 // Launch -Xrun agents 4004 // Must be done in the JVMTI live phase so that for backward compatibility the JDWP 4005 // back-end can launch with -Xdebug -Xrunjdwp. 4006 if (!EagerXrunInit && Arguments::init_libraries_at_startup()) { 4007 create_vm_init_libraries(); 4008 } 4009 4010 if (CleanChunkPoolAsync) { 4011 Chunk::start_chunk_pool_cleaner_task(); 4012 } 4013 4014 // Start the service thread 4015 // The service thread enqueues JVMTI deferred events and does various hashtable 4016 // and other cleanups. Needs to start before the compilers start posting events. 4017 ServiceThread::initialize(); 4018 4019 // initialize compiler(s) 4020 #if defined(COMPILER1) || COMPILER2_OR_JVMCI 4021 #if INCLUDE_JVMCI 4022 bool force_JVMCI_intialization = false; 4023 if (EnableJVMCI) { 4024 // Initialize JVMCI eagerly when it is explicitly requested. 4025 // Or when JVMCILibDumpJNIConfig or JVMCIPrintProperties is enabled. 4026 force_JVMCI_intialization = EagerJVMCI || JVMCIPrintProperties || JVMCILibDumpJNIConfig; 4027 4028 if (!force_JVMCI_intialization) { 4029 // 8145270: Force initialization of JVMCI runtime otherwise requests for blocking 4030 // compilations via JVMCI will not actually block until JVMCI is initialized. 4031 force_JVMCI_intialization = UseJVMCICompiler && (!UseInterpreter || !BackgroundCompilation); 4032 } 4033 } 4034 #endif 4035 CompileBroker::compilation_init_phase1(CHECK_JNI_ERR); 4036 // Postpone completion of compiler initialization to after JVMCI 4037 // is initialized to avoid timeouts of blocking compilations. 4038 if (JVMCI_ONLY(!force_JVMCI_intialization) NOT_JVMCI(true)) { 4039 CompileBroker::compilation_init_phase2(); 4040 } 4041 #endif 4042 4043 // Pre-initialize some JSR292 core classes to avoid deadlock during class loading. 4044 // It is done after compilers are initialized, because otherwise compilations of 4045 // signature polymorphic MH intrinsics can be missed 4046 // (see SystemDictionary::find_method_handle_intrinsic). 4047 initialize_jsr292_core_classes(CHECK_JNI_ERR); 4048 4049 // This will initialize the module system. Only java.base classes can be 4050 // loaded until phase 2 completes 4051 call_initPhase2(CHECK_JNI_ERR); 4052 4053 JFR_ONLY(Jfr::on_create_vm_2();) 4054 4055 // Always call even when there are not JVMTI environments yet, since environments 4056 // may be attached late and JVMTI must track phases of VM execution 4057 JvmtiExport::enter_start_phase(); 4058 4059 // Notify JVMTI agents that VM has started (JNI is up) - nop if no agents. 4060 JvmtiExport::post_vm_start(); 4061 4062 // Final system initialization including security manager and system class loader 4063 call_initPhase3(CHECK_JNI_ERR); 4064 4065 // cache the system and platform class loaders 4066 SystemDictionary::compute_java_loaders(CHECK_JNI_ERR); 4067 4068 #if INCLUDE_CDS 4069 // capture the module path info from the ModuleEntryTable 4070 ClassLoader::initialize_module_path(THREAD); 4071 #endif 4072 4073 #if INCLUDE_JVMCI 4074 if (force_JVMCI_intialization) { 4075 JVMCI::initialize_compiler(CHECK_JNI_ERR); 4076 CompileBroker::compilation_init_phase2(); 4077 } 4078 #endif 4079 4080 // Always call even when there are not JVMTI environments yet, since environments 4081 // may be attached late and JVMTI must track phases of VM execution 4082 JvmtiExport::enter_live_phase(); 4083 4084 // Make perfmemory accessible 4085 PerfMemory::set_accessible(true); 4086 4087 // Notify JVMTI agents that VM initialization is complete - nop if no agents. 4088 JvmtiExport::post_vm_initialized(); 4089 4090 JFR_ONLY(Jfr::on_create_vm_3();) 4091 4092 #if INCLUDE_MANAGEMENT 4093 Management::initialize(THREAD); 4094 4095 if (HAS_PENDING_EXCEPTION) { 4096 // management agent fails to start possibly due to 4097 // configuration problem and is responsible for printing 4098 // stack trace if appropriate. Simply exit VM. 4099 vm_exit(1); 4100 } 4101 #endif // INCLUDE_MANAGEMENT 4102 4103 if (MemProfiling) MemProfiler::engage(); 4104 StatSampler::engage(); 4105 if (CheckJNICalls) JniPeriodicChecker::engage(); 4106 4107 BiasedLocking::init(); 4108 4109 #if INCLUDE_RTM_OPT 4110 RTMLockingCounters::init(); 4111 #endif 4112 4113 call_postVMInitHook(THREAD); 4114 // The Java side of PostVMInitHook.run must deal with all 4115 // exceptions and provide means of diagnosis. 4116 if (HAS_PENDING_EXCEPTION) { 4117 CLEAR_PENDING_EXCEPTION; 4118 } 4119 4120 { 4121 MutexLocker ml(PeriodicTask_lock); 4122 // Make sure the WatcherThread can be started by WatcherThread::start() 4123 // or by dynamic enrollment. 4124 WatcherThread::make_startable(); 4125 // Start up the WatcherThread if there are any periodic tasks 4126 // NOTE: All PeriodicTasks should be registered by now. If they 4127 // aren't, late joiners might appear to start slowly (we might 4128 // take a while to process their first tick). 4129 if (PeriodicTask::num_tasks() > 0) { 4130 WatcherThread::start(); 4131 } 4132 } 4133 4134 create_vm_timer.end(); 4135 #ifdef ASSERT 4136 _vm_complete = true; 4137 #endif 4138 4139 if (DumpSharedSpaces) { 4140 MetaspaceShared::preload_and_dump(CHECK_JNI_ERR); 4141 ShouldNotReachHere(); 4142 } 4143 4144 return JNI_OK; 4145 } 4146 4147 // type for the Agent_OnLoad and JVM_OnLoad entry points 4148 extern "C" { 4149 typedef jint (JNICALL *OnLoadEntry_t)(JavaVM *, char *, void *); 4150 } 4151 // Find a command line agent library and return its entry point for 4152 // -agentlib: -agentpath: -Xrun 4153 // num_symbol_entries must be passed-in since only the caller knows the number of symbols in the array. 4154 static OnLoadEntry_t lookup_on_load(AgentLibrary* agent, 4155 const char *on_load_symbols[], 4156 size_t num_symbol_entries) { 4157 OnLoadEntry_t on_load_entry = NULL; 4158 void *library = NULL; 4159 4160 if (!agent->valid()) { 4161 char buffer[JVM_MAXPATHLEN]; 4162 char ebuf[1024] = ""; 4163 const char *name = agent->name(); 4164 const char *msg = "Could not find agent library "; 4165 4166 // First check to see if agent is statically linked into executable 4167 if (os::find_builtin_agent(agent, on_load_symbols, num_symbol_entries)) { 4168 library = agent->os_lib(); 4169 } else if (agent->is_absolute_path()) { 4170 library = os::dll_load(name, ebuf, sizeof ebuf); 4171 if (library == NULL) { 4172 const char *sub_msg = " in absolute path, with error: "; 4173 size_t len = strlen(msg) + strlen(name) + strlen(sub_msg) + strlen(ebuf) + 1; 4174 char *buf = NEW_C_HEAP_ARRAY(char, len, mtThread); 4175 jio_snprintf(buf, len, "%s%s%s%s", msg, name, sub_msg, ebuf); 4176 // If we can't find the agent, exit. 4177 vm_exit_during_initialization(buf, NULL); 4178 FREE_C_HEAP_ARRAY(char, buf); 4179 } 4180 } else { 4181 // Try to load the agent from the standard dll directory 4182 if (os::dll_locate_lib(buffer, sizeof(buffer), Arguments::get_dll_dir(), 4183 name)) { 4184 library = os::dll_load(buffer, ebuf, sizeof ebuf); 4185 } 4186 if (library == NULL) { // Try the library path directory. 4187 if (os::dll_build_name(buffer, sizeof(buffer), name)) { 4188 library = os::dll_load(buffer, ebuf, sizeof ebuf); 4189 } 4190 if (library == NULL) { 4191 const char *sub_msg = " on the library path, with error: "; 4192 const char *sub_msg2 = "\nModule java.instrument may be missing from runtime image."; 4193 4194 size_t len = strlen(msg) + strlen(name) + strlen(sub_msg) + 4195 strlen(ebuf) + strlen(sub_msg2) + 1; 4196 char *buf = NEW_C_HEAP_ARRAY(char, len, mtThread); 4197 if (!agent->is_instrument_lib()) { 4198 jio_snprintf(buf, len, "%s%s%s%s", msg, name, sub_msg, ebuf); 4199 } else { 4200 jio_snprintf(buf, len, "%s%s%s%s%s", msg, name, sub_msg, ebuf, sub_msg2); 4201 } 4202 // If we can't find the agent, exit. 4203 vm_exit_during_initialization(buf, NULL); 4204 FREE_C_HEAP_ARRAY(char, buf); 4205 } 4206 } 4207 } 4208 agent->set_os_lib(library); 4209 agent->set_valid(); 4210 } 4211 4212 // Find the OnLoad function. 4213 on_load_entry = 4214 CAST_TO_FN_PTR(OnLoadEntry_t, os::find_agent_function(agent, 4215 false, 4216 on_load_symbols, 4217 num_symbol_entries)); 4218 return on_load_entry; 4219 } 4220 4221 // Find the JVM_OnLoad entry point 4222 static OnLoadEntry_t lookup_jvm_on_load(AgentLibrary* agent) { 4223 const char *on_load_symbols[] = JVM_ONLOAD_SYMBOLS; 4224 return lookup_on_load(agent, on_load_symbols, sizeof(on_load_symbols) / sizeof(char*)); 4225 } 4226 4227 // Find the Agent_OnLoad entry point 4228 static OnLoadEntry_t lookup_agent_on_load(AgentLibrary* agent) { 4229 const char *on_load_symbols[] = AGENT_ONLOAD_SYMBOLS; 4230 return lookup_on_load(agent, on_load_symbols, sizeof(on_load_symbols) / sizeof(char*)); 4231 } 4232 4233 // For backwards compatibility with -Xrun 4234 // Convert libraries with no JVM_OnLoad, but which have Agent_OnLoad to be 4235 // treated like -agentpath: 4236 // Must be called before agent libraries are created 4237 void Threads::convert_vm_init_libraries_to_agents() { 4238 AgentLibrary* agent; 4239 AgentLibrary* next; 4240 4241 for (agent = Arguments::libraries(); agent != NULL; agent = next) { 4242 next = agent->next(); // cache the next agent now as this agent may get moved off this list 4243 OnLoadEntry_t on_load_entry = lookup_jvm_on_load(agent); 4244 4245 // If there is an JVM_OnLoad function it will get called later, 4246 // otherwise see if there is an Agent_OnLoad 4247 if (on_load_entry == NULL) { 4248 on_load_entry = lookup_agent_on_load(agent); 4249 if (on_load_entry != NULL) { 4250 // switch it to the agent list -- so that Agent_OnLoad will be called, 4251 // JVM_OnLoad won't be attempted and Agent_OnUnload will 4252 Arguments::convert_library_to_agent(agent); 4253 } else { 4254 vm_exit_during_initialization("Could not find JVM_OnLoad or Agent_OnLoad function in the library", agent->name()); 4255 } 4256 } 4257 } 4258 } 4259 4260 // Create agents for -agentlib: -agentpath: and converted -Xrun 4261 // Invokes Agent_OnLoad 4262 // Called very early -- before JavaThreads exist 4263 void Threads::create_vm_init_agents() { 4264 extern struct JavaVM_ main_vm; 4265 AgentLibrary* agent; 4266 4267 JvmtiExport::enter_onload_phase(); 4268 4269 for (agent = Arguments::agents(); agent != NULL; agent = agent->next()) { 4270 // CDS dumping does not support native JVMTI agent. 4271 // CDS dumping supports Java agent if the AllowArchivingWithJavaAgent diagnostic option is specified. 4272 if (Arguments::is_dumping_archive()) { 4273 if(!agent->is_instrument_lib()) { 4274 vm_exit_during_cds_dumping("CDS dumping does not support native JVMTI agent, name", agent->name()); 4275 } else if (!AllowArchivingWithJavaAgent) { 4276 vm_exit_during_cds_dumping( 4277 "Must enable AllowArchivingWithJavaAgent in order to run Java agent during CDS dumping"); 4278 } 4279 } 4280 4281 OnLoadEntry_t on_load_entry = lookup_agent_on_load(agent); 4282 4283 if (on_load_entry != NULL) { 4284 // Invoke the Agent_OnLoad function 4285 jint err = (*on_load_entry)(&main_vm, agent->options(), NULL); 4286 if (err != JNI_OK) { 4287 vm_exit_during_initialization("agent library failed to init", agent->name()); 4288 } 4289 } else { 4290 vm_exit_during_initialization("Could not find Agent_OnLoad function in the agent library", agent->name()); 4291 } 4292 } 4293 4294 JvmtiExport::enter_primordial_phase(); 4295 } 4296 4297 extern "C" { 4298 typedef void (JNICALL *Agent_OnUnload_t)(JavaVM *); 4299 } 4300 4301 void Threads::shutdown_vm_agents() { 4302 // Send any Agent_OnUnload notifications 4303 const char *on_unload_symbols[] = AGENT_ONUNLOAD_SYMBOLS; 4304 size_t num_symbol_entries = ARRAY_SIZE(on_unload_symbols); 4305 extern struct JavaVM_ main_vm; 4306 for (AgentLibrary* agent = Arguments::agents(); agent != NULL; agent = agent->next()) { 4307 4308 // Find the Agent_OnUnload function. 4309 Agent_OnUnload_t unload_entry = CAST_TO_FN_PTR(Agent_OnUnload_t, 4310 os::find_agent_function(agent, 4311 false, 4312 on_unload_symbols, 4313 num_symbol_entries)); 4314 4315 // Invoke the Agent_OnUnload function 4316 if (unload_entry != NULL) { 4317 JavaThread* thread = JavaThread::current(); 4318 ThreadToNativeFromVM ttn(thread); 4319 HandleMark hm(thread); 4320 (*unload_entry)(&main_vm); 4321 } 4322 } 4323 } 4324 4325 // Called for after the VM is initialized for -Xrun libraries which have not been converted to agent libraries 4326 // Invokes JVM_OnLoad 4327 void Threads::create_vm_init_libraries() { 4328 extern struct JavaVM_ main_vm; 4329 AgentLibrary* agent; 4330 4331 for (agent = Arguments::libraries(); agent != NULL; agent = agent->next()) { 4332 OnLoadEntry_t on_load_entry = lookup_jvm_on_load(agent); 4333 4334 if (on_load_entry != NULL) { 4335 // Invoke the JVM_OnLoad function 4336 JavaThread* thread = JavaThread::current(); 4337 ThreadToNativeFromVM ttn(thread); 4338 HandleMark hm(thread); 4339 jint err = (*on_load_entry)(&main_vm, agent->options(), NULL); 4340 if (err != JNI_OK) { 4341 vm_exit_during_initialization("-Xrun library failed to init", agent->name()); 4342 } 4343 } else { 4344 vm_exit_during_initialization("Could not find JVM_OnLoad function in -Xrun library", agent->name()); 4345 } 4346 } 4347 } 4348 4349 4350 // Last thread running calls java.lang.Shutdown.shutdown() 4351 void JavaThread::invoke_shutdown_hooks() { 4352 HandleMark hm(this); 4353 4354 // We could get here with a pending exception, if so clear it now. 4355 if (this->has_pending_exception()) { 4356 this->clear_pending_exception(); 4357 } 4358 4359 EXCEPTION_MARK; 4360 Klass* shutdown_klass = 4361 SystemDictionary::resolve_or_null(vmSymbols::java_lang_Shutdown(), 4362 THREAD); 4363 if (shutdown_klass != NULL) { 4364 // SystemDictionary::resolve_or_null will return null if there was 4365 // an exception. If we cannot load the Shutdown class, just don't 4366 // call Shutdown.shutdown() at all. This will mean the shutdown hooks 4367 // won't be run. Note that if a shutdown hook was registered, 4368 // the Shutdown class would have already been loaded 4369 // (Runtime.addShutdownHook will load it). 4370 JavaValue result(T_VOID); 4371 JavaCalls::call_static(&result, 4372 shutdown_klass, 4373 vmSymbols::shutdown_name(), 4374 vmSymbols::void_method_signature(), 4375 THREAD); 4376 } 4377 CLEAR_PENDING_EXCEPTION; 4378 } 4379 4380 // Threads::destroy_vm() is normally called from jni_DestroyJavaVM() when 4381 // the program falls off the end of main(). Another VM exit path is through 4382 // vm_exit() when the program calls System.exit() to return a value or when 4383 // there is a serious error in VM. The two shutdown paths are not exactly 4384 // the same, but they share Shutdown.shutdown() at Java level and before_exit() 4385 // and VM_Exit op at VM level. 4386 // 4387 // Shutdown sequence: 4388 // + Shutdown native memory tracking if it is on 4389 // + Wait until we are the last non-daemon thread to execute 4390 // <-- every thing is still working at this moment --> 4391 // + Call java.lang.Shutdown.shutdown(), which will invoke Java level 4392 // shutdown hooks 4393 // + Call before_exit(), prepare for VM exit 4394 // > run VM level shutdown hooks (they are registered through JVM_OnExit(), 4395 // currently the only user of this mechanism is File.deleteOnExit()) 4396 // > stop StatSampler, watcher thread, 4397 // post thread end and vm death events to JVMTI, 4398 // stop signal thread 4399 // + Call JavaThread::exit(), it will: 4400 // > release JNI handle blocks, remove stack guard pages 4401 // > remove this thread from Threads list 4402 // <-- no more Java code from this thread after this point --> 4403 // + Stop VM thread, it will bring the remaining VM to a safepoint and stop 4404 // the compiler threads at safepoint 4405 // <-- do not use anything that could get blocked by Safepoint --> 4406 // + Disable tracing at JNI/JVM barriers 4407 // + Set _vm_exited flag for threads that are still running native code 4408 // + Call exit_globals() 4409 // > deletes tty 4410 // > deletes PerfMemory resources 4411 // + Delete this thread 4412 // + Return to caller 4413 4414 bool Threads::destroy_vm() { 4415 JavaThread* thread = JavaThread::current(); 4416 4417 #ifdef ASSERT 4418 _vm_complete = false; 4419 #endif 4420 // Wait until we are the last non-daemon thread to execute 4421 { MonitorLocker nu(Threads_lock); 4422 while (Threads::number_of_non_daemon_threads() > 1) 4423 // This wait should make safepoint checks, wait without a timeout, 4424 // and wait as a suspend-equivalent condition. 4425 nu.wait(0, Mutex::_as_suspend_equivalent_flag); 4426 } 4427 4428 EventShutdown e; 4429 if (e.should_commit()) { 4430 e.set_reason("No remaining non-daemon Java threads"); 4431 e.commit(); 4432 } 4433 4434 // Hang forever on exit if we are reporting an error. 4435 if (ShowMessageBoxOnError && VMError::is_error_reported()) { 4436 os::infinite_sleep(); 4437 } 4438 os::wait_for_keypress_at_exit(); 4439 4440 // run Java level shutdown hooks 4441 thread->invoke_shutdown_hooks(); 4442 4443 before_exit(thread); 4444 4445 thread->exit(true); 4446 4447 // Stop VM thread. 4448 { 4449 // 4945125 The vm thread comes to a safepoint during exit. 4450 // GC vm_operations can get caught at the safepoint, and the 4451 // heap is unparseable if they are caught. Grab the Heap_lock 4452 // to prevent this. The GC vm_operations will not be able to 4453 // queue until after the vm thread is dead. After this point, 4454 // we'll never emerge out of the safepoint before the VM exits. 4455 4456 MutexLocker ml(Heap_lock, Mutex::_no_safepoint_check_flag); 4457 4458 VMThread::wait_for_vm_thread_exit(); 4459 assert(SafepointSynchronize::is_at_safepoint(), "VM thread should exit at Safepoint"); 4460 VMThread::destroy(); 4461 } 4462 4463 // Now, all Java threads are gone except daemon threads. Daemon threads 4464 // running Java code or in VM are stopped by the Safepoint. However, 4465 // daemon threads executing native code are still running. But they 4466 // will be stopped at native=>Java/VM barriers. Note that we can't 4467 // simply kill or suspend them, as it is inherently deadlock-prone. 4468 4469 VM_Exit::set_vm_exited(); 4470 4471 // Clean up ideal graph printers after the VMThread has started 4472 // the final safepoint which will block all the Compiler threads. 4473 // Note that this Thread has already logically exited so the 4474 // clean_up() function's use of a JavaThreadIteratorWithHandle 4475 // would be a problem except set_vm_exited() has remembered the 4476 // shutdown thread which is granted a policy exception. 4477 #if defined(COMPILER2) && !defined(PRODUCT) 4478 IdealGraphPrinter::clean_up(); 4479 #endif 4480 4481 notify_vm_shutdown(); 4482 4483 // exit_globals() will delete tty 4484 exit_globals(); 4485 4486 // We are after VM_Exit::set_vm_exited() so we can't call 4487 // thread->smr_delete() or we will block on the Threads_lock. 4488 // Deleting the shutdown thread here is safe because another 4489 // JavaThread cannot have an active ThreadsListHandle for 4490 // this JavaThread. 4491 delete thread; 4492 4493 #if INCLUDE_JVMCI 4494 if (JVMCICounterSize > 0) { 4495 FREE_C_HEAP_ARRAY(jlong, JavaThread::_jvmci_old_thread_counters); 4496 } 4497 #endif 4498 4499 LogConfiguration::finalize(); 4500 4501 return true; 4502 } 4503 4504 4505 jboolean Threads::is_supported_jni_version_including_1_1(jint version) { 4506 if (version == JNI_VERSION_1_1) return JNI_TRUE; 4507 return is_supported_jni_version(version); 4508 } 4509 4510 4511 jboolean Threads::is_supported_jni_version(jint version) { 4512 if (version == JNI_VERSION_1_2) return JNI_TRUE; 4513 if (version == JNI_VERSION_1_4) return JNI_TRUE; 4514 if (version == JNI_VERSION_1_6) return JNI_TRUE; 4515 if (version == JNI_VERSION_1_8) return JNI_TRUE; 4516 if (version == JNI_VERSION_9) return JNI_TRUE; 4517 if (version == JNI_VERSION_10) return JNI_TRUE; 4518 return JNI_FALSE; 4519 } 4520 4521 4522 void Threads::add(JavaThread* p, bool force_daemon) { 4523 // The threads lock must be owned at this point 4524 assert(Threads_lock->owned_by_self(), "must have threads lock"); 4525 4526 BarrierSet::barrier_set()->on_thread_attach(p); 4527 4528 // Once a JavaThread is added to the Threads list, smr_delete() has 4529 // to be used to delete it. Otherwise we can just delete it directly. 4530 p->set_on_thread_list(); 4531 4532 _number_of_threads++; 4533 oop threadObj = p->threadObj(); 4534 bool daemon = true; 4535 // Bootstrapping problem: threadObj can be null for initial 4536 // JavaThread (or for threads attached via JNI) 4537 if ((!force_daemon) && !is_daemon((threadObj))) { 4538 _number_of_non_daemon_threads++; 4539 daemon = false; 4540 } 4541 4542 ThreadService::add_thread(p, daemon); 4543 4544 // Maintain fast thread list 4545 ThreadsSMRSupport::add_thread(p); 4546 4547 // Possible GC point. 4548 Events::log(p, "Thread added: " INTPTR_FORMAT, p2i(p)); 4549 } 4550 4551 void Threads::remove(JavaThread* p, bool is_daemon) { 4552 4553 // Reclaim the ObjectMonitors from the om_in_use_list and om_free_list of the moribund thread. 4554 ObjectSynchronizer::om_flush(p); 4555 4556 // Extra scope needed for Thread_lock, so we can check 4557 // that we do not remove thread without safepoint code notice 4558 { MonitorLocker ml(Threads_lock); 4559 4560 assert(ThreadsSMRSupport::get_java_thread_list()->includes(p), "p must be present"); 4561 4562 // Maintain fast thread list 4563 ThreadsSMRSupport::remove_thread(p); 4564 4565 _number_of_threads--; 4566 if (!is_daemon) { 4567 _number_of_non_daemon_threads--; 4568 4569 // Only one thread left, do a notify on the Threads_lock so a thread waiting 4570 // on destroy_vm will wake up. 4571 if (number_of_non_daemon_threads() == 1) { 4572 ml.notify_all(); 4573 } 4574 } 4575 ThreadService::remove_thread(p, is_daemon); 4576 4577 // Make sure that safepoint code disregard this thread. This is needed since 4578 // the thread might mess around with locks after this point. This can cause it 4579 // to do callbacks into the safepoint code. However, the safepoint code is not aware 4580 // of this thread since it is removed from the queue. 4581 p->set_terminated_value(); 4582 } // unlock Threads_lock 4583 4584 // Since Events::log uses a lock, we grab it outside the Threads_lock 4585 Events::log(p, "Thread exited: " INTPTR_FORMAT, p2i(p)); 4586 } 4587 4588 // Operations on the Threads list for GC. These are not explicitly locked, 4589 // but the garbage collector must provide a safe context for them to run. 4590 // In particular, these things should never be called when the Threads_lock 4591 // is held by some other thread. (Note: the Safepoint abstraction also 4592 // uses the Threads_lock to guarantee this property. It also makes sure that 4593 // all threads gets blocked when exiting or starting). 4594 4595 void Threads::oops_do(OopClosure* f, CodeBlobClosure* cf) { 4596 ALL_JAVA_THREADS(p) { 4597 p->oops_do(f, cf); 4598 } 4599 VMThread::vm_thread()->oops_do(f, cf); 4600 } 4601 4602 void Threads::change_thread_claim_token() { 4603 if (++_thread_claim_token == 0) { 4604 // On overflow of the token counter, there is a risk of future 4605 // collisions between a new global token value and a stale token 4606 // for a thread, because not all iterations visit all threads. 4607 // (Though it's pretty much a theoretical concern for non-trivial 4608 // token counter sizes.) To deal with the possibility, reset all 4609 // the thread tokens to zero on global token overflow. 4610 struct ResetClaims : public ThreadClosure { 4611 virtual void do_thread(Thread* t) { 4612 t->claim_threads_do(false, 0); 4613 } 4614 } reset_claims; 4615 Threads::threads_do(&reset_claims); 4616 // On overflow, update the global token to non-zero, to 4617 // avoid the special "never claimed" initial thread value. 4618 _thread_claim_token = 1; 4619 } 4620 } 4621 4622 #ifdef ASSERT 4623 void assert_thread_claimed(const char* kind, Thread* t, uintx expected) { 4624 const uintx token = t->threads_do_token(); 4625 assert(token == expected, 4626 "%s " PTR_FORMAT " has incorrect value " UINTX_FORMAT " != " 4627 UINTX_FORMAT, kind, p2i(t), token, expected); 4628 } 4629 4630 void Threads::assert_all_threads_claimed() { 4631 ALL_JAVA_THREADS(p) { 4632 assert_thread_claimed("Thread", p, _thread_claim_token); 4633 } 4634 assert_thread_claimed("VMThread", VMThread::vm_thread(), _thread_claim_token); 4635 } 4636 #endif // ASSERT 4637 4638 class ParallelOopsDoThreadClosure : public ThreadClosure { 4639 private: 4640 OopClosure* _f; 4641 CodeBlobClosure* _cf; 4642 public: 4643 ParallelOopsDoThreadClosure(OopClosure* f, CodeBlobClosure* cf) : _f(f), _cf(cf) {} 4644 void do_thread(Thread* t) { 4645 t->oops_do(_f, _cf); 4646 } 4647 }; 4648 4649 void Threads::possibly_parallel_oops_do(bool is_par, OopClosure* f, CodeBlobClosure* cf) { 4650 ParallelOopsDoThreadClosure tc(f, cf); 4651 possibly_parallel_threads_do(is_par, &tc); 4652 } 4653 4654 void Threads::nmethods_do(CodeBlobClosure* cf) { 4655 ALL_JAVA_THREADS(p) { 4656 // This is used by the code cache sweeper to mark nmethods that are active 4657 // on the stack of a Java thread. Ignore the sweeper thread itself to avoid 4658 // marking CodeCacheSweeperThread::_scanned_compiled_method as active. 4659 if(!p->is_Code_cache_sweeper_thread()) { 4660 p->nmethods_do(cf); 4661 } 4662 } 4663 } 4664 4665 void Threads::metadata_do(MetadataClosure* f) { 4666 ALL_JAVA_THREADS(p) { 4667 p->metadata_do(f); 4668 } 4669 } 4670 4671 class ThreadHandlesClosure : public ThreadClosure { 4672 void (*_f)(Metadata*); 4673 public: 4674 ThreadHandlesClosure(void f(Metadata*)) : _f(f) {} 4675 virtual void do_thread(Thread* thread) { 4676 thread->metadata_handles_do(_f); 4677 } 4678 }; 4679 4680 void Threads::metadata_handles_do(void f(Metadata*)) { 4681 // Only walk the Handles in Thread. 4682 ThreadHandlesClosure handles_closure(f); 4683 threads_do(&handles_closure); 4684 } 4685 4686 // Get count Java threads that are waiting to enter the specified monitor. 4687 GrowableArray<JavaThread*>* Threads::get_pending_threads(ThreadsList * t_list, 4688 int count, 4689 address monitor) { 4690 GrowableArray<JavaThread*>* result = new GrowableArray<JavaThread*>(count); 4691 4692 int i = 0; 4693 DO_JAVA_THREADS(t_list, p) { 4694 if (!p->can_call_java()) continue; 4695 4696 address pending = (address)p->current_pending_monitor(); 4697 if (pending == monitor) { // found a match 4698 if (i < count) result->append(p); // save the first count matches 4699 i++; 4700 } 4701 } 4702 4703 return result; 4704 } 4705 4706 4707 JavaThread *Threads::owning_thread_from_monitor_owner(ThreadsList * t_list, 4708 address owner) { 4709 // NULL owner means not locked so we can skip the search 4710 if (owner == NULL) return NULL; 4711 4712 DO_JAVA_THREADS(t_list, p) { 4713 // first, see if owner is the address of a Java thread 4714 if (owner == (address)p) return p; 4715 } 4716 4717 // Cannot assert on lack of success here since this function may be 4718 // used by code that is trying to report useful problem information 4719 // like deadlock detection. 4720 if (UseHeavyMonitors) return NULL; 4721 4722 // If we didn't find a matching Java thread and we didn't force use of 4723 // heavyweight monitors, then the owner is the stack address of the 4724 // Lock Word in the owning Java thread's stack. 4725 // 4726 JavaThread* the_owner = NULL; 4727 DO_JAVA_THREADS(t_list, q) { 4728 if (q->is_lock_owned(owner)) { 4729 the_owner = q; 4730 break; 4731 } 4732 } 4733 4734 // cannot assert on lack of success here; see above comment 4735 return the_owner; 4736 } 4737 4738 // Threads::print_on() is called at safepoint by VM_PrintThreads operation. 4739 void Threads::print_on(outputStream* st, bool print_stacks, 4740 bool internal_format, bool print_concurrent_locks, 4741 bool print_extended_info) { 4742 char buf[32]; 4743 st->print_raw_cr(os::local_time_string(buf, sizeof(buf))); 4744 4745 st->print_cr("Full thread dump %s (%s %s):", 4746 VM_Version::vm_name(), 4747 VM_Version::vm_release(), 4748 VM_Version::vm_info_string()); 4749 st->cr(); 4750 4751 #if INCLUDE_SERVICES 4752 // Dump concurrent locks 4753 ConcurrentLocksDump concurrent_locks; 4754 if (print_concurrent_locks) { 4755 concurrent_locks.dump_at_safepoint(); 4756 } 4757 #endif // INCLUDE_SERVICES 4758 4759 ThreadsSMRSupport::print_info_on(st); 4760 st->cr(); 4761 4762 ALL_JAVA_THREADS(p) { 4763 ResourceMark rm; 4764 p->print_on(st, print_extended_info); 4765 if (print_stacks) { 4766 if (internal_format) { 4767 p->trace_stack(); 4768 } else { 4769 p->print_stack_on(st); 4770 } 4771 } 4772 st->cr(); 4773 #if INCLUDE_SERVICES 4774 if (print_concurrent_locks) { 4775 concurrent_locks.print_locks_on(p, st); 4776 } 4777 #endif // INCLUDE_SERVICES 4778 } 4779 4780 VMThread::vm_thread()->print_on(st); 4781 st->cr(); 4782 Universe::heap()->print_gc_threads_on(st); 4783 WatcherThread* wt = WatcherThread::watcher_thread(); 4784 if (wt != NULL) { 4785 wt->print_on(st); 4786 st->cr(); 4787 } 4788 4789 st->flush(); 4790 } 4791 4792 void Threads::print_on_error(Thread* this_thread, outputStream* st, Thread* current, char* buf, 4793 int buflen, bool* found_current) { 4794 if (this_thread != NULL) { 4795 bool is_current = (current == this_thread); 4796 *found_current = *found_current || is_current; 4797 st->print("%s", is_current ? "=>" : " "); 4798 4799 st->print(PTR_FORMAT, p2i(this_thread)); 4800 st->print(" "); 4801 this_thread->print_on_error(st, buf, buflen); 4802 st->cr(); 4803 } 4804 } 4805 4806 class PrintOnErrorClosure : public ThreadClosure { 4807 outputStream* _st; 4808 Thread* _current; 4809 char* _buf; 4810 int _buflen; 4811 bool* _found_current; 4812 public: 4813 PrintOnErrorClosure(outputStream* st, Thread* current, char* buf, 4814 int buflen, bool* found_current) : 4815 _st(st), _current(current), _buf(buf), _buflen(buflen), _found_current(found_current) {} 4816 4817 virtual void do_thread(Thread* thread) { 4818 Threads::print_on_error(thread, _st, _current, _buf, _buflen, _found_current); 4819 } 4820 }; 4821 4822 // Threads::print_on_error() is called by fatal error handler. It's possible 4823 // that VM is not at safepoint and/or current thread is inside signal handler. 4824 // Don't print stack trace, as the stack may not be walkable. Don't allocate 4825 // memory (even in resource area), it might deadlock the error handler. 4826 void Threads::print_on_error(outputStream* st, Thread* current, char* buf, 4827 int buflen) { 4828 ThreadsSMRSupport::print_info_on(st); 4829 st->cr(); 4830 4831 bool found_current = false; 4832 st->print_cr("Java Threads: ( => current thread )"); 4833 ALL_JAVA_THREADS(thread) { 4834 print_on_error(thread, st, current, buf, buflen, &found_current); 4835 } 4836 st->cr(); 4837 4838 st->print_cr("Other Threads:"); 4839 print_on_error(VMThread::vm_thread(), st, current, buf, buflen, &found_current); 4840 print_on_error(WatcherThread::watcher_thread(), st, current, buf, buflen, &found_current); 4841 4842 PrintOnErrorClosure print_closure(st, current, buf, buflen, &found_current); 4843 Universe::heap()->gc_threads_do(&print_closure); 4844 4845 if (!found_current) { 4846 st->cr(); 4847 st->print("=>" PTR_FORMAT " (exited) ", p2i(current)); 4848 current->print_on_error(st, buf, buflen); 4849 st->cr(); 4850 } 4851 st->cr(); 4852 4853 st->print_cr("Threads with active compile tasks:"); 4854 print_threads_compiling(st, buf, buflen); 4855 } 4856 4857 void Threads::print_threads_compiling(outputStream* st, char* buf, int buflen, bool short_form) { 4858 ALL_JAVA_THREADS(thread) { 4859 if (thread->is_Compiler_thread()) { 4860 CompilerThread* ct = (CompilerThread*) thread; 4861 4862 // Keep task in local variable for NULL check. 4863 // ct->_task might be set to NULL by concurring compiler thread 4864 // because it completed the compilation. The task is never freed, 4865 // though, just returned to a free list. 4866 CompileTask* task = ct->task(); 4867 if (task != NULL) { 4868 thread->print_name_on_error(st, buf, buflen); 4869 st->print(" "); 4870 task->print(st, NULL, short_form, true); 4871 } 4872 } 4873 } 4874 } 4875 4876 4877 // Internal SpinLock and Mutex 4878 // Based on ParkEvent 4879 4880 // Ad-hoc mutual exclusion primitives: SpinLock and Mux 4881 // 4882 // We employ SpinLocks _only for low-contention, fixed-length 4883 // short-duration critical sections where we're concerned 4884 // about native mutex_t or HotSpot Mutex:: latency. 4885 // The mux construct provides a spin-then-block mutual exclusion 4886 // mechanism. 4887 // 4888 // Testing has shown that contention on the ListLock guarding gFreeList 4889 // is common. If we implement ListLock as a simple SpinLock it's common 4890 // for the JVM to devolve to yielding with little progress. This is true 4891 // despite the fact that the critical sections protected by ListLock are 4892 // extremely short. 4893 // 4894 // TODO-FIXME: ListLock should be of type SpinLock. 4895 // We should make this a 1st-class type, integrated into the lock 4896 // hierarchy as leaf-locks. Critically, the SpinLock structure 4897 // should have sufficient padding to avoid false-sharing and excessive 4898 // cache-coherency traffic. 4899 4900 4901 typedef volatile int SpinLockT; 4902 4903 void Thread::SpinAcquire(volatile int * adr, const char * LockName) { 4904 if (Atomic::cmpxchg(adr, 0, 1) == 0) { 4905 return; // normal fast-path return 4906 } 4907 4908 // Slow-path : We've encountered contention -- Spin/Yield/Block strategy. 4909 int ctr = 0; 4910 int Yields = 0; 4911 for (;;) { 4912 while (*adr != 0) { 4913 ++ctr; 4914 if ((ctr & 0xFFF) == 0 || !os::is_MP()) { 4915 if (Yields > 5) { 4916 os::naked_short_sleep(1); 4917 } else { 4918 os::naked_yield(); 4919 ++Yields; 4920 } 4921 } else { 4922 SpinPause(); 4923 } 4924 } 4925 if (Atomic::cmpxchg(adr, 0, 1) == 0) return; 4926 } 4927 } 4928 4929 void Thread::SpinRelease(volatile int * adr) { 4930 assert(*adr != 0, "invariant"); 4931 OrderAccess::fence(); // guarantee at least release consistency. 4932 // Roach-motel semantics. 4933 // It's safe if subsequent LDs and STs float "up" into the critical section, 4934 // but prior LDs and STs within the critical section can't be allowed 4935 // to reorder or float past the ST that releases the lock. 4936 // Loads and stores in the critical section - which appear in program 4937 // order before the store that releases the lock - must also appear 4938 // before the store that releases the lock in memory visibility order. 4939 // Conceptually we need a #loadstore|#storestore "release" MEMBAR before 4940 // the ST of 0 into the lock-word which releases the lock, so fence 4941 // more than covers this on all platforms. 4942 *adr = 0; 4943 } 4944 4945 // muxAcquire and muxRelease: 4946 // 4947 // * muxAcquire and muxRelease support a single-word lock-word construct. 4948 // The LSB of the word is set IFF the lock is held. 4949 // The remainder of the word points to the head of a singly-linked list 4950 // of threads blocked on the lock. 4951 // 4952 // * The current implementation of muxAcquire-muxRelease uses its own 4953 // dedicated Thread._MuxEvent instance. If we're interested in 4954 // minimizing the peak number of extant ParkEvent instances then 4955 // we could eliminate _MuxEvent and "borrow" _ParkEvent as long 4956 // as certain invariants were satisfied. Specifically, care would need 4957 // to be taken with regards to consuming unpark() "permits". 4958 // A safe rule of thumb is that a thread would never call muxAcquire() 4959 // if it's enqueued (cxq, EntryList, WaitList, etc) and will subsequently 4960 // park(). Otherwise the _ParkEvent park() operation in muxAcquire() could 4961 // consume an unpark() permit intended for monitorenter, for instance. 4962 // One way around this would be to widen the restricted-range semaphore 4963 // implemented in park(). Another alternative would be to provide 4964 // multiple instances of the PlatformEvent() for each thread. One 4965 // instance would be dedicated to muxAcquire-muxRelease, for instance. 4966 // 4967 // * Usage: 4968 // -- Only as leaf locks 4969 // -- for short-term locking only as muxAcquire does not perform 4970 // thread state transitions. 4971 // 4972 // Alternatives: 4973 // * We could implement muxAcquire and muxRelease with MCS or CLH locks 4974 // but with parking or spin-then-park instead of pure spinning. 4975 // * Use Taura-Oyama-Yonenzawa locks. 4976 // * It's possible to construct a 1-0 lock if we encode the lockword as 4977 // (List,LockByte). Acquire will CAS the full lockword while Release 4978 // will STB 0 into the LockByte. The 1-0 scheme admits stranding, so 4979 // acquiring threads use timers (ParkTimed) to detect and recover from 4980 // the stranding window. Thread/Node structures must be aligned on 256-byte 4981 // boundaries by using placement-new. 4982 // * Augment MCS with advisory back-link fields maintained with CAS(). 4983 // Pictorially: LockWord -> T1 <-> T2 <-> T3 <-> ... <-> Tn <-> Owner. 4984 // The validity of the backlinks must be ratified before we trust the value. 4985 // If the backlinks are invalid the exiting thread must back-track through the 4986 // the forward links, which are always trustworthy. 4987 // * Add a successor indication. The LockWord is currently encoded as 4988 // (List, LOCKBIT:1). We could also add a SUCCBIT or an explicit _succ variable 4989 // to provide the usual futile-wakeup optimization. 4990 // See RTStt for details. 4991 // 4992 4993 4994 const intptr_t LOCKBIT = 1; 4995 4996 void Thread::muxAcquire(volatile intptr_t * Lock, const char * LockName) { 4997 intptr_t w = Atomic::cmpxchg(Lock, (intptr_t)0, LOCKBIT); 4998 if (w == 0) return; 4999 if ((w & LOCKBIT) == 0 && Atomic::cmpxchg(Lock, w, w|LOCKBIT) == w) { 5000 return; 5001 } 5002 5003 ParkEvent * const Self = Thread::current()->_MuxEvent; 5004 assert((intptr_t(Self) & LOCKBIT) == 0, "invariant"); 5005 for (;;) { 5006 int its = (os::is_MP() ? 100 : 0) + 1; 5007 5008 // Optional spin phase: spin-then-park strategy 5009 while (--its >= 0) { 5010 w = *Lock; 5011 if ((w & LOCKBIT) == 0 && Atomic::cmpxchg(Lock, w, w|LOCKBIT) == w) { 5012 return; 5013 } 5014 } 5015 5016 Self->reset(); 5017 Self->OnList = intptr_t(Lock); 5018 // The following fence() isn't _strictly necessary as the subsequent 5019 // CAS() both serializes execution and ratifies the fetched *Lock value. 5020 OrderAccess::fence(); 5021 for (;;) { 5022 w = *Lock; 5023 if ((w & LOCKBIT) == 0) { 5024 if (Atomic::cmpxchg(Lock, w, w|LOCKBIT) == w) { 5025 Self->OnList = 0; // hygiene - allows stronger asserts 5026 return; 5027 } 5028 continue; // Interference -- *Lock changed -- Just retry 5029 } 5030 assert(w & LOCKBIT, "invariant"); 5031 Self->ListNext = (ParkEvent *) (w & ~LOCKBIT); 5032 if (Atomic::cmpxchg(Lock, w, intptr_t(Self)|LOCKBIT) == w) break; 5033 } 5034 5035 while (Self->OnList != 0) { 5036 Self->park(); 5037 } 5038 } 5039 } 5040 5041 // Release() must extract a successor from the list and then wake that thread. 5042 // It can "pop" the front of the list or use a detach-modify-reattach (DMR) scheme 5043 // similar to that used by ParkEvent::Allocate() and ::Release(). DMR-based 5044 // Release() would : 5045 // (A) CAS() or swap() null to *Lock, releasing the lock and detaching the list. 5046 // (B) Extract a successor from the private list "in-hand" 5047 // (C) attempt to CAS() the residual back into *Lock over null. 5048 // If there were any newly arrived threads and the CAS() would fail. 5049 // In that case Release() would detach the RATs, re-merge the list in-hand 5050 // with the RATs and repeat as needed. Alternately, Release() might 5051 // detach and extract a successor, but then pass the residual list to the wakee. 5052 // The wakee would be responsible for reattaching and remerging before it 5053 // competed for the lock. 5054 // 5055 // Both "pop" and DMR are immune from ABA corruption -- there can be 5056 // multiple concurrent pushers, but only one popper or detacher. 5057 // This implementation pops from the head of the list. This is unfair, 5058 // but tends to provide excellent throughput as hot threads remain hot. 5059 // (We wake recently run threads first). 5060 // 5061 // All paths through muxRelease() will execute a CAS. 5062 // Release consistency -- We depend on the CAS in muxRelease() to provide full 5063 // bidirectional fence/MEMBAR semantics, ensuring that all prior memory operations 5064 // executed within the critical section are complete and globally visible before the 5065 // store (CAS) to the lock-word that releases the lock becomes globally visible. 5066 void Thread::muxRelease(volatile intptr_t * Lock) { 5067 for (;;) { 5068 const intptr_t w = Atomic::cmpxchg(Lock, LOCKBIT, (intptr_t)0); 5069 assert(w & LOCKBIT, "invariant"); 5070 if (w == LOCKBIT) return; 5071 ParkEvent * const List = (ParkEvent *) (w & ~LOCKBIT); 5072 assert(List != NULL, "invariant"); 5073 assert(List->OnList == intptr_t(Lock), "invariant"); 5074 ParkEvent * const nxt = List->ListNext; 5075 guarantee((intptr_t(nxt) & LOCKBIT) == 0, "invariant"); 5076 5077 // The following CAS() releases the lock and pops the head element. 5078 // The CAS() also ratifies the previously fetched lock-word value. 5079 if (Atomic::cmpxchg(Lock, w, intptr_t(nxt)) != w) { 5080 continue; 5081 } 5082 List->OnList = 0; 5083 OrderAccess::fence(); 5084 List->unpark(); 5085 return; 5086 } 5087 } 5088 5089 5090 void Threads::verify() { 5091 ALL_JAVA_THREADS(p) { 5092 p->verify(); 5093 } 5094 VMThread* thread = VMThread::vm_thread(); 5095 if (thread != NULL) thread->verify(); 5096 }