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