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