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