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