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