1 /*
   2  * Copyright (c) 1997, 2022, Oracle and/or its affiliates. All rights reserved.
   3  * Copyright (c) 2021, Azul Systems, Inc. All rights reserved.
   4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   5  *
   6  * This code is free software; you can redistribute it and/or modify it
   7  * under the terms of the GNU General Public License version 2 only, as
   8  * published by the Free Software Foundation.
   9  *
  10  * This code is distributed in the hope that it will be useful, but WITHOUT
  11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  13  * version 2 for more details (a copy is included in the LICENSE file that
  14  * accompanied this code).
  15  *
  16  * You should have received a copy of the GNU General Public License version
  17  * 2 along with this work; if not, write to the Free Software Foundation,
  18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  19  *
  20  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  21  * or visit www.oracle.com if you need additional information or have any
  22  * questions.
  23  *
  24  */
  25 
  26 #include "precompiled.hpp"
  27 #include "jvm.h"
  28 #include "cds/dynamicArchive.hpp"
  29 #include "ci/ciEnv.hpp"
  30 #include "classfile/javaClasses.inline.hpp"
  31 #include "classfile/javaThreadStatus.hpp"
  32 #include "classfile/systemDictionary.hpp"
  33 #include "classfile/vmClasses.hpp"
  34 #include "classfile/vmSymbols.hpp"
  35 #include "code/codeCache.hpp"
  36 #include "code/scopeDesc.hpp"
  37 #include "compiler/compileTask.hpp"
  38 #include "compiler/compilerThread.hpp"
  39 #include "gc/shared/oopStorage.hpp"
  40 #include "gc/shared/oopStorageSet.hpp"
  41 #include "gc/shared/tlab_globals.hpp"
  42 #include "jfr/jfrEvents.hpp"
  43 #include "jvmtifiles/jvmtiEnv.hpp"
  44 #include "logging/log.hpp"
  45 #include "logging/logAsyncWriter.hpp"
  46 #include "logging/logStream.hpp"
  47 #include "memory/allocation.inline.hpp"
  48 #include "memory/iterator.hpp"
  49 #include "memory/universe.hpp"
  50 #include "oops/access.inline.hpp"
  51 #include "oops/inlineKlass.hpp"
  52 #include "oops/instanceKlass.hpp"
  53 #include "oops/klass.inline.hpp"
  54 #include "oops/oop.inline.hpp"
  55 #include "oops/oopHandle.inline.hpp"
  56 #include "oops/verifyOopClosure.hpp"
  57 #include "prims/jvm_misc.hpp"
  58 #include "prims/jvmtiDeferredUpdates.hpp"
  59 #include "prims/jvmtiExport.hpp"
  60 #include "prims/jvmtiThreadState.inline.hpp"
  61 #include "runtime/atomic.hpp"
  62 #include "runtime/continuation.hpp"
  63 #include "runtime/continuationEntry.inline.hpp"
  64 #include "runtime/continuationHelper.inline.hpp"
  65 #include "runtime/deoptimization.hpp"
  66 #include "runtime/frame.inline.hpp"
  67 #include "runtime/handles.inline.hpp"
  68 #include "runtime/handshake.hpp"
  69 #include "runtime/interfaceSupport.inline.hpp"
  70 #include "runtime/java.hpp"
  71 #include "runtime/javaCalls.hpp"
  72 #include "runtime/javaThread.inline.hpp"
  73 #include "runtime/jniHandles.inline.hpp"
  74 #include "runtime/mutexLocker.hpp"
  75 #include "runtime/orderAccess.hpp"
  76 #include "runtime/osThread.hpp"
  77 #include "runtime/safepoint.hpp"
  78 #include "runtime/safepointMechanism.inline.hpp"
  79 #include "runtime/safepointVerifiers.hpp"
  80 #include "runtime/serviceThread.hpp"
  81 #include "runtime/stackFrameStream.inline.hpp"
  82 #include "runtime/stackWatermarkSet.hpp"
  83 #include "runtime/synchronizer.hpp"
  84 #include "runtime/threadCritical.hpp"
  85 #include "runtime/threadSMR.inline.hpp"
  86 #include "runtime/threadStatisticalInfo.hpp"
  87 #include "runtime/threadWXSetters.inline.hpp"
  88 #include "runtime/timer.hpp"
  89 #include "runtime/timerTrace.hpp"
  90 #include "runtime/vframe.inline.hpp"
  91 #include "runtime/vframeArray.hpp"
  92 #include "runtime/vframe_hp.hpp"
  93 #include "runtime/vmThread.hpp"
  94 #include "runtime/vmOperations.hpp"
  95 #include "services/threadService.hpp"
  96 #include "utilities/copy.hpp"
  97 #include "utilities/defaultStream.hpp"
  98 #include "utilities/dtrace.hpp"
  99 #include "utilities/events.hpp"
 100 #include "utilities/macros.hpp"
 101 #include "utilities/preserveException.hpp"
 102 #include "utilities/spinYield.hpp"
 103 #if INCLUDE_JVMCI
 104 #include "jvmci/jvmci.hpp"
 105 #include "jvmci/jvmciEnv.hpp"
 106 #endif
 107 #if INCLUDE_JFR
 108 #include "jfr/jfr.hpp"
 109 #endif
 110 
 111 // Set by os layer.
 112 size_t      JavaThread::_stack_size_at_create = 0;
 113 
 114 #ifdef DTRACE_ENABLED
 115 
 116 // Only bother with this argument setup if dtrace is available
 117 
 118   #define HOTSPOT_THREAD_PROBE_start HOTSPOT_THREAD_START
 119   #define HOTSPOT_THREAD_PROBE_stop HOTSPOT_THREAD_STOP
 120 
 121   #define DTRACE_THREAD_PROBE(probe, javathread)                           \
 122     {                                                                      \
 123       ResourceMark rm(this);                                               \
 124       int len = 0;                                                         \
 125       const char* name = (javathread)->name();                             \
 126       len = strlen(name);                                                  \
 127       HOTSPOT_THREAD_PROBE_##probe(/* probe = start, stop */               \
 128         (char *) name, len,                                                \
 129         java_lang_Thread::thread_id((javathread)->threadObj()),            \
 130         (uintptr_t) (javathread)->osthread()->thread_id(),                 \
 131         java_lang_Thread::is_daemon((javathread)->threadObj()));           \
 132     }
 133 
 134 #else //  ndef DTRACE_ENABLED
 135 
 136   #define DTRACE_THREAD_PROBE(probe, javathread)
 137 
 138 #endif // ndef DTRACE_ENABLED
 139 
 140 void JavaThread::smr_delete() {
 141   if (_on_thread_list) {
 142     ThreadsSMRSupport::smr_delete(this);
 143   } else {
 144     delete this;
 145   }
 146 }
 147 
 148 // Initialized by VMThread at vm_global_init
 149 OopStorage* JavaThread::_thread_oop_storage = NULL;
 150 
 151 OopStorage* JavaThread::thread_oop_storage() {
 152   assert(_thread_oop_storage != NULL, "not yet initialized");
 153   return _thread_oop_storage;
 154 }
 155 
 156 void JavaThread::set_threadOopHandles(oop p) {
 157   assert(_thread_oop_storage != NULL, "not yet initialized");
 158   _threadObj   = OopHandle(_thread_oop_storage, p);
 159   _vthread     = OopHandle(_thread_oop_storage, p);
 160   _jvmti_vthread = OopHandle(_thread_oop_storage, NULL);
 161   _extentLocalCache = OopHandle(_thread_oop_storage, NULL);
 162 }
 163 
 164 oop JavaThread::threadObj() const {
 165   // Ideally we would verify the current thread is oop_safe when this is called, but as we can
 166   // be called from a signal handler we would have to use Thread::current_or_null_safe(). That
 167   // has overhead and also interacts poorly with GetLastError on Windows due to the use of TLS.
 168   // Instead callers must verify oop safe access.
 169   return _threadObj.resolve();
 170 }
 171 
 172 oop JavaThread::vthread() const {
 173   return _vthread.resolve();
 174 }
 175 
 176 void JavaThread::set_vthread(oop p) {
 177   assert(_thread_oop_storage != NULL, "not yet initialized");
 178   _vthread.replace(p);
 179 }
 180 
 181 oop JavaThread::jvmti_vthread() const {
 182   return _jvmti_vthread.resolve();
 183 }
 184 
 185 void JavaThread::set_jvmti_vthread(oop p) {
 186   assert(_thread_oop_storage != NULL, "not yet initialized");
 187   _jvmti_vthread.replace(p);
 188 }
 189 
 190 oop JavaThread::extentLocalCache() const {
 191   return _extentLocalCache.resolve();
 192 }
 193 
 194 void JavaThread::set_extentLocalCache(oop p) {
 195   assert(_thread_oop_storage != NULL, "not yet initialized");
 196   _extentLocalCache.replace(p);
 197 }
 198 
 199 void JavaThread::allocate_threadObj(Handle thread_group, const char* thread_name,
 200                                     bool daemon, TRAPS) {
 201   assert(thread_group.not_null(), "thread group should be specified");
 202   assert(threadObj() == NULL, "should only create Java thread object once");
 203 
 204   InstanceKlass* ik = vmClasses::Thread_klass();
 205   assert(ik->is_initialized(), "must be");
 206   instanceHandle thread_oop = ik->allocate_instance_handle(CHECK);
 207 
 208   // We are called from jni_AttachCurrentThread/jni_AttachCurrentThreadAsDaemon.
 209   // We cannot use JavaCalls::construct_new_instance because the java.lang.Thread
 210   // constructor calls Thread.current(), which must be set here.
 211   java_lang_Thread::set_thread(thread_oop(), this);
 212   set_threadOopHandles(thread_oop());
 213 
 214   JavaValue result(T_VOID);
 215   if (thread_name != NULL) {
 216     Handle name = java_lang_String::create_from_str(thread_name, CHECK);
 217     // Thread gets assigned specified name and null target
 218     JavaCalls::call_special(&result,
 219                             thread_oop,
 220                             ik,
 221                             vmSymbols::object_initializer_name(),
 222                             vmSymbols::threadgroup_string_void_signature(),
 223                             thread_group,
 224                             name,
 225                             THREAD);
 226   } else {
 227     // Thread gets assigned name "Thread-nnn" and null target
 228     // (java.lang.Thread doesn't have a constructor taking only a ThreadGroup argument)
 229     JavaCalls::call_special(&result,
 230                             thread_oop,
 231                             ik,
 232                             vmSymbols::object_initializer_name(),
 233                             vmSymbols::threadgroup_runnable_void_signature(),
 234                             thread_group,
 235                             Handle(),
 236                             THREAD);
 237   }
 238   os::set_priority(this, NormPriority);
 239 
 240   if (daemon) {
 241     java_lang_Thread::set_daemon(thread_oop());
 242   }
 243 }
 244 
 245 // ======= JavaThread ========
 246 
 247 #if INCLUDE_JVMCI
 248 
 249 jlong* JavaThread::_jvmci_old_thread_counters;
 250 
 251 bool jvmci_counters_include(JavaThread* thread) {
 252   return !JVMCICountersExcludeCompiler || !thread->is_Compiler_thread();
 253 }
 254 
 255 void JavaThread::collect_counters(jlong* array, int length) {
 256   assert(length == JVMCICounterSize, "wrong value");
 257   for (int i = 0; i < length; i++) {
 258     array[i] = _jvmci_old_thread_counters[i];
 259   }
 260   for (JavaThread* tp : ThreadsListHandle()) {
 261     if (jvmci_counters_include(tp)) {
 262       for (int i = 0; i < length; i++) {
 263         array[i] += tp->_jvmci_counters[i];
 264       }
 265     }
 266   }
 267 }
 268 
 269 // Attempt to enlarge the array for per thread counters.
 270 jlong* resize_counters_array(jlong* old_counters, int current_size, int new_size) {
 271   jlong* new_counters = NEW_C_HEAP_ARRAY_RETURN_NULL(jlong, new_size, mtJVMCI);
 272   if (new_counters == NULL) {
 273     return NULL;
 274   }
 275   if (old_counters == NULL) {
 276     old_counters = new_counters;
 277     memset(old_counters, 0, sizeof(jlong) * new_size);
 278   } else {
 279     for (int i = 0; i < MIN2((int) current_size, new_size); i++) {
 280       new_counters[i] = old_counters[i];
 281     }
 282     if (new_size > current_size) {
 283       memset(new_counters + current_size, 0, sizeof(jlong) * (new_size - current_size));
 284     }
 285     FREE_C_HEAP_ARRAY(jlong, old_counters);
 286   }
 287   return new_counters;
 288 }
 289 
 290 // Attempt to enlarge the array for per thread counters.
 291 bool JavaThread::resize_counters(int current_size, int new_size) {
 292   jlong* new_counters = resize_counters_array(_jvmci_counters, current_size, new_size);
 293   if (new_counters == NULL) {
 294     return false;
 295   } else {
 296     _jvmci_counters = new_counters;
 297     return true;
 298   }
 299 }
 300 
 301 class VM_JVMCIResizeCounters : public VM_Operation {
 302  private:
 303   int _new_size;
 304   bool _failed;
 305 
 306  public:
 307   VM_JVMCIResizeCounters(int new_size) : _new_size(new_size), _failed(false) { }
 308   VMOp_Type type()                  const        { return VMOp_JVMCIResizeCounters; }
 309   bool allow_nested_vm_operations() const        { return true; }
 310   void doit() {
 311     // Resize the old thread counters array
 312     jlong* new_counters = resize_counters_array(JavaThread::_jvmci_old_thread_counters, JVMCICounterSize, _new_size);
 313     if (new_counters == NULL) {
 314       _failed = true;
 315       return;
 316     } else {
 317       JavaThread::_jvmci_old_thread_counters = new_counters;
 318     }
 319 
 320     // Now resize each threads array
 321     for (JavaThread* tp : ThreadsListHandle()) {
 322       if (!tp->resize_counters(JVMCICounterSize, _new_size)) {
 323         _failed = true;
 324         break;
 325       }
 326     }
 327     if (!_failed) {
 328       JVMCICounterSize = _new_size;
 329     }
 330   }
 331 
 332   bool failed() { return _failed; }
 333 };
 334 
 335 bool JavaThread::resize_all_jvmci_counters(int new_size) {
 336   VM_JVMCIResizeCounters op(new_size);
 337   VMThread::execute(&op);
 338   return !op.failed();
 339 }
 340 
 341 #endif // INCLUDE_JVMCI
 342 
 343 #ifdef ASSERT
 344 // Checks safepoint allowed and clears unhandled oops at potential safepoints.
 345 void JavaThread::check_possible_safepoint() {
 346   if (_no_safepoint_count > 0) {
 347     print_owned_locks();
 348     assert(false, "Possible safepoint reached by thread that does not allow it");
 349   }
 350 #ifdef CHECK_UNHANDLED_OOPS
 351   // Clear unhandled oops in JavaThreads so we get a crash right away.
 352   clear_unhandled_oops();
 353 #endif // CHECK_UNHANDLED_OOPS
 354 
 355   // Macos/aarch64 should be in the right state for safepoint (e.g.
 356   // deoptimization needs WXWrite).  Crashes caused by the wrong state rarely
 357   // happens in practice, making such issues hard to find and reproduce.
 358 #if defined(__APPLE__) && defined(AARCH64)
 359   if (AssertWXAtThreadSync) {
 360     assert_wx_state(WXWrite);
 361   }
 362 #endif
 363 }
 364 
 365 void JavaThread::check_for_valid_safepoint_state() {
 366   // Check NoSafepointVerifier, which is implied by locks taken that can be
 367   // shared with the VM thread.  This makes sure that no locks with allow_vm_block
 368   // are held.
 369   check_possible_safepoint();
 370 
 371   if (thread_state() != _thread_in_vm) {
 372     fatal("LEAF method calling lock?");
 373   }
 374 
 375   if (GCALotAtAllSafepoints) {
 376     // We could enter a safepoint here and thus have a gc
 377     InterfaceSupport::check_gc_alot();
 378   }
 379 }
 380 #endif // ASSERT
 381 
 382 // A JavaThread is a normal Java thread
 383 
 384 JavaThread::JavaThread() :
 385   // Initialize fields
 386 
 387   _in_asgct(false),
 388   _on_thread_list(false),
 389   DEBUG_ONLY(_java_call_counter(0) COMMA)
 390   _entry_point(nullptr),
 391   _deopt_mark(nullptr),
 392   _deopt_nmethod(nullptr),
 393   _vframe_array_head(nullptr),
 394   _vframe_array_last(nullptr),
 395   _jvmti_deferred_updates(nullptr),
 396   _callee_target(nullptr),
 397   _vm_result(nullptr),
 398   _vm_result_2(nullptr),
 399 
 400   _current_pending_monitor(NULL),
 401   _current_pending_monitor_is_from_java(true),
 402   _current_waiting_monitor(NULL),
 403   _active_handles(NULL),
 404   _free_handle_block(NULL),
 405   _Stalled(0),
 406 
 407   _monitor_chunks(nullptr),
 408 
 409   _suspend_flags(0),
 410 
 411   _thread_state(_thread_new),
 412   _saved_exception_pc(nullptr),
 413 #ifdef ASSERT
 414   _no_safepoint_count(0),
 415   _visited_for_critical_count(false),
 416 #endif
 417 
 418   _terminated(_not_terminated),
 419   _in_deopt_handler(0),
 420   _doing_unsafe_access(false),
 421   _do_not_unlock_if_synchronized(false),
 422 #if INCLUDE_JVMTI
 423   _carrier_thread_suspended(false),
 424   _is_in_VTMS_transition(false),
 425 #ifdef ASSERT
 426   _is_VTMS_transition_disabler(false),
 427 #endif
 428 #endif
 429   _jni_attach_state(_not_attaching_via_jni),
 430 #if INCLUDE_JVMCI
 431   _pending_deoptimization(-1),
 432   _pending_monitorenter(false),
 433   _pending_transfer_to_interpreter(false),
 434   _in_retryable_allocation(false),
 435   _pending_failed_speculation(0),
 436   _jvmci{nullptr},
 437   _libjvmci_runtime(nullptr),
 438   _jvmci_counters(nullptr),
 439   _jvmci_reserved0(0),
 440   _jvmci_reserved1(0),
 441   _jvmci_reserved_oop0(nullptr),
 442 #endif // INCLUDE_JVMCI
 443 
 444   _exception_oop(oop()),
 445   _exception_pc(0),
 446   _exception_handler_pc(0),
 447   _is_method_handle_return(0),
 448 
 449   _jni_active_critical(0),
 450   _pending_jni_exception_check_fn(nullptr),
 451   _depth_first_number(0),
 452 
 453   // JVMTI PopFrame support
 454   _popframe_condition(popframe_inactive),
 455   _frames_to_pop_failed_realloc(0),
 456 
 457   _cont_entry(nullptr),
 458   _cont_fastpath(0),
 459   _cont_fastpath_thread_state(1),
 460   _held_monitor_count(0),
 461   _jni_monitor_count(0),
 462 
 463   _handshake(this),
 464 
 465   _popframe_preserved_args(nullptr),
 466   _popframe_preserved_args_size(0),
 467 
 468   _jvmti_thread_state(nullptr),
 469   _interp_only_mode(0),
 470   _should_post_on_exceptions_flag(JNI_FALSE),
 471   _thread_stat(new ThreadStatistics()),
 472 
 473   _parker(),
 474 
 475   _class_to_be_initialized(nullptr),
 476 
 477   _SleepEvent(ParkEvent::Allocate(this))
 478 {
 479   set_jni_functions(jni_functions());
 480 
 481 #if INCLUDE_JVMCI
 482   assert(_jvmci._implicit_exception_pc == nullptr, "must be");
 483   if (JVMCICounterSize > 0) {
 484     resize_counters(0, (int) JVMCICounterSize);
 485   }
 486 #endif // INCLUDE_JVMCI
 487 
 488   // Setup safepoint state info for this thread
 489   ThreadSafepointState::create(this);
 490 
 491   SafepointMechanism::initialize_header(this);
 492 
 493   set_requires_cross_modify_fence(false);
 494 
 495   pd_initialize();
 496   assert(deferred_card_mark().is_empty(), "Default MemRegion ctor");
 497 }
 498 
 499 JavaThread::JavaThread(bool is_attaching_via_jni) : JavaThread() {
 500   if (is_attaching_via_jni) {
 501     _jni_attach_state = _attaching_via_jni;
 502   }
 503 }
 504 
 505 
 506 // interrupt support
 507 
 508 void JavaThread::interrupt() {
 509   // All callers should have 'this' thread protected by a
 510   // ThreadsListHandle so that it cannot terminate and deallocate
 511   // itself.
 512   debug_only(check_for_dangling_thread_pointer(this);)
 513 
 514   // For Windows _interrupt_event
 515   WINDOWS_ONLY(osthread()->set_interrupted(true);)
 516 
 517   // For Thread.sleep
 518   _SleepEvent->unpark();
 519 
 520   // For JSR166 LockSupport.park
 521   parker()->unpark();
 522 
 523   // For ObjectMonitor and JvmtiRawMonitor
 524   _ParkEvent->unpark();
 525 }
 526 
 527 
 528 bool JavaThread::is_interrupted(bool clear_interrupted) {
 529   debug_only(check_for_dangling_thread_pointer(this);)
 530 
 531   if (_threadObj.peek() == NULL) {
 532     // If there is no j.l.Thread then it is impossible to have
 533     // been interrupted. We can find NULL during VM initialization
 534     // or when a JNI thread is still in the process of attaching.
 535     // In such cases this must be the current thread.
 536     assert(this == Thread::current(), "invariant");
 537     return false;
 538   }
 539 
 540   bool interrupted = java_lang_Thread::interrupted(threadObj());
 541 
 542   // NOTE that since there is no "lock" around the interrupt and
 543   // is_interrupted operations, there is the possibility that the
 544   // interrupted flag will be "false" but that the
 545   // low-level events will be in the signaled state. This is
 546   // intentional. The effect of this is that Object.wait() and
 547   // LockSupport.park() will appear to have a spurious wakeup, which
 548   // is allowed and not harmful, and the possibility is so rare that
 549   // it is not worth the added complexity to add yet another lock.
 550   // For the sleep event an explicit reset is performed on entry
 551   // to JavaThread::sleep, so there is no early return. It has also been
 552   // recommended not to put the interrupted flag into the "event"
 553   // structure because it hides the issue.
 554   // Also, because there is no lock, we must only clear the interrupt
 555   // state if we are going to report that we were interrupted; otherwise
 556   // an interrupt that happens just after we read the field would be lost.
 557   if (interrupted && clear_interrupted) {
 558     assert(this == Thread::current(), "only the current thread can clear");
 559     java_lang_Thread::set_interrupted(threadObj(), false);
 560     WINDOWS_ONLY(osthread()->set_interrupted(false);)
 561   }
 562 
 563   return interrupted;
 564 }
 565 
 566 void JavaThread::block_if_vm_exited() {
 567   if (_terminated == _vm_exited) {
 568     // _vm_exited is set at safepoint, and Threads_lock is never released
 569     // so we will block here forever.
 570     // Here we can be doing a jump from a safe state to an unsafe state without
 571     // proper transition, but it happens after the final safepoint has begun so
 572     // this jump won't cause any safepoint problems.
 573     set_thread_state(_thread_in_vm);
 574     Threads_lock->lock();
 575     ShouldNotReachHere();
 576   }
 577 }
 578 
 579 JavaThread::JavaThread(ThreadFunction entry_point, size_t stack_sz) : JavaThread() {
 580   _jni_attach_state = _not_attaching_via_jni;
 581   set_entry_point(entry_point);
 582   // Create the native thread itself.
 583   // %note runtime_23
 584   os::ThreadType thr_type = os::java_thread;
 585   thr_type = entry_point == &CompilerThread::thread_entry ? os::compiler_thread :
 586                                                             os::java_thread;
 587   os::create_thread(this, thr_type, stack_sz);
 588   // The _osthread may be NULL here because we ran out of memory (too many threads active).
 589   // We need to throw and OutOfMemoryError - however we cannot do this here because the caller
 590   // may hold a lock and all locks must be unlocked before throwing the exception (throwing
 591   // the exception consists of creating the exception object & initializing it, initialization
 592   // will leave the VM via a JavaCall and then all locks must be unlocked).
 593   //
 594   // The thread is still suspended when we reach here. Thread must be explicit started
 595   // by creator! Furthermore, the thread must also explicitly be added to the Threads list
 596   // by calling Threads:add. The reason why this is not done here, is because the thread
 597   // object must be fully initialized (take a look at JVM_Start)
 598 }
 599 
 600 JavaThread::~JavaThread() {
 601 
 602   // Ask ServiceThread to release the threadObj OopHandle
 603   ServiceThread::add_oop_handle_release(_threadObj);
 604   ServiceThread::add_oop_handle_release(_vthread);
 605   ServiceThread::add_oop_handle_release(_jvmti_vthread);
 606 
 607   // Return the sleep event to the free list
 608   ParkEvent::Release(_SleepEvent);
 609   _SleepEvent = NULL;
 610 
 611   // Free any remaining  previous UnrollBlock
 612   vframeArray* old_array = vframe_array_last();
 613 
 614   if (old_array != NULL) {
 615     Deoptimization::UnrollBlock* old_info = old_array->unroll_block();
 616     old_array->set_unroll_block(NULL);
 617     delete old_info;
 618     delete old_array;
 619   }
 620 
 621   JvmtiDeferredUpdates* updates = deferred_updates();
 622   if (updates != NULL) {
 623     // This can only happen if thread is destroyed before deoptimization occurs.
 624     assert(updates->count() > 0, "Updates holder not deleted");
 625     // free deferred updates.
 626     delete updates;
 627     set_deferred_updates(NULL);
 628   }
 629 
 630   // All Java related clean up happens in exit
 631   ThreadSafepointState::destroy(this);
 632   if (_thread_stat != NULL) delete _thread_stat;
 633 
 634 #if INCLUDE_JVMCI
 635   if (JVMCICounterSize > 0) {
 636     FREE_C_HEAP_ARRAY(jlong, _jvmci_counters);
 637   }
 638 #endif // INCLUDE_JVMCI
 639 }
 640 
 641 
 642 // First JavaThread specific code executed by a new Java thread.
 643 void JavaThread::pre_run() {
 644   // empty - see comments in run()
 645 }
 646 
 647 // The main routine called by a new Java thread. This isn't overridden
 648 // by subclasses, instead different subclasses define a different "entry_point"
 649 // which defines the actual logic for that kind of thread.
 650 void JavaThread::run() {
 651   // initialize thread-local alloc buffer related fields
 652   initialize_tlab();
 653 
 654   _stack_overflow_state.create_stack_guard_pages();
 655 
 656   cache_global_variables();
 657 
 658   // Thread is now sufficiently initialized to be handled by the safepoint code as being
 659   // in the VM. Change thread state from _thread_new to _thread_in_vm
 660   assert(this->thread_state() == _thread_new, "wrong thread state");
 661   set_thread_state(_thread_in_vm);
 662 
 663   // Before a thread is on the threads list it is always safe, so after leaving the
 664   // _thread_new we should emit a instruction barrier. The distance to modified code
 665   // from here is probably far enough, but this is consistent and safe.
 666   OrderAccess::cross_modify_fence();
 667 
 668   assert(JavaThread::current() == this, "sanity check");
 669   assert(!Thread::current()->owns_locks(), "sanity check");
 670 
 671   DTRACE_THREAD_PROBE(start, this);
 672 
 673   // This operation might block. We call that after all safepoint checks for a new thread has
 674   // been completed.
 675   set_active_handles(JNIHandleBlock::allocate_block());
 676 
 677   if (JvmtiExport::should_post_thread_life()) {
 678     JvmtiExport::post_thread_start(this);
 679 
 680   }
 681 
 682   // We call another function to do the rest so we are sure that the stack addresses used
 683   // from there will be lower than the stack base just computed.
 684   thread_main_inner();
 685 }
 686 
 687 void JavaThread::thread_main_inner() {
 688   assert(JavaThread::current() == this, "sanity check");
 689   assert(_threadObj.peek() != NULL, "just checking");
 690 
 691   // Execute thread entry point unless this thread has a pending exception
 692   // or has been stopped before starting.
 693   // Note: Due to JVM_StopThread we can have pending exceptions already!
 694   if (!this->has_pending_exception() &&
 695       !java_lang_Thread::is_stillborn(this->threadObj())) {
 696     {
 697       ResourceMark rm(this);
 698       this->set_native_thread_name(this->name());
 699     }
 700     HandleMark hm(this);
 701     this->entry_point()(this, this);
 702   }
 703 
 704   DTRACE_THREAD_PROBE(stop, this);
 705 
 706   // Cleanup is handled in post_run()
 707 }
 708 
 709 // Shared teardown for all JavaThreads
 710 void JavaThread::post_run() {
 711   this->exit(false);
 712   this->unregister_thread_stack_with_NMT();
 713   // Defer deletion to here to ensure 'this' is still referenceable in call_run
 714   // for any shared tear-down.
 715   this->smr_delete();
 716 }
 717 
 718 static void ensure_join(JavaThread* thread) {
 719   // We do not need to grab the Threads_lock, since we are operating on ourself.
 720   Handle threadObj(thread, thread->threadObj());
 721   assert(threadObj.not_null(), "java thread object must exist");
 722   ObjectLocker lock(threadObj, thread);
 723   // Ignore pending exception (ThreadDeath), since we are exiting anyway
 724   thread->clear_pending_exception();
 725   // Thread is exiting. So set thread_status field in  java.lang.Thread class to TERMINATED.
 726   java_lang_Thread::set_thread_status(threadObj(), JavaThreadStatus::TERMINATED);
 727   // Clear the native thread instance - this makes isAlive return false and allows the join()
 728   // to complete once we've done the notify_all below
 729   java_lang_Thread::set_thread(threadObj(), NULL);
 730   lock.notify_all(thread);
 731   // Ignore pending exception (ThreadDeath), since we are exiting anyway
 732   thread->clear_pending_exception();
 733 }
 734 
 735 static bool is_daemon(oop threadObj) {
 736   return (threadObj != NULL && java_lang_Thread::is_daemon(threadObj));
 737 }
 738 
 739 // For any new cleanup additions, please check to see if they need to be applied to
 740 // cleanup_failed_attach_current_thread as well.
 741 void JavaThread::exit(bool destroy_vm, ExitType exit_type) {
 742   assert(this == JavaThread::current(), "thread consistency check");
 743   assert(!is_exiting(), "should not be exiting or terminated already");
 744 
 745   elapsedTimer _timer_exit_phase1;
 746   elapsedTimer _timer_exit_phase2;
 747   elapsedTimer _timer_exit_phase3;
 748   elapsedTimer _timer_exit_phase4;
 749 
 750   if (log_is_enabled(Debug, os, thread, timer)) {
 751     _timer_exit_phase1.start();
 752   }
 753 
 754   HandleMark hm(this);
 755   Handle uncaught_exception(this, this->pending_exception());
 756   this->clear_pending_exception();
 757   Handle threadObj(this, this->threadObj());
 758   assert(threadObj.not_null(), "Java thread object should be created");
 759 
 760   if (!destroy_vm) {
 761     if (uncaught_exception.not_null()) {
 762       EXCEPTION_MARK;
 763       // Call method Thread.dispatchUncaughtException().
 764       Klass* thread_klass = vmClasses::Thread_klass();
 765       JavaValue result(T_VOID);
 766       JavaCalls::call_virtual(&result,
 767                               threadObj, thread_klass,
 768                               vmSymbols::dispatchUncaughtException_name(),
 769                               vmSymbols::throwable_void_signature(),
 770                               uncaught_exception,
 771                               THREAD);
 772       if (HAS_PENDING_EXCEPTION) {
 773         ResourceMark rm(this);
 774         jio_fprintf(defaultStream::error_stream(),
 775                     "\nException: %s thrown from the UncaughtExceptionHandler"
 776                     " in thread \"%s\"\n",
 777                     pending_exception()->klass()->external_name(),
 778                     name());
 779         CLEAR_PENDING_EXCEPTION;
 780       }
 781     }
 782 
 783     if (!is_Compiler_thread()) {
 784       // We have finished executing user-defined Java code and now have to do the
 785       // implementation specific clean-up by calling Thread.exit(). We prevent any
 786       // asynchronous exceptions from being delivered while in Thread.exit()
 787       // to ensure the clean-up is not corrupted.
 788       NoAsyncExceptionDeliveryMark _no_async(this);
 789 
 790       EXCEPTION_MARK;
 791       JavaValue result(T_VOID);
 792       Klass* thread_klass = vmClasses::Thread_klass();
 793       JavaCalls::call_virtual(&result,
 794                               threadObj, thread_klass,
 795                               vmSymbols::exit_method_name(),
 796                               vmSymbols::void_method_signature(),
 797                               THREAD);
 798       CLEAR_PENDING_EXCEPTION;
 799     }
 800 
 801     // notify JVMTI
 802     if (JvmtiExport::should_post_thread_life()) {
 803       JvmtiExport::post_thread_end(this);
 804     }
 805   } else {
 806     // before_exit() has already posted JVMTI THREAD_END events
 807   }
 808 
 809   // Cleanup any pending async exception now since we cannot access oops after
 810   // BarrierSet::barrier_set()->on_thread_detach() has been executed.
 811   if (has_async_exception_condition()) {
 812     handshake_state()->clean_async_exception_operation();
 813   }
 814 
 815   // The careful dance between thread suspension and exit is handled here.
 816   // Since we are in thread_in_vm state and suspension is done with handshakes,
 817   // we can just put in the exiting state and it will be correctly handled.
 818   // Also, no more async exceptions will be added to the queue after this point.
 819   set_terminated(_thread_exiting);
 820   ThreadService::current_thread_exiting(this, is_daemon(threadObj()));
 821 
 822   if (log_is_enabled(Debug, os, thread, timer)) {
 823     _timer_exit_phase1.stop();
 824     _timer_exit_phase2.start();
 825   }
 826 
 827   // Capture daemon status before the thread is marked as terminated.
 828   bool daemon = is_daemon(threadObj());
 829 
 830   // Notify waiters on thread object. This has to be done after exit() is called
 831   // on the thread (if the thread is the last thread in a daemon ThreadGroup the
 832   // group should have the destroyed bit set before waiters are notified).
 833   ensure_join(this);
 834   assert(!this->has_pending_exception(), "ensure_join should have cleared");
 835 
 836   if (log_is_enabled(Debug, os, thread, timer)) {
 837     _timer_exit_phase2.stop();
 838     _timer_exit_phase3.start();
 839   }
 840   // 6282335 JNI DetachCurrentThread spec states that all Java monitors
 841   // held by this thread must be released. The spec does not distinguish
 842   // between JNI-acquired and regular Java monitors. We can only see
 843   // regular Java monitors here if monitor enter-exit matching is broken.
 844   //
 845   // ensure_join() ignores IllegalThreadStateExceptions, and so does
 846   // ObjectSynchronizer::release_monitors_owned_by_thread().
 847   if (exit_type == jni_detach) {
 848     // Sanity check even though JNI DetachCurrentThread() would have
 849     // returned JNI_ERR if there was a Java frame. JavaThread exit
 850     // should be done executing Java code by the time we get here.
 851     assert(!this->has_last_Java_frame(),
 852            "should not have a Java frame when detaching or exiting");
 853     ObjectSynchronizer::release_monitors_owned_by_thread(this);
 854     assert(!this->has_pending_exception(), "release_monitors should have cleared");
 855   }
 856 
 857   // Since above code may not release JNI monitors and if someone forgot to do an
 858   // JNI monitorexit, held count should be equal jni count.
 859   // Consider scan all object monitor for this owner if JNI count > 0 (at least on detach).
 860   assert(this->held_monitor_count() == this->jni_monitor_count(),
 861          "held monitor count should be equal to jni: " INT64_FORMAT " != " INT64_FORMAT,
 862          (int64_t)this->held_monitor_count(), (int64_t)this->jni_monitor_count());
 863   if (CheckJNICalls && this->jni_monitor_count() > 0) {
 864     // We would like a fatal here, but due to we never checked this before there
 865     // is a lot of tests which breaks, even with an error log.
 866     log_debug(jni)("JavaThread %s (tid: " UINTX_FORMAT ") with Objects still locked by JNI MonitorEnter.",
 867       exit_type == JavaThread::normal_exit ? "exiting" : "detaching", os::current_thread_id());
 868   }
 869 
 870   // These things needs to be done while we are still a Java Thread. Make sure that thread
 871   // is in a consistent state, in case GC happens
 872   JFR_ONLY(Jfr::on_thread_exit(this);)
 873 
 874   if (active_handles() != NULL) {
 875     JNIHandleBlock* block = active_handles();
 876     set_active_handles(NULL);
 877     JNIHandleBlock::release_block(block);
 878   }
 879 
 880   if (free_handle_block() != NULL) {
 881     JNIHandleBlock* block = free_handle_block();
 882     set_free_handle_block(NULL);
 883     JNIHandleBlock::release_block(block);
 884   }
 885 
 886   // These have to be removed while this is still a valid thread.
 887   _stack_overflow_state.remove_stack_guard_pages();
 888 
 889   if (UseTLAB) {
 890     tlab().retire();
 891   }
 892 
 893   if (JvmtiEnv::environments_might_exist()) {
 894     JvmtiExport::cleanup_thread(this);
 895   }
 896 
 897   // We need to cache the thread name for logging purposes below as once
 898   // we have called on_thread_detach this thread must not access any oops.
 899   char* thread_name = NULL;
 900   if (log_is_enabled(Debug, os, thread, timer)) {
 901     ResourceMark rm(this);
 902     thread_name = os::strdup(name());
 903   }
 904 
 905   log_info(os, thread)("JavaThread %s (tid: " UINTX_FORMAT ").",
 906     exit_type == JavaThread::normal_exit ? "exiting" : "detaching",
 907     os::current_thread_id());
 908 
 909   if (log_is_enabled(Debug, os, thread, timer)) {
 910     _timer_exit_phase3.stop();
 911     _timer_exit_phase4.start();
 912   }
 913 
 914 #if INCLUDE_JVMCI
 915   if (JVMCICounterSize > 0) {
 916     if (jvmci_counters_include(this)) {
 917       for (int i = 0; i < JVMCICounterSize; i++) {
 918         _jvmci_old_thread_counters[i] += _jvmci_counters[i];
 919       }
 920     }
 921   }
 922 #endif // INCLUDE_JVMCI
 923 
 924   // Remove from list of active threads list, and notify VM thread if we are the last non-daemon thread.
 925   // We call BarrierSet::barrier_set()->on_thread_detach() here so no touching of oops after this point.
 926   Threads::remove(this, daemon);
 927 
 928   if (log_is_enabled(Debug, os, thread, timer)) {
 929     _timer_exit_phase4.stop();
 930     log_debug(os, thread, timer)("name='%s'"
 931                                  ", exit-phase1=" JLONG_FORMAT
 932                                  ", exit-phase2=" JLONG_FORMAT
 933                                  ", exit-phase3=" JLONG_FORMAT
 934                                  ", exit-phase4=" JLONG_FORMAT,
 935                                  thread_name,
 936                                  _timer_exit_phase1.milliseconds(),
 937                                  _timer_exit_phase2.milliseconds(),
 938                                  _timer_exit_phase3.milliseconds(),
 939                                  _timer_exit_phase4.milliseconds());
 940     os::free(thread_name);
 941   }
 942 }
 943 
 944 void JavaThread::cleanup_failed_attach_current_thread(bool is_daemon) {
 945   if (active_handles() != NULL) {
 946     JNIHandleBlock* block = active_handles();
 947     set_active_handles(NULL);
 948     JNIHandleBlock::release_block(block);
 949   }
 950 
 951   if (free_handle_block() != NULL) {
 952     JNIHandleBlock* block = free_handle_block();
 953     set_free_handle_block(NULL);
 954     JNIHandleBlock::release_block(block);
 955   }
 956 
 957   // These have to be removed while this is still a valid thread.
 958   _stack_overflow_state.remove_stack_guard_pages();
 959 
 960   if (UseTLAB) {
 961     tlab().retire();
 962   }
 963 
 964   Threads::remove(this, is_daemon);
 965   this->smr_delete();
 966 }
 967 
 968 JavaThread* JavaThread::active() {
 969   Thread* thread = Thread::current();
 970   if (thread->is_Java_thread()) {
 971     return JavaThread::cast(thread);
 972   } else {
 973     assert(thread->is_VM_thread(), "this must be a vm thread");
 974     VM_Operation* op = ((VMThread*) thread)->vm_operation();
 975     JavaThread *ret = op == NULL ? NULL : JavaThread::cast(op->calling_thread());
 976     return ret;
 977   }
 978 }
 979 
 980 bool JavaThread::is_lock_owned(address adr) const {
 981   if (Thread::is_lock_owned(adr)) return true;
 982 
 983   for (MonitorChunk* chunk = monitor_chunks(); chunk != NULL; chunk = chunk->next()) {
 984     if (chunk->contains(adr)) return true;
 985   }
 986 
 987   return false;
 988 }
 989 
 990 bool JavaThread::is_lock_owned_current(address adr) const {
 991   address stack_end = _stack_base - _stack_size;
 992   const ContinuationEntry* ce = vthread_continuation();
 993   address stack_base = ce != nullptr ? (address)ce->entry_sp() : _stack_base;
 994   if (stack_base > adr && adr >= stack_end) {
 995     return true;
 996   }
 997 
 998   for (MonitorChunk* chunk = monitor_chunks(); chunk != NULL; chunk = chunk->next()) {
 999     if (chunk->contains(adr)) {
1000       return true;
1001     }
1002   }
1003 
1004   return false;
1005 }
1006 
1007 bool JavaThread::is_lock_owned_carrier(address adr) const {
1008   assert(is_vthread_mounted(), "");
1009   address stack_end = _stack_base - _stack_size;
1010   address stack_base = (address)vthread_continuation()->entry_sp();
1011   return stack_base > adr && adr >= stack_end;
1012 }
1013 
1014 oop JavaThread::exception_oop() const {
1015   return Atomic::load(&_exception_oop);
1016 }
1017 
1018 void JavaThread::set_exception_oop(oop o) {
1019   Atomic::store(&_exception_oop, o);
1020 }
1021 
1022 void JavaThread::add_monitor_chunk(MonitorChunk* chunk) {
1023   chunk->set_next(monitor_chunks());
1024   set_monitor_chunks(chunk);
1025 }
1026 
1027 void JavaThread::remove_monitor_chunk(MonitorChunk* chunk) {
1028   guarantee(monitor_chunks() != NULL, "must be non empty");
1029   if (monitor_chunks() == chunk) {
1030     set_monitor_chunks(chunk->next());
1031   } else {
1032     MonitorChunk* prev = monitor_chunks();
1033     while (prev->next() != chunk) prev = prev->next();
1034     prev->set_next(chunk->next());
1035   }
1036 }
1037 
1038 void JavaThread::handle_special_runtime_exit_condition() {
1039   if (is_obj_deopt_suspend()) {
1040     frame_anchor()->make_walkable();
1041     wait_for_object_deoptimization();
1042   }
1043   JFR_ONLY(SUSPEND_THREAD_CONDITIONAL(this);)
1044 }
1045 
1046 
1047 // Asynchronous exceptions support
1048 //
1049 void JavaThread::handle_async_exception(oop java_throwable) {
1050   assert(java_throwable != NULL, "should have an _async_exception to throw");
1051   assert(!is_at_poll_safepoint(), "should have never called this method");
1052 
1053   if (has_last_Java_frame()) {
1054     frame f = last_frame();
1055     if (f.is_runtime_frame()) {
1056       // If the topmost frame is a runtime stub, then we are calling into
1057       // OptoRuntime from compiled code. Some runtime stubs (new, monitor_exit..)
1058       // must deoptimize the caller before continuing, as the compiled exception
1059       // handler table may not be valid.
1060       RegisterMap reg_map(this,
1061                           RegisterMap::UpdateMap::skip,
1062                           RegisterMap::ProcessFrames::include,
1063                           RegisterMap::WalkContinuation::skip);
1064       frame compiled_frame = f.sender(&reg_map);
1065       if (!StressCompiledExceptionHandlers && compiled_frame.can_be_deoptimized()) {
1066         Deoptimization::deoptimize(this, compiled_frame);
1067       }
1068     }
1069   }
1070 
1071   // Only overwrite an already pending exception if it is not a ThreadDeath.
1072   if (!has_pending_exception() || !pending_exception()->is_a(vmClasses::ThreadDeath_klass())) {
1073 
1074     // We cannot call Exceptions::_throw(...) here because we cannot block
1075     set_pending_exception(java_throwable, __FILE__, __LINE__);
1076 
1077     // Clear any extent-local bindings on ThreadDeath
1078     set_extentLocalCache(NULL);
1079     oop threadOop = threadObj();
1080     assert(threadOop != NULL, "must be");
1081     java_lang_Thread::clear_extentLocalBindings(threadOop);
1082 
1083     LogTarget(Info, exceptions) lt;
1084     if (lt.is_enabled()) {
1085       ResourceMark rm;
1086       LogStream ls(lt);
1087       ls.print("Async. exception installed at runtime exit (" INTPTR_FORMAT ")", p2i(this));
1088       if (has_last_Java_frame()) {
1089         frame f = last_frame();
1090         ls.print(" (pc: " INTPTR_FORMAT " sp: " INTPTR_FORMAT " )", p2i(f.pc()), p2i(f.sp()));
1091       }
1092       ls.print_cr(" of type: %s", java_throwable->klass()->external_name());
1093     }
1094   }
1095 }
1096 
1097 void JavaThread::install_async_exception(AsyncExceptionHandshake* aeh) {
1098   // Do not throw asynchronous exceptions against the compiler thread
1099   // or if the thread is already exiting.
1100   if (!can_call_java() || is_exiting()) {
1101     delete aeh;
1102     return;
1103   }
1104 
1105   // Don't install a new pending async exception if there is already
1106   // a pending ThreadDeath one. Just interrupt thread from potential
1107   // wait()/sleep()/park() and return.
1108   if (has_async_exception_condition(true /* ThreadDeath_only */)) {
1109     java_lang_Thread::set_interrupted(threadObj(), true);
1110     this->interrupt();
1111     delete aeh;
1112     return;
1113   }
1114 
1115   oop exception = aeh->exception();
1116   Handshake::execute(aeh, this);  // Install asynchronous handshake
1117 
1118   ResourceMark rm;
1119   if (log_is_enabled(Info, exceptions)) {
1120     log_info(exceptions)("Pending Async. exception installed of type: %s",
1121                          InstanceKlass::cast(exception->klass())->external_name());
1122   }
1123   // for AbortVMOnException flag
1124   Exceptions::debug_check_abort(exception->klass()->external_name());
1125 
1126   // Interrupt thread so it will wake up from a potential wait()/sleep()/park()
1127   java_lang_Thread::set_interrupted(threadObj(), true);
1128   this->interrupt();
1129 }
1130 
1131 class InstallAsyncExceptionHandshake : public HandshakeClosure {
1132   AsyncExceptionHandshake* _aeh;
1133 public:
1134   InstallAsyncExceptionHandshake(AsyncExceptionHandshake* aeh) :
1135     HandshakeClosure("InstallAsyncException"), _aeh(aeh) {}
1136   ~InstallAsyncExceptionHandshake() {
1137     // If InstallAsyncExceptionHandshake was never executed we need to clean up _aeh.
1138     delete _aeh;
1139   }
1140   void do_thread(Thread* thr) {
1141     JavaThread* target = JavaThread::cast(thr);
1142     target->install_async_exception(_aeh);
1143     _aeh = nullptr;
1144   }
1145 };
1146 
1147 void JavaThread::send_async_exception(JavaThread* target, oop java_throwable) {
1148   OopHandle e(Universe::vm_global(), java_throwable);
1149   InstallAsyncExceptionHandshake iaeh(new AsyncExceptionHandshake(e));
1150   Handshake::execute(&iaeh, target);
1151 }
1152 
1153 #if INCLUDE_JVMTI
1154 void JavaThread::set_is_in_VTMS_transition(bool val) {
1155   _is_in_VTMS_transition = val;
1156 }
1157 
1158 #ifdef ASSERT
1159 void JavaThread::set_is_VTMS_transition_disabler(bool val) {
1160   _is_VTMS_transition_disabler = val;
1161 }
1162 #endif
1163 #endif
1164 
1165 // External suspension mechanism.
1166 //
1167 // Guarantees on return (for a valid target thread):
1168 //   - Target thread will not execute any new bytecode.
1169 //   - Target thread will not enter any new monitors.
1170 //
1171 bool JavaThread::java_suspend() {
1172 #if INCLUDE_JVMTI
1173   // Suspending a JavaThread in VTMS transition or disabling VTMS transitions can cause deadlocks.
1174   assert(!is_in_VTMS_transition(), "no suspend allowed in VTMS transition");
1175   assert(!is_VTMS_transition_disabler(), "no suspend allowed for VTMS transition disablers");
1176 #endif
1177 
1178   guarantee(Thread::is_JavaThread_protected(/* target */ this),
1179             "target JavaThread is not protected in calling context.");
1180   return this->handshake_state()->suspend();
1181 }
1182 
1183 bool JavaThread::java_resume() {
1184   guarantee(Thread::is_JavaThread_protected_by_TLH(/* target */ this),
1185             "missing ThreadsListHandle in calling context.");
1186   return this->handshake_state()->resume();
1187 }
1188 
1189 // Wait for another thread to perform object reallocation and relocking on behalf of
1190 // this thread. The current thread is required to change to _thread_blocked in order
1191 // to be seen to be safepoint/handshake safe whilst suspended and only after becoming
1192 // handshake safe, the other thread can complete the handshake used to synchronize
1193 // with this thread and then perform the reallocation and relocking.
1194 // See EscapeBarrier::sync_and_suspend_*()
1195 
1196 void JavaThread::wait_for_object_deoptimization() {
1197   assert(!has_last_Java_frame() || frame_anchor()->walkable(), "should have walkable stack");
1198   assert(this == Thread::current(), "invariant");
1199 
1200   bool spin_wait = os::is_MP();
1201   do {
1202     ThreadBlockInVM tbivm(this, true /* allow_suspend */);
1203     // Wait for object deoptimization if requested.
1204     if (spin_wait) {
1205       // A single deoptimization is typically very short. Microbenchmarks
1206       // showed 5% better performance when spinning.
1207       const uint spin_limit = 10 * SpinYield::default_spin_limit;
1208       SpinYield spin(spin_limit);
1209       for (uint i = 0; is_obj_deopt_suspend() && i < spin_limit; i++) {
1210         spin.wait();
1211       }
1212       // Spin just once
1213       spin_wait = false;
1214     } else {
1215       MonitorLocker ml(this, EscapeBarrier_lock, Monitor::_no_safepoint_check_flag);
1216       if (is_obj_deopt_suspend()) {
1217         ml.wait();
1218       }
1219     }
1220     // A handshake for obj. deoptimization suspend could have been processed so
1221     // we must check after processing.
1222   } while (is_obj_deopt_suspend());
1223 }
1224 
1225 #ifdef ASSERT
1226 // Verify the JavaThread has not yet been published in the Threads::list, and
1227 // hence doesn't need protection from concurrent access at this stage.
1228 void JavaThread::verify_not_published() {
1229   // Cannot create a ThreadsListHandle here and check !tlh.includes(this)
1230   // since an unpublished JavaThread doesn't participate in the
1231   // Thread-SMR protocol for keeping a ThreadsList alive.
1232   assert(!on_thread_list(), "JavaThread shouldn't have been published yet!");
1233 }
1234 #endif
1235 
1236 // Slow path when the native==>Java barriers detect a safepoint/handshake is
1237 // pending, when _suspend_flags is non-zero or when we need to process a stack
1238 // watermark. Also check for pending async exceptions (except unsafe access error).
1239 // Note only the native==>Java barriers can call this function when thread state
1240 // is _thread_in_native_trans.
1241 void JavaThread::check_special_condition_for_native_trans(JavaThread *thread) {
1242   assert(thread->thread_state() == _thread_in_native_trans, "wrong state");
1243   assert(!thread->has_last_Java_frame() || thread->frame_anchor()->walkable(), "Unwalkable stack in native->Java transition");
1244 
1245   thread->set_thread_state(_thread_in_vm);
1246 
1247   // Enable WXWrite: called directly from interpreter native wrapper.
1248   MACOS_AARCH64_ONLY(ThreadWXEnable wx(WXWrite, thread));
1249 
1250   SafepointMechanism::process_if_requested_with_exit_check(thread, true /* check asyncs */);
1251 
1252   // After returning from native, it could be that the stack frames are not
1253   // yet safe to use. We catch such situations in the subsequent stack watermark
1254   // barrier, which will trap unsafe stack frames.
1255   StackWatermarkSet::before_unwind(thread);
1256 }
1257 
1258 #ifndef PRODUCT
1259 // Deoptimization
1260 // Function for testing deoptimization
1261 void JavaThread::deoptimize() {
1262   StackFrameStream fst(this, false /* update */, true /* process_frames */);
1263   bool deopt = false;           // Dump stack only if a deopt actually happens.
1264   bool only_at = strlen(DeoptimizeOnlyAt) > 0;
1265   // Iterate over all frames in the thread and deoptimize
1266   for (; !fst.is_done(); fst.next()) {
1267     if (fst.current()->can_be_deoptimized()) {
1268 
1269       if (only_at) {
1270         // Deoptimize only at particular bcis.  DeoptimizeOnlyAt
1271         // consists of comma or carriage return separated numbers so
1272         // search for the current bci in that string.
1273         address pc = fst.current()->pc();
1274         nmethod* nm =  (nmethod*) fst.current()->cb();
1275         ScopeDesc* sd = nm->scope_desc_at(pc);
1276         char buffer[8];
1277         jio_snprintf(buffer, sizeof(buffer), "%d", sd->bci());
1278         size_t len = strlen(buffer);
1279         const char * found = strstr(DeoptimizeOnlyAt, buffer);
1280         while (found != NULL) {
1281           if ((found[len] == ',' || found[len] == '\n' || found[len] == '\0') &&
1282               (found == DeoptimizeOnlyAt || found[-1] == ',' || found[-1] == '\n')) {
1283             // Check that the bci found is bracketed by terminators.
1284             break;
1285           }
1286           found = strstr(found + 1, buffer);
1287         }
1288         if (!found) {
1289           continue;
1290         }
1291       }
1292 
1293       if (DebugDeoptimization && !deopt) {
1294         deopt = true; // One-time only print before deopt
1295         tty->print_cr("[BEFORE Deoptimization]");
1296         trace_frames();
1297         trace_stack();
1298       }
1299       Deoptimization::deoptimize(this, *fst.current());
1300     }
1301   }
1302 
1303   if (DebugDeoptimization && deopt) {
1304     tty->print_cr("[AFTER Deoptimization]");
1305     trace_frames();
1306   }
1307 }
1308 
1309 
1310 // Make zombies
1311 void JavaThread::make_zombies() {
1312   for (StackFrameStream fst(this, true /* update */, true /* process_frames */); !fst.is_done(); fst.next()) {
1313     if (fst.current()->can_be_deoptimized()) {
1314       // it is a Java nmethod
1315       nmethod* nm = CodeCache::find_nmethod(fst.current()->pc());
1316       nm->make_not_entrant();
1317     }
1318   }
1319 }
1320 #endif // PRODUCT
1321 
1322 
1323 void JavaThread::deoptimize_marked_methods() {
1324   if (!has_last_Java_frame()) return;
1325   StackFrameStream fst(this, false /* update */, true /* process_frames */);
1326   for (; !fst.is_done(); fst.next()) {
1327     if (fst.current()->should_be_deoptimized()) {
1328       Deoptimization::deoptimize(this, *fst.current());
1329     }
1330   }
1331 }
1332 
1333 #ifdef ASSERT
1334 void JavaThread::verify_frame_info() {
1335   assert((!has_last_Java_frame() && java_call_counter() == 0) ||
1336          (has_last_Java_frame() && java_call_counter() > 0),
1337          "unexpected frame info: has_last_frame=%s, java_call_counter=%d",
1338          has_last_Java_frame() ? "true" : "false", java_call_counter());
1339 }
1340 #endif
1341 
1342 // Push on a new block of JNI handles.
1343 void JavaThread::push_jni_handle_block() {
1344   // Allocate a new block for JNI handles.
1345   // Inlined code from jni_PushLocalFrame()
1346   JNIHandleBlock* old_handles = active_handles();
1347   JNIHandleBlock* new_handles = JNIHandleBlock::allocate_block(this);
1348   assert(old_handles != NULL && new_handles != NULL, "should not be NULL");
1349   new_handles->set_pop_frame_link(old_handles);  // make sure java handles get gc'd.
1350   set_active_handles(new_handles);
1351 }
1352 
1353 // Pop off the current block of JNI handles.
1354 void JavaThread::pop_jni_handle_block() {
1355   // Release our JNI handle block
1356   JNIHandleBlock* old_handles = active_handles();
1357   JNIHandleBlock* new_handles = old_handles->pop_frame_link();
1358   assert(new_handles != nullptr, "should never set active handles to null");
1359   set_active_handles(new_handles);
1360   old_handles->set_pop_frame_link(NULL);
1361   JNIHandleBlock::release_block(old_handles, this);
1362 }
1363 
1364 void JavaThread::oops_do_no_frames(OopClosure* f, CodeBlobClosure* cf) {
1365   // Verify that the deferred card marks have been flushed.
1366   assert(deferred_card_mark().is_empty(), "Should be empty during GC");
1367 
1368   // Traverse the GCHandles
1369   Thread::oops_do_no_frames(f, cf);
1370 
1371   if (active_handles() != NULL) {
1372     active_handles()->oops_do(f);
1373   }
1374 
1375   DEBUG_ONLY(verify_frame_info();)
1376 
1377   if (has_last_Java_frame()) {
1378     // Traverse the monitor chunks
1379     for (MonitorChunk* chunk = monitor_chunks(); chunk != NULL; chunk = chunk->next()) {
1380       chunk->oops_do(f);
1381     }
1382   }
1383 
1384   assert(vframe_array_head() == NULL, "deopt in progress at a safepoint!");
1385   // If we have deferred set_locals there might be oops waiting to be
1386   // written
1387   GrowableArray<jvmtiDeferredLocalVariableSet*>* list = JvmtiDeferredUpdates::deferred_locals(this);
1388   if (list != NULL) {
1389     for (int i = 0; i < list->length(); i++) {
1390       list->at(i)->oops_do(f);
1391     }
1392   }
1393 
1394   // Traverse instance variables at the end since the GC may be moving things
1395   // around using this function
1396   f->do_oop((oop*) &_vm_result);
1397   f->do_oop((oop*) &_exception_oop);
1398 #if INCLUDE_JVMCI
1399   f->do_oop((oop*) &_jvmci_reserved_oop0);
1400 #endif
1401 
1402   if (jvmti_thread_state() != NULL) {
1403     jvmti_thread_state()->oops_do(f, cf);
1404   }
1405 }
1406 
1407 void JavaThread::oops_do_frames(OopClosure* f, CodeBlobClosure* cf) {
1408   if (!has_last_Java_frame()) {
1409     return;
1410   }
1411   // Finish any pending lazy GC activity for the frames
1412   StackWatermarkSet::finish_processing(this, NULL /* context */, StackWatermarkKind::gc);
1413   // Traverse the execution stack
1414   for (StackFrameStream fst(this, true /* update */, false /* process_frames */); !fst.is_done(); fst.next()) {
1415     fst.current()->oops_do(f, cf, fst.register_map());
1416   }
1417 }
1418 
1419 #ifdef ASSERT
1420 void JavaThread::verify_states_for_handshake() {
1421   // This checks that the thread has a correct frame state during a handshake.
1422   verify_frame_info();
1423 }
1424 #endif
1425 
1426 void JavaThread::nmethods_do(CodeBlobClosure* cf) {
1427   DEBUG_ONLY(verify_frame_info();)
1428   MACOS_AARCH64_ONLY(ThreadWXEnable wx(WXWrite, Thread::current());)
1429 
1430   if (has_last_Java_frame()) {
1431     // Traverse the execution stack
1432     for (StackFrameStream fst(this, true /* update */, true /* process_frames */); !fst.is_done(); fst.next()) {
1433       fst.current()->nmethods_do(cf);
1434     }
1435   }
1436 
1437   if (jvmti_thread_state() != NULL) {
1438     jvmti_thread_state()->nmethods_do(cf);
1439   }
1440 }
1441 
1442 void JavaThread::metadata_do(MetadataClosure* f) {
1443   if (has_last_Java_frame()) {
1444     // Traverse the execution stack to call f() on the methods in the stack
1445     for (StackFrameStream fst(this, true /* update */, true /* process_frames */); !fst.is_done(); fst.next()) {
1446       fst.current()->metadata_do(f);
1447     }
1448   } else if (is_Compiler_thread()) {
1449     // need to walk ciMetadata in current compile tasks to keep alive.
1450     CompilerThread* ct = (CompilerThread*)this;
1451     if (ct->env() != NULL) {
1452       ct->env()->metadata_do(f);
1453     }
1454     CompileTask* task = ct->task();
1455     if (task != NULL) {
1456       task->metadata_do(f);
1457     }
1458   }
1459 }
1460 
1461 // Printing
1462 const char* _get_thread_state_name(JavaThreadState _thread_state) {
1463   switch (_thread_state) {
1464   case _thread_uninitialized:     return "_thread_uninitialized";
1465   case _thread_new:               return "_thread_new";
1466   case _thread_new_trans:         return "_thread_new_trans";
1467   case _thread_in_native:         return "_thread_in_native";
1468   case _thread_in_native_trans:   return "_thread_in_native_trans";
1469   case _thread_in_vm:             return "_thread_in_vm";
1470   case _thread_in_vm_trans:       return "_thread_in_vm_trans";
1471   case _thread_in_Java:           return "_thread_in_Java";
1472   case _thread_in_Java_trans:     return "_thread_in_Java_trans";
1473   case _thread_blocked:           return "_thread_blocked";
1474   case _thread_blocked_trans:     return "_thread_blocked_trans";
1475   default:                        return "unknown thread state";
1476   }
1477 }
1478 
1479 void JavaThread::print_thread_state_on(outputStream *st) const {
1480   st->print_cr("   JavaThread state: %s", _get_thread_state_name(_thread_state));
1481 }
1482 
1483 const char* JavaThread::thread_state_name() const {
1484   return _get_thread_state_name(_thread_state);
1485 }
1486 
1487 // Called by Threads::print() for VM_PrintThreads operation
1488 void JavaThread::print_on(outputStream *st, bool print_extended_info) const {
1489   st->print_raw("\"");
1490   st->print_raw(name());
1491   st->print_raw("\" ");
1492   oop thread_oop = threadObj();
1493   if (thread_oop != NULL) {
1494     st->print("#" INT64_FORMAT " [%ld] ", (int64_t)java_lang_Thread::thread_id(thread_oop), (long) osthread()->thread_id());
1495     if (java_lang_Thread::is_daemon(thread_oop))  st->print("daemon ");
1496     st->print("prio=%d ", java_lang_Thread::priority(thread_oop));
1497   }
1498   Thread::print_on(st, print_extended_info);
1499   // print guess for valid stack memory region (assume 4K pages); helps lock debugging
1500   st->print_cr("[" INTPTR_FORMAT "]", (intptr_t)last_Java_sp() & ~right_n_bits(12));
1501   if (thread_oop != NULL) {
1502     if (is_vthread_mounted()) {
1503       oop vt = vthread();
1504       assert(vt != NULL, "");
1505       st->print_cr("   Carrying virtual thread #" INT64_FORMAT, (int64_t)java_lang_Thread::thread_id(vt));
1506     } else {
1507       st->print_cr("   java.lang.Thread.State: %s", java_lang_Thread::thread_status_name(thread_oop));
1508     }
1509   }
1510 #ifndef PRODUCT
1511   _safepoint_state->print_on(st);
1512 #endif // PRODUCT
1513   if (is_Compiler_thread()) {
1514     CompileTask *task = ((CompilerThread*)this)->task();
1515     if (task != NULL) {
1516       st->print("   Compiling: ");
1517       task->print(st, NULL, true, false);
1518     } else {
1519       st->print("   No compile task");
1520     }
1521     st->cr();
1522   }
1523 }
1524 
1525 void JavaThread::print() const { print_on(tty); }
1526 
1527 void JavaThread::print_name_on_error(outputStream* st, char *buf, int buflen) const {
1528   st->print("%s", get_thread_name_string(buf, buflen));
1529 }
1530 
1531 // Called by fatal error handler. The difference between this and
1532 // JavaThread::print() is that we can't grab lock or allocate memory.
1533 void JavaThread::print_on_error(outputStream* st, char *buf, int buflen) const {
1534   st->print("%s \"%s\"", type_name(), get_thread_name_string(buf, buflen));
1535   Thread* current = Thread::current_or_null_safe();
1536   assert(current != nullptr, "cannot be called by a detached thread");
1537   if (!current->is_Java_thread() || JavaThread::cast(current)->is_oop_safe()) {
1538     // Only access threadObj() if current thread is not a JavaThread
1539     // or if it is a JavaThread that can safely access oops.
1540     oop thread_obj = threadObj();
1541     if (thread_obj != nullptr) {
1542       if (java_lang_Thread::is_daemon(thread_obj)) st->print(" daemon");
1543     }
1544   }
1545   st->print(" [");
1546   st->print("%s", _get_thread_state_name(_thread_state));
1547   if (osthread()) {
1548     st->print(", id=%d", osthread()->thread_id());
1549   }
1550   st->print(", stack(" PTR_FORMAT "," PTR_FORMAT ")",
1551             p2i(stack_end()), p2i(stack_base()));
1552   st->print("]");
1553 
1554   ThreadsSMRSupport::print_info_on(this, st);
1555   return;
1556 }
1557 
1558 
1559 // Verification
1560 
1561 void JavaThread::frames_do(void f(frame*, const RegisterMap* map)) {
1562   // ignore if there is no stack
1563   if (!has_last_Java_frame()) return;
1564   // traverse the stack frames. Starts from top frame.
1565   for (StackFrameStream fst(this, true /* update_map */, true /* process_frames */, false /* walk_cont */); !fst.is_done(); fst.next()) {
1566     frame* fr = fst.current();
1567     f(fr, fst.register_map());
1568   }
1569 }
1570 
1571 static void frame_verify(frame* f, const RegisterMap *map) { f->verify(map); }
1572 
1573 void JavaThread::verify() {
1574   // Verify oops in the thread.
1575   oops_do(&VerifyOopClosure::verify_oop, NULL);
1576 
1577   // Verify the stack frames.
1578   frames_do(frame_verify);
1579 }
1580 
1581 // CR 6300358 (sub-CR 2137150)
1582 // Most callers of this method assume that it can't return NULL but a
1583 // thread may not have a name whilst it is in the process of attaching to
1584 // the VM - see CR 6412693, and there are places where a JavaThread can be
1585 // seen prior to having its threadObj set (e.g., JNI attaching threads and
1586 // if vm exit occurs during initialization). These cases can all be accounted
1587 // for such that this method never returns NULL.
1588 const char* JavaThread::name() const  {
1589   if (Thread::is_JavaThread_protected(/* target */ this)) {
1590     // The target JavaThread is protected so get_thread_name_string() is safe:
1591     return get_thread_name_string();
1592   }
1593 
1594   // The target JavaThread is not protected so we return the default:
1595   return Thread::name();
1596 }
1597 
1598 // Returns a non-NULL representation of this thread's name, or a suitable
1599 // descriptive string if there is no set name.
1600 const char* JavaThread::get_thread_name_string(char* buf, int buflen) const {
1601   const char* name_str;
1602 #ifdef ASSERT
1603   Thread* current = Thread::current_or_null_safe();
1604   assert(current != nullptr, "cannot be called by a detached thread");
1605   if (!current->is_Java_thread() || JavaThread::cast(current)->is_oop_safe()) {
1606     // Only access threadObj() if current thread is not a JavaThread
1607     // or if it is a JavaThread that can safely access oops.
1608 #endif
1609     oop thread_obj = threadObj();
1610     if (thread_obj != NULL) {
1611       oop name = java_lang_Thread::name(thread_obj);
1612       if (name != NULL) {
1613         if (buf == NULL) {
1614           name_str = java_lang_String::as_utf8_string(name);
1615         } else {
1616           name_str = java_lang_String::as_utf8_string(name, buf, buflen);
1617         }
1618       } else if (is_attaching_via_jni()) { // workaround for 6412693 - see 6404306
1619         name_str = "<no-name - thread is attaching>";
1620       } else {
1621         name_str = "<un-named>";
1622       }
1623     } else {
1624       name_str = Thread::name();
1625     }
1626 #ifdef ASSERT
1627   } else {
1628     // Current JavaThread has exited...
1629     if (current == this) {
1630       // ... and is asking about itself:
1631       name_str = "<no-name - current JavaThread has exited>";
1632     } else {
1633       // ... and it can't safely determine this JavaThread's name so
1634       // use the default thread name.
1635       name_str = Thread::name();
1636     }
1637   }
1638 #endif
1639   assert(name_str != NULL, "unexpected NULL thread name");
1640   return name_str;
1641 }
1642 
1643 // Helper to extract the name from the thread oop for logging.
1644 const char* JavaThread::name_for(oop thread_obj) {
1645   assert(thread_obj != NULL, "precondition");
1646   oop name = java_lang_Thread::name(thread_obj);
1647   const char* name_str;
1648   if (name != NULL) {
1649     name_str = java_lang_String::as_utf8_string(name);
1650   } else {
1651     name_str = "<un-named>";
1652   }
1653   return name_str;
1654 }
1655 
1656 void JavaThread::prepare(jobject jni_thread, ThreadPriority prio) {
1657 
1658   assert(Threads_lock->owner() == Thread::current(), "must have threads lock");
1659   assert(NoPriority <= prio && prio <= MaxPriority, "sanity check");
1660   // Link Java Thread object <-> C++ Thread
1661 
1662   // Get the C++ thread object (an oop) from the JNI handle (a jthread)
1663   // and put it into a new Handle.  The Handle "thread_oop" can then
1664   // be used to pass the C++ thread object to other methods.
1665 
1666   // Set the Java level thread object (jthread) field of the
1667   // new thread (a JavaThread *) to C++ thread object using the
1668   // "thread_oop" handle.
1669 
1670   // Set the thread field (a JavaThread *) of the
1671   // oop representing the java_lang_Thread to the new thread (a JavaThread *).
1672 
1673   Handle thread_oop(Thread::current(),
1674                     JNIHandles::resolve_non_null(jni_thread));
1675   assert(InstanceKlass::cast(thread_oop->klass())->is_linked(),
1676          "must be initialized");
1677   set_threadOopHandles(thread_oop());
1678   java_lang_Thread::set_thread(thread_oop(), this);
1679 
1680   if (prio == NoPriority) {
1681     prio = java_lang_Thread::priority(thread_oop());
1682     assert(prio != NoPriority, "A valid priority should be present");
1683   }
1684 
1685   // Push the Java priority down to the native thread; needs Threads_lock
1686   Thread::set_priority(this, prio);
1687 
1688   // Add the new thread to the Threads list and set it in motion.
1689   // We must have threads lock in order to call Threads::add.
1690   // It is crucial that we do not block before the thread is
1691   // added to the Threads list for if a GC happens, then the java_thread oop
1692   // will not be visited by GC.
1693   Threads::add(this);
1694 }
1695 
1696 oop JavaThread::current_park_blocker() {
1697   // Support for JSR-166 locks
1698   oop thread_oop = threadObj();
1699   if (thread_oop != NULL) {
1700     return java_lang_Thread::park_blocker(thread_oop);
1701   }
1702   return NULL;
1703 }
1704 
1705 
1706 void JavaThread::print_stack_on(outputStream* st) {
1707   if (!has_last_Java_frame()) return;
1708 
1709   Thread* current_thread = Thread::current();
1710   ResourceMark rm(current_thread);
1711   HandleMark hm(current_thread);
1712 
1713   RegisterMap reg_map(this,
1714                       RegisterMap::UpdateMap::include,
1715                       RegisterMap::ProcessFrames::include,
1716                       RegisterMap::WalkContinuation::skip);
1717   vframe* start_vf = platform_thread_last_java_vframe(&reg_map);
1718   int count = 0;
1719   for (vframe* f = start_vf; f != NULL; f = f->sender()) {
1720     if (f->is_java_frame()) {
1721       javaVFrame* jvf = javaVFrame::cast(f);
1722       java_lang_Throwable::print_stack_element(st, jvf->method(), jvf->bci());
1723 
1724       // Print out lock information
1725       if (JavaMonitorsInStackTrace) {
1726         jvf->print_lock_info_on(st, count);
1727       }
1728     } else {
1729       // Ignore non-Java frames
1730     }
1731 
1732     // Bail-out case for too deep stacks if MaxJavaStackTraceDepth > 0
1733     count++;
1734     if (MaxJavaStackTraceDepth > 0 && MaxJavaStackTraceDepth == count) return;
1735   }
1736 }
1737 
1738 #if INCLUDE_JVMTI
1739 // Rebind JVMTI thread state from carrier to virtual or from virtual to carrier.
1740 JvmtiThreadState* JavaThread::rebind_to_jvmti_thread_state_of(oop thread_oop) {
1741   set_jvmti_vthread(thread_oop);
1742 
1743   // unbind current JvmtiThreadState from JavaThread
1744   JvmtiThreadState::unbind_from(jvmti_thread_state(), this);
1745 
1746   // bind new JvmtiThreadState to JavaThread
1747   JvmtiThreadState::bind_to(java_lang_Thread::jvmti_thread_state(thread_oop), this);
1748 
1749   return jvmti_thread_state();
1750 }
1751 #endif
1752 
1753 // JVMTI PopFrame support
1754 void JavaThread::popframe_preserve_args(ByteSize size_in_bytes, void* start) {
1755   assert(_popframe_preserved_args == NULL, "should not wipe out old PopFrame preserved arguments");
1756   if (in_bytes(size_in_bytes) != 0) {
1757     _popframe_preserved_args = NEW_C_HEAP_ARRAY(char, in_bytes(size_in_bytes), mtThread);
1758     _popframe_preserved_args_size = in_bytes(size_in_bytes);
1759     Copy::conjoint_jbytes(start, _popframe_preserved_args, _popframe_preserved_args_size);
1760   }
1761 }
1762 
1763 void* JavaThread::popframe_preserved_args() {
1764   return _popframe_preserved_args;
1765 }
1766 
1767 ByteSize JavaThread::popframe_preserved_args_size() {
1768   return in_ByteSize(_popframe_preserved_args_size);
1769 }
1770 
1771 WordSize JavaThread::popframe_preserved_args_size_in_words() {
1772   int sz = in_bytes(popframe_preserved_args_size());
1773   assert(sz % wordSize == 0, "argument size must be multiple of wordSize");
1774   return in_WordSize(sz / wordSize);
1775 }
1776 
1777 void JavaThread::popframe_free_preserved_args() {
1778   assert(_popframe_preserved_args != NULL, "should not free PopFrame preserved arguments twice");
1779   FREE_C_HEAP_ARRAY(char, (char*)_popframe_preserved_args);
1780   _popframe_preserved_args = NULL;
1781   _popframe_preserved_args_size = 0;
1782 }
1783 
1784 #ifndef PRODUCT
1785 
1786 void JavaThread::trace_frames() {
1787   tty->print_cr("[Describe stack]");
1788   int frame_no = 1;
1789   for (StackFrameStream fst(this, true /* update */, true /* process_frames */); !fst.is_done(); fst.next()) {
1790     tty->print("  %d. ", frame_no++);
1791     fst.current()->print_value_on(tty, this);
1792     tty->cr();
1793   }
1794 }
1795 
1796 class PrintAndVerifyOopClosure: public OopClosure {
1797  protected:
1798   template <class T> inline void do_oop_work(T* p) {
1799     oop obj = RawAccess<>::oop_load(p);
1800     if (obj == NULL) return;
1801     tty->print(INTPTR_FORMAT ": ", p2i(p));
1802     if (oopDesc::is_oop_or_null(obj)) {
1803       if (obj->is_objArray()) {
1804         tty->print_cr("valid objArray: " INTPTR_FORMAT, p2i(obj));
1805       } else {
1806         obj->print();
1807       }
1808     } else {
1809       tty->print_cr("invalid oop: " INTPTR_FORMAT, p2i(obj));
1810     }
1811     tty->cr();
1812   }
1813  public:
1814   virtual void do_oop(oop* p) { do_oop_work(p); }
1815   virtual void do_oop(narrowOop* p)  { do_oop_work(p); }
1816 };
1817 
1818 #ifdef ASSERT
1819 // Print or validate the layout of stack frames
1820 void JavaThread::print_frame_layout(int depth, bool validate_only) {
1821   ResourceMark rm;
1822   PreserveExceptionMark pm(this);
1823   FrameValues values;
1824   int frame_no = 0;
1825   for (StackFrameStream fst(this, true, true, true); !fst.is_done(); fst.next()) {
1826     fst.current()->describe(values, ++frame_no, fst.register_map());
1827     if (depth == frame_no) break;
1828   }
1829   Continuation::describe(values);
1830   if (validate_only) {
1831     values.validate();
1832   } else {
1833     tty->print_cr("[Describe stack layout]");
1834     values.print(this);
1835   }
1836 }
1837 #endif
1838 
1839 void JavaThread::trace_stack_from(vframe* start_vf) {
1840   ResourceMark rm;
1841   int vframe_no = 1;
1842   for (vframe* f = start_vf; f; f = f->sender()) {
1843     if (f->is_java_frame()) {
1844       javaVFrame::cast(f)->print_activation(vframe_no++);
1845     } else {
1846       f->print();
1847     }
1848     if (vframe_no > StackPrintLimit) {
1849       tty->print_cr("...<more frames>...");
1850       return;
1851     }
1852   }
1853 }
1854 
1855 
1856 void JavaThread::trace_stack() {
1857   if (!has_last_Java_frame()) return;
1858   Thread* current_thread = Thread::current();
1859   ResourceMark rm(current_thread);
1860   HandleMark hm(current_thread);
1861   RegisterMap reg_map(this,
1862                       RegisterMap::UpdateMap::include,
1863                       RegisterMap::ProcessFrames::include,
1864                       RegisterMap::WalkContinuation::skip);
1865   trace_stack_from(last_java_vframe(&reg_map));
1866 }
1867 
1868 
1869 #endif // PRODUCT
1870 
1871 void JavaThread::inc_held_monitor_count(int i, bool jni) {
1872 #ifdef SUPPORT_MONITOR_COUNT
1873   assert(_held_monitor_count >= 0, "Must always be greater than 0: " INT64_FORMAT, (int64_t)_held_monitor_count);
1874   _held_monitor_count += i;
1875   if (jni) {
1876     assert(_jni_monitor_count >= 0, "Must always be greater than 0: " INT64_FORMAT, (int64_t)_jni_monitor_count);
1877     _jni_monitor_count += i;
1878   }
1879 #endif
1880 }
1881 
1882 void JavaThread::dec_held_monitor_count(int i, bool jni) {
1883 #ifdef SUPPORT_MONITOR_COUNT
1884   _held_monitor_count -= i;
1885   assert(_held_monitor_count >= 0, "Must always be greater than 0: " INT64_FORMAT, (int64_t)_held_monitor_count);
1886   if (jni) {
1887     _jni_monitor_count -= i;
1888     assert(_jni_monitor_count >= 0, "Must always be greater than 0: " INT64_FORMAT, (int64_t)_jni_monitor_count);
1889   }
1890 #endif
1891 }
1892 
1893 frame JavaThread::vthread_last_frame() {
1894   assert (is_vthread_mounted(), "Virtual thread not mounted");
1895   return last_frame();
1896 }
1897 
1898 frame JavaThread::carrier_last_frame(RegisterMap* reg_map) {
1899   const ContinuationEntry* entry = vthread_continuation();
1900   guarantee (entry != NULL, "Not a carrier thread");
1901   frame f = entry->to_frame();
1902   if (reg_map->process_frames()) {
1903     entry->flush_stack_processing(this);
1904   }
1905   entry->update_register_map(reg_map);
1906   return f.sender(reg_map);
1907 }
1908 
1909 frame JavaThread::platform_thread_last_frame(RegisterMap* reg_map) {
1910   return is_vthread_mounted() ? carrier_last_frame(reg_map) : last_frame();
1911 }
1912 
1913 javaVFrame* JavaThread::last_java_vframe(const frame f, RegisterMap *reg_map) {
1914   assert(reg_map != NULL, "a map must be given");
1915   for (vframe* vf = vframe::new_vframe(&f, reg_map, this); vf; vf = vf->sender()) {
1916     if (vf->is_java_frame()) return javaVFrame::cast(vf);
1917   }
1918   return NULL;
1919 }
1920 
1921 oop JavaThread::get_continuation() const {
1922   assert(threadObj() != nullptr, "must be set");
1923   return java_lang_Thread::continuation(threadObj());
1924 }
1925 
1926 Klass* JavaThread::security_get_caller_class(int depth) {
1927   ResetNoHandleMark rnhm;
1928   HandleMark hm(Thread::current());
1929 
1930   vframeStream vfst(this);
1931   vfst.security_get_caller_frame(depth);
1932   if (!vfst.at_end()) {
1933     return vfst.method()->method_holder();
1934   }
1935   return NULL;
1936 }
1937 
1938 // java.lang.Thread.sleep support
1939 // Returns true if sleep time elapsed as expected, and false
1940 // if the thread was interrupted.
1941 bool JavaThread::sleep(jlong millis) {
1942   assert(this == Thread::current(),  "thread consistency check");
1943 
1944   ParkEvent * const slp = this->_SleepEvent;
1945   // Because there can be races with thread interruption sending an unpark()
1946   // to the event, we explicitly reset it here to avoid an immediate return.
1947   // The actual interrupt state will be checked before we park().
1948   slp->reset();
1949   // Thread interruption establishes a happens-before ordering in the
1950   // Java Memory Model, so we need to ensure we synchronize with the
1951   // interrupt state.
1952   OrderAccess::fence();
1953 
1954   jlong prevtime = os::javaTimeNanos();
1955 
1956   for (;;) {
1957     // interruption has precedence over timing out
1958     if (this->is_interrupted(true)) {
1959       return false;
1960     }
1961 
1962     if (millis <= 0) {
1963       return true;
1964     }
1965 
1966     {
1967       ThreadBlockInVM tbivm(this);
1968       OSThreadWaitState osts(this->osthread(), false /* not Object.wait() */);
1969       slp->park(millis);
1970     }
1971 
1972     // Update elapsed time tracking
1973     jlong newtime = os::javaTimeNanos();
1974     if (newtime - prevtime < 0) {
1975       // time moving backwards, should only happen if no monotonic clock
1976       // not a guarantee() because JVM should not abort on kernel/glibc bugs
1977       assert(false,
1978              "unexpected time moving backwards detected in JavaThread::sleep()");
1979     } else {
1980       millis -= (newtime - prevtime) / NANOSECS_PER_MILLISEC;
1981     }
1982     prevtime = newtime;
1983   }
1984 }
1985 
1986 // Last thread running calls java.lang.Shutdown.shutdown()
1987 void JavaThread::invoke_shutdown_hooks() {
1988   HandleMark hm(this);
1989 
1990   // We could get here with a pending exception, if so clear it now or
1991   // it will cause MetaspaceShared::link_shared_classes to
1992   // fail for dynamic dump.
1993   if (this->has_pending_exception()) {
1994     this->clear_pending_exception();
1995   }
1996 
1997 #if INCLUDE_CDS
1998   // Link all classes for dynamic CDS dumping before vm exit.
1999   // Same operation is being done in JVM_BeforeHalt for handling the
2000   // case where the application calls System.exit().
2001   if (DynamicArchive::should_dump_at_vm_exit()) {
2002     DynamicArchive::prepare_for_dump_at_exit();
2003   }
2004 #endif
2005 
2006   EXCEPTION_MARK;
2007   Klass* shutdown_klass =
2008     SystemDictionary::resolve_or_null(vmSymbols::java_lang_Shutdown(),
2009                                       THREAD);
2010   if (shutdown_klass != NULL) {
2011     // SystemDictionary::resolve_or_null will return null if there was
2012     // an exception.  If we cannot load the Shutdown class, just don't
2013     // call Shutdown.shutdown() at all.  This will mean the shutdown hooks
2014     // won't be run.  Note that if a shutdown hook was registered,
2015     // the Shutdown class would have already been loaded
2016     // (Runtime.addShutdownHook will load it).
2017     JavaValue result(T_VOID);
2018     JavaCalls::call_static(&result,
2019                            shutdown_klass,
2020                            vmSymbols::shutdown_name(),
2021                            vmSymbols::void_method_signature(),
2022                            THREAD);
2023   }
2024   CLEAR_PENDING_EXCEPTION;
2025 }
2026 
2027 #ifndef PRODUCT
2028 void JavaThread::verify_cross_modify_fence_failure(JavaThread *thread) {
2029    report_vm_error(__FILE__, __LINE__, "Cross modify fence failure", "%p", thread);
2030 }
2031 #endif
2032 
2033 // Helper function to create the java.lang.Thread object for a
2034 // VM-internal thread. The thread will have the given name, and be
2035 // a member of the "system" ThreadGroup.
2036 Handle JavaThread::create_system_thread_object(const char* name,
2037                                                bool is_visible, TRAPS) {
2038   Handle string = java_lang_String::create_from_str(name, CHECK_NH);
2039 
2040   // Initialize thread_oop to put it into the system threadGroup.
2041   // This is done by calling the Thread(ThreadGroup group, String name) constructor.
2042   Handle thread_group(THREAD, Universe::system_thread_group());
2043   Handle thread_oop =
2044     JavaCalls::construct_new_instance(vmClasses::Thread_klass(),
2045                                       vmSymbols::threadgroup_string_void_signature(),
2046                                       thread_group,
2047                                       string,
2048                                       CHECK_NH);
2049 
2050   return thread_oop;
2051 }
2052 
2053 // Starts the target JavaThread as a daemon of the given priority, and
2054 // bound to the given java.lang.Thread instance.
2055 // The Threads_lock is held for the duration.
2056 void JavaThread::start_internal_daemon(JavaThread* current, JavaThread* target,
2057                                        Handle thread_oop, ThreadPriority prio) {
2058 
2059   assert(target->osthread() != NULL, "target thread is not properly initialized");
2060 
2061   MutexLocker mu(current, Threads_lock);
2062 
2063   // Initialize the fields of the thread_oop first.
2064 
2065   java_lang_Thread::set_thread(thread_oop(), target); // isAlive == true now
2066 
2067   if (prio != NoPriority) {
2068     java_lang_Thread::set_priority(thread_oop(), prio);
2069     // Note: we don't call os::set_priority here. Possibly we should,
2070     // else all threads should call it themselves when they first run.
2071   }
2072 
2073   java_lang_Thread::set_daemon(thread_oop());
2074 
2075   // Now bind the thread_oop to the target JavaThread.
2076   target->set_threadOopHandles(thread_oop());
2077 
2078   Threads::add(target); // target is now visible for safepoint/handshake
2079   Thread::start(target);
2080 }
2081 
2082 void JavaThread::vm_exit_on_osthread_failure(JavaThread* thread) {
2083   // At this point it may be possible that no osthread was created for the
2084   // JavaThread due to lack of resources. However, since this must work
2085   // for critical system threads just check and abort if this fails.
2086   if (thread->osthread() == nullptr) {
2087     // This isn't really an OOM condition, but historically this is what
2088     // we report.
2089     vm_exit_during_initialization("java.lang.OutOfMemoryError",
2090                                   os::native_thread_creation_failed_msg());
2091   }
2092 }