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