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