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