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