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