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