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