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