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