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