1 /*
   2  * Copyright (c) 1997, 2022, Oracle and/or its affiliates. All rights reserved.
   3  * Copyright (c) 2021, Azul Systems, Inc. All rights reserved.
   4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   5  *
   6  * This code is free software; you can redistribute it and/or modify it
   7  * under the terms of the GNU General Public License version 2 only, as
   8  * published by the Free Software Foundation.
   9  *
  10  * This code is distributed in the hope that it will be useful, but WITHOUT
  11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  13  * version 2 for more details (a copy is included in the LICENSE file that
  14  * accompanied this code).
  15  *
  16  * You should have received a copy of the GNU General Public License version
  17  * 2 along with this work; if not, write to the Free Software Foundation,
  18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  19  *
  20  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  21  * or visit www.oracle.com if you need additional information or have any
  22  * questions.
  23  *
  24  */
  25 
  26 #include "precompiled.hpp"
  27 #include "jvm.h"
  28 #include "cds/dynamicArchive.hpp"
  29 #include "cds/metaspaceShared.hpp"
  30 #include "classfile/classLoader.hpp"
  31 #include "classfile/javaClasses.hpp"
  32 #include "classfile/javaThreadStatus.hpp"
  33 #include "classfile/systemDictionary.hpp"
  34 #include "classfile/vmClasses.hpp"
  35 #include "classfile/vmSymbols.hpp"
  36 #include "code/codeCache.hpp"
  37 #include "code/scopeDesc.hpp"
  38 #include "compiler/compileBroker.hpp"
  39 #include "compiler/compileTask.hpp"
  40 #include "compiler/compilerThread.hpp"
  41 #include "gc/shared/barrierSet.hpp"
  42 #include "gc/shared/collectedHeap.hpp"
  43 #include "gc/shared/gcId.hpp"
  44 #include "gc/shared/gcLocker.inline.hpp"
  45 #include "gc/shared/gcVMOperations.hpp"
  46 #include "gc/shared/oopStorage.hpp"
  47 #include "gc/shared/oopStorageSet.hpp"
  48 #include "gc/shared/stringdedup/stringDedup.hpp"
  49 #include "gc/shared/tlab_globals.hpp"
  50 #include "interpreter/interpreter.hpp"
  51 #include "interpreter/linkResolver.hpp"
  52 #include "interpreter/oopMapCache.hpp"
  53 #include "jfr/jfrEvents.hpp"
  54 #include "jvmtifiles/jvmtiEnv.hpp"
  55 #include "logging/log.hpp"
  56 #include "logging/logAsyncWriter.hpp"
  57 #include "logging/logConfiguration.hpp"
  58 #include "logging/logStream.hpp"
  59 #include "memory/allocation.inline.hpp"
  60 #include "memory/iterator.hpp"
  61 #include "memory/oopFactory.hpp"
  62 #include "memory/resourceArea.hpp"
  63 #include "memory/universe.hpp"
  64 #include "oops/access.inline.hpp"
  65 #include "oops/instanceKlass.hpp"
  66 #include "oops/klass.inline.hpp"
  67 #include "oops/objArrayOop.hpp"
  68 #include "oops/oop.inline.hpp"
  69 #include "oops/oopHandle.inline.hpp"
  70 #include "oops/symbol.hpp"
  71 #include "oops/typeArrayOop.inline.hpp"
  72 #include "oops/inlineKlass.hpp"
  73 #include "oops/verifyOopClosure.hpp"
  74 #include "prims/jvm_misc.hpp"
  75 #include "prims/jvmtiDeferredUpdates.hpp"
  76 #include "prims/jvmtiExport.hpp"
  77 #include "prims/jvmtiThreadState.hpp"
  78 #include "runtime/arguments.hpp"
  79 #include "runtime/atomic.hpp"
  80 #include "runtime/fieldDescriptor.inline.hpp"
  81 #include "runtime/flags/jvmFlagLimit.hpp"
  82 #include "runtime/deoptimization.hpp"
  83 #include "runtime/frame.inline.hpp"
  84 #include "runtime/handles.inline.hpp"
  85 #include "runtime/handshake.hpp"
  86 #include "runtime/init.hpp"
  87 #include "runtime/interfaceSupport.inline.hpp"
  88 #include "runtime/java.hpp"
  89 #include "runtime/javaCalls.hpp"
  90 #include "runtime/jniHandles.inline.hpp"
  91 #include "runtime/jniPeriodicChecker.hpp"
  92 #include "runtime/monitorDeflationThread.hpp"
  93 #include "runtime/mutexLocker.hpp"
  94 #include "runtime/nonJavaThread.hpp"
  95 #include "runtime/objectMonitor.hpp"
  96 #include "runtime/orderAccess.hpp"
  97 #include "runtime/osThread.hpp"
  98 #include "runtime/safepoint.hpp"
  99 #include "runtime/safepointMechanism.inline.hpp"
 100 #include "runtime/safepointVerifiers.hpp"
 101 #include "runtime/serviceThread.hpp"
 102 #include "runtime/sharedRuntime.hpp"
 103 #include "runtime/stackFrameStream.inline.hpp"
 104 #include "runtime/stackWatermarkSet.hpp"
 105 #include "runtime/statSampler.hpp"
 106 #include "runtime/task.hpp"
 107 #include "runtime/thread.inline.hpp"
 108 #include "runtime/threadCritical.hpp"
 109 #include "runtime/threadSMR.inline.hpp"
 110 #include "runtime/threadStatisticalInfo.hpp"
 111 #include "runtime/threadWXSetters.inline.hpp"
 112 #include "runtime/timer.hpp"
 113 #include "runtime/timerTrace.hpp"
 114 #include "runtime/vframe.inline.hpp"
 115 #include "runtime/vframeArray.hpp"
 116 #include "runtime/vframe_hp.hpp"
 117 #include "runtime/vmThread.hpp"
 118 #include "runtime/vmOperations.hpp"
 119 #include "runtime/vm_version.hpp"
 120 #include "services/attachListener.hpp"
 121 #include "services/management.hpp"
 122 #include "services/memTracker.hpp"
 123 #include "services/threadService.hpp"
 124 #include "utilities/align.hpp"
 125 #include "utilities/copy.hpp"
 126 #include "utilities/defaultStream.hpp"
 127 #include "utilities/dtrace.hpp"
 128 #include "utilities/events.hpp"
 129 #include "utilities/macros.hpp"
 130 #include "utilities/preserveException.hpp"
 131 #include "utilities/spinYield.hpp"
 132 #include "utilities/vmError.hpp"
 133 #if INCLUDE_JVMCI
 134 #include "jvmci/jvmci.hpp"
 135 #include "jvmci/jvmciEnv.hpp"
 136 #endif
 137 #ifdef COMPILER1
 138 #include "c1/c1_Compiler.hpp"
 139 #endif
 140 #ifdef COMPILER2
 141 #include "opto/c2compiler.hpp"
 142 #include "opto/idealGraphPrinter.hpp"
 143 #endif
 144 #if INCLUDE_RTM_OPT
 145 #include "runtime/rtmLocking.hpp"
 146 #endif
 147 #if INCLUDE_JFR
 148 #include "jfr/jfr.hpp"
 149 #endif
 150 
 151 // Initialization after module runtime initialization
 152 void universe_post_module_init();  // must happen after call_initPhase2
 153 
 154 #ifdef DTRACE_ENABLED
 155 
 156 // Only bother with this argument setup if dtrace is available
 157 
 158   #define HOTSPOT_THREAD_PROBE_start HOTSPOT_THREAD_START
 159   #define HOTSPOT_THREAD_PROBE_stop HOTSPOT_THREAD_STOP
 160 
 161   #define DTRACE_THREAD_PROBE(probe, javathread)                           \
 162     {                                                                      \
 163       ResourceMark rm(this);                                               \
 164       int len = 0;                                                         \
 165       const char* name = (javathread)->name();                             \
 166       len = strlen(name);                                                  \
 167       HOTSPOT_THREAD_PROBE_##probe(/* probe = start, stop */               \
 168         (char *) name, len,                                                \
 169         java_lang_Thread::thread_id((javathread)->threadObj()),            \
 170         (uintptr_t) (javathread)->osthread()->thread_id(),                 \
 171         java_lang_Thread::is_daemon((javathread)->threadObj()));           \
 172     }
 173 
 174 #else //  ndef DTRACE_ENABLED
 175 
 176   #define DTRACE_THREAD_PROBE(probe, javathread)
 177 
 178 #endif // ndef DTRACE_ENABLED
 179 
 180 #ifndef USE_LIBRARY_BASED_TLS_ONLY
 181 // Current thread is maintained as a thread-local variable
 182 THREAD_LOCAL Thread* Thread::_thr_current = NULL;
 183 #endif
 184 
 185 // ======= Thread ========
 186 void* Thread::allocate(size_t size, bool throw_excpt, MEMFLAGS flags) {
 187   return throw_excpt ? AllocateHeap(size, flags, CURRENT_PC)
 188                        : AllocateHeap(size, flags, CURRENT_PC, AllocFailStrategy::RETURN_NULL);
 189 }
 190 
 191 void Thread::operator delete(void* p) {
 192   FreeHeap(p);
 193 }
 194 
 195 void JavaThread::smr_delete() {
 196   if (_on_thread_list) {
 197     ThreadsSMRSupport::smr_delete(this);
 198   } else {
 199     delete this;
 200   }
 201 }
 202 
 203 // Base class for all threads: VMThread, WatcherThread, ConcurrentMarkSweepThread,
 204 // JavaThread
 205 
 206 DEBUG_ONLY(Thread* Thread::_starting_thread = NULL;)
 207 
 208 Thread::Thread() {
 209 
 210   DEBUG_ONLY(_run_state = PRE_CALL_RUN;)
 211 
 212   // stack and get_thread
 213   set_stack_base(NULL);
 214   set_stack_size(0);
 215   set_lgrp_id(-1);
 216   DEBUG_ONLY(clear_suspendible_thread();)
 217 
 218   // allocated data structures
 219   set_osthread(NULL);
 220   set_resource_area(new (mtThread)ResourceArea());
 221   DEBUG_ONLY(_current_resource_mark = NULL;)
 222   set_handle_area(new (mtThread) HandleArea(NULL));
 223   set_metadata_handles(new (ResourceObj::C_HEAP, mtClass) GrowableArray<Metadata*>(30, mtClass));
 224   set_last_handle_mark(NULL);
 225   DEBUG_ONLY(_missed_ic_stub_refill_verifier = NULL);
 226 
 227   // Initial value of zero ==> never claimed.
 228   _threads_do_token = 0;
 229   _threads_hazard_ptr = NULL;
 230   _threads_list_ptr = NULL;
 231   _nested_threads_hazard_ptr_cnt = 0;
 232   _rcu_counter = 0;
 233 
 234   // the handle mark links itself to last_handle_mark
 235   new HandleMark(this);
 236 
 237   // plain initialization
 238   debug_only(_owned_locks = NULL;)
 239   NOT_PRODUCT(_skip_gcalot = false;)
 240   _jvmti_env_iteration_count = 0;
 241   set_allocated_bytes(0);
 242   _current_pending_raw_monitor = NULL;
 243 
 244   // thread-specific hashCode stream generator state - Marsaglia shift-xor form
 245   _hashStateX = os::random();
 246   _hashStateY = 842502087;
 247   _hashStateZ = 0x8767;    // (int)(3579807591LL & 0xffff) ;
 248   _hashStateW = 273326509;
 249 
 250   // Many of the following fields are effectively final - immutable
 251   // Note that nascent threads can't use the Native Monitor-Mutex
 252   // construct until the _MutexEvent is initialized ...
 253   // CONSIDER: instead of using a fixed set of purpose-dedicated ParkEvents
 254   // we might instead use a stack of ParkEvents that we could provision on-demand.
 255   // The stack would act as a cache to avoid calls to ParkEvent::Allocate()
 256   // and ::Release()
 257   _ParkEvent   = ParkEvent::Allocate(this);
 258 
 259 #ifdef CHECK_UNHANDLED_OOPS
 260   if (CheckUnhandledOops) {
 261     _unhandled_oops = new UnhandledOops(this);
 262   }
 263 #endif // CHECK_UNHANDLED_OOPS
 264 
 265   // Notify the barrier set that a thread is being created. The initial
 266   // thread is created before the barrier set is available.  The call to
 267   // BarrierSet::on_thread_create() for this thread is therefore deferred
 268   // to BarrierSet::set_barrier_set().
 269   BarrierSet* const barrier_set = BarrierSet::barrier_set();
 270   if (barrier_set != NULL) {
 271     barrier_set->on_thread_create(this);
 272   } else {
 273     // Only the main thread should be created before the barrier set
 274     // and that happens just before Thread::current is set. No other thread
 275     // can attach as the VM is not created yet, so they can't execute this code.
 276     // If the main thread creates other threads before the barrier set that is an error.
 277     assert(Thread::current_or_null() == NULL, "creating thread before barrier set");
 278   }
 279 
 280   MACOS_AARCH64_ONLY(DEBUG_ONLY(_wx_init = false));
 281 }
 282 
 283 void Thread::initialize_tlab() {
 284   if (UseTLAB) {
 285     tlab().initialize();
 286   }
 287 }
 288 
 289 void Thread::initialize_thread_current() {
 290 #ifndef USE_LIBRARY_BASED_TLS_ONLY
 291   assert(_thr_current == NULL, "Thread::current already initialized");
 292   _thr_current = this;
 293 #endif
 294   assert(ThreadLocalStorage::thread() == NULL, "ThreadLocalStorage::thread already initialized");
 295   ThreadLocalStorage::set_thread(this);
 296   assert(Thread::current() == ThreadLocalStorage::thread(), "TLS mismatch!");
 297 }
 298 
 299 void Thread::clear_thread_current() {
 300   assert(Thread::current() == ThreadLocalStorage::thread(), "TLS mismatch!");
 301 #ifndef USE_LIBRARY_BASED_TLS_ONLY
 302   _thr_current = NULL;
 303 #endif
 304   ThreadLocalStorage::set_thread(NULL);
 305 }
 306 
 307 void Thread::record_stack_base_and_size() {
 308   // Note: at this point, Thread object is not yet initialized. Do not rely on
 309   // any members being initialized. Do not rely on Thread::current() being set.
 310   // If possible, refrain from doing anything which may crash or assert since
 311   // quite probably those crash dumps will be useless.
 312   set_stack_base(os::current_stack_base());
 313   set_stack_size(os::current_stack_size());
 314 
 315   // Set stack limits after thread is initialized.
 316   if (is_Java_thread()) {
 317     JavaThread::cast(this)->stack_overflow_state()->initialize(stack_base(), stack_end());
 318   }
 319 }
 320 
 321 void Thread::register_thread_stack_with_NMT() {
 322   MemTracker::record_thread_stack(stack_end(), stack_size());
 323 }
 324 
 325 void Thread::unregister_thread_stack_with_NMT() {
 326   MemTracker::release_thread_stack(stack_end(), stack_size());
 327 }
 328 
 329 void Thread::call_run() {
 330   DEBUG_ONLY(_run_state = CALL_RUN;)
 331 
 332   // At this point, Thread object should be fully initialized and
 333   // Thread::current() should be set.
 334 
 335   assert(Thread::current_or_null() != NULL, "current thread is unset");
 336   assert(Thread::current_or_null() == this, "current thread is wrong");
 337 
 338   // Perform common initialization actions
 339 
 340   MACOS_AARCH64_ONLY(this->init_wx());
 341 
 342   register_thread_stack_with_NMT();
 343 
 344   JFR_ONLY(Jfr::on_thread_start(this);)
 345 
 346   log_debug(os, thread)("Thread " UINTX_FORMAT " stack dimensions: "
 347     PTR_FORMAT "-" PTR_FORMAT " (" SIZE_FORMAT "k).",
 348     os::current_thread_id(), p2i(stack_end()),
 349     p2i(stack_base()), stack_size()/1024);
 350 
 351   // Perform <ChildClass> initialization actions
 352   DEBUG_ONLY(_run_state = PRE_RUN;)
 353   this->pre_run();
 354 
 355   // Invoke <ChildClass>::run()
 356   DEBUG_ONLY(_run_state = RUN;)
 357   this->run();
 358   // Returned from <ChildClass>::run(). Thread finished.
 359 
 360   // Perform common tear-down actions
 361 
 362   assert(Thread::current_or_null() != NULL, "current thread is unset");
 363   assert(Thread::current_or_null() == this, "current thread is wrong");
 364 
 365   // Perform <ChildClass> tear-down actions
 366   DEBUG_ONLY(_run_state = POST_RUN;)
 367   this->post_run();
 368 
 369   // Note: at this point the thread object may already have deleted itself,
 370   // so from here on do not dereference *this*. Not all thread types currently
 371   // delete themselves when they terminate. But no thread should ever be deleted
 372   // asynchronously with respect to its termination - that is what _run_state can
 373   // be used to check.
 374 
 375   assert(Thread::current_or_null() == NULL, "current thread still present");
 376 }
 377 
 378 Thread::~Thread() {
 379 
 380   // Attached threads will remain in PRE_CALL_RUN, as will threads that don't actually
 381   // get started due to errors etc. Any active thread should at least reach post_run
 382   // before it is deleted (usually in post_run()).
 383   assert(_run_state == PRE_CALL_RUN ||
 384          _run_state == POST_RUN, "Active Thread deleted before post_run(): "
 385          "_run_state=%d", (int)_run_state);
 386 
 387   // Notify the barrier set that a thread is being destroyed. Note that a barrier
 388   // set might not be available if we encountered errors during bootstrapping.
 389   BarrierSet* const barrier_set = BarrierSet::barrier_set();
 390   if (barrier_set != NULL) {
 391     barrier_set->on_thread_destroy(this);
 392   }
 393 
 394   // deallocate data structures
 395   delete resource_area();
 396   // since the handle marks are using the handle area, we have to deallocated the root
 397   // handle mark before deallocating the thread's handle area,
 398   assert(last_handle_mark() != NULL, "check we have an element");
 399   delete last_handle_mark();
 400   assert(last_handle_mark() == NULL, "check we have reached the end");
 401 
 402   ParkEvent::Release(_ParkEvent);
 403   // Set to NULL as a termination indicator for has_terminated().
 404   Atomic::store(&_ParkEvent, (ParkEvent*)NULL);
 405 
 406   delete handle_area();
 407   delete metadata_handles();
 408 
 409   // osthread() can be NULL, if creation of thread failed.
 410   if (osthread() != NULL) os::free_thread(osthread());
 411 
 412   // Clear Thread::current if thread is deleting itself and it has not
 413   // already been done. This must be done before the memory is deallocated.
 414   // Needed to ensure JNI correctly detects non-attached threads.
 415   if (this == Thread::current_or_null()) {
 416     Thread::clear_thread_current();
 417   }
 418 
 419   CHECK_UNHANDLED_OOPS_ONLY(if (CheckUnhandledOops) delete unhandled_oops();)
 420 }
 421 
 422 #ifdef ASSERT
 423 // A JavaThread is considered dangling if it not handshake-safe with respect to
 424 // the current thread, it is not on a ThreadsList, or not at safepoint.
 425 void Thread::check_for_dangling_thread_pointer(Thread *thread) {
 426   assert(!thread->is_Java_thread() ||
 427          JavaThread::cast(thread)->is_handshake_safe_for(Thread::current()) ||
 428          !JavaThread::cast(thread)->on_thread_list() ||
 429          SafepointSynchronize::is_at_safepoint() ||
 430          ThreadsSMRSupport::is_a_protected_JavaThread_with_lock(JavaThread::cast(thread)),
 431          "possibility of dangling Thread pointer");
 432 }
 433 #endif
 434 
 435 // Is the target JavaThread protected by the calling Thread or by some other
 436 // mechanism?
 437 //
 438 bool Thread::is_JavaThread_protected(const JavaThread* target) {
 439   Thread* current_thread = Thread::current();
 440 
 441   // Do the simplest check first:
 442   if (SafepointSynchronize::is_at_safepoint()) {
 443     // The target is protected since JavaThreads cannot exit
 444     // while we're at a safepoint.
 445     return true;
 446   }
 447 
 448   // If the target hasn't been started yet then it is trivially
 449   // "protected". We assume the caller is the thread that will do
 450   // the starting.
 451   if (target->osthread() == NULL || target->osthread()->get_state() <= INITIALIZED) {
 452     return true;
 453   }
 454 
 455   // Now make the simple checks based on who the caller is:
 456   if (current_thread == target || Threads_lock->owner() == current_thread) {
 457     // Target JavaThread is self or calling thread owns the Threads_lock.
 458     // Second check is the same as Threads_lock->owner_is_self(),
 459     // but we already have the current thread so check directly.
 460     return true;
 461   }
 462 
 463   // Check the ThreadsLists associated with the calling thread (if any)
 464   // to see if one of them protects the target JavaThread:
 465   if (is_JavaThread_protected_by_TLH(target)) {
 466     return true;
 467   }
 468 
 469   // Use this debug code with -XX:+UseNewCode to diagnose locations that
 470   // are missing a ThreadsListHandle or other protection mechanism:
 471   // guarantee(!UseNewCode, "current_thread=" INTPTR_FORMAT " is not protecting target="
 472   //           INTPTR_FORMAT, p2i(current_thread), p2i(target));
 473 
 474   // Note: Since 'target' isn't protected by a TLH, the call to
 475   // target->is_handshake_safe_for() may crash, but we have debug bits so
 476   // we'll be able to figure out what protection mechanism is missing.
 477   assert(target->is_handshake_safe_for(current_thread), "JavaThread=" INTPTR_FORMAT
 478          " is not protected and not handshake safe.", p2i(target));
 479 
 480   // The target JavaThread is not protected so it is not safe to query:
 481   return false;
 482 }
 483 
 484 // Is the target JavaThread protected by a ThreadsListHandle (TLH) associated
 485 // with the calling Thread?
 486 //
 487 bool Thread::is_JavaThread_protected_by_TLH(const JavaThread* target) {
 488   Thread* current_thread = Thread::current();
 489 
 490   // Check the ThreadsLists associated with the calling thread (if any)
 491   // to see if one of them protects the target JavaThread:
 492   for (SafeThreadsListPtr* stlp = current_thread->_threads_list_ptr;
 493        stlp != NULL; stlp = stlp->previous()) {
 494     if (stlp->list()->includes(target)) {
 495       // The target JavaThread is protected by this ThreadsList:
 496       return true;
 497     }
 498   }
 499 
 500   // The target JavaThread is not protected by a TLH so it is not safe to query:
 501   return false;
 502 }
 503 
 504 ThreadPriority Thread::get_priority(const Thread* const thread) {
 505   ThreadPriority priority;
 506   // Can return an error!
 507   (void)os::get_priority(thread, priority);
 508   assert(MinPriority <= priority && priority <= MaxPriority, "non-Java priority found");
 509   return priority;
 510 }
 511 
 512 void Thread::set_priority(Thread* thread, ThreadPriority priority) {
 513   debug_only(check_for_dangling_thread_pointer(thread);)
 514   // Can return an error!
 515   (void)os::set_priority(thread, priority);
 516 }
 517 
 518 
 519 void Thread::start(Thread* thread) {
 520   // Start is different from resume in that its safety is guaranteed by context or
 521   // being called from a Java method synchronized on the Thread object.
 522   if (thread->is_Java_thread()) {
 523     // Initialize the thread state to RUNNABLE before starting this thread.
 524     // Can not set it after the thread started because we do not know the
 525     // exact thread state at that time. It could be in MONITOR_WAIT or
 526     // in SLEEPING or some other state.
 527     java_lang_Thread::set_thread_status(JavaThread::cast(thread)->threadObj(),
 528                                         JavaThreadStatus::RUNNABLE);
 529   }
 530   os::start_thread(thread);
 531 }
 532 
 533 // GC Support
 534 bool Thread::claim_par_threads_do(uintx claim_token) {
 535   uintx token = _threads_do_token;
 536   if (token != claim_token) {
 537     uintx res = Atomic::cmpxchg(&_threads_do_token, token, claim_token);
 538     if (res == token) {
 539       return true;
 540     }
 541     guarantee(res == claim_token, "invariant");
 542   }
 543   return false;
 544 }
 545 
 546 void Thread::oops_do_no_frames(OopClosure* f, CodeBlobClosure* cf) {
 547   // Do oop for ThreadShadow
 548   f->do_oop((oop*)&_pending_exception);
 549   handle_area()->oops_do(f);
 550 }
 551 
 552 // If the caller is a NamedThread, then remember, in the current scope,
 553 // the given JavaThread in its _processed_thread field.
 554 class RememberProcessedThread: public StackObj {
 555   NamedThread* _cur_thr;
 556 public:
 557   RememberProcessedThread(Thread* thread) {
 558     Thread* self = Thread::current();
 559     if (self->is_Named_thread()) {
 560       _cur_thr = (NamedThread *)self;
 561       assert(_cur_thr->processed_thread() == NULL, "nesting not supported");
 562       _cur_thr->set_processed_thread(thread);
 563     } else {
 564       _cur_thr = NULL;
 565     }
 566   }
 567 
 568   ~RememberProcessedThread() {
 569     if (_cur_thr) {
 570       assert(_cur_thr->processed_thread() != NULL, "nesting not supported");
 571       _cur_thr->set_processed_thread(NULL);
 572     }
 573   }
 574 };
 575 
 576 void Thread::oops_do(OopClosure* f, CodeBlobClosure* cf) {
 577   // Record JavaThread to GC thread
 578   RememberProcessedThread rpt(this);
 579   oops_do_no_frames(f, cf);
 580   oops_do_frames(f, cf);
 581 }
 582 
 583 void Thread::metadata_handles_do(void f(Metadata*)) {
 584   // Only walk the Handles in Thread.
 585   if (metadata_handles() != NULL) {
 586     for (int i = 0; i< metadata_handles()->length(); i++) {
 587       f(metadata_handles()->at(i));
 588     }
 589   }
 590 }
 591 
 592 void Thread::print_on(outputStream* st, bool print_extended_info) const {
 593   // get_priority assumes osthread initialized
 594   if (osthread() != NULL) {
 595     int os_prio;
 596     if (os::get_native_priority(this, &os_prio) == OS_OK) {
 597       st->print("os_prio=%d ", os_prio);
 598     }
 599 
 600     st->print("cpu=%.2fms ",
 601               os::thread_cpu_time(const_cast<Thread*>(this), true) / 1000000.0
 602               );
 603     st->print("elapsed=%.2fs ",
 604               _statistical_info.getElapsedTime() / 1000.0
 605               );
 606     if (is_Java_thread() && (PrintExtendedThreadInfo || print_extended_info)) {
 607       size_t allocated_bytes = (size_t) const_cast<Thread*>(this)->cooked_allocated_bytes();
 608       st->print("allocated=" SIZE_FORMAT "%s ",
 609                 byte_size_in_proper_unit(allocated_bytes),
 610                 proper_unit_for_byte_size(allocated_bytes)
 611                 );
 612       st->print("defined_classes=" INT64_FORMAT " ", _statistical_info.getDefineClassCount());
 613     }
 614 
 615     st->print("tid=" INTPTR_FORMAT " ", p2i(this));
 616     osthread()->print_on(st);
 617   }
 618   ThreadsSMRSupport::print_info_on(this, st);
 619   st->print(" ");
 620   debug_only(if (WizardMode) print_owned_locks_on(st);)
 621 }
 622 
 623 void Thread::print() const { print_on(tty); }
 624 
 625 // Thread::print_on_error() is called by fatal error handler. Don't use
 626 // any lock or allocate memory.
 627 void Thread::print_on_error(outputStream* st, char* buf, int buflen) const {
 628   assert(!(is_Compiler_thread() || is_Java_thread()), "Can't call name() here if it allocates");
 629 
 630   st->print("%s \"%s\"", type_name(), name());
 631 
 632   OSThread* os_thr = osthread();
 633   if (os_thr != NULL) {
 634     if (os_thr->get_state() != ZOMBIE) {
 635       st->print(" [stack: " PTR_FORMAT "," PTR_FORMAT "]",
 636                 p2i(stack_end()), p2i(stack_base()));
 637       st->print(" [id=%d]", osthread()->thread_id());
 638     } else {
 639       st->print(" terminated");
 640     }
 641   } else {
 642     st->print(" unknown state (no osThread)");
 643   }
 644   ThreadsSMRSupport::print_info_on(this, st);
 645 }
 646 
 647 void Thread::print_value_on(outputStream* st) const {
 648   if (is_Named_thread()) {
 649     st->print(" \"%s\" ", name());
 650   }
 651   st->print(INTPTR_FORMAT, p2i(this));   // print address
 652 }
 653 
 654 #ifdef ASSERT
 655 void Thread::print_owned_locks_on(outputStream* st) const {
 656   Mutex* cur = _owned_locks;
 657   if (cur == NULL) {
 658     st->print(" (no locks) ");
 659   } else {
 660     st->print_cr(" Locks owned:");
 661     while (cur) {
 662       cur->print_on(st);
 663       cur = cur->next();
 664     }
 665   }
 666 }
 667 #endif // ASSERT
 668 
 669 // We had to move these methods here, because vm threads get into ObjectSynchronizer::enter
 670 // However, there is a note in JavaThread::is_lock_owned() about the VM threads not being
 671 // used for compilation in the future. If that change is made, the need for these methods
 672 // should be revisited, and they should be removed if possible.
 673 
 674 bool Thread::is_lock_owned(address adr) const {
 675   return is_in_full_stack(adr);
 676 }
 677 
 678 bool Thread::set_as_starting_thread() {
 679   assert(_starting_thread == NULL, "already initialized: "
 680          "_starting_thread=" INTPTR_FORMAT, p2i(_starting_thread));
 681   // NOTE: this must be called inside the main thread.
 682   DEBUG_ONLY(_starting_thread = this;)
 683   return os::create_main_thread(JavaThread::cast(this));
 684 }
 685 
 686 static void initialize_class(Symbol* class_name, TRAPS) {
 687   Klass* klass = SystemDictionary::resolve_or_fail(class_name, true, CHECK);
 688   InstanceKlass::cast(klass)->initialize(CHECK);
 689 }
 690 
 691 
 692 // Creates the initial ThreadGroup
 693 static Handle create_initial_thread_group(TRAPS) {
 694   Handle system_instance = JavaCalls::construct_new_instance(
 695                             vmClasses::ThreadGroup_klass(),
 696                             vmSymbols::void_method_signature(),
 697                             CHECK_NH);
 698   Universe::set_system_thread_group(system_instance());
 699 
 700   Handle string = java_lang_String::create_from_str("main", CHECK_NH);
 701   Handle main_instance = JavaCalls::construct_new_instance(
 702                             vmClasses::ThreadGroup_klass(),
 703                             vmSymbols::threadgroup_string_void_signature(),
 704                             system_instance,
 705                             string,
 706                             CHECK_NH);
 707   return main_instance;
 708 }
 709 
 710 // Creates the initial Thread, and sets it to running.
 711 static void create_initial_thread(Handle thread_group, JavaThread* thread,
 712                                  TRAPS) {
 713   InstanceKlass* ik = vmClasses::Thread_klass();
 714   assert(ik->is_initialized(), "must be");
 715   instanceHandle thread_oop = ik->allocate_instance_handle(CHECK);
 716 
 717   // Cannot use JavaCalls::construct_new_instance because the java.lang.Thread
 718   // constructor calls Thread.current(), which must be set here for the
 719   // initial thread.
 720   java_lang_Thread::set_thread(thread_oop(), thread);
 721   java_lang_Thread::set_priority(thread_oop(), NormPriority);
 722   thread->set_threadObj(thread_oop());
 723 
 724   Handle string = java_lang_String::create_from_str("main", CHECK);
 725 
 726   JavaValue result(T_VOID);
 727   JavaCalls::call_special(&result, thread_oop,
 728                           ik,
 729                           vmSymbols::object_initializer_name(),
 730                           vmSymbols::threadgroup_string_void_signature(),
 731                           thread_group,
 732                           string,
 733                           CHECK);
 734 
 735   // Set thread status to running since main thread has
 736   // been started and running.
 737   java_lang_Thread::set_thread_status(thread_oop(),
 738                                       JavaThreadStatus::RUNNABLE);
 739 }
 740 
 741 // Extract version and vendor specific information from
 742 // java.lang.VersionProps fields.
 743 // Returned char* is allocated in the thread's resource area
 744 // so must be copied for permanency.
 745 static const char* get_java_version_info(InstanceKlass* ik,
 746                                          Symbol* field_name) {
 747   fieldDescriptor fd;
 748   bool found = ik != NULL &&
 749                ik->find_local_field(field_name,
 750                                     vmSymbols::string_signature(), &fd);
 751   if (found) {
 752     oop name_oop = ik->java_mirror()->obj_field(fd.offset());
 753     if (name_oop == NULL) {
 754       return NULL;
 755     }
 756     const char* name = java_lang_String::as_utf8_string(name_oop);
 757     return name;
 758   } else {
 759     return NULL;
 760   }
 761 }
 762 
 763 // General purpose hook into Java code, run once when the VM is initialized.
 764 // The Java library method itself may be changed independently from the VM.
 765 static void call_postVMInitHook(TRAPS) {
 766   Klass* klass = SystemDictionary::resolve_or_null(vmSymbols::jdk_internal_vm_PostVMInitHook(), THREAD);
 767   if (klass != NULL) {
 768     JavaValue result(T_VOID);
 769     JavaCalls::call_static(&result, klass, vmSymbols::run_method_name(),
 770                            vmSymbols::void_method_signature(),
 771                            CHECK);
 772   }
 773 }
 774 
 775 // Initialized by VMThread at vm_global_init
 776 static OopStorage* _thread_oop_storage = NULL;
 777 
 778 oop  JavaThread::threadObj() const    {
 779   return _threadObj.resolve();
 780 }
 781 
 782 void JavaThread::set_threadObj(oop p) {
 783   assert(_thread_oop_storage != NULL, "not yet initialized");
 784   _threadObj = OopHandle(_thread_oop_storage, p);
 785 }
 786 
 787 OopStorage* JavaThread::thread_oop_storage() {
 788   assert(_thread_oop_storage != NULL, "not yet initialized");
 789   return _thread_oop_storage;
 790 }
 791 
 792 void JavaThread::allocate_threadObj(Handle thread_group, const char* thread_name,
 793                                     bool daemon, TRAPS) {
 794   assert(thread_group.not_null(), "thread group should be specified");
 795   assert(threadObj() == NULL, "should only create Java thread object once");
 796 
 797   InstanceKlass* ik = vmClasses::Thread_klass();
 798   assert(ik->is_initialized(), "must be");
 799   instanceHandle thread_oop = ik->allocate_instance_handle(CHECK);
 800 
 801   // We are called from jni_AttachCurrentThread/jni_AttachCurrentThreadAsDaemon.
 802   // We cannot use JavaCalls::construct_new_instance because the java.lang.Thread
 803   // constructor calls Thread.current(), which must be set here.
 804   java_lang_Thread::set_thread(thread_oop(), this);
 805   java_lang_Thread::set_priority(thread_oop(), NormPriority);
 806   set_threadObj(thread_oop());
 807 
 808   JavaValue result(T_VOID);
 809   if (thread_name != NULL) {
 810     Handle name = java_lang_String::create_from_str(thread_name, CHECK);
 811     // Thread gets assigned specified name and null target
 812     JavaCalls::call_special(&result,
 813                             thread_oop,
 814                             ik,
 815                             vmSymbols::object_initializer_name(),
 816                             vmSymbols::threadgroup_string_void_signature(),
 817                             thread_group,
 818                             name,
 819                             THREAD);
 820   } else {
 821     // Thread gets assigned name "Thread-nnn" and null target
 822     // (java.lang.Thread doesn't have a constructor taking only a ThreadGroup argument)
 823     JavaCalls::call_special(&result,
 824                             thread_oop,
 825                             ik,
 826                             vmSymbols::object_initializer_name(),
 827                             vmSymbols::threadgroup_runnable_void_signature(),
 828                             thread_group,
 829                             Handle(),
 830                             THREAD);
 831   }
 832 
 833 
 834   if (daemon) {
 835     java_lang_Thread::set_daemon(thread_oop());
 836   }
 837 
 838   if (HAS_PENDING_EXCEPTION) {
 839     return;
 840   }
 841 
 842   Klass* group = vmClasses::ThreadGroup_klass();
 843   Handle threadObj(THREAD, this->threadObj());
 844 
 845   JavaCalls::call_special(&result,
 846                           thread_group,
 847                           group,
 848                           vmSymbols::add_method_name(),
 849                           vmSymbols::thread_void_signature(),
 850                           threadObj,          // Arg 1
 851                           THREAD);
 852 }
 853 
 854 // ======= JavaThread ========
 855 
 856 #if INCLUDE_JVMCI
 857 
 858 jlong* JavaThread::_jvmci_old_thread_counters;
 859 
 860 bool jvmci_counters_include(JavaThread* thread) {
 861   return !JVMCICountersExcludeCompiler || !thread->is_Compiler_thread();
 862 }
 863 
 864 void JavaThread::collect_counters(jlong* array, int length) {
 865   assert(length == JVMCICounterSize, "wrong value");
 866   for (int i = 0; i < length; i++) {
 867     array[i] = _jvmci_old_thread_counters[i];
 868   }
 869   for (JavaThread* tp : ThreadsListHandle()) {
 870     if (jvmci_counters_include(tp)) {
 871       for (int i = 0; i < length; i++) {
 872         array[i] += tp->_jvmci_counters[i];
 873       }
 874     }
 875   }
 876 }
 877 
 878 // Attempt to enlarge the array for per thread counters.
 879 jlong* resize_counters_array(jlong* old_counters, int current_size, int new_size) {
 880   jlong* new_counters = NEW_C_HEAP_ARRAY_RETURN_NULL(jlong, new_size, mtJVMCI);
 881   if (new_counters == NULL) {
 882     return NULL;
 883   }
 884   if (old_counters == NULL) {
 885     old_counters = new_counters;
 886     memset(old_counters, 0, sizeof(jlong) * new_size);
 887   } else {
 888     for (int i = 0; i < MIN2((int) current_size, new_size); i++) {
 889       new_counters[i] = old_counters[i];
 890     }
 891     if (new_size > current_size) {
 892       memset(new_counters + current_size, 0, sizeof(jlong) * (new_size - current_size));
 893     }
 894     FREE_C_HEAP_ARRAY(jlong, old_counters);
 895   }
 896   return new_counters;
 897 }
 898 
 899 // Attempt to enlarge the array for per thread counters.
 900 bool JavaThread::resize_counters(int current_size, int new_size) {
 901   jlong* new_counters = resize_counters_array(_jvmci_counters, current_size, new_size);
 902   if (new_counters == NULL) {
 903     return false;
 904   } else {
 905     _jvmci_counters = new_counters;
 906     return true;
 907   }
 908 }
 909 
 910 class VM_JVMCIResizeCounters : public VM_Operation {
 911  private:
 912   int _new_size;
 913   bool _failed;
 914 
 915  public:
 916   VM_JVMCIResizeCounters(int new_size) : _new_size(new_size), _failed(false) { }
 917   VMOp_Type type()                  const        { return VMOp_JVMCIResizeCounters; }
 918   bool allow_nested_vm_operations() const        { return true; }
 919   void doit() {
 920     // Resize the old thread counters array
 921     jlong* new_counters = resize_counters_array(JavaThread::_jvmci_old_thread_counters, JVMCICounterSize, _new_size);
 922     if (new_counters == NULL) {
 923       _failed = true;
 924       return;
 925     } else {
 926       JavaThread::_jvmci_old_thread_counters = new_counters;
 927     }
 928 
 929     // Now resize each threads array
 930     for (JavaThread* tp : ThreadsListHandle()) {
 931       if (!tp->resize_counters(JVMCICounterSize, _new_size)) {
 932         _failed = true;
 933         break;
 934       }
 935     }
 936     if (!_failed) {
 937       JVMCICounterSize = _new_size;
 938     }
 939   }
 940 
 941   bool failed() { return _failed; }
 942 };
 943 
 944 bool JavaThread::resize_all_jvmci_counters(int new_size) {
 945   VM_JVMCIResizeCounters op(new_size);
 946   VMThread::execute(&op);
 947   return !op.failed();
 948 }
 949 
 950 #endif // INCLUDE_JVMCI
 951 
 952 #ifdef ASSERT
 953 // Checks safepoint allowed and clears unhandled oops at potential safepoints.
 954 void JavaThread::check_possible_safepoint() {
 955   if (_no_safepoint_count > 0) {
 956     print_owned_locks();
 957     assert(false, "Possible safepoint reached by thread that does not allow it");
 958   }
 959 #ifdef CHECK_UNHANDLED_OOPS
 960   // Clear unhandled oops in JavaThreads so we get a crash right away.
 961   clear_unhandled_oops();
 962 #endif // CHECK_UNHANDLED_OOPS
 963 
 964   // Macos/aarch64 should be in the right state for safepoint (e.g.
 965   // deoptimization needs WXWrite).  Crashes caused by the wrong state rarely
 966   // happens in practice, making such issues hard to find and reproduce.
 967 #if defined(__APPLE__) && defined(AARCH64)
 968   if (AssertWXAtThreadSync) {
 969     assert_wx_state(WXWrite);
 970   }
 971 #endif
 972 }
 973 
 974 void JavaThread::check_for_valid_safepoint_state() {
 975   // Check NoSafepointVerifier, which is implied by locks taken that can be
 976   // shared with the VM thread.  This makes sure that no locks with allow_vm_block
 977   // are held.
 978   check_possible_safepoint();
 979 
 980   if (thread_state() != _thread_in_vm) {
 981     fatal("LEAF method calling lock?");
 982   }
 983 
 984   if (GCALotAtAllSafepoints) {
 985     // We could enter a safepoint here and thus have a gc
 986     InterfaceSupport::check_gc_alot();
 987   }
 988 }
 989 #endif // ASSERT
 990 
 991 // A JavaThread is a normal Java thread
 992 
 993 JavaThread::JavaThread() :
 994   // Initialize fields
 995 
 996   _on_thread_list(false),
 997   DEBUG_ONLY(_java_call_counter(0) COMMA)
 998   _entry_point(nullptr),
 999   _deopt_mark(nullptr),
1000   _deopt_nmethod(nullptr),
1001   _vframe_array_head(nullptr),
1002   _vframe_array_last(nullptr),
1003   _jvmti_deferred_updates(nullptr),
1004   _callee_target(nullptr),
1005   _vm_result(nullptr),
1006   _vm_result_2(nullptr),
1007   _return_buffered_value(nullptr),
1008 
1009   _current_pending_monitor(NULL),
1010   _current_pending_monitor_is_from_java(true),
1011   _current_waiting_monitor(NULL),
1012   _active_handles(NULL),
1013   _free_handle_block(NULL),
1014   _Stalled(0),
1015 
1016   _monitor_chunks(nullptr),
1017 
1018   _suspend_flags(0),
1019   _pending_async_exception(nullptr),
1020 #ifdef ASSERT
1021   _is_unsafe_access_error(false),
1022 #endif
1023 
1024   _thread_state(_thread_new),
1025   _saved_exception_pc(nullptr),
1026 #ifdef ASSERT
1027   _no_safepoint_count(0),
1028   _visited_for_critical_count(false),
1029 #endif
1030 
1031   _terminated(_not_terminated),
1032   _in_deopt_handler(0),
1033   _doing_unsafe_access(false),
1034   _do_not_unlock_if_synchronized(false),
1035   _jni_attach_state(_not_attaching_via_jni),
1036 #if INCLUDE_JVMCI
1037   _pending_deoptimization(-1),
1038   _pending_monitorenter(false),
1039   _pending_transfer_to_interpreter(false),
1040   _in_retryable_allocation(false),
1041   _pending_failed_speculation(0),
1042   _jvmci{nullptr},
1043   _jvmci_counters(nullptr),
1044   _jvmci_reserved0(0),
1045   _jvmci_reserved1(0),
1046   _jvmci_reserved_oop0(nullptr),
1047 #endif // INCLUDE_JVMCI
1048 
1049   _exception_oop(oop()),
1050   _exception_pc(0),
1051   _exception_handler_pc(0),
1052   _is_method_handle_return(0),
1053 
1054   _jni_active_critical(0),
1055   _pending_jni_exception_check_fn(nullptr),
1056   _depth_first_number(0),
1057 
1058   // JVMTI PopFrame support
1059   _popframe_condition(popframe_inactive),
1060   _frames_to_pop_failed_realloc(0),
1061 
1062   _handshake(this),
1063 
1064   _popframe_preserved_args(nullptr),
1065   _popframe_preserved_args_size(0),
1066 
1067   _jvmti_thread_state(nullptr),
1068   _interp_only_mode(0),
1069   _should_post_on_exceptions_flag(JNI_FALSE),
1070   _thread_stat(new ThreadStatistics()),
1071 
1072   _parker(),
1073 
1074   _class_to_be_initialized(nullptr),
1075 
1076   _SleepEvent(ParkEvent::Allocate(this))
1077 {
1078   set_jni_functions(jni_functions());
1079 #if INCLUDE_JVMCI
1080   assert(_jvmci._implicit_exception_pc == nullptr, "must be");
1081   if (JVMCICounterSize > 0) {
1082     resize_counters(0, (int) JVMCICounterSize);
1083   }
1084 #endif // INCLUDE_JVMCI
1085 
1086   // Setup safepoint state info for this thread
1087   ThreadSafepointState::create(this);
1088 
1089   SafepointMechanism::initialize_header(this);
1090 
1091   set_requires_cross_modify_fence(false);
1092 
1093   pd_initialize();
1094   assert(deferred_card_mark().is_empty(), "Default MemRegion ctor");
1095 }
1096 
1097 JavaThread::JavaThread(bool is_attaching_via_jni) : JavaThread() {
1098   if (is_attaching_via_jni) {
1099     _jni_attach_state = _attaching_via_jni;
1100   }
1101 }
1102 
1103 
1104 // interrupt support
1105 
1106 void JavaThread::interrupt() {
1107   // All callers should have 'this' thread protected by a
1108   // ThreadsListHandle so that it cannot terminate and deallocate
1109   // itself.
1110   debug_only(check_for_dangling_thread_pointer(this);)
1111 
1112   // For Windows _interrupt_event
1113   WINDOWS_ONLY(osthread()->set_interrupted(true);)
1114 
1115   // For Thread.sleep
1116   _SleepEvent->unpark();
1117 
1118   // For JSR166 LockSupport.park
1119   parker()->unpark();
1120 
1121   // For ObjectMonitor and JvmtiRawMonitor
1122   _ParkEvent->unpark();
1123 }
1124 
1125 
1126 bool JavaThread::is_interrupted(bool clear_interrupted) {
1127   debug_only(check_for_dangling_thread_pointer(this);)
1128 
1129   if (_threadObj.peek() == NULL) {
1130     // If there is no j.l.Thread then it is impossible to have
1131     // been interrupted. We can find NULL during VM initialization
1132     // or when a JNI thread is still in the process of attaching.
1133     // In such cases this must be the current thread.
1134     assert(this == Thread::current(), "invariant");
1135     return false;
1136   }
1137 
1138   bool interrupted = java_lang_Thread::interrupted(threadObj());
1139 
1140   // NOTE that since there is no "lock" around the interrupt and
1141   // is_interrupted operations, there is the possibility that the
1142   // interrupted flag will be "false" but that the
1143   // low-level events will be in the signaled state. This is
1144   // intentional. The effect of this is that Object.wait() and
1145   // LockSupport.park() will appear to have a spurious wakeup, which
1146   // is allowed and not harmful, and the possibility is so rare that
1147   // it is not worth the added complexity to add yet another lock.
1148   // For the sleep event an explicit reset is performed on entry
1149   // to JavaThread::sleep, so there is no early return. It has also been
1150   // recommended not to put the interrupted flag into the "event"
1151   // structure because it hides the issue.
1152   // Also, because there is no lock, we must only clear the interrupt
1153   // state if we are going to report that we were interrupted; otherwise
1154   // an interrupt that happens just after we read the field would be lost.
1155   if (interrupted && clear_interrupted) {
1156     assert(this == Thread::current(), "only the current thread can clear");
1157     java_lang_Thread::set_interrupted(threadObj(), false);
1158     WINDOWS_ONLY(osthread()->set_interrupted(false);)
1159   }
1160 
1161   return interrupted;
1162 }
1163 
1164 void JavaThread::block_if_vm_exited() {
1165   if (_terminated == _vm_exited) {
1166     // _vm_exited is set at safepoint, and Threads_lock is never released
1167     // we will block here forever.
1168     // Here we can be doing a jump from a safe state to an unsafe state without
1169     // proper transition, but it happens after the final safepoint has begun.
1170     set_thread_state(_thread_in_vm);
1171     Threads_lock->lock();
1172     ShouldNotReachHere();
1173   }
1174 }
1175 
1176 JavaThread::JavaThread(ThreadFunction entry_point, size_t stack_sz) : JavaThread() {
1177   _jni_attach_state = _not_attaching_via_jni;
1178   set_entry_point(entry_point);
1179   // Create the native thread itself.
1180   // %note runtime_23
1181   os::ThreadType thr_type = os::java_thread;
1182   thr_type = entry_point == &CompilerThread::thread_entry ? os::compiler_thread :
1183                                                             os::java_thread;
1184   os::create_thread(this, thr_type, stack_sz);
1185   // The _osthread may be NULL here because we ran out of memory (too many threads active).
1186   // We need to throw and OutOfMemoryError - however we cannot do this here because the caller
1187   // may hold a lock and all locks must be unlocked before throwing the exception (throwing
1188   // the exception consists of creating the exception object & initializing it, initialization
1189   // will leave the VM via a JavaCall and then all locks must be unlocked).
1190   //
1191   // The thread is still suspended when we reach here. Thread must be explicit started
1192   // by creator! Furthermore, the thread must also explicitly be added to the Threads list
1193   // by calling Threads:add. The reason why this is not done here, is because the thread
1194   // object must be fully initialized (take a look at JVM_Start)
1195 }
1196 
1197 JavaThread::~JavaThread() {
1198 
1199   // Ask ServiceThread to release the threadObj OopHandle
1200   ServiceThread::add_oop_handle_release(_threadObj);
1201 
1202   // Return the sleep event to the free list
1203   ParkEvent::Release(_SleepEvent);
1204   _SleepEvent = NULL;
1205 
1206   // Free any remaining  previous UnrollBlock
1207   vframeArray* old_array = vframe_array_last();
1208 
1209   if (old_array != NULL) {
1210     Deoptimization::UnrollBlock* old_info = old_array->unroll_block();
1211     old_array->set_unroll_block(NULL);
1212     delete old_info;
1213     delete old_array;
1214   }
1215 
1216   JvmtiDeferredUpdates* updates = deferred_updates();
1217   if (updates != NULL) {
1218     // This can only happen if thread is destroyed before deoptimization occurs.
1219     assert(updates->count() > 0, "Updates holder not deleted");
1220     // free deferred updates.
1221     delete updates;
1222     set_deferred_updates(NULL);
1223   }
1224 
1225   // All Java related clean up happens in exit
1226   ThreadSafepointState::destroy(this);
1227   if (_thread_stat != NULL) delete _thread_stat;
1228 
1229 #if INCLUDE_JVMCI
1230   if (JVMCICounterSize > 0) {
1231     FREE_C_HEAP_ARRAY(jlong, _jvmci_counters);
1232   }
1233 #endif // INCLUDE_JVMCI
1234 }
1235 
1236 
1237 // First JavaThread specific code executed by a new Java thread.
1238 void JavaThread::pre_run() {
1239   // empty - see comments in run()
1240 }
1241 
1242 // The main routine called by a new Java thread. This isn't overridden
1243 // by subclasses, instead different subclasses define a different "entry_point"
1244 // which defines the actual logic for that kind of thread.
1245 void JavaThread::run() {
1246   // initialize thread-local alloc buffer related fields
1247   initialize_tlab();
1248 
1249   _stack_overflow_state.create_stack_guard_pages();
1250 
1251   cache_global_variables();
1252 
1253   // Thread is now sufficiently initialized to be handled by the safepoint code as being
1254   // in the VM. Change thread state from _thread_new to _thread_in_vm
1255   assert(this->thread_state() == _thread_new, "wrong thread state");
1256   set_thread_state(_thread_in_vm);
1257 
1258   // Before a thread is on the threads list it is always safe, so after leaving the
1259   // _thread_new we should emit a instruction barrier. The distance to modified code
1260   // from here is probably far enough, but this is consistent and safe.
1261   OrderAccess::cross_modify_fence();
1262 
1263   assert(JavaThread::current() == this, "sanity check");
1264   assert(!Thread::current()->owns_locks(), "sanity check");
1265 
1266   DTRACE_THREAD_PROBE(start, this);
1267 
1268   // This operation might block. We call that after all safepoint checks for a new thread has
1269   // been completed.
1270   set_active_handles(JNIHandleBlock::allocate_block());
1271 
1272   if (JvmtiExport::should_post_thread_life()) {
1273     JvmtiExport::post_thread_start(this);
1274 
1275   }
1276 
1277   // We call another function to do the rest so we are sure that the stack addresses used
1278   // from there will be lower than the stack base just computed.
1279   thread_main_inner();
1280 }
1281 
1282 void JavaThread::thread_main_inner() {
1283   assert(JavaThread::current() == this, "sanity check");
1284   assert(_threadObj.peek() != NULL, "just checking");
1285 
1286   // Execute thread entry point unless this thread has a pending exception
1287   // or has been stopped before starting.
1288   // Note: Due to JVM_StopThread we can have pending exceptions already!
1289   if (!this->has_pending_exception() &&
1290       !java_lang_Thread::is_stillborn(this->threadObj())) {
1291     {
1292       ResourceMark rm(this);
1293       this->set_native_thread_name(this->name());
1294     }
1295     HandleMark hm(this);
1296     this->entry_point()(this, this);
1297   }
1298 
1299   DTRACE_THREAD_PROBE(stop, this);
1300 
1301   // Cleanup is handled in post_run()
1302 }
1303 
1304 // Shared teardown for all JavaThreads
1305 void JavaThread::post_run() {
1306   this->exit(false);
1307   this->unregister_thread_stack_with_NMT();
1308   // Defer deletion to here to ensure 'this' is still referenceable in call_run
1309   // for any shared tear-down.
1310   this->smr_delete();
1311 }
1312 
1313 static void ensure_join(JavaThread* thread) {
1314   // We do not need to grab the Threads_lock, since we are operating on ourself.
1315   Handle threadObj(thread, thread->threadObj());
1316   assert(threadObj.not_null(), "java thread object must exist");
1317   ObjectLocker lock(threadObj, thread);
1318   // Ignore pending exception (ThreadDeath), since we are exiting anyway
1319   thread->clear_pending_exception();
1320   // Thread is exiting. So set thread_status field in  java.lang.Thread class to TERMINATED.
1321   java_lang_Thread::set_thread_status(threadObj(), JavaThreadStatus::TERMINATED);
1322   // Clear the native thread instance - this makes isAlive return false and allows the join()
1323   // to complete once we've done the notify_all below
1324   java_lang_Thread::set_thread(threadObj(), NULL);
1325   lock.notify_all(thread);
1326   // Ignore pending exception (ThreadDeath), since we are exiting anyway
1327   thread->clear_pending_exception();
1328 }
1329 
1330 static bool is_daemon(oop threadObj) {
1331   return (threadObj != NULL && java_lang_Thread::is_daemon(threadObj));
1332 }
1333 
1334 // For any new cleanup additions, please check to see if they need to be applied to
1335 // cleanup_failed_attach_current_thread as well.
1336 void JavaThread::exit(bool destroy_vm, ExitType exit_type) {
1337   assert(this == JavaThread::current(), "thread consistency check");
1338 
1339   elapsedTimer _timer_exit_phase1;
1340   elapsedTimer _timer_exit_phase2;
1341   elapsedTimer _timer_exit_phase3;
1342   elapsedTimer _timer_exit_phase4;
1343 
1344   if (log_is_enabled(Debug, os, thread, timer)) {
1345     _timer_exit_phase1.start();
1346   }
1347 
1348   HandleMark hm(this);
1349   Handle uncaught_exception(this, this->pending_exception());
1350   this->clear_pending_exception();
1351   Handle threadObj(this, this->threadObj());
1352   assert(threadObj.not_null(), "Java thread object should be created");
1353 
1354   if (!destroy_vm) {
1355     if (uncaught_exception.not_null()) {
1356       EXCEPTION_MARK;
1357       // Call method Thread.dispatchUncaughtException().
1358       Klass* thread_klass = vmClasses::Thread_klass();
1359       JavaValue result(T_VOID);
1360       JavaCalls::call_virtual(&result,
1361                               threadObj, thread_klass,
1362                               vmSymbols::dispatchUncaughtException_name(),
1363                               vmSymbols::throwable_void_signature(),
1364                               uncaught_exception,
1365                               THREAD);
1366       if (HAS_PENDING_EXCEPTION) {
1367         ResourceMark rm(this);
1368         jio_fprintf(defaultStream::error_stream(),
1369                     "\nException: %s thrown from the UncaughtExceptionHandler"
1370                     " in thread \"%s\"\n",
1371                     pending_exception()->klass()->external_name(),
1372                     name());
1373         CLEAR_PENDING_EXCEPTION;
1374       }
1375     }
1376 
1377     if (!is_Compiler_thread()) {
1378       // We have finished executing user-defined Java code and now have to do the
1379       // implementation specific clean-up by calling Thread.exit(). We prevent any
1380       // asynchronous exceptions from being delivered while in Thread.exit()
1381       // to ensure the clean-up is not corrupted.
1382       NoAsyncExceptionDeliveryMark _no_async(this);
1383 
1384       EXCEPTION_MARK;
1385       JavaValue result(T_VOID);
1386       Klass* thread_klass = vmClasses::Thread_klass();
1387       JavaCalls::call_virtual(&result,
1388                               threadObj, thread_klass,
1389                               vmSymbols::exit_method_name(),
1390                               vmSymbols::void_method_signature(),
1391                               THREAD);
1392       CLEAR_PENDING_EXCEPTION;
1393     }
1394 
1395     // notify JVMTI
1396     if (JvmtiExport::should_post_thread_life()) {
1397       JvmtiExport::post_thread_end(this);
1398     }
1399 
1400     // The careful dance between thread suspension and exit is handled here.
1401     // Since we are in thread_in_vm state and suspension is done with handshakes,
1402     // we can just put in the exiting state and it will be correctly handled.
1403     set_terminated(_thread_exiting);
1404 
1405     ThreadService::current_thread_exiting(this, is_daemon(threadObj()));
1406   } else {
1407     assert(!is_terminated() && !is_exiting(), "must not be exiting");
1408     // before_exit() has already posted JVMTI THREAD_END events
1409   }
1410 
1411   if (log_is_enabled(Debug, os, thread, timer)) {
1412     _timer_exit_phase1.stop();
1413     _timer_exit_phase2.start();
1414   }
1415 
1416   // Capture daemon status before the thread is marked as terminated.
1417   bool daemon = is_daemon(threadObj());
1418 
1419   // Notify waiters on thread object. This has to be done after exit() is called
1420   // on the thread (if the thread is the last thread in a daemon ThreadGroup the
1421   // group should have the destroyed bit set before waiters are notified).
1422   ensure_join(this);
1423   assert(!this->has_pending_exception(), "ensure_join should have cleared");
1424 
1425   if (log_is_enabled(Debug, os, thread, timer)) {
1426     _timer_exit_phase2.stop();
1427     _timer_exit_phase3.start();
1428   }
1429   // 6282335 JNI DetachCurrentThread spec states that all Java monitors
1430   // held by this thread must be released. The spec does not distinguish
1431   // between JNI-acquired and regular Java monitors. We can only see
1432   // regular Java monitors here if monitor enter-exit matching is broken.
1433   //
1434   // ensure_join() ignores IllegalThreadStateExceptions, and so does
1435   // ObjectSynchronizer::release_monitors_owned_by_thread().
1436   if (exit_type == jni_detach) {
1437     // Sanity check even though JNI DetachCurrentThread() would have
1438     // returned JNI_ERR if there was a Java frame. JavaThread exit
1439     // should be done executing Java code by the time we get here.
1440     assert(!this->has_last_Java_frame(),
1441            "should not have a Java frame when detaching or exiting");
1442     ObjectSynchronizer::release_monitors_owned_by_thread(this);
1443     assert(!this->has_pending_exception(), "release_monitors should have cleared");
1444   }
1445 
1446   // These things needs to be done while we are still a Java Thread. Make sure that thread
1447   // is in a consistent state, in case GC happens
1448   JFR_ONLY(Jfr::on_thread_exit(this);)
1449 
1450   if (active_handles() != NULL) {
1451     JNIHandleBlock* block = active_handles();
1452     set_active_handles(NULL);
1453     JNIHandleBlock::release_block(block);
1454   }
1455 
1456   if (free_handle_block() != NULL) {
1457     JNIHandleBlock* block = free_handle_block();
1458     set_free_handle_block(NULL);
1459     JNIHandleBlock::release_block(block);
1460   }
1461 
1462   // These have to be removed while this is still a valid thread.
1463   _stack_overflow_state.remove_stack_guard_pages();
1464 
1465   if (UseTLAB) {
1466     tlab().retire();
1467   }
1468 
1469   if (JvmtiEnv::environments_might_exist()) {
1470     JvmtiExport::cleanup_thread(this);
1471   }
1472 
1473   // We need to cache the thread name for logging purposes below as once
1474   // we have called on_thread_detach this thread must not access any oops.
1475   char* thread_name = NULL;
1476   if (log_is_enabled(Debug, os, thread, timer)) {
1477     ResourceMark rm(this);
1478     thread_name = os::strdup(name());
1479   }
1480 
1481   log_info(os, thread)("JavaThread %s (tid: " UINTX_FORMAT ").",
1482     exit_type == JavaThread::normal_exit ? "exiting" : "detaching",
1483     os::current_thread_id());
1484 
1485   if (log_is_enabled(Debug, os, thread, timer)) {
1486     _timer_exit_phase3.stop();
1487     _timer_exit_phase4.start();
1488   }
1489 
1490 #if INCLUDE_JVMCI
1491   if (JVMCICounterSize > 0) {
1492     if (jvmci_counters_include(this)) {
1493       for (int i = 0; i < JVMCICounterSize; i++) {
1494         _jvmci_old_thread_counters[i] += _jvmci_counters[i];
1495       }
1496     }
1497   }
1498 #endif // INCLUDE_JVMCI
1499 
1500   // Remove from list of active threads list, and notify VM thread if we are the last non-daemon thread
1501   Threads::remove(this, daemon);
1502 
1503   if (log_is_enabled(Debug, os, thread, timer)) {
1504     _timer_exit_phase4.stop();
1505     log_debug(os, thread, timer)("name='%s'"
1506                                  ", exit-phase1=" JLONG_FORMAT
1507                                  ", exit-phase2=" JLONG_FORMAT
1508                                  ", exit-phase3=" JLONG_FORMAT
1509                                  ", exit-phase4=" JLONG_FORMAT,
1510                                  thread_name,
1511                                  _timer_exit_phase1.milliseconds(),
1512                                  _timer_exit_phase2.milliseconds(),
1513                                  _timer_exit_phase3.milliseconds(),
1514                                  _timer_exit_phase4.milliseconds());
1515     os::free(thread_name);
1516   }
1517 }
1518 
1519 void JavaThread::cleanup_failed_attach_current_thread(bool is_daemon) {
1520   if (active_handles() != NULL) {
1521     JNIHandleBlock* block = active_handles();
1522     set_active_handles(NULL);
1523     JNIHandleBlock::release_block(block);
1524   }
1525 
1526   if (free_handle_block() != NULL) {
1527     JNIHandleBlock* block = free_handle_block();
1528     set_free_handle_block(NULL);
1529     JNIHandleBlock::release_block(block);
1530   }
1531 
1532   // These have to be removed while this is still a valid thread.
1533   _stack_overflow_state.remove_stack_guard_pages();
1534 
1535   if (UseTLAB) {
1536     tlab().retire();
1537   }
1538 
1539   Threads::remove(this, is_daemon);
1540   this->smr_delete();
1541 }
1542 
1543 JavaThread* JavaThread::active() {
1544   Thread* thread = Thread::current();
1545   if (thread->is_Java_thread()) {
1546     return JavaThread::cast(thread);
1547   } else {
1548     assert(thread->is_VM_thread(), "this must be a vm thread");
1549     VM_Operation* op = ((VMThread*) thread)->vm_operation();
1550     JavaThread *ret = op == NULL ? NULL : JavaThread::cast(op->calling_thread());
1551     return ret;
1552   }
1553 }
1554 
1555 bool JavaThread::is_lock_owned(address adr) const {
1556   if (Thread::is_lock_owned(adr)) return true;
1557 
1558   for (MonitorChunk* chunk = monitor_chunks(); chunk != NULL; chunk = chunk->next()) {
1559     if (chunk->contains(adr)) return true;
1560   }
1561 
1562   return false;
1563 }
1564 
1565 oop JavaThread::exception_oop() const {
1566   return Atomic::load(&_exception_oop);
1567 }
1568 
1569 void JavaThread::set_exception_oop(oop o) {
1570   Atomic::store(&_exception_oop, o);
1571 }
1572 
1573 void JavaThread::add_monitor_chunk(MonitorChunk* chunk) {
1574   chunk->set_next(monitor_chunks());
1575   set_monitor_chunks(chunk);
1576 }
1577 
1578 void JavaThread::remove_monitor_chunk(MonitorChunk* chunk) {
1579   guarantee(monitor_chunks() != NULL, "must be non empty");
1580   if (monitor_chunks() == chunk) {
1581     set_monitor_chunks(chunk->next());
1582   } else {
1583     MonitorChunk* prev = monitor_chunks();
1584     while (prev->next() != chunk) prev = prev->next();
1585     prev->set_next(chunk->next());
1586   }
1587 }
1588 
1589 
1590 // Asynchronous exceptions support
1591 //
1592 void JavaThread::check_and_handle_async_exceptions() {
1593   if (has_last_Java_frame() && has_async_exception_condition()) {
1594     // If we are at a polling page safepoint (not a poll return)
1595     // then we must defer async exception because live registers
1596     // will be clobbered by the exception path. Poll return is
1597     // ok because the call we are returning from already collides
1598     // with exception handling registers and so there is no issue.
1599     // (The exception handling path kills call result registers but
1600     //  this is ok since the exception kills the result anyway).
1601 
1602     if (is_at_poll_safepoint()) {
1603       // if the code we are returning to has deoptimized we must defer
1604       // the exception otherwise live registers get clobbered on the
1605       // exception path before deoptimization is able to retrieve them.
1606       //
1607       RegisterMap map(this, false);
1608       frame caller_fr = last_frame().sender(&map);
1609       assert(caller_fr.is_compiled_frame(), "what?");
1610       if (caller_fr.is_deoptimized_frame()) {
1611         log_info(exceptions)("deferred async exception at compiled safepoint");
1612         return;
1613       }
1614     }
1615   }
1616 
1617   if (!clear_async_exception_condition()) {
1618     if ((_suspend_flags & _async_delivery_disabled) != 0) {
1619       log_info(exceptions)("Async exception delivery is disabled");
1620     }
1621     return;
1622   }
1623 
1624   if (_pending_async_exception != NULL) {
1625     // Only overwrite an already pending exception if it is not a threadDeath.
1626     if (!has_pending_exception() || !pending_exception()->is_a(vmClasses::ThreadDeath_klass())) {
1627 
1628       // We cannot call Exceptions::_throw(...) here because we cannot block
1629       set_pending_exception(_pending_async_exception, __FILE__, __LINE__);
1630 
1631       LogTarget(Info, exceptions) lt;
1632       if (lt.is_enabled()) {
1633         ResourceMark rm;
1634         LogStream ls(lt);
1635         ls.print("Async. exception installed at runtime exit (" INTPTR_FORMAT ")", p2i(this));
1636           if (has_last_Java_frame()) {
1637             frame f = last_frame();
1638            ls.print(" (pc: " INTPTR_FORMAT " sp: " INTPTR_FORMAT " )", p2i(f.pc()), p2i(f.sp()));
1639           }
1640         ls.print_cr(" of type: %s", _pending_async_exception->klass()->external_name());
1641       }
1642     }
1643     // Always null out the _pending_async_exception oop here since the async condition was
1644     // already cleared above and thus considered handled.
1645     _pending_async_exception = NULL;
1646   } else {
1647     assert(_is_unsafe_access_error, "must be");
1648     DEBUG_ONLY(_is_unsafe_access_error = false);
1649 
1650     // We may be at method entry which requires we save the do-not-unlock flag.
1651     UnlockFlagSaver fs(this);
1652     Exceptions::throw_unsafe_access_internal_error(this, __FILE__, __LINE__, "a fault occurred in an unsafe memory access operation");
1653     // We might have blocked in a ThreadBlockInVM wrapper in the call above so make sure we process pending
1654     // suspend requests and object reallocation operations if any since we might be going to Java after this.
1655     SafepointMechanism::process_if_requested_with_exit_check(this, true /* check asyncs */);
1656   }
1657 }
1658 
1659 void JavaThread::handle_special_runtime_exit_condition(bool check_asyncs) {
1660 
1661   if (is_obj_deopt_suspend()) {
1662     frame_anchor()->make_walkable(this);
1663     wait_for_object_deoptimization();
1664   }
1665 
1666   // We might be here for reasons in addition to the self-suspend request
1667   // so check for other async requests.
1668   if (check_asyncs) {
1669     check_and_handle_async_exceptions();
1670   }
1671 
1672   JFR_ONLY(SUSPEND_THREAD_CONDITIONAL(this);)
1673 }
1674 
1675 class InstallAsyncExceptionClosure : public HandshakeClosure {
1676   Handle _throwable; // The Throwable thrown at the target Thread
1677 public:
1678   InstallAsyncExceptionClosure(Handle throwable) : HandshakeClosure("InstallAsyncException"), _throwable(throwable) {}
1679 
1680   void do_thread(Thread* thr) {
1681     JavaThread* target = JavaThread::cast(thr);
1682     // Note that this now allows multiple ThreadDeath exceptions to be
1683     // thrown at a thread.
1684     // The target thread has run and has not exited yet.
1685     target->send_thread_stop(_throwable());
1686   }
1687 };
1688 
1689 void JavaThread::send_async_exception(JavaThread* target, oop java_throwable) {
1690   Handle throwable(Thread::current(), java_throwable);
1691   InstallAsyncExceptionClosure vm_stop(throwable);
1692   Handshake::execute(&vm_stop, target);
1693 }
1694 
1695 void JavaThread::send_thread_stop(oop java_throwable)  {
1696   ResourceMark rm;
1697   assert(is_handshake_safe_for(Thread::current()),
1698          "should be self or handshakee");
1699 
1700   // Do not throw asynchronous exceptions against the compiler thread
1701   // (the compiler thread should not be a Java thread -- fix in 1.4.2)
1702   if (!can_call_java()) return;
1703 
1704   {
1705     // Actually throw the Throwable against the target Thread - however
1706     // only if there is no thread death exception installed already.
1707     if (_pending_async_exception == NULL || !_pending_async_exception->is_a(vmClasses::ThreadDeath_klass())) {
1708       // If the topmost frame is a runtime stub, then we are calling into
1709       // OptoRuntime from compiled code. Some runtime stubs (new, monitor_exit..)
1710       // must deoptimize the caller before continuing, as the compiled  exception handler table
1711       // may not be valid
1712       if (has_last_Java_frame()) {
1713         frame f = last_frame();
1714         if (f.is_runtime_frame() || f.is_safepoint_blob_frame()) {
1715           RegisterMap reg_map(this, false);
1716           frame compiled_frame = f.sender(&reg_map);
1717           if (!StressCompiledExceptionHandlers && compiled_frame.can_be_deoptimized()) {
1718             Deoptimization::deoptimize(this, compiled_frame);
1719           }
1720         }
1721       }
1722 
1723       // Set async. pending exception in thread.
1724       set_pending_async_exception(java_throwable);
1725 
1726       if (log_is_enabled(Info, exceptions)) {
1727          ResourceMark rm;
1728         log_info(exceptions)("Pending Async. exception installed of type: %s",
1729                              InstanceKlass::cast(_pending_async_exception->klass())->external_name());
1730       }
1731       // for AbortVMOnException flag
1732       Exceptions::debug_check_abort(_pending_async_exception->klass()->external_name());
1733     }
1734   }
1735 
1736 
1737   // Interrupt thread so it will wake up from a potential wait()/sleep()/park()
1738   java_lang_Thread::set_interrupted(threadObj(), true);
1739   this->interrupt();
1740 }
1741 
1742 
1743 // External suspension mechanism.
1744 //
1745 // Guarantees on return (for a valid target thread):
1746 //   - Target thread will not execute any new bytecode.
1747 //   - Target thread will not enter any new monitors.
1748 //
1749 bool JavaThread::java_suspend() {
1750   guarantee(Thread::is_JavaThread_protected_by_TLH(/* target */ this),
1751             "missing ThreadsListHandle in calling context.");
1752   return this->handshake_state()->suspend();
1753 }
1754 
1755 bool JavaThread::java_resume() {
1756   guarantee(Thread::is_JavaThread_protected_by_TLH(/* target */ this),
1757             "missing ThreadsListHandle in calling context.");
1758   return this->handshake_state()->resume();
1759 }
1760 
1761 // Wait for another thread to perform object reallocation and relocking on behalf of
1762 // this thread. The current thread is required to change to _thread_blocked in order
1763 // to be seen to be safepoint/handshake safe whilst suspended and only after becoming
1764 // handshake safe, the other thread can complete the handshake used to synchronize
1765 // with this thread and then perform the reallocation and relocking.
1766 // See EscapeBarrier::sync_and_suspend_*()
1767 
1768 void JavaThread::wait_for_object_deoptimization() {
1769   assert(!has_last_Java_frame() || frame_anchor()->walkable(), "should have walkable stack");
1770   assert(this == Thread::current(), "invariant");
1771 
1772   bool spin_wait = os::is_MP();
1773   do {
1774     ThreadBlockInVM tbivm(this, true /* allow_suspend */);
1775     // Wait for object deoptimization if requested.
1776     if (spin_wait) {
1777       // A single deoptimization is typically very short. Microbenchmarks
1778       // showed 5% better performance when spinning.
1779       const uint spin_limit = 10 * SpinYield::default_spin_limit;
1780       SpinYield spin(spin_limit);
1781       for (uint i = 0; is_obj_deopt_suspend() && i < spin_limit; i++) {
1782         spin.wait();
1783       }
1784       // Spin just once
1785       spin_wait = false;
1786     } else {
1787       MonitorLocker ml(this, EscapeBarrier_lock, Monitor::_no_safepoint_check_flag);
1788       if (is_obj_deopt_suspend()) {
1789         ml.wait();
1790       }
1791     }
1792     // A handshake for obj. deoptimization suspend could have been processed so
1793     // we must check after processing.
1794   } while (is_obj_deopt_suspend());
1795 }
1796 
1797 #ifdef ASSERT
1798 // Verify the JavaThread has not yet been published in the Threads::list, and
1799 // hence doesn't need protection from concurrent access at this stage.
1800 void JavaThread::verify_not_published() {
1801   // Cannot create a ThreadsListHandle here and check !tlh.includes(this)
1802   // since an unpublished JavaThread doesn't participate in the
1803   // Thread-SMR protocol for keeping a ThreadsList alive.
1804   assert(!on_thread_list(), "JavaThread shouldn't have been published yet!");
1805 }
1806 #endif
1807 
1808 // Slow path when the native==>Java barriers detect a safepoint/handshake is
1809 // pending, when _suspend_flags is non-zero or when we need to process a stack
1810 // watermark. Also check for pending async exceptions (except unsafe access error).
1811 // Note only the native==>Java barriers can call this function when thread state
1812 // is _thread_in_native_trans.
1813 void JavaThread::check_special_condition_for_native_trans(JavaThread *thread) {
1814   assert(thread->thread_state() == _thread_in_native_trans, "wrong state");
1815   assert(!thread->has_last_Java_frame() || thread->frame_anchor()->walkable(), "Unwalkable stack in native->Java transition");
1816 
1817   thread->set_thread_state(_thread_in_vm);
1818 
1819   // Enable WXWrite: called directly from interpreter native wrapper.
1820   MACOS_AARCH64_ONLY(ThreadWXEnable wx(WXWrite, thread));
1821 
1822   SafepointMechanism::process_if_requested_with_exit_check(thread, true /* check asyncs */);
1823 
1824   // After returning from native, it could be that the stack frames are not
1825   // yet safe to use. We catch such situations in the subsequent stack watermark
1826   // barrier, which will trap unsafe stack frames.
1827   StackWatermarkSet::before_unwind(thread);
1828 }
1829 
1830 #ifndef PRODUCT
1831 // Deoptimization
1832 // Function for testing deoptimization
1833 void JavaThread::deoptimize() {
1834   StackFrameStream fst(this, false /* update */, true /* process_frames */);
1835   bool deopt = false;           // Dump stack only if a deopt actually happens.
1836   bool only_at = strlen(DeoptimizeOnlyAt) > 0;
1837   // Iterate over all frames in the thread and deoptimize
1838   for (; !fst.is_done(); fst.next()) {
1839     if (fst.current()->can_be_deoptimized()) {
1840 
1841       if (only_at) {
1842         // Deoptimize only at particular bcis.  DeoptimizeOnlyAt
1843         // consists of comma or carriage return separated numbers so
1844         // search for the current bci in that string.
1845         address pc = fst.current()->pc();
1846         nmethod* nm =  (nmethod*) fst.current()->cb();
1847         ScopeDesc* sd = nm->scope_desc_at(pc);
1848         char buffer[8];
1849         jio_snprintf(buffer, sizeof(buffer), "%d", sd->bci());
1850         size_t len = strlen(buffer);
1851         const char * found = strstr(DeoptimizeOnlyAt, buffer);
1852         while (found != NULL) {
1853           if ((found[len] == ',' || found[len] == '\n' || found[len] == '\0') &&
1854               (found == DeoptimizeOnlyAt || found[-1] == ',' || found[-1] == '\n')) {
1855             // Check that the bci found is bracketed by terminators.
1856             break;
1857           }
1858           found = strstr(found + 1, buffer);
1859         }
1860         if (!found) {
1861           continue;
1862         }
1863       }
1864 
1865       if (DebugDeoptimization && !deopt) {
1866         deopt = true; // One-time only print before deopt
1867         tty->print_cr("[BEFORE Deoptimization]");
1868         trace_frames();
1869         trace_stack();
1870       }
1871       Deoptimization::deoptimize(this, *fst.current());
1872     }
1873   }
1874 
1875   if (DebugDeoptimization && deopt) {
1876     tty->print_cr("[AFTER Deoptimization]");
1877     trace_frames();
1878   }
1879 }
1880 
1881 
1882 // Make zombies
1883 void JavaThread::make_zombies() {
1884   for (StackFrameStream fst(this, true /* update */, true /* process_frames */); !fst.is_done(); fst.next()) {
1885     if (fst.current()->can_be_deoptimized()) {
1886       // it is a Java nmethod
1887       nmethod* nm = CodeCache::find_nmethod(fst.current()->pc());
1888       nm->make_not_entrant();
1889     }
1890   }
1891 }
1892 #endif // PRODUCT
1893 
1894 
1895 void JavaThread::deoptimize_marked_methods() {
1896   if (!has_last_Java_frame()) return;
1897   StackFrameStream fst(this, false /* update */, true /* process_frames */);
1898   for (; !fst.is_done(); fst.next()) {
1899     if (fst.current()->should_be_deoptimized()) {
1900       Deoptimization::deoptimize(this, *fst.current());
1901     }
1902   }
1903 }
1904 
1905 #ifdef ASSERT
1906 void JavaThread::verify_frame_info() {
1907   assert((!has_last_Java_frame() && java_call_counter() == 0) ||
1908          (has_last_Java_frame() && java_call_counter() > 0),
1909          "unexpected frame info: has_last_frame=%s, java_call_counter=%d",
1910          has_last_Java_frame() ? "true" : "false", java_call_counter());
1911 }
1912 #endif
1913 
1914 // Push on a new block of JNI handles.
1915 void JavaThread::push_jni_handle_block() {
1916   // Allocate a new block for JNI handles.
1917   // Inlined code from jni_PushLocalFrame()
1918   JNIHandleBlock* old_handles = active_handles();
1919   JNIHandleBlock* new_handles = JNIHandleBlock::allocate_block(this);
1920   assert(old_handles != NULL && new_handles != NULL, "should not be NULL");
1921   new_handles->set_pop_frame_link(old_handles);  // make sure java handles get gc'd.
1922   set_active_handles(new_handles);
1923 }
1924 
1925 // Pop off the current block of JNI handles.
1926 void JavaThread::pop_jni_handle_block() {
1927   // Release our JNI handle block
1928   JNIHandleBlock* old_handles = active_handles();
1929   JNIHandleBlock* new_handles = old_handles->pop_frame_link();
1930   assert(new_handles != nullptr, "should never set active handles to null");
1931   set_active_handles(new_handles);
1932   old_handles->set_pop_frame_link(NULL);
1933   JNIHandleBlock::release_block(old_handles, this);
1934 }
1935 
1936 void JavaThread::oops_do_no_frames(OopClosure* f, CodeBlobClosure* cf) {
1937   // Verify that the deferred card marks have been flushed.
1938   assert(deferred_card_mark().is_empty(), "Should be empty during GC");
1939 
1940   // Traverse the GCHandles
1941   Thread::oops_do_no_frames(f, cf);
1942 
1943   if (active_handles() != NULL) {
1944     active_handles()->oops_do(f);
1945   }
1946 
1947   DEBUG_ONLY(verify_frame_info();)
1948 
1949   if (has_last_Java_frame()) {
1950     // Traverse the monitor chunks
1951     for (MonitorChunk* chunk = monitor_chunks(); chunk != NULL; chunk = chunk->next()) {
1952       chunk->oops_do(f);
1953     }
1954   }
1955 
1956   assert(vframe_array_head() == NULL, "deopt in progress at a safepoint!");
1957   // If we have deferred set_locals there might be oops waiting to be
1958   // written
1959   GrowableArray<jvmtiDeferredLocalVariableSet*>* list = JvmtiDeferredUpdates::deferred_locals(this);
1960   if (list != NULL) {
1961     for (int i = 0; i < list->length(); i++) {
1962       list->at(i)->oops_do(f);
1963     }
1964   }
1965 
1966   // Traverse instance variables at the end since the GC may be moving things
1967   // around using this function
1968   f->do_oop((oop*) &_vm_result);
1969   f->do_oop((oop*) &_exception_oop);
1970   f->do_oop((oop*) &_pending_async_exception);
1971 #if INCLUDE_JVMCI
1972   f->do_oop((oop*) &_jvmci_reserved_oop0);
1973 #endif
1974 
1975   if (jvmti_thread_state() != NULL) {
1976     jvmti_thread_state()->oops_do(f, cf);
1977   }
1978 }
1979 
1980 void JavaThread::oops_do_frames(OopClosure* f, CodeBlobClosure* cf) {
1981   if (!has_last_Java_frame()) {
1982     return;
1983   }
1984   // Finish any pending lazy GC activity for the frames
1985   StackWatermarkSet::finish_processing(this, NULL /* context */, StackWatermarkKind::gc);
1986   // Traverse the execution stack
1987   for (StackFrameStream fst(this, true /* update */, false /* process_frames */); !fst.is_done(); fst.next()) {
1988     fst.current()->oops_do(f, cf, fst.register_map());
1989   }
1990 }
1991 
1992 #ifdef ASSERT
1993 void JavaThread::verify_states_for_handshake() {
1994   // This checks that the thread has a correct frame state during a handshake.
1995   verify_frame_info();
1996 }
1997 #endif
1998 
1999 void JavaThread::nmethods_do(CodeBlobClosure* cf) {
2000   DEBUG_ONLY(verify_frame_info();)
2001 
2002   if (has_last_Java_frame()) {
2003     // Traverse the execution stack
2004     for (StackFrameStream fst(this, true /* update */, true /* process_frames */); !fst.is_done(); fst.next()) {
2005       fst.current()->nmethods_do(cf);
2006     }
2007   }
2008 
2009   if (jvmti_thread_state() != NULL) {
2010     jvmti_thread_state()->nmethods_do(cf);
2011   }
2012 }
2013 
2014 void JavaThread::metadata_do(MetadataClosure* f) {
2015   if (has_last_Java_frame()) {
2016     // Traverse the execution stack to call f() on the methods in the stack
2017     for (StackFrameStream fst(this, true /* update */, true /* process_frames */); !fst.is_done(); fst.next()) {
2018       fst.current()->metadata_do(f);
2019     }
2020   } else if (is_Compiler_thread()) {
2021     // need to walk ciMetadata in current compile tasks to keep alive.
2022     CompilerThread* ct = (CompilerThread*)this;
2023     if (ct->env() != NULL) {
2024       ct->env()->metadata_do(f);
2025     }
2026     CompileTask* task = ct->task();
2027     if (task != NULL) {
2028       task->metadata_do(f);
2029     }
2030   }
2031 }
2032 
2033 // Printing
2034 const char* _get_thread_state_name(JavaThreadState _thread_state) {
2035   switch (_thread_state) {
2036   case _thread_uninitialized:     return "_thread_uninitialized";
2037   case _thread_new:               return "_thread_new";
2038   case _thread_new_trans:         return "_thread_new_trans";
2039   case _thread_in_native:         return "_thread_in_native";
2040   case _thread_in_native_trans:   return "_thread_in_native_trans";
2041   case _thread_in_vm:             return "_thread_in_vm";
2042   case _thread_in_vm_trans:       return "_thread_in_vm_trans";
2043   case _thread_in_Java:           return "_thread_in_Java";
2044   case _thread_in_Java_trans:     return "_thread_in_Java_trans";
2045   case _thread_blocked:           return "_thread_blocked";
2046   case _thread_blocked_trans:     return "_thread_blocked_trans";
2047   default:                        return "unknown thread state";
2048   }
2049 }
2050 
2051 #ifndef PRODUCT
2052 void JavaThread::print_thread_state_on(outputStream *st) const {
2053   st->print_cr("   JavaThread state: %s", _get_thread_state_name(_thread_state));
2054 };
2055 #endif // PRODUCT
2056 
2057 // Called by Threads::print() for VM_PrintThreads operation
2058 void JavaThread::print_on(outputStream *st, bool print_extended_info) const {
2059   st->print_raw("\"");
2060   st->print_raw(name());
2061   st->print_raw("\" ");
2062   oop thread_oop = threadObj();
2063   if (thread_oop != NULL) {
2064     st->print("#" INT64_FORMAT " ", (int64_t)java_lang_Thread::thread_id(thread_oop));
2065     if (java_lang_Thread::is_daemon(thread_oop))  st->print("daemon ");
2066     st->print("prio=%d ", java_lang_Thread::priority(thread_oop));
2067   }
2068   Thread::print_on(st, print_extended_info);
2069   // print guess for valid stack memory region (assume 4K pages); helps lock debugging
2070   st->print_cr("[" INTPTR_FORMAT "]", (intptr_t)last_Java_sp() & ~right_n_bits(12));
2071   if (thread_oop != NULL) {
2072     st->print_cr("   java.lang.Thread.State: %s", java_lang_Thread::thread_status_name(thread_oop));
2073   }
2074 #ifndef PRODUCT
2075   _safepoint_state->print_on(st);
2076 #endif // PRODUCT
2077   if (is_Compiler_thread()) {
2078     CompileTask *task = ((CompilerThread*)this)->task();
2079     if (task != NULL) {
2080       st->print("   Compiling: ");
2081       task->print(st, NULL, true, false);
2082     } else {
2083       st->print("   No compile task");
2084     }
2085     st->cr();
2086   }
2087 }
2088 
2089 void JavaThread::print() const { print_on(tty); }
2090 
2091 void JavaThread::print_name_on_error(outputStream* st, char *buf, int buflen) const {
2092   st->print("%s", get_thread_name_string(buf, buflen));
2093 }
2094 
2095 // Called by fatal error handler. The difference between this and
2096 // JavaThread::print() is that we can't grab lock or allocate memory.
2097 void JavaThread::print_on_error(outputStream* st, char *buf, int buflen) const {
2098   st->print("%s \"%s\"", type_name(), get_thread_name_string(buf, buflen));
2099   oop thread_obj = threadObj();
2100   if (thread_obj != NULL) {
2101     if (java_lang_Thread::is_daemon(thread_obj)) st->print(" daemon");
2102   }
2103   st->print(" [");
2104   st->print("%s", _get_thread_state_name(_thread_state));
2105   if (osthread()) {
2106     st->print(", id=%d", osthread()->thread_id());
2107   }
2108   st->print(", stack(" PTR_FORMAT "," PTR_FORMAT ")",
2109             p2i(stack_end()), p2i(stack_base()));
2110   st->print("]");
2111 
2112   ThreadsSMRSupport::print_info_on(this, st);
2113   return;
2114 }
2115 
2116 
2117 // Verification
2118 
2119 void JavaThread::frames_do(void f(frame*, const RegisterMap* map)) {
2120   // ignore if there is no stack
2121   if (!has_last_Java_frame()) return;
2122   // traverse the stack frames. Starts from top frame.
2123   for (StackFrameStream fst(this, true /* update */, true /* process_frames */); !fst.is_done(); fst.next()) {
2124     frame* fr = fst.current();
2125     f(fr, fst.register_map());
2126   }
2127 }
2128 
2129 static void frame_verify(frame* f, const RegisterMap *map) { f->verify(map); }
2130 
2131 void JavaThread::verify() {
2132   // Verify oops in the thread.
2133   oops_do(&VerifyOopClosure::verify_oop, NULL);
2134 
2135   // Verify the stack frames.
2136   frames_do(frame_verify);
2137 }
2138 
2139 // CR 6300358 (sub-CR 2137150)
2140 // Most callers of this method assume that it can't return NULL but a
2141 // thread may not have a name whilst it is in the process of attaching to
2142 // the VM - see CR 6412693, and there are places where a JavaThread can be
2143 // seen prior to having its threadObj set (e.g., JNI attaching threads and
2144 // if vm exit occurs during initialization). These cases can all be accounted
2145 // for such that this method never returns NULL.
2146 const char* JavaThread::name() const  {
2147   if (Thread::is_JavaThread_protected(/* target */ this)) {
2148     // The target JavaThread is protected so get_thread_name_string() is safe:
2149     return get_thread_name_string();
2150   }
2151 
2152   // The target JavaThread is not protected so we return the default:
2153   return Thread::name();
2154 }
2155 
2156 // Returns a non-NULL representation of this thread's name, or a suitable
2157 // descriptive string if there is no set name.
2158 const char* JavaThread::get_thread_name_string(char* buf, int buflen) const {
2159   const char* name_str;
2160   oop thread_obj = threadObj();
2161   if (thread_obj != NULL) {
2162     oop name = java_lang_Thread::name(thread_obj);
2163     if (name != NULL) {
2164       if (buf == NULL) {
2165         name_str = java_lang_String::as_utf8_string(name);
2166       } else {
2167         name_str = java_lang_String::as_utf8_string(name, buf, buflen);
2168       }
2169     } else if (is_attaching_via_jni()) { // workaround for 6412693 - see 6404306
2170       name_str = "<no-name - thread is attaching>";
2171     } else {
2172       name_str = "<un-named>";
2173     }
2174   } else {
2175     name_str = Thread::name();
2176   }
2177   assert(name_str != NULL, "unexpected NULL thread name");
2178   return name_str;
2179 }
2180 
2181 // Helper to extract the name from the thread oop for logging.
2182 const char* JavaThread::name_for(oop thread_obj) {
2183   assert(thread_obj != NULL, "precondition");
2184   oop name = java_lang_Thread::name(thread_obj);
2185   const char* name_str;
2186   if (name != NULL) {
2187     name_str = java_lang_String::as_utf8_string(name);
2188   } else {
2189     name_str = "<un-named>";
2190   }
2191   return name_str;
2192 }
2193 
2194 void JavaThread::prepare(jobject jni_thread, ThreadPriority prio) {
2195 
2196   assert(Threads_lock->owner() == Thread::current(), "must have threads lock");
2197   assert(NoPriority <= prio && prio <= MaxPriority, "sanity check");
2198   // Link Java Thread object <-> C++ Thread
2199 
2200   // Get the C++ thread object (an oop) from the JNI handle (a jthread)
2201   // and put it into a new Handle.  The Handle "thread_oop" can then
2202   // be used to pass the C++ thread object to other methods.
2203 
2204   // Set the Java level thread object (jthread) field of the
2205   // new thread (a JavaThread *) to C++ thread object using the
2206   // "thread_oop" handle.
2207 
2208   // Set the thread field (a JavaThread *) of the
2209   // oop representing the java_lang_Thread to the new thread (a JavaThread *).
2210 
2211   Handle thread_oop(Thread::current(),
2212                     JNIHandles::resolve_non_null(jni_thread));
2213   assert(InstanceKlass::cast(thread_oop->klass())->is_linked(),
2214          "must be initialized");
2215   set_threadObj(thread_oop());
2216   java_lang_Thread::set_thread(thread_oop(), this);
2217 
2218   if (prio == NoPriority) {
2219     prio = java_lang_Thread::priority(thread_oop());
2220     assert(prio != NoPriority, "A valid priority should be present");
2221   }
2222 
2223   // Push the Java priority down to the native thread; needs Threads_lock
2224   Thread::set_priority(this, prio);
2225 
2226   // Add the new thread to the Threads list and set it in motion.
2227   // We must have threads lock in order to call Threads::add.
2228   // It is crucial that we do not block before the thread is
2229   // added to the Threads list for if a GC happens, then the java_thread oop
2230   // will not be visited by GC.
2231   Threads::add(this);
2232 }
2233 
2234 oop JavaThread::current_park_blocker() {
2235   // Support for JSR-166 locks
2236   oop thread_oop = threadObj();
2237   if (thread_oop != NULL) {
2238     return java_lang_Thread::park_blocker(thread_oop);
2239   }
2240   return NULL;
2241 }
2242 
2243 
2244 void JavaThread::print_stack_on(outputStream* st) {
2245   if (!has_last_Java_frame()) return;
2246 
2247   Thread* current_thread = Thread::current();
2248   ResourceMark rm(current_thread);
2249   HandleMark hm(current_thread);
2250 
2251   RegisterMap reg_map(this);
2252   vframe* start_vf = last_java_vframe(&reg_map);
2253   int count = 0;
2254   for (vframe* f = start_vf; f != NULL; f = f->sender()) {
2255     if (f->is_java_frame()) {
2256       javaVFrame* jvf = javaVFrame::cast(f);
2257       java_lang_Throwable::print_stack_element(st, jvf->method(), jvf->bci());
2258 
2259       // Print out lock information
2260       if (JavaMonitorsInStackTrace) {
2261         jvf->print_lock_info_on(st, count);
2262       }
2263     } else {
2264       // Ignore non-Java frames
2265     }
2266 
2267     // Bail-out case for too deep stacks if MaxJavaStackTraceDepth > 0
2268     count++;
2269     if (MaxJavaStackTraceDepth > 0 && MaxJavaStackTraceDepth == count) return;
2270   }
2271 }
2272 
2273 
2274 // JVMTI PopFrame support
2275 void JavaThread::popframe_preserve_args(ByteSize size_in_bytes, void* start) {
2276   assert(_popframe_preserved_args == NULL, "should not wipe out old PopFrame preserved arguments");
2277   if (in_bytes(size_in_bytes) != 0) {
2278     _popframe_preserved_args = NEW_C_HEAP_ARRAY(char, in_bytes(size_in_bytes), mtThread);
2279     _popframe_preserved_args_size = in_bytes(size_in_bytes);
2280     Copy::conjoint_jbytes(start, _popframe_preserved_args, _popframe_preserved_args_size);
2281   }
2282 }
2283 
2284 void* JavaThread::popframe_preserved_args() {
2285   return _popframe_preserved_args;
2286 }
2287 
2288 ByteSize JavaThread::popframe_preserved_args_size() {
2289   return in_ByteSize(_popframe_preserved_args_size);
2290 }
2291 
2292 WordSize JavaThread::popframe_preserved_args_size_in_words() {
2293   int sz = in_bytes(popframe_preserved_args_size());
2294   assert(sz % wordSize == 0, "argument size must be multiple of wordSize");
2295   return in_WordSize(sz / wordSize);
2296 }
2297 
2298 void JavaThread::popframe_free_preserved_args() {
2299   assert(_popframe_preserved_args != NULL, "should not free PopFrame preserved arguments twice");
2300   FREE_C_HEAP_ARRAY(char, (char*)_popframe_preserved_args);
2301   _popframe_preserved_args = NULL;
2302   _popframe_preserved_args_size = 0;
2303 }
2304 
2305 #ifndef PRODUCT
2306 
2307 void JavaThread::trace_frames() {
2308   tty->print_cr("[Describe stack]");
2309   int frame_no = 1;
2310   for (StackFrameStream fst(this, true /* update */, true /* process_frames */); !fst.is_done(); fst.next()) {
2311     tty->print("  %d. ", frame_no++);
2312     fst.current()->print_value_on(tty, this);
2313     tty->cr();
2314   }
2315 }
2316 
2317 class PrintAndVerifyOopClosure: public OopClosure {
2318  protected:
2319   template <class T> inline void do_oop_work(T* p) {
2320     oop obj = RawAccess<>::oop_load(p);
2321     if (obj == NULL) return;
2322     tty->print(INTPTR_FORMAT ": ", p2i(p));
2323     if (oopDesc::is_oop_or_null(obj)) {
2324       if (obj->is_objArray()) {
2325         tty->print_cr("valid objArray: " INTPTR_FORMAT, p2i(obj));
2326       } else {
2327         obj->print();
2328       }
2329     } else {
2330       tty->print_cr("invalid oop: " INTPTR_FORMAT, p2i(obj));
2331     }
2332     tty->cr();
2333   }
2334  public:
2335   virtual void do_oop(oop* p) { do_oop_work(p); }
2336   virtual void do_oop(narrowOop* p)  { do_oop_work(p); }
2337 };
2338 
2339 #ifdef ASSERT
2340 // Print or validate the layout of stack frames
2341 void JavaThread::print_frame_layout(int depth, bool validate_only) {
2342   ResourceMark rm;
2343   PreserveExceptionMark pm(this);
2344   FrameValues values;
2345   int frame_no = 0;
2346   for (StackFrameStream fst(this, false /* update */, true /* process_frames */); !fst.is_done(); fst.next()) {
2347     fst.current()->describe(values, ++frame_no);
2348     if (depth == frame_no) break;
2349   }
2350   if (validate_only) {
2351     values.validate();
2352   } else {
2353     tty->print_cr("[Describe stack layout]");
2354     values.print(this);
2355   }
2356 }
2357 #endif
2358 
2359 void JavaThread::trace_stack_from(vframe* start_vf) {
2360   ResourceMark rm;
2361   int vframe_no = 1;
2362   for (vframe* f = start_vf; f; f = f->sender()) {
2363     if (f->is_java_frame()) {
2364       javaVFrame::cast(f)->print_activation(vframe_no++);
2365     } else {
2366       f->print();
2367     }
2368     if (vframe_no > StackPrintLimit) {
2369       tty->print_cr("...<more frames>...");
2370       return;
2371     }
2372   }
2373 }
2374 
2375 
2376 void JavaThread::trace_stack() {
2377   if (!has_last_Java_frame()) return;
2378   Thread* current_thread = Thread::current();
2379   ResourceMark rm(current_thread);
2380   HandleMark hm(current_thread);
2381   RegisterMap reg_map(this);
2382   trace_stack_from(last_java_vframe(&reg_map));
2383 }
2384 
2385 
2386 #endif // PRODUCT
2387 
2388 
2389 javaVFrame* JavaThread::last_java_vframe(RegisterMap *reg_map) {
2390   assert(reg_map != NULL, "a map must be given");
2391   frame f = last_frame();
2392   for (vframe* vf = vframe::new_vframe(&f, reg_map, this); vf; vf = vf->sender()) {
2393     if (vf->is_java_frame()) return javaVFrame::cast(vf);
2394   }
2395   return NULL;
2396 }
2397 
2398 
2399 Klass* JavaThread::security_get_caller_class(int depth) {
2400   vframeStream vfst(this);
2401   vfst.security_get_caller_frame(depth);
2402   if (!vfst.at_end()) {
2403     return vfst.method()->method_holder();
2404   }
2405   return NULL;
2406 }
2407 
2408 // java.lang.Thread.sleep support
2409 // Returns true if sleep time elapsed as expected, and false
2410 // if the thread was interrupted.
2411 bool JavaThread::sleep(jlong millis) {
2412   assert(this == Thread::current(),  "thread consistency check");
2413 
2414   ParkEvent * const slp = this->_SleepEvent;
2415   // Because there can be races with thread interruption sending an unpark()
2416   // to the event, we explicitly reset it here to avoid an immediate return.
2417   // The actual interrupt state will be checked before we park().
2418   slp->reset();
2419   // Thread interruption establishes a happens-before ordering in the
2420   // Java Memory Model, so we need to ensure we synchronize with the
2421   // interrupt state.
2422   OrderAccess::fence();
2423 
2424   jlong prevtime = os::javaTimeNanos();
2425 
2426   for (;;) {
2427     // interruption has precedence over timing out
2428     if (this->is_interrupted(true)) {
2429       return false;
2430     }
2431 
2432     if (millis <= 0) {
2433       return true;
2434     }
2435 
2436     {
2437       ThreadBlockInVM tbivm(this);
2438       OSThreadWaitState osts(this->osthread(), false /* not Object.wait() */);
2439       slp->park(millis);
2440     }
2441 
2442     // Update elapsed time tracking
2443     jlong newtime = os::javaTimeNanos();
2444     if (newtime - prevtime < 0) {
2445       // time moving backwards, should only happen if no monotonic clock
2446       // not a guarantee() because JVM should not abort on kernel/glibc bugs
2447       assert(false,
2448              "unexpected time moving backwards detected in JavaThread::sleep()");
2449     } else {
2450       millis -= (newtime - prevtime) / NANOSECS_PER_MILLISEC;
2451     }
2452     prevtime = newtime;
2453   }
2454 }
2455 
2456 
2457 // ======= Threads ========
2458 
2459 // The Threads class links together all active threads, and provides
2460 // operations over all threads. It is protected by the Threads_lock,
2461 // which is also used in other global contexts like safepointing.
2462 // ThreadsListHandles are used to safely perform operations on one
2463 // or more threads without the risk of the thread exiting during the
2464 // operation.
2465 //
2466 // Note: The Threads_lock is currently more widely used than we
2467 // would like. We are actively migrating Threads_lock uses to other
2468 // mechanisms in order to reduce Threads_lock contention.
2469 
2470 int         Threads::_number_of_threads = 0;
2471 int         Threads::_number_of_non_daemon_threads = 0;
2472 int         Threads::_return_code = 0;
2473 uintx       Threads::_thread_claim_token = 1; // Never zero.
2474 size_t      JavaThread::_stack_size_at_create = 0;
2475 
2476 #ifdef ASSERT
2477 bool        Threads::_vm_complete = false;
2478 #endif
2479 
2480 // All NonJavaThreads (i.e., every non-JavaThread in the system).
2481 void Threads::non_java_threads_do(ThreadClosure* tc) {
2482   NoSafepointVerifier nsv;
2483   for (NonJavaThread::Iterator njti; !njti.end(); njti.step()) {
2484     tc->do_thread(njti.current());
2485   }
2486 }
2487 
2488 // All JavaThreads
2489 #define ALL_JAVA_THREADS(X) \
2490   for (JavaThread* X : *ThreadsSMRSupport::get_java_thread_list())
2491 
2492 // All JavaThreads
2493 void Threads::java_threads_do(ThreadClosure* tc) {
2494   assert_locked_or_safepoint(Threads_lock);
2495   // ALL_JAVA_THREADS iterates through all JavaThreads.
2496   ALL_JAVA_THREADS(p) {
2497     tc->do_thread(p);
2498   }
2499 }
2500 
2501 void Threads::java_threads_and_vm_thread_do(ThreadClosure* tc) {
2502   assert_locked_or_safepoint(Threads_lock);
2503   java_threads_do(tc);
2504   tc->do_thread(VMThread::vm_thread());
2505 }
2506 
2507 // All JavaThreads + all non-JavaThreads (i.e., every thread in the system).
2508 void Threads::threads_do(ThreadClosure* tc) {
2509   assert_locked_or_safepoint(Threads_lock);
2510   java_threads_do(tc);
2511   non_java_threads_do(tc);
2512 }
2513 
2514 void Threads::possibly_parallel_threads_do(bool is_par, ThreadClosure* tc) {
2515   uintx claim_token = Threads::thread_claim_token();
2516   ALL_JAVA_THREADS(p) {
2517     if (p->claim_threads_do(is_par, claim_token)) {
2518       tc->do_thread(p);
2519     }
2520   }
2521   VMThread* vmt = VMThread::vm_thread();
2522   if (vmt->claim_threads_do(is_par, claim_token)) {
2523     tc->do_thread(vmt);
2524   }
2525 }
2526 
2527 // The system initialization in the library has three phases.
2528 //
2529 // Phase 1: java.lang.System class initialization
2530 //     java.lang.System is a primordial class loaded and initialized
2531 //     by the VM early during startup.  java.lang.System.<clinit>
2532 //     only does registerNatives and keeps the rest of the class
2533 //     initialization work later until thread initialization completes.
2534 //
2535 //     System.initPhase1 initializes the system properties, the static
2536 //     fields in, out, and err. Set up java signal handlers, OS-specific
2537 //     system settings, and thread group of the main thread.
2538 static void call_initPhase1(TRAPS) {
2539   Klass* klass = vmClasses::System_klass();
2540   JavaValue result(T_VOID);
2541   JavaCalls::call_static(&result, klass, vmSymbols::initPhase1_name(),
2542                                          vmSymbols::void_method_signature(), CHECK);
2543 }
2544 
2545 // Phase 2. Module system initialization
2546 //     This will initialize the module system.  Only java.base classes
2547 //     can be loaded until phase 2 completes.
2548 //
2549 //     Call System.initPhase2 after the compiler initialization and jsr292
2550 //     classes get initialized because module initialization runs a lot of java
2551 //     code, that for performance reasons, should be compiled.  Also, this will
2552 //     enable the startup code to use lambda and other language features in this
2553 //     phase and onward.
2554 //
2555 //     After phase 2, The VM will begin search classes from -Xbootclasspath/a.
2556 static void call_initPhase2(TRAPS) {
2557   TraceTime timer("Initialize module system", TRACETIME_LOG(Info, startuptime));
2558 
2559   Klass* klass = vmClasses::System_klass();
2560 
2561   JavaValue result(T_INT);
2562   JavaCallArguments args;
2563   args.push_int(DisplayVMOutputToStderr);
2564   args.push_int(log_is_enabled(Debug, init)); // print stack trace if exception thrown
2565   JavaCalls::call_static(&result, klass, vmSymbols::initPhase2_name(),
2566                                          vmSymbols::boolean_boolean_int_signature(), &args, CHECK);
2567   if (result.get_jint() != JNI_OK) {
2568     vm_exit_during_initialization(); // no message or exception
2569   }
2570 
2571   universe_post_module_init();
2572 }
2573 
2574 // Phase 3. final setup - set security manager, system class loader and TCCL
2575 //
2576 //     This will instantiate and set the security manager, set the system class
2577 //     loader as well as the thread context class loader.  The security manager
2578 //     and system class loader may be a custom class loaded from -Xbootclasspath/a,
2579 //     other modules or the application's classpath.
2580 static void call_initPhase3(TRAPS) {
2581   Klass* klass = vmClasses::System_klass();
2582   JavaValue result(T_VOID);
2583   JavaCalls::call_static(&result, klass, vmSymbols::initPhase3_name(),
2584                                          vmSymbols::void_method_signature(), CHECK);
2585 }
2586 
2587 void Threads::initialize_java_lang_classes(JavaThread* main_thread, TRAPS) {
2588   TraceTime timer("Initialize java.lang classes", TRACETIME_LOG(Info, startuptime));
2589 
2590   if (EagerXrunInit && Arguments::init_libraries_at_startup()) {
2591     create_vm_init_libraries();
2592   }
2593 
2594   initialize_class(vmSymbols::java_lang_String(), CHECK);
2595 
2596   // Inject CompactStrings value after the static initializers for String ran.
2597   java_lang_String::set_compact_strings(CompactStrings);
2598 
2599   // Initialize java_lang.System (needed before creating the thread)
2600   initialize_class(vmSymbols::java_lang_System(), CHECK);
2601   // The VM creates & returns objects of this class. Make sure it's initialized.
2602   initialize_class(vmSymbols::java_lang_Class(), CHECK);
2603   initialize_class(vmSymbols::java_lang_ThreadGroup(), CHECK);
2604   Handle thread_group = create_initial_thread_group(CHECK);
2605   Universe::set_main_thread_group(thread_group());
2606   initialize_class(vmSymbols::java_lang_Thread(), CHECK);
2607   create_initial_thread(thread_group, main_thread, CHECK);
2608 
2609   // The VM creates objects of this class.
2610   initialize_class(vmSymbols::java_lang_Module(), CHECK);
2611 
2612 #ifdef ASSERT
2613   InstanceKlass *k = vmClasses::UnsafeConstants_klass();
2614   assert(k->is_not_initialized(), "UnsafeConstants should not already be initialized");
2615 #endif
2616 
2617   // initialize the hardware-specific constants needed by Unsafe
2618   initialize_class(vmSymbols::jdk_internal_misc_UnsafeConstants(), CHECK);
2619   jdk_internal_misc_UnsafeConstants::set_unsafe_constants();
2620 
2621   // The VM preresolves methods to these classes. Make sure that they get initialized
2622   initialize_class(vmSymbols::java_lang_reflect_Method(), CHECK);
2623   initialize_class(vmSymbols::java_lang_ref_Finalizer(), CHECK);
2624 
2625   // Phase 1 of the system initialization in the library, java.lang.System class initialization
2626   call_initPhase1(CHECK);
2627 
2628   // Get the Java runtime name, version, and vendor info after java.lang.System is initialized.
2629   // Some values are actually configure-time constants but some can be set via the jlink tool and
2630   // so must be read dynamically. We treat them all the same.
2631   InstanceKlass* ik = SystemDictionary::find_instance_klass(vmSymbols::java_lang_VersionProps(),
2632                                                             Handle(), Handle());
2633   {
2634     ResourceMark rm(main_thread);
2635     JDK_Version::set_java_version(get_java_version_info(ik, vmSymbols::java_version_name()));
2636 
2637     JDK_Version::set_runtime_name(get_java_version_info(ik, vmSymbols::java_runtime_name_name()));
2638 
2639     JDK_Version::set_runtime_version(get_java_version_info(ik, vmSymbols::java_runtime_version_name()));
2640 
2641     JDK_Version::set_runtime_vendor_version(get_java_version_info(ik, vmSymbols::java_runtime_vendor_version_name()));
2642 
2643     JDK_Version::set_runtime_vendor_vm_bug_url(get_java_version_info(ik, vmSymbols::java_runtime_vendor_vm_bug_url_name()));
2644   }
2645 
2646   // an instance of OutOfMemory exception has been allocated earlier
2647   initialize_class(vmSymbols::java_lang_OutOfMemoryError(), CHECK);
2648   initialize_class(vmSymbols::java_lang_NullPointerException(), CHECK);
2649   initialize_class(vmSymbols::java_lang_ClassCastException(), CHECK);
2650   initialize_class(vmSymbols::java_lang_ArrayStoreException(), CHECK);
2651   initialize_class(vmSymbols::java_lang_ArithmeticException(), CHECK);
2652   initialize_class(vmSymbols::java_lang_StackOverflowError(), CHECK);
2653   initialize_class(vmSymbols::java_lang_IllegalMonitorStateException(), CHECK);
2654   initialize_class(vmSymbols::java_lang_IllegalArgumentException(), CHECK);
2655 }
2656 
2657 void Threads::initialize_jsr292_core_classes(TRAPS) {
2658   TraceTime timer("Initialize java.lang.invoke classes", TRACETIME_LOG(Info, startuptime));
2659 
2660   initialize_class(vmSymbols::java_lang_invoke_MethodHandle(), CHECK);
2661   initialize_class(vmSymbols::java_lang_invoke_ResolvedMethodName(), CHECK);
2662   initialize_class(vmSymbols::java_lang_invoke_MemberName(), CHECK);
2663   initialize_class(vmSymbols::java_lang_invoke_MethodHandleNatives(), CHECK);
2664 }
2665 
2666 jint Threads::create_vm(JavaVMInitArgs* args, bool* canTryAgain) {
2667   extern void JDK_Version_init();
2668 
2669   // Preinitialize version info.
2670   VM_Version::early_initialize();
2671 
2672   // Check version
2673   if (!is_supported_jni_version(args->version)) return JNI_EVERSION;
2674 
2675   // Initialize library-based TLS
2676   ThreadLocalStorage::init();
2677 
2678   // Initialize the output stream module
2679   ostream_init();
2680 
2681   // Process java launcher properties.
2682   Arguments::process_sun_java_launcher_properties(args);
2683 
2684   // Initialize the os module
2685   os::init();
2686 
2687   MACOS_AARCH64_ONLY(os::current_thread_enable_wx(WXWrite));
2688 
2689   // Record VM creation timing statistics
2690   TraceVmCreationTime create_vm_timer;
2691   create_vm_timer.start();
2692 
2693   // Initialize system properties.
2694   Arguments::init_system_properties();
2695 
2696   // So that JDK version can be used as a discriminator when parsing arguments
2697   JDK_Version_init();
2698 
2699   // Update/Initialize System properties after JDK version number is known
2700   Arguments::init_version_specific_system_properties();
2701 
2702   // Make sure to initialize log configuration *before* parsing arguments
2703   LogConfiguration::initialize(create_vm_timer.begin_time());
2704 
2705   // Parse arguments
2706   // Note: this internally calls os::init_container_support()
2707   jint parse_result = Arguments::parse(args);
2708   if (parse_result != JNI_OK) return parse_result;
2709 
2710   // Initialize NMT right after argument parsing to keep the pre-NMT-init window small.
2711   MemTracker::initialize();
2712 
2713   os::init_before_ergo();
2714 
2715   jint ergo_result = Arguments::apply_ergo();
2716   if (ergo_result != JNI_OK) return ergo_result;
2717 
2718   // Final check of all ranges after ergonomics which may change values.
2719   if (!JVMFlagLimit::check_all_ranges()) {
2720     return JNI_EINVAL;
2721   }
2722 
2723   // Final check of all 'AfterErgo' constraints after ergonomics which may change values.
2724   bool constraint_result = JVMFlagLimit::check_all_constraints(JVMFlagConstraintPhase::AfterErgo);
2725   if (!constraint_result) {
2726     return JNI_EINVAL;
2727   }
2728 
2729   if (PauseAtStartup) {
2730     os::pause();
2731   }
2732 
2733   HOTSPOT_VM_INIT_BEGIN();
2734 
2735   // Timing (must come after argument parsing)
2736   TraceTime timer("Create VM", TRACETIME_LOG(Info, startuptime));
2737 
2738   // Initialize the os module after parsing the args
2739   jint os_init_2_result = os::init_2();
2740   if (os_init_2_result != JNI_OK) return os_init_2_result;
2741 
2742 #ifdef CAN_SHOW_REGISTERS_ON_ASSERT
2743   // Initialize assert poison page mechanism.
2744   if (ShowRegistersOnAssert) {
2745     initialize_assert_poison();
2746   }
2747 #endif // CAN_SHOW_REGISTERS_ON_ASSERT
2748 
2749   SafepointMechanism::initialize();
2750 
2751   jint adjust_after_os_result = Arguments::adjust_after_os();
2752   if (adjust_after_os_result != JNI_OK) return adjust_after_os_result;
2753 
2754   // Initialize output stream logging
2755   ostream_init_log();
2756 
2757   // Convert -Xrun to -agentlib: if there is no JVM_OnLoad
2758   // Must be before create_vm_init_agents()
2759   if (Arguments::init_libraries_at_startup()) {
2760     convert_vm_init_libraries_to_agents();
2761   }
2762 
2763   // Launch -agentlib/-agentpath and converted -Xrun agents
2764   if (Arguments::init_agents_at_startup()) {
2765     create_vm_init_agents();
2766   }
2767 
2768   // Initialize Threads state
2769   _number_of_threads = 0;
2770   _number_of_non_daemon_threads = 0;
2771 
2772   // Initialize global data structures and create system classes in heap
2773   vm_init_globals();
2774 
2775 #if INCLUDE_JVMCI
2776   if (JVMCICounterSize > 0) {
2777     JavaThread::_jvmci_old_thread_counters = NEW_C_HEAP_ARRAY(jlong, JVMCICounterSize, mtJVMCI);
2778     memset(JavaThread::_jvmci_old_thread_counters, 0, sizeof(jlong) * JVMCICounterSize);
2779   } else {
2780     JavaThread::_jvmci_old_thread_counters = NULL;
2781   }
2782 #endif // INCLUDE_JVMCI
2783 
2784   // Initialize OopStorage for threadObj
2785   _thread_oop_storage = OopStorageSet::create_strong("Thread OopStorage", mtThread);
2786 
2787   // Attach the main thread to this os thread
2788   JavaThread* main_thread = new JavaThread();
2789   main_thread->set_thread_state(_thread_in_vm);
2790   main_thread->initialize_thread_current();
2791   // must do this before set_active_handles
2792   main_thread->record_stack_base_and_size();
2793   main_thread->register_thread_stack_with_NMT();
2794   main_thread->set_active_handles(JNIHandleBlock::allocate_block());
2795   MACOS_AARCH64_ONLY(main_thread->init_wx());
2796 
2797   if (!main_thread->set_as_starting_thread()) {
2798     vm_shutdown_during_initialization(
2799                                       "Failed necessary internal allocation. Out of swap space");
2800     main_thread->smr_delete();
2801     *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again
2802     return JNI_ENOMEM;
2803   }
2804 
2805   // Enable guard page *after* os::create_main_thread(), otherwise it would
2806   // crash Linux VM, see notes in os_linux.cpp.
2807   main_thread->stack_overflow_state()->create_stack_guard_pages();
2808 
2809   // Initialize Java-Level synchronization subsystem
2810   ObjectMonitor::Initialize();
2811   ObjectSynchronizer::initialize();
2812 
2813   // Initialize global modules
2814   jint status = init_globals();
2815   if (status != JNI_OK) {
2816     main_thread->smr_delete();
2817     *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again
2818     return status;
2819   }
2820 
2821   JFR_ONLY(Jfr::on_create_vm_1();)
2822 
2823   // Should be done after the heap is fully created
2824   main_thread->cache_global_variables();
2825 
2826   { MutexLocker mu(Threads_lock);
2827     Threads::add(main_thread);
2828   }
2829 
2830   // Any JVMTI raw monitors entered in onload will transition into
2831   // real raw monitor. VM is setup enough here for raw monitor enter.
2832   JvmtiExport::transition_pending_onload_raw_monitors();
2833 
2834   // Create the VMThread
2835   { TraceTime timer("Start VMThread", TRACETIME_LOG(Info, startuptime));
2836 
2837     VMThread::create();
2838     VMThread* vmthread = VMThread::vm_thread();
2839 
2840     if (!os::create_thread(vmthread, os::vm_thread)) {
2841       vm_exit_during_initialization("Cannot create VM thread. "
2842                                     "Out of system resources.");
2843     }
2844 
2845     // Wait for the VM thread to become ready, and VMThread::run to initialize
2846     // Monitors can have spurious returns, must always check another state flag
2847     {
2848       MonitorLocker ml(Notify_lock);
2849       os::start_thread(vmthread);
2850       while (!vmthread->is_running()) {
2851         ml.wait();
2852       }
2853     }
2854   }
2855 
2856   assert(Universe::is_fully_initialized(), "not initialized");
2857   if (VerifyDuringStartup) {
2858     // Make sure we're starting with a clean slate.
2859     VM_Verify verify_op;
2860     VMThread::execute(&verify_op);
2861   }
2862 
2863   // We need this to update the java.vm.info property in case any flags used
2864   // to initially define it have been changed. This is needed for both CDS
2865   // since UseSharedSpaces may be changed after java.vm.info
2866   // is initially computed. See Abstract_VM_Version::vm_info_string().
2867   // This update must happen before we initialize the java classes, but
2868   // after any initialization logic that might modify the flags.
2869   Arguments::update_vm_info_property(VM_Version::vm_info_string());
2870 
2871   JavaThread* THREAD = JavaThread::current(); // For exception macros.
2872   HandleMark hm(THREAD);
2873 
2874   // Always call even when there are not JVMTI environments yet, since environments
2875   // may be attached late and JVMTI must track phases of VM execution
2876   JvmtiExport::enter_early_start_phase();
2877 
2878   // Notify JVMTI agents that VM has started (JNI is up) - nop if no agents.
2879   JvmtiExport::post_early_vm_start();
2880 
2881   initialize_java_lang_classes(main_thread, CHECK_JNI_ERR);
2882 
2883   quicken_jni_functions();
2884 
2885   // No more stub generation allowed after that point.
2886   StubCodeDesc::freeze();
2887 
2888   // Set flag that basic initialization has completed. Used by exceptions and various
2889   // debug stuff, that does not work until all basic classes have been initialized.
2890   set_init_completed();
2891 
2892   LogConfiguration::post_initialize();
2893   Metaspace::post_initialize();
2894 
2895   HOTSPOT_VM_INIT_END();
2896 
2897   // record VM initialization completion time
2898 #if INCLUDE_MANAGEMENT
2899   Management::record_vm_init_completed();
2900 #endif // INCLUDE_MANAGEMENT
2901 
2902   // Signal Dispatcher needs to be started before VMInit event is posted
2903   os::initialize_jdk_signal_support(CHECK_JNI_ERR);
2904 
2905   // Start Attach Listener if +StartAttachListener or it can't be started lazily
2906   if (!DisableAttachMechanism) {
2907     AttachListener::vm_start();
2908     if (StartAttachListener || AttachListener::init_at_startup()) {
2909       AttachListener::init();
2910     }
2911   }
2912 
2913   // Launch -Xrun agents
2914   // Must be done in the JVMTI live phase so that for backward compatibility the JDWP
2915   // back-end can launch with -Xdebug -Xrunjdwp.
2916   if (!EagerXrunInit && Arguments::init_libraries_at_startup()) {
2917     create_vm_init_libraries();
2918   }
2919 
2920   Chunk::start_chunk_pool_cleaner_task();
2921 
2922   // Start the service thread
2923   // The service thread enqueues JVMTI deferred events and does various hashtable
2924   // and other cleanups.  Needs to start before the compilers start posting events.
2925   ServiceThread::initialize();
2926 
2927   // Start the monitor deflation thread:
2928   MonitorDeflationThread::initialize();
2929 
2930   // initialize compiler(s)
2931 #if defined(COMPILER1) || COMPILER2_OR_JVMCI
2932 #if INCLUDE_JVMCI
2933   bool force_JVMCI_intialization = false;
2934   if (EnableJVMCI) {
2935     // Initialize JVMCI eagerly when it is explicitly requested.
2936     // Or when JVMCILibDumpJNIConfig or JVMCIPrintProperties is enabled.
2937     force_JVMCI_intialization = EagerJVMCI || JVMCIPrintProperties || JVMCILibDumpJNIConfig;
2938 
2939     if (!force_JVMCI_intialization) {
2940       // 8145270: Force initialization of JVMCI runtime otherwise requests for blocking
2941       // compilations via JVMCI will not actually block until JVMCI is initialized.
2942       force_JVMCI_intialization = UseJVMCICompiler && (!UseInterpreter || !BackgroundCompilation);
2943     }
2944   }
2945 #endif
2946   CompileBroker::compilation_init_phase1(CHECK_JNI_ERR);
2947   // Postpone completion of compiler initialization to after JVMCI
2948   // is initialized to avoid timeouts of blocking compilations.
2949   if (JVMCI_ONLY(!force_JVMCI_intialization) NOT_JVMCI(true)) {
2950     CompileBroker::compilation_init_phase2();
2951   }
2952 #endif
2953 
2954   // Pre-initialize some JSR292 core classes to avoid deadlock during class loading.
2955   // It is done after compilers are initialized, because otherwise compilations of
2956   // signature polymorphic MH intrinsics can be missed
2957   // (see SystemDictionary::find_method_handle_intrinsic).
2958   initialize_jsr292_core_classes(CHECK_JNI_ERR);
2959 
2960   // This will initialize the module system.  Only java.base classes can be
2961   // loaded until phase 2 completes
2962   call_initPhase2(CHECK_JNI_ERR);
2963 
2964   JFR_ONLY(Jfr::on_create_vm_2();)
2965 
2966   // Always call even when there are not JVMTI environments yet, since environments
2967   // may be attached late and JVMTI must track phases of VM execution
2968   JvmtiExport::enter_start_phase();
2969 
2970   // Notify JVMTI agents that VM has started (JNI is up) - nop if no agents.
2971   JvmtiExport::post_vm_start();
2972 
2973   // Final system initialization including security manager and system class loader
2974   call_initPhase3(CHECK_JNI_ERR);
2975 
2976   // cache the system and platform class loaders
2977   SystemDictionary::compute_java_loaders(CHECK_JNI_ERR);
2978 
2979 #if INCLUDE_CDS
2980   // capture the module path info from the ModuleEntryTable
2981   ClassLoader::initialize_module_path(THREAD);
2982   if (HAS_PENDING_EXCEPTION) {
2983     java_lang_Throwable::print(PENDING_EXCEPTION, tty);
2984     vm_exit_during_initialization("ClassLoader::initialize_module_path() failed unexpectedly");
2985   }
2986 #endif
2987 
2988 #if INCLUDE_JVMCI
2989   if (force_JVMCI_intialization) {
2990     JVMCI::initialize_compiler(CHECK_JNI_ERR);
2991     CompileBroker::compilation_init_phase2();
2992   }
2993 #endif
2994 
2995   // Always call even when there are not JVMTI environments yet, since environments
2996   // may be attached late and JVMTI must track phases of VM execution
2997   JvmtiExport::enter_live_phase();
2998 
2999   // Make perfmemory accessible
3000   PerfMemory::set_accessible(true);
3001 
3002   // Notify JVMTI agents that VM initialization is complete - nop if no agents.
3003   JvmtiExport::post_vm_initialized();
3004 
3005   JFR_ONLY(Jfr::on_create_vm_3();)
3006 
3007 #if INCLUDE_MANAGEMENT
3008   Management::initialize(THREAD);
3009 
3010   if (HAS_PENDING_EXCEPTION) {
3011     // management agent fails to start possibly due to
3012     // configuration problem and is responsible for printing
3013     // stack trace if appropriate. Simply exit VM.
3014     vm_exit(1);
3015   }
3016 #endif // INCLUDE_MANAGEMENT
3017 
3018   StatSampler::engage();
3019   if (CheckJNICalls)                  JniPeriodicChecker::engage();
3020 
3021 #if INCLUDE_RTM_OPT
3022   RTMLockingCounters::init();
3023 #endif
3024 
3025   call_postVMInitHook(THREAD);
3026   // The Java side of PostVMInitHook.run must deal with all
3027   // exceptions and provide means of diagnosis.
3028   if (HAS_PENDING_EXCEPTION) {
3029     CLEAR_PENDING_EXCEPTION;
3030   }
3031 
3032   {
3033     MutexLocker ml(PeriodicTask_lock);
3034     // Make sure the WatcherThread can be started by WatcherThread::start()
3035     // or by dynamic enrollment.
3036     WatcherThread::make_startable();
3037     // Start up the WatcherThread if there are any periodic tasks
3038     // NOTE:  All PeriodicTasks should be registered by now. If they
3039     //   aren't, late joiners might appear to start slowly (we might
3040     //   take a while to process their first tick).
3041     if (PeriodicTask::num_tasks() > 0) {
3042       WatcherThread::start();
3043     }
3044   }
3045 
3046   create_vm_timer.end();
3047 #ifdef ASSERT
3048   _vm_complete = true;
3049 #endif
3050 
3051   if (DumpSharedSpaces) {
3052     MetaspaceShared::preload_and_dump();
3053     ShouldNotReachHere();
3054   }
3055 
3056   return JNI_OK;
3057 }
3058 
3059 // type for the Agent_OnLoad and JVM_OnLoad entry points
3060 extern "C" {
3061   typedef jint (JNICALL *OnLoadEntry_t)(JavaVM *, char *, void *);
3062 }
3063 // Find a command line agent library and return its entry point for
3064 //         -agentlib:  -agentpath:   -Xrun
3065 // num_symbol_entries must be passed-in since only the caller knows the number of symbols in the array.
3066 static OnLoadEntry_t lookup_on_load(AgentLibrary* agent,
3067                                     const char *on_load_symbols[],
3068                                     size_t num_symbol_entries) {
3069   OnLoadEntry_t on_load_entry = NULL;
3070   void *library = NULL;
3071 
3072   if (!agent->valid()) {
3073     char buffer[JVM_MAXPATHLEN];
3074     char ebuf[1024] = "";
3075     const char *name = agent->name();
3076     const char *msg = "Could not find agent library ";
3077 
3078     // First check to see if agent is statically linked into executable
3079     if (os::find_builtin_agent(agent, on_load_symbols, num_symbol_entries)) {
3080       library = agent->os_lib();
3081     } else if (agent->is_absolute_path()) {
3082       library = os::dll_load(name, ebuf, sizeof ebuf);
3083       if (library == NULL) {
3084         const char *sub_msg = " in absolute path, with error: ";
3085         size_t len = strlen(msg) + strlen(name) + strlen(sub_msg) + strlen(ebuf) + 1;
3086         char *buf = NEW_C_HEAP_ARRAY(char, len, mtThread);
3087         jio_snprintf(buf, len, "%s%s%s%s", msg, name, sub_msg, ebuf);
3088         // If we can't find the agent, exit.
3089         vm_exit_during_initialization(buf, NULL);
3090         FREE_C_HEAP_ARRAY(char, buf);
3091       }
3092     } else {
3093       // Try to load the agent from the standard dll directory
3094       if (os::dll_locate_lib(buffer, sizeof(buffer), Arguments::get_dll_dir(),
3095                              name)) {
3096         library = os::dll_load(buffer, ebuf, sizeof ebuf);
3097       }
3098       if (library == NULL) { // Try the library path directory.
3099         if (os::dll_build_name(buffer, sizeof(buffer), name)) {
3100           library = os::dll_load(buffer, ebuf, sizeof ebuf);
3101         }
3102         if (library == NULL) {
3103           const char *sub_msg = " on the library path, with error: ";
3104           const char *sub_msg2 = "\nModule java.instrument may be missing from runtime image.";
3105 
3106           size_t len = strlen(msg) + strlen(name) + strlen(sub_msg) +
3107                        strlen(ebuf) + strlen(sub_msg2) + 1;
3108           char *buf = NEW_C_HEAP_ARRAY(char, len, mtThread);
3109           if (!agent->is_instrument_lib()) {
3110             jio_snprintf(buf, len, "%s%s%s%s", msg, name, sub_msg, ebuf);
3111           } else {
3112             jio_snprintf(buf, len, "%s%s%s%s%s", msg, name, sub_msg, ebuf, sub_msg2);
3113           }
3114           // If we can't find the agent, exit.
3115           vm_exit_during_initialization(buf, NULL);
3116           FREE_C_HEAP_ARRAY(char, buf);
3117         }
3118       }
3119     }
3120     agent->set_os_lib(library);
3121     agent->set_valid();
3122   }
3123 
3124   // Find the OnLoad function.
3125   on_load_entry =
3126     CAST_TO_FN_PTR(OnLoadEntry_t, os::find_agent_function(agent,
3127                                                           false,
3128                                                           on_load_symbols,
3129                                                           num_symbol_entries));
3130   return on_load_entry;
3131 }
3132 
3133 // Find the JVM_OnLoad entry point
3134 static OnLoadEntry_t lookup_jvm_on_load(AgentLibrary* agent) {
3135   const char *on_load_symbols[] = JVM_ONLOAD_SYMBOLS;
3136   return lookup_on_load(agent, on_load_symbols, sizeof(on_load_symbols) / sizeof(char*));
3137 }
3138 
3139 // Find the Agent_OnLoad entry point
3140 static OnLoadEntry_t lookup_agent_on_load(AgentLibrary* agent) {
3141   const char *on_load_symbols[] = AGENT_ONLOAD_SYMBOLS;
3142   return lookup_on_load(agent, on_load_symbols, sizeof(on_load_symbols) / sizeof(char*));
3143 }
3144 
3145 // For backwards compatibility with -Xrun
3146 // Convert libraries with no JVM_OnLoad, but which have Agent_OnLoad to be
3147 // treated like -agentpath:
3148 // Must be called before agent libraries are created
3149 void Threads::convert_vm_init_libraries_to_agents() {
3150   AgentLibrary* agent;
3151   AgentLibrary* next;
3152 
3153   for (agent = Arguments::libraries(); agent != NULL; agent = next) {
3154     next = agent->next();  // cache the next agent now as this agent may get moved off this list
3155     OnLoadEntry_t on_load_entry = lookup_jvm_on_load(agent);
3156 
3157     // If there is an JVM_OnLoad function it will get called later,
3158     // otherwise see if there is an Agent_OnLoad
3159     if (on_load_entry == NULL) {
3160       on_load_entry = lookup_agent_on_load(agent);
3161       if (on_load_entry != NULL) {
3162         // switch it to the agent list -- so that Agent_OnLoad will be called,
3163         // JVM_OnLoad won't be attempted and Agent_OnUnload will
3164         Arguments::convert_library_to_agent(agent);
3165       } else {
3166         vm_exit_during_initialization("Could not find JVM_OnLoad or Agent_OnLoad function in the library", agent->name());
3167       }
3168     }
3169   }
3170 }
3171 
3172 // Create agents for -agentlib:  -agentpath:  and converted -Xrun
3173 // Invokes Agent_OnLoad
3174 // Called very early -- before JavaThreads exist
3175 void Threads::create_vm_init_agents() {
3176   extern struct JavaVM_ main_vm;
3177   AgentLibrary* agent;
3178 
3179   JvmtiExport::enter_onload_phase();
3180 
3181   for (agent = Arguments::agents(); agent != NULL; agent = agent->next()) {
3182     // CDS dumping does not support native JVMTI agent.
3183     // CDS dumping supports Java agent if the AllowArchivingWithJavaAgent diagnostic option is specified.
3184     if (Arguments::is_dumping_archive()) {
3185       if(!agent->is_instrument_lib()) {
3186         vm_exit_during_cds_dumping("CDS dumping does not support native JVMTI agent, name", agent->name());
3187       } else if (!AllowArchivingWithJavaAgent) {
3188         vm_exit_during_cds_dumping(
3189           "Must enable AllowArchivingWithJavaAgent in order to run Java agent during CDS dumping");
3190       }
3191     }
3192 
3193     OnLoadEntry_t  on_load_entry = lookup_agent_on_load(agent);
3194 
3195     if (on_load_entry != NULL) {
3196       // Invoke the Agent_OnLoad function
3197       jint err = (*on_load_entry)(&main_vm, agent->options(), NULL);
3198       if (err != JNI_OK) {
3199         vm_exit_during_initialization("agent library failed to init", agent->name());
3200       }
3201     } else {
3202       vm_exit_during_initialization("Could not find Agent_OnLoad function in the agent library", agent->name());
3203     }
3204   }
3205 
3206   JvmtiExport::enter_primordial_phase();
3207 }
3208 
3209 extern "C" {
3210   typedef void (JNICALL *Agent_OnUnload_t)(JavaVM *);
3211 }
3212 
3213 void Threads::shutdown_vm_agents() {
3214   // Send any Agent_OnUnload notifications
3215   const char *on_unload_symbols[] = AGENT_ONUNLOAD_SYMBOLS;
3216   size_t num_symbol_entries = ARRAY_SIZE(on_unload_symbols);
3217   extern struct JavaVM_ main_vm;
3218   for (AgentLibrary* agent = Arguments::agents(); agent != NULL; agent = agent->next()) {
3219 
3220     // Find the Agent_OnUnload function.
3221     Agent_OnUnload_t unload_entry = CAST_TO_FN_PTR(Agent_OnUnload_t,
3222                                                    os::find_agent_function(agent,
3223                                                    false,
3224                                                    on_unload_symbols,
3225                                                    num_symbol_entries));
3226 
3227     // Invoke the Agent_OnUnload function
3228     if (unload_entry != NULL) {
3229       JavaThread* thread = JavaThread::current();
3230       ThreadToNativeFromVM ttn(thread);
3231       HandleMark hm(thread);
3232       (*unload_entry)(&main_vm);
3233     }
3234   }
3235 }
3236 
3237 // Called for after the VM is initialized for -Xrun libraries which have not been converted to agent libraries
3238 // Invokes JVM_OnLoad
3239 void Threads::create_vm_init_libraries() {
3240   extern struct JavaVM_ main_vm;
3241   AgentLibrary* agent;
3242 
3243   for (agent = Arguments::libraries(); agent != NULL; agent = agent->next()) {
3244     OnLoadEntry_t on_load_entry = lookup_jvm_on_load(agent);
3245 
3246     if (on_load_entry != NULL) {
3247       // Invoke the JVM_OnLoad function
3248       JavaThread* thread = JavaThread::current();
3249       ThreadToNativeFromVM ttn(thread);
3250       HandleMark hm(thread);
3251       jint err = (*on_load_entry)(&main_vm, agent->options(), NULL);
3252       if (err != JNI_OK) {
3253         vm_exit_during_initialization("-Xrun library failed to init", agent->name());
3254       }
3255     } else {
3256       vm_exit_during_initialization("Could not find JVM_OnLoad function in -Xrun library", agent->name());
3257     }
3258   }
3259 }
3260 
3261 
3262 // Last thread running calls java.lang.Shutdown.shutdown()
3263 void JavaThread::invoke_shutdown_hooks() {
3264   HandleMark hm(this);
3265 
3266   // We could get here with a pending exception, if so clear it now or
3267   // it will cause MetaspaceShared::link_shared_classes to
3268   // fail for dynamic dump.
3269   if (this->has_pending_exception()) {
3270     this->clear_pending_exception();
3271   }
3272 
3273 #if INCLUDE_CDS
3274   // Link all classes for dynamic CDS dumping before vm exit.
3275   // Same operation is being done in JVM_BeforeHalt for handling the
3276   // case where the application calls System.exit().
3277   if (DynamicArchive::should_dump_at_vm_exit()) {
3278     DynamicArchive::prepare_for_dump_at_exit();
3279   }
3280 #endif
3281 
3282   EXCEPTION_MARK;
3283   Klass* shutdown_klass =
3284     SystemDictionary::resolve_or_null(vmSymbols::java_lang_Shutdown(),
3285                                       THREAD);
3286   if (shutdown_klass != NULL) {
3287     // SystemDictionary::resolve_or_null will return null if there was
3288     // an exception.  If we cannot load the Shutdown class, just don't
3289     // call Shutdown.shutdown() at all.  This will mean the shutdown hooks
3290     // won't be run.  Note that if a shutdown hook was registered,
3291     // the Shutdown class would have already been loaded
3292     // (Runtime.addShutdownHook will load it).
3293     JavaValue result(T_VOID);
3294     JavaCalls::call_static(&result,
3295                            shutdown_klass,
3296                            vmSymbols::shutdown_name(),
3297                            vmSymbols::void_method_signature(),
3298                            THREAD);
3299   }
3300   CLEAR_PENDING_EXCEPTION;
3301 }
3302 
3303 // Threads::destroy_vm() is normally called from jni_DestroyJavaVM() when
3304 // the program falls off the end of main(). Another VM exit path is through
3305 // vm_exit() when the program calls System.exit() to return a value or when
3306 // there is a serious error in VM. The two shutdown paths are not exactly
3307 // the same, but they share Shutdown.shutdown() at Java level and before_exit()
3308 // and VM_Exit op at VM level.
3309 //
3310 // Shutdown sequence:
3311 //   + Shutdown native memory tracking if it is on
3312 //   + Wait until we are the last non-daemon thread to execute
3313 //     <-- every thing is still working at this moment -->
3314 //   + Call java.lang.Shutdown.shutdown(), which will invoke Java level
3315 //        shutdown hooks
3316 //   + Call before_exit(), prepare for VM exit
3317 //      > run VM level shutdown hooks (they are registered through JVM_OnExit(),
3318 //        currently the only user of this mechanism is File.deleteOnExit())
3319 //      > stop StatSampler, watcher thread,
3320 //        post thread end and vm death events to JVMTI,
3321 //        stop signal thread
3322 //   + Call JavaThread::exit(), it will:
3323 //      > release JNI handle blocks, remove stack guard pages
3324 //      > remove this thread from Threads list
3325 //     <-- no more Java code from this thread after this point -->
3326 //   + Stop VM thread, it will bring the remaining VM to a safepoint and stop
3327 //     the compiler threads at safepoint
3328 //     <-- do not use anything that could get blocked by Safepoint -->
3329 //   + Disable tracing at JNI/JVM barriers
3330 //   + Set _vm_exited flag for threads that are still running native code
3331 //   + Call exit_globals()
3332 //      > deletes tty
3333 //      > deletes PerfMemory resources
3334 //   + Delete this thread
3335 //   + Return to caller
3336 
3337 void Threads::destroy_vm() {
3338   JavaThread* thread = JavaThread::current();
3339 
3340 #ifdef ASSERT
3341   _vm_complete = false;
3342 #endif
3343   // Wait until we are the last non-daemon thread to execute
3344   {
3345     MonitorLocker nu(Threads_lock);
3346     while (Threads::number_of_non_daemon_threads() > 1)
3347       // This wait should make safepoint checks, wait without a timeout.
3348       nu.wait(0);
3349   }
3350 
3351   EventShutdown e;
3352   if (e.should_commit()) {
3353     e.set_reason("No remaining non-daemon Java threads");
3354     e.commit();
3355   }
3356 
3357   // Hang forever on exit if we are reporting an error.
3358   if (ShowMessageBoxOnError && VMError::is_error_reported()) {
3359     os::infinite_sleep();
3360   }
3361   os::wait_for_keypress_at_exit();
3362 
3363   // run Java level shutdown hooks
3364   thread->invoke_shutdown_hooks();
3365 
3366   before_exit(thread);
3367 
3368   thread->exit(true);
3369 
3370   // We are no longer on the main thread list but could still be in a
3371   // secondary list where another thread may try to interact with us.
3372   // So wait until all such interactions are complete before we bring
3373   // the VM to the termination safepoint. Normally this would be done
3374   // using thread->smr_delete() below where we delete the thread, but
3375   // we can't call that after the termination safepoint is active as
3376   // we will deadlock on the Threads_lock. Once all interactions are
3377   // complete it is safe to directly delete the thread at any time.
3378   ThreadsSMRSupport::wait_until_not_protected(thread);
3379 
3380   // Stop VM thread.
3381   {
3382     // 4945125 The vm thread comes to a safepoint during exit.
3383     // GC vm_operations can get caught at the safepoint, and the
3384     // heap is unparseable if they are caught. Grab the Heap_lock
3385     // to prevent this. The GC vm_operations will not be able to
3386     // queue until after the vm thread is dead. After this point,
3387     // we'll never emerge out of the safepoint before the VM exits.
3388     // Assert that the thread is terminated so that acquiring the
3389     // Heap_lock doesn't cause the terminated thread to participate in
3390     // the safepoint protocol.
3391 
3392     assert(thread->is_terminated(), "must be terminated here");
3393     MutexLocker ml(Heap_lock);
3394 
3395     VMThread::wait_for_vm_thread_exit();
3396     assert(SafepointSynchronize::is_at_safepoint(), "VM thread should exit at Safepoint");
3397     VMThread::destroy();
3398   }
3399 
3400   // Now, all Java threads are gone except daemon threads. Daemon threads
3401   // running Java code or in VM are stopped by the Safepoint. However,
3402   // daemon threads executing native code are still running.  But they
3403   // will be stopped at native=>Java/VM barriers. Note that we can't
3404   // simply kill or suspend them, as it is inherently deadlock-prone.
3405 
3406   VM_Exit::set_vm_exited();
3407 
3408   // Clean up ideal graph printers after the VMThread has started
3409   // the final safepoint which will block all the Compiler threads.
3410   // Note that this Thread has already logically exited so the
3411   // clean_up() function's use of a JavaThreadIteratorWithHandle
3412   // would be a problem except set_vm_exited() has remembered the
3413   // shutdown thread which is granted a policy exception.
3414 #if defined(COMPILER2) && !defined(PRODUCT)
3415   IdealGraphPrinter::clean_up();
3416 #endif
3417 
3418   notify_vm_shutdown();
3419 
3420   // exit_globals() will delete tty
3421   exit_globals();
3422 
3423   // Deleting the shutdown thread here is safe. See comment on
3424   // wait_until_not_protected() above.
3425   delete thread;
3426 
3427 #if INCLUDE_JVMCI
3428   if (JVMCICounterSize > 0) {
3429     FREE_C_HEAP_ARRAY(jlong, JavaThread::_jvmci_old_thread_counters);
3430   }
3431 #endif
3432 
3433   LogConfiguration::finalize();
3434 }
3435 
3436 
3437 jboolean Threads::is_supported_jni_version_including_1_1(jint version) {
3438   if (version == JNI_VERSION_1_1) return JNI_TRUE;
3439   return is_supported_jni_version(version);
3440 }
3441 
3442 
3443 jboolean Threads::is_supported_jni_version(jint version) {
3444   if (version == JNI_VERSION_1_2) return JNI_TRUE;
3445   if (version == JNI_VERSION_1_4) return JNI_TRUE;
3446   if (version == JNI_VERSION_1_6) return JNI_TRUE;
3447   if (version == JNI_VERSION_1_8) return JNI_TRUE;
3448   if (version == JNI_VERSION_9) return JNI_TRUE;
3449   if (version == JNI_VERSION_10) return JNI_TRUE;
3450   return JNI_FALSE;
3451 }
3452 
3453 
3454 void Threads::add(JavaThread* p, bool force_daemon) {
3455   // The threads lock must be owned at this point
3456   assert(Threads_lock->owned_by_self(), "must have threads lock");
3457 
3458   BarrierSet::barrier_set()->on_thread_attach(p);
3459 
3460   // Once a JavaThread is added to the Threads list, smr_delete() has
3461   // to be used to delete it. Otherwise we can just delete it directly.
3462   p->set_on_thread_list();
3463 
3464   _number_of_threads++;
3465   oop threadObj = p->threadObj();
3466   bool daemon = true;
3467   // Bootstrapping problem: threadObj can be null for initial
3468   // JavaThread (or for threads attached via JNI)
3469   if ((!force_daemon) && !is_daemon((threadObj))) {
3470     _number_of_non_daemon_threads++;
3471     daemon = false;
3472   }
3473 
3474   ThreadService::add_thread(p, daemon);
3475 
3476   // Maintain fast thread list
3477   ThreadsSMRSupport::add_thread(p);
3478 
3479   // Increase the ObjectMonitor ceiling for the new thread.
3480   ObjectSynchronizer::inc_in_use_list_ceiling();
3481 
3482   // Possible GC point.
3483   Events::log(p, "Thread added: " INTPTR_FORMAT, p2i(p));
3484 
3485   // Make new thread known to active EscapeBarrier
3486   EscapeBarrier::thread_added(p);
3487 }
3488 
3489 void Threads::remove(JavaThread* p, bool is_daemon) {
3490   // Extra scope needed for Thread_lock, so we can check
3491   // that we do not remove thread without safepoint code notice
3492   { MonitorLocker ml(Threads_lock);
3493 
3494     // BarrierSet state must be destroyed after the last thread transition
3495     // before the thread terminates. Thread transitions result in calls to
3496     // StackWatermarkSet::on_safepoint(), which performs GC processing,
3497     // requiring the GC state to be alive.
3498     BarrierSet::barrier_set()->on_thread_detach(p);
3499 
3500     assert(ThreadsSMRSupport::get_java_thread_list()->includes(p), "p must be present");
3501 
3502     // Maintain fast thread list
3503     ThreadsSMRSupport::remove_thread(p);
3504 
3505     _number_of_threads--;
3506     if (!is_daemon) {
3507       _number_of_non_daemon_threads--;
3508 
3509       // Only one thread left, do a notify on the Threads_lock so a thread waiting
3510       // on destroy_vm will wake up.
3511       if (number_of_non_daemon_threads() == 1) {
3512         ml.notify_all();
3513       }
3514     }
3515     ThreadService::remove_thread(p, is_daemon);
3516 
3517     // Make sure that safepoint code disregard this thread. This is needed since
3518     // the thread might mess around with locks after this point. This can cause it
3519     // to do callbacks into the safepoint code. However, the safepoint code is not aware
3520     // of this thread since it is removed from the queue.
3521     p->set_terminated(JavaThread::_thread_terminated);
3522 
3523     // Notify threads waiting in EscapeBarriers
3524     EscapeBarrier::thread_removed(p);
3525   } // unlock Threads_lock
3526 
3527   // Reduce the ObjectMonitor ceiling for the exiting thread.
3528   ObjectSynchronizer::dec_in_use_list_ceiling();
3529 
3530   // Since Events::log uses a lock, we grab it outside the Threads_lock
3531   Events::log(p, "Thread exited: " INTPTR_FORMAT, p2i(p));
3532 }
3533 
3534 // Operations on the Threads list for GC.  These are not explicitly locked,
3535 // but the garbage collector must provide a safe context for them to run.
3536 // In particular, these things should never be called when the Threads_lock
3537 // is held by some other thread. (Note: the Safepoint abstraction also
3538 // uses the Threads_lock to guarantee this property. It also makes sure that
3539 // all threads gets blocked when exiting or starting).
3540 
3541 void Threads::oops_do(OopClosure* f, CodeBlobClosure* cf) {
3542   ALL_JAVA_THREADS(p) {
3543     p->oops_do(f, cf);
3544   }
3545   VMThread::vm_thread()->oops_do(f, cf);
3546 }
3547 
3548 void Threads::change_thread_claim_token() {
3549   if (++_thread_claim_token == 0) {
3550     // On overflow of the token counter, there is a risk of future
3551     // collisions between a new global token value and a stale token
3552     // for a thread, because not all iterations visit all threads.
3553     // (Though it's pretty much a theoretical concern for non-trivial
3554     // token counter sizes.)  To deal with the possibility, reset all
3555     // the thread tokens to zero on global token overflow.
3556     struct ResetClaims : public ThreadClosure {
3557       virtual void do_thread(Thread* t) {
3558         t->claim_threads_do(false, 0);
3559       }
3560     } reset_claims;
3561     Threads::threads_do(&reset_claims);
3562     // On overflow, update the global token to non-zero, to
3563     // avoid the special "never claimed" initial thread value.
3564     _thread_claim_token = 1;
3565   }
3566 }
3567 
3568 #ifdef ASSERT
3569 void assert_thread_claimed(const char* kind, Thread* t, uintx expected) {
3570   const uintx token = t->threads_do_token();
3571   assert(token == expected,
3572          "%s " PTR_FORMAT " has incorrect value " UINTX_FORMAT " != "
3573          UINTX_FORMAT, kind, p2i(t), token, expected);
3574 }
3575 
3576 void Threads::assert_all_threads_claimed() {
3577   ALL_JAVA_THREADS(p) {
3578     assert_thread_claimed("Thread", p, _thread_claim_token);
3579   }
3580   assert_thread_claimed("VMThread", VMThread::vm_thread(), _thread_claim_token);
3581 }
3582 #endif // ASSERT
3583 
3584 class ParallelOopsDoThreadClosure : public ThreadClosure {
3585 private:
3586   OopClosure* _f;
3587   CodeBlobClosure* _cf;
3588 public:
3589   ParallelOopsDoThreadClosure(OopClosure* f, CodeBlobClosure* cf) : _f(f), _cf(cf) {}
3590   void do_thread(Thread* t) {
3591     t->oops_do(_f, _cf);
3592   }
3593 };
3594 
3595 void Threads::possibly_parallel_oops_do(bool is_par, OopClosure* f, CodeBlobClosure* cf) {
3596   ParallelOopsDoThreadClosure tc(f, cf);
3597   possibly_parallel_threads_do(is_par, &tc);
3598 }
3599 
3600 void Threads::metadata_do(MetadataClosure* f) {
3601   ALL_JAVA_THREADS(p) {
3602     p->metadata_do(f);
3603   }
3604 }
3605 
3606 class ThreadHandlesClosure : public ThreadClosure {
3607   void (*_f)(Metadata*);
3608  public:
3609   ThreadHandlesClosure(void f(Metadata*)) : _f(f) {}
3610   virtual void do_thread(Thread* thread) {
3611     thread->metadata_handles_do(_f);
3612   }
3613 };
3614 
3615 void Threads::metadata_handles_do(void f(Metadata*)) {
3616   // Only walk the Handles in Thread.
3617   ThreadHandlesClosure handles_closure(f);
3618   threads_do(&handles_closure);
3619 }
3620 
3621 // Get count Java threads that are waiting to enter the specified monitor.
3622 GrowableArray<JavaThread*>* Threads::get_pending_threads(ThreadsList * t_list,
3623                                                          int count,
3624                                                          address monitor) {
3625   GrowableArray<JavaThread*>* result = new GrowableArray<JavaThread*>(count);
3626 
3627   int i = 0;
3628   for (JavaThread* p : *t_list) {
3629     if (!p->can_call_java()) continue;
3630 
3631     // The first stage of async deflation does not affect any field
3632     // used by this comparison so the ObjectMonitor* is usable here.
3633     address pending = (address)p->current_pending_monitor();
3634     if (pending == monitor) {             // found a match
3635       if (i < count) result->append(p);   // save the first count matches
3636       i++;
3637     }
3638   }
3639 
3640   return result;
3641 }
3642 
3643 
3644 JavaThread *Threads::owning_thread_from_monitor_owner(ThreadsList * t_list,
3645                                                       address owner) {
3646   // NULL owner means not locked so we can skip the search
3647   if (owner == NULL) return NULL;
3648 
3649   for (JavaThread* p : *t_list) {
3650     // first, see if owner is the address of a Java thread
3651     if (owner == (address)p) return p;
3652   }
3653 
3654   // Cannot assert on lack of success here since this function may be
3655   // used by code that is trying to report useful problem information
3656   // like deadlock detection.
3657   if (UseHeavyMonitors) return NULL;
3658 
3659   // If we didn't find a matching Java thread and we didn't force use of
3660   // heavyweight monitors, then the owner is the stack address of the
3661   // Lock Word in the owning Java thread's stack.
3662   //
3663   JavaThread* the_owner = NULL;
3664   for (JavaThread* q : *t_list) {
3665     if (q->is_lock_owned(owner)) {
3666       the_owner = q;
3667       break;
3668     }
3669   }
3670 
3671   // cannot assert on lack of success here; see above comment
3672   return the_owner;
3673 }
3674 
3675 class PrintOnClosure : public ThreadClosure {
3676 private:
3677   outputStream* _st;
3678 
3679 public:
3680   PrintOnClosure(outputStream* st) :
3681       _st(st) {}
3682 
3683   virtual void do_thread(Thread* thread) {
3684     if (thread != NULL) {
3685       thread->print_on(_st);
3686       _st->cr();
3687     }
3688   }
3689 };
3690 
3691 // Threads::print_on() is called at safepoint by VM_PrintThreads operation.
3692 void Threads::print_on(outputStream* st, bool print_stacks,
3693                        bool internal_format, bool print_concurrent_locks,
3694                        bool print_extended_info) {
3695   char buf[32];
3696   st->print_raw_cr(os::local_time_string(buf, sizeof(buf)));
3697 
3698   st->print_cr("Full thread dump %s (%s %s):",
3699                VM_Version::vm_name(),
3700                VM_Version::vm_release(),
3701                VM_Version::vm_info_string());
3702   st->cr();
3703 
3704 #if INCLUDE_SERVICES
3705   // Dump concurrent locks
3706   ConcurrentLocksDump concurrent_locks;
3707   if (print_concurrent_locks) {
3708     concurrent_locks.dump_at_safepoint();
3709   }
3710 #endif // INCLUDE_SERVICES
3711 
3712   ThreadsSMRSupport::print_info_on(st);
3713   st->cr();
3714 
3715   ALL_JAVA_THREADS(p) {
3716     ResourceMark rm;
3717     p->print_on(st, print_extended_info);
3718     if (print_stacks) {
3719       if (internal_format) {
3720         p->trace_stack();
3721       } else {
3722         p->print_stack_on(st);
3723       }
3724     }
3725     st->cr();
3726 #if INCLUDE_SERVICES
3727     if (print_concurrent_locks) {
3728       concurrent_locks.print_locks_on(p, st);
3729     }
3730 #endif // INCLUDE_SERVICES
3731   }
3732 
3733   PrintOnClosure cl(st);
3734   cl.do_thread(VMThread::vm_thread());
3735   Universe::heap()->gc_threads_do(&cl);
3736   if (StringDedup::is_enabled()) {
3737     StringDedup::threads_do(&cl);
3738   }
3739   cl.do_thread(WatcherThread::watcher_thread());
3740   cl.do_thread(AsyncLogWriter::instance());
3741 
3742   st->flush();
3743 }
3744 
3745 void Threads::print_on_error(Thread* this_thread, outputStream* st, Thread* current, char* buf,
3746                              int buflen, bool* found_current) {
3747   if (this_thread != NULL) {
3748     bool is_current = (current == this_thread);
3749     *found_current = *found_current || is_current;
3750     st->print("%s", is_current ? "=>" : "  ");
3751 
3752     st->print(PTR_FORMAT, p2i(this_thread));
3753     st->print(" ");
3754     this_thread->print_on_error(st, buf, buflen);
3755     st->cr();
3756   }
3757 }
3758 
3759 class PrintOnErrorClosure : public ThreadClosure {
3760   outputStream* _st;
3761   Thread* _current;
3762   char* _buf;
3763   int _buflen;
3764   bool* _found_current;
3765  public:
3766   PrintOnErrorClosure(outputStream* st, Thread* current, char* buf,
3767                       int buflen, bool* found_current) :
3768    _st(st), _current(current), _buf(buf), _buflen(buflen), _found_current(found_current) {}
3769 
3770   virtual void do_thread(Thread* thread) {
3771     Threads::print_on_error(thread, _st, _current, _buf, _buflen, _found_current);
3772   }
3773 };
3774 
3775 // Threads::print_on_error() is called by fatal error handler. It's possible
3776 // that VM is not at safepoint and/or current thread is inside signal handler.
3777 // Don't print stack trace, as the stack may not be walkable. Don't allocate
3778 // memory (even in resource area), it might deadlock the error handler.
3779 void Threads::print_on_error(outputStream* st, Thread* current, char* buf,
3780                              int buflen) {
3781   ThreadsSMRSupport::print_info_on(st);
3782   st->cr();
3783 
3784   bool found_current = false;
3785   st->print_cr("Java Threads: ( => current thread )");
3786   ALL_JAVA_THREADS(thread) {
3787     print_on_error(thread, st, current, buf, buflen, &found_current);
3788   }
3789   st->cr();
3790 
3791   st->print_cr("Other Threads:");
3792   print_on_error(VMThread::vm_thread(), st, current, buf, buflen, &found_current);
3793   print_on_error(WatcherThread::watcher_thread(), st, current, buf, buflen, &found_current);
3794   print_on_error(AsyncLogWriter::instance(), st, current, buf, buflen, &found_current);
3795 
3796   if (Universe::heap() != NULL) {
3797     PrintOnErrorClosure print_closure(st, current, buf, buflen, &found_current);
3798     Universe::heap()->gc_threads_do(&print_closure);
3799   }
3800 
3801   if (StringDedup::is_enabled()) {
3802     PrintOnErrorClosure print_closure(st, current, buf, buflen, &found_current);
3803     StringDedup::threads_do(&print_closure);
3804   }
3805 
3806   if (!found_current) {
3807     st->cr();
3808     st->print("=>" PTR_FORMAT " (exited) ", p2i(current));
3809     current->print_on_error(st, buf, buflen);
3810     st->cr();
3811   }
3812   st->cr();
3813 
3814   st->print_cr("Threads with active compile tasks:");
3815   print_threads_compiling(st, buf, buflen);
3816 }
3817 
3818 void Threads::print_threads_compiling(outputStream* st, char* buf, int buflen, bool short_form) {
3819   ALL_JAVA_THREADS(thread) {
3820     if (thread->is_Compiler_thread()) {
3821       CompilerThread* ct = (CompilerThread*) thread;
3822 
3823       // Keep task in local variable for NULL check.
3824       // ct->_task might be set to NULL by concurring compiler thread
3825       // because it completed the compilation. The task is never freed,
3826       // though, just returned to a free list.
3827       CompileTask* task = ct->task();
3828       if (task != NULL) {
3829         thread->print_name_on_error(st, buf, buflen);
3830         st->print("  ");
3831         task->print(st, NULL, short_form, true);
3832       }
3833     }
3834   }
3835 }
3836 
3837 
3838 // Ad-hoc mutual exclusion primitives: SpinLock
3839 //
3840 // We employ SpinLocks _only for low-contention, fixed-length
3841 // short-duration critical sections where we're concerned
3842 // about native mutex_t or HotSpot Mutex:: latency.
3843 //
3844 // TODO-FIXME: ListLock should be of type SpinLock.
3845 // We should make this a 1st-class type, integrated into the lock
3846 // hierarchy as leaf-locks.  Critically, the SpinLock structure
3847 // should have sufficient padding to avoid false-sharing and excessive
3848 // cache-coherency traffic.
3849 
3850 
3851 typedef volatile int SpinLockT;
3852 
3853 void Thread::SpinAcquire(volatile int * adr, const char * LockName) {
3854   if (Atomic::cmpxchg(adr, 0, 1) == 0) {
3855     return;   // normal fast-path return
3856   }
3857 
3858   // Slow-path : We've encountered contention -- Spin/Yield/Block strategy.
3859   int ctr = 0;
3860   int Yields = 0;
3861   for (;;) {
3862     while (*adr != 0) {
3863       ++ctr;
3864       if ((ctr & 0xFFF) == 0 || !os::is_MP()) {
3865         if (Yields > 5) {
3866           os::naked_short_sleep(1);
3867         } else {
3868           os::naked_yield();
3869           ++Yields;
3870         }
3871       } else {
3872         SpinPause();
3873       }
3874     }
3875     if (Atomic::cmpxchg(adr, 0, 1) == 0) return;
3876   }
3877 }
3878 
3879 void Thread::SpinRelease(volatile int * adr) {
3880   assert(*adr != 0, "invariant");
3881   OrderAccess::fence();      // guarantee at least release consistency.
3882   // Roach-motel semantics.
3883   // It's safe if subsequent LDs and STs float "up" into the critical section,
3884   // but prior LDs and STs within the critical section can't be allowed
3885   // to reorder or float past the ST that releases the lock.
3886   // Loads and stores in the critical section - which appear in program
3887   // order before the store that releases the lock - must also appear
3888   // before the store that releases the lock in memory visibility order.
3889   // Conceptually we need a #loadstore|#storestore "release" MEMBAR before
3890   // the ST of 0 into the lock-word which releases the lock, so fence
3891   // more than covers this on all platforms.
3892   *adr = 0;
3893 }
3894 
3895 
3896 void Threads::verify() {
3897   ALL_JAVA_THREADS(p) {
3898     p->verify();
3899   }
3900   VMThread* thread = VMThread::vm_thread();
3901   if (thread != NULL) thread->verify();
3902 }
3903 
3904 #ifndef PRODUCT
3905 void JavaThread::verify_cross_modify_fence_failure(JavaThread *thread) {
3906    report_vm_error(__FILE__, __LINE__, "Cross modify fence failure", "%p", thread);
3907 }
3908 #endif
3909 
3910 // Helper function to create the java.lang.Thread object for a
3911 // VM-internal thread. The thread will have the given name, be
3912 // part of the System ThreadGroup and if is_visible is true will be
3913 // discoverable via the system ThreadGroup.
3914 Handle JavaThread::create_system_thread_object(const char* name,
3915                                                bool is_visible, TRAPS) {
3916   Handle string = java_lang_String::create_from_str(name, CHECK_NH);
3917 
3918   // Initialize thread_oop to put it into the system threadGroup.
3919   // This is done by calling the Thread(ThreadGroup tg, String name)
3920   // constructor, which adds the new thread to the group as an unstarted
3921   // thread.
3922   Handle thread_group(THREAD, Universe::system_thread_group());
3923   Handle thread_oop =
3924     JavaCalls::construct_new_instance(vmClasses::Thread_klass(),
3925                                       vmSymbols::threadgroup_string_void_signature(),
3926                                       thread_group,
3927                                       string,
3928                                       CHECK_NH);
3929 
3930   // If the Thread is intended to be visible then we have to mimic what
3931   // Thread.start() would do, by adding it to its ThreadGroup: tg.add(t).
3932   if (is_visible) {
3933     Klass* group = vmClasses::ThreadGroup_klass();
3934     JavaValue result(T_VOID);
3935     JavaCalls::call_special(&result,
3936                             thread_group,
3937                             group,
3938                             vmSymbols::add_method_name(),
3939                             vmSymbols::thread_void_signature(),
3940                             thread_oop,
3941                             CHECK_NH);
3942   }
3943 
3944   return thread_oop;
3945 }
3946 
3947 // Starts the target JavaThread as a daemon of the given priority, and
3948 // bound to the given java.lang.Thread instance.
3949 // The Threads_lock is held for the duration.
3950 void JavaThread::start_internal_daemon(JavaThread* current, JavaThread* target,
3951                                        Handle thread_oop, ThreadPriority prio) {
3952 
3953   assert(target->osthread() != NULL, "target thread is not properly initialized");
3954 
3955   MutexLocker mu(current, Threads_lock);
3956 
3957   // Initialize the fields of the thread_oop first.
3958 
3959   java_lang_Thread::set_thread(thread_oop(), target); // isAlive == true now
3960 
3961   if (prio != NoPriority) {
3962     java_lang_Thread::set_priority(thread_oop(), prio);
3963     // Note: we don't call os::set_priority here. Possibly we should,
3964     // else all threads should call it themselves when they first run.
3965   }
3966 
3967   java_lang_Thread::set_daemon(thread_oop());
3968 
3969   // Now bind the thread_oop to the target JavaThread.
3970   target->set_threadObj(thread_oop());
3971 
3972   Threads::add(target); // target is now visible for safepoint/handshake
3973   Thread::start(target);
3974 }
3975 
3976 void JavaThread::vm_exit_on_osthread_failure(JavaThread* thread) {
3977   // At this point it may be possible that no osthread was created for the
3978   // JavaThread due to lack of resources. However, since this must work
3979   // for critical system threads just check and abort if this fails.
3980   if (thread->osthread() == nullptr) {
3981     // This isn't really an OOM condition, but historically this is what
3982     // we report.
3983     vm_exit_during_initialization("java.lang.OutOfMemoryError",
3984                                   os::native_thread_creation_failed_msg());
3985   }
3986 }