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