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