1 /*
   2  * Copyright (c) 1997, 2024, 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 #ifndef SHARE_RUNTIME_JAVATHREAD_HPP
  27 #define SHARE_RUNTIME_JAVATHREAD_HPP
  28 
  29 #include "jni.h"
  30 #include "memory/allocation.hpp"
  31 #include "oops/oop.hpp"
  32 #include "oops/oopHandle.hpp"
  33 #include "runtime/frame.hpp"
  34 #include "runtime/globals.hpp"
  35 #include "runtime/handshake.hpp"
  36 #include "runtime/javaFrameAnchor.hpp"
  37 #include "runtime/lockStack.hpp"
  38 #include "runtime/park.hpp"
  39 #include "runtime/safepointMechanism.hpp"
  40 #include "runtime/stackWatermarkSet.hpp"
  41 #include "runtime/stackOverflow.hpp"
  42 #include "runtime/thread.hpp"
  43 #include "runtime/threadHeapSampler.hpp"
  44 #include "runtime/threadStatisticalInfo.hpp"
  45 #include "utilities/exceptions.hpp"
  46 #include "utilities/globalDefinitions.hpp"
  47 #include "utilities/macros.hpp"
  48 #if INCLUDE_JFR
  49 #include "jfr/support/jfrThreadExtension.hpp"
  50 #endif
  51 
  52 class AsyncExceptionHandshake;
  53 class ContinuationEntry;
  54 class DeoptResourceMark;
  55 class InternalOOMEMark;
  56 class JNIHandleBlock;
  57 class JVMCIRuntime;
  58 
  59 class JvmtiDeferredUpdates;
  60 class JvmtiSampledObjectAllocEventCollector;
  61 class JvmtiThreadState;
  62 
  63 class Metadata;
  64 class ObjectMonitor;
  65 class OopHandleList;
  66 class OopStorage;
  67 class OSThread;
  68 
  69 class ThreadsList;
  70 class ThreadSafepointState;
  71 class ThreadStatistics;
  72 
  73 class vframeArray;
  74 class vframe;
  75 class javaVFrame;
  76 
  77 class JavaThread;
  78 typedef void (*ThreadFunction)(JavaThread*, TRAPS);
  79 
  80 class JavaThread: public Thread {
  81   friend class VMStructs;
  82   friend class JVMCIVMStructs;
  83   friend class WhiteBox;
  84   friend class ThreadsSMRSupport; // to access _threadObj for exiting_threads_oops_do
  85   friend class HandshakeState;
  86   friend class Continuation;
  87   friend class Threads;
  88   friend class ServiceThread; // for deferred OopHandle release access
  89  private:
  90   bool           _on_thread_list;                // Is set when this JavaThread is added to the Threads list
  91 
  92   // All references to Java objects managed via OopHandles. These
  93   // have to be released by the ServiceThread after the JavaThread has
  94   // terminated - see add_oop_handles_for_release().
  95   OopHandle      _threadObj;                     // The Java level thread object
  96   OopHandle      _vthread; // the value returned by Thread.currentThread(): the virtual thread, if mounted, otherwise _threadObj
  97   OopHandle      _jvmti_vthread;
  98   OopHandle      _scopedValueCache;
  99 
 100   static OopStorage* _thread_oop_storage;
 101 
 102 #ifdef ASSERT
 103  private:
 104   int _java_call_counter;
 105 
 106  public:
 107   int  java_call_counter()                       { return _java_call_counter; }
 108   void inc_java_call_counter()                   { _java_call_counter++; }
 109   void dec_java_call_counter() {
 110     assert(_java_call_counter > 0, "Invalid nesting of JavaCallWrapper");
 111     _java_call_counter--;
 112   }
 113  private:  // restore original namespace restriction
 114 #endif  // ifdef ASSERT
 115 
 116   JavaFrameAnchor _anchor;                       // Encapsulation of current java frame and it state
 117 
 118   ThreadFunction _entry_point;
 119 
 120   JNIEnv        _jni_environment;
 121 
 122   // Deopt support
 123   DeoptResourceMark*  _deopt_mark;               // Holds special ResourceMark for deoptimization
 124 
 125   nmethod*      _deopt_nmethod;                  // nmethod that is currently being deoptimized
 126   vframeArray*  _vframe_array_head;              // Holds the heap of the active vframeArrays
 127   vframeArray*  _vframe_array_last;              // Holds last vFrameArray we popped
 128   // Holds updates by JVMTI agents for compiled frames that cannot be performed immediately. They
 129   // will be carried out as soon as possible which, in most cases, is just before deoptimization of
 130   // the frame, when control returns to it.
 131   JvmtiDeferredUpdates* _jvmti_deferred_updates;
 132 
 133   // Handshake value for fixing 6243940. We need a place for the i2c
 134   // adapter to store the callee Method*. This value is NEVER live
 135   // across a gc point so it does NOT have to be gc'd
 136   // The handshake is open ended since we can't be certain that it will
 137   // be nulled. This is because we rarely ever see the race and end up
 138   // in handle_wrong_method which is the backend of the handshake. See
 139   // code in i2c adapters and handle_wrong_method.
 140 
 141   Method*       _callee_target;
 142 
 143   // Used to pass back results to the interpreter or generated code running Java code.
 144   oop           _vm_result;    // oop result is GC-preserved
 145   Metadata*     _vm_result_2;  // non-oop result
 146   oop           _return_buffered_value; // buffered value being returned
 147 
 148   // See ReduceInitialCardMarks: this holds the precise space interval of
 149   // the most recent slow path allocation for which compiled code has
 150   // elided card-marks for performance along the fast-path.
 151   MemRegion     _deferred_card_mark;
 152 
 153   ObjectMonitor* volatile _current_pending_monitor;     // ObjectMonitor this thread is waiting to lock
 154   bool           _current_pending_monitor_is_from_java; // locking is from Java code
 155   ObjectMonitor* volatile _current_waiting_monitor;     // ObjectMonitor on which this thread called Object.wait()
 156 
 157   // Active_handles points to a block of handles
 158   JNIHandleBlock* _active_handles;
 159 
 160   // One-element thread local free list
 161   JNIHandleBlock* _free_handle_block;
 162 
 163  public:
 164   // For tracking the heavyweight monitor the thread is pending on.
 165   ObjectMonitor* current_pending_monitor() {
 166     // Use Atomic::load() to prevent data race between concurrent modification and
 167     // concurrent readers, e.g. ThreadService::get_current_contended_monitor().
 168     // Especially, reloading pointer from thread after null check must be prevented.
 169     return Atomic::load(&_current_pending_monitor);
 170   }
 171   void set_current_pending_monitor(ObjectMonitor* monitor) {
 172     Atomic::store(&_current_pending_monitor, monitor);
 173   }
 174   void set_current_pending_monitor_is_from_java(bool from_java) {
 175     _current_pending_monitor_is_from_java = from_java;
 176   }
 177   bool current_pending_monitor_is_from_java() {
 178     return _current_pending_monitor_is_from_java;
 179   }
 180   ObjectMonitor* current_waiting_monitor() {
 181     // See the comment in current_pending_monitor() above.
 182     return Atomic::load(&_current_waiting_monitor);
 183   }
 184   void set_current_waiting_monitor(ObjectMonitor* monitor) {
 185     Atomic::store(&_current_waiting_monitor, monitor);
 186   }
 187 
 188   // JNI handle support
 189   JNIHandleBlock* active_handles() const         { return _active_handles; }
 190   void set_active_handles(JNIHandleBlock* block) { _active_handles = block; }
 191   JNIHandleBlock* free_handle_block() const      { return _free_handle_block; }
 192   void set_free_handle_block(JNIHandleBlock* block) { _free_handle_block = block; }
 193 
 194   void push_jni_handle_block();
 195   void pop_jni_handle_block();
 196 
 197  private:
 198   enum SuspendFlags {
 199     // NOTE: avoid using the sign-bit as cc generates different test code
 200     //       when the sign-bit is used, and sometimes incorrectly - see CR 6398077
 201     _trace_flag             = 0x00000004U, // call tracing backend
 202     _obj_deopt              = 0x00000008U  // suspend for object reallocation and relocking for JVMTI agent
 203   };
 204 
 205   // various suspension related flags - atomically updated
 206   volatile uint32_t _suspend_flags;
 207 
 208   inline void set_suspend_flag(SuspendFlags f);
 209   inline void clear_suspend_flag(SuspendFlags f);
 210 
 211  public:
 212   inline void set_trace_flag();
 213   inline void clear_trace_flag();
 214   inline void set_obj_deopt_flag();
 215   inline void clear_obj_deopt_flag();
 216   bool is_trace_suspend()      { return (_suspend_flags & _trace_flag) != 0; }
 217   bool is_obj_deopt_suspend()  { return (_suspend_flags & _obj_deopt) != 0; }
 218 
 219   // Asynchronous exception support
 220  private:
 221   friend class InstallAsyncExceptionHandshake;
 222   friend class AsyncExceptionHandshake;
 223   friend class HandshakeState;
 224 
 225   void handle_async_exception(oop java_throwable);
 226  public:
 227   void install_async_exception(AsyncExceptionHandshake* aec = nullptr);
 228   bool has_async_exception_condition();
 229   inline void set_pending_unsafe_access_error();
 230   static void send_async_exception(JavaThread* jt, oop java_throwable);
 231 
 232   class NoAsyncExceptionDeliveryMark : public StackObj {
 233     friend JavaThread;
 234     JavaThread *_target;
 235     inline NoAsyncExceptionDeliveryMark(JavaThread *t);
 236     inline ~NoAsyncExceptionDeliveryMark();
 237   };
 238 
 239   // Safepoint support
 240  public:                                                        // Expose _thread_state for SafeFetchInt()
 241   volatile JavaThreadState _thread_state;
 242   ThreadSafepointState*          _safepoint_state;              // Holds information about a thread during a safepoint
 243   address                        _saved_exception_pc;           // Saved pc of instruction where last implicit exception happened
 244   NOT_PRODUCT(bool               _requires_cross_modify_fence;) // State used by VerifyCrossModifyFence
 245 #ifdef ASSERT
 246   // Debug support for checking if code allows safepoints or not.
 247   // Safepoints in the VM can happen because of allocation, invoking a VM operation, or blocking on
 248   // mutex, or blocking on an object synchronizer (Java locking).
 249   // If _no_safepoint_count is non-zero, then an assertion failure will happen in any of
 250   // the above cases. The class NoSafepointVerifier is used to set this counter.
 251   int _no_safepoint_count;                             // If 0, thread allow a safepoint to happen
 252 
 253  public:
 254   void inc_no_safepoint_count() { _no_safepoint_count++; }
 255   void dec_no_safepoint_count() { _no_safepoint_count--; }
 256   bool is_in_no_safepoint_scope() { return _no_safepoint_count > 0; }
 257 #endif // ASSERT
 258  public:
 259   // These functions check conditions before possibly going to a safepoint.
 260   // including NoSafepointVerifier.
 261   void check_for_valid_safepoint_state() NOT_DEBUG_RETURN;
 262   void check_possible_safepoint()        NOT_DEBUG_RETURN;
 263 
 264 #ifdef ASSERT
 265  private:
 266   volatile uint64_t _visited_for_critical_count;
 267 
 268  public:
 269   void set_visited_for_critical_count(uint64_t safepoint_id) {
 270     assert(_visited_for_critical_count == 0, "Must be reset before set");
 271     assert((safepoint_id & 0x1) == 1, "Must be odd");
 272     _visited_for_critical_count = safepoint_id;
 273   }
 274   void reset_visited_for_critical_count(uint64_t safepoint_id) {
 275     assert(_visited_for_critical_count == safepoint_id, "Was not visited");
 276     _visited_for_critical_count = 0;
 277   }
 278   bool was_visited_for_critical_count(uint64_t safepoint_id) const {
 279     return _visited_for_critical_count == safepoint_id;
 280   }
 281 #endif // ASSERT
 282 
 283   // JavaThread termination support
 284  public:
 285   enum TerminatedTypes {
 286     _not_terminated = 0xDEAD - 3,
 287     _thread_exiting,                             // JavaThread::exit() has been called for this thread
 288     _thread_gc_barrier_detached,                 // thread's GC barrier has been detached
 289     _thread_terminated,                          // JavaThread is removed from thread list
 290     _vm_exited                                   // JavaThread is still executing native code, but VM is terminated
 291                                                  // only VM_Exit can set _vm_exited
 292   };
 293 
 294  private:
 295   // In general a JavaThread's _terminated field transitions as follows:
 296   //
 297   //   _not_terminated => _thread_exiting => _thread_gc_barrier_detached => _thread_terminated
 298   //
 299   // _vm_exited is a special value to cover the case of a JavaThread
 300   // executing native code after the VM itself is terminated.
 301   //
 302   // A JavaThread that fails to JNI attach has these _terminated field transitions:
 303   //   _not_terminated => _thread_terminated
 304   //
 305   volatile TerminatedTypes _terminated;
 306 
 307   jint                  _in_deopt_handler;       // count of deoptimization
 308                                                  // handlers thread is in
 309   volatile bool         _doing_unsafe_access;    // Thread may fault due to unsafe access
 310   bool                  _do_not_unlock_if_synchronized;  // Do not unlock the receiver of a synchronized method (since it was
 311                                                          // never locked) when throwing an exception. Used by interpreter only.
 312 #if INCLUDE_JVMTI
 313   volatile bool         _carrier_thread_suspended;       // Carrier thread is externally suspended
 314   bool                  _is_in_VTMS_transition;          // thread is in virtual thread mount state transition
 315   bool                  _is_in_tmp_VTMS_transition;      // thread is in temporary virtual thread mount state transition
 316   bool                  _is_disable_suspend;             // JVMTI suspend is temporarily disabled; used on current thread only
 317   bool                  _VTMS_transition_mark;           // used for sync between VTMS transitions and disablers
 318 #ifdef ASSERT
 319   bool                  _is_VTMS_transition_disabler;    // thread currently disabled VTMS transitions
 320 #endif
 321 #endif
 322 
 323   // JNI attach states:
 324   enum JNIAttachStates {
 325     _not_attaching_via_jni = 1,  // thread is not attaching via JNI
 326     _attaching_via_jni,          // thread is attaching via JNI
 327     _attached_via_jni            // thread has attached via JNI
 328   };
 329 
 330   // A regular JavaThread's _jni_attach_state is _not_attaching_via_jni.
 331   // A native thread that is attaching via JNI starts with a value
 332   // of _attaching_via_jni and transitions to _attached_via_jni.
 333   volatile JNIAttachStates _jni_attach_state;
 334 
 335   // In scope of an InternalOOMEMark?
 336   bool _is_in_internal_oome_mark;
 337 
 338 #if INCLUDE_JVMCI
 339   // The _pending_* fields below are used to communicate extra information
 340   // from an uncommon trap in JVMCI compiled code to the uncommon trap handler.
 341 
 342   // Communicates the DeoptReason and DeoptAction of the uncommon trap
 343   int       _pending_deoptimization;
 344 
 345   // Specifies whether the uncommon trap is to bci 0 of a synchronized method
 346   // before the monitor has been acquired.
 347   bool      _pending_monitorenter;
 348 
 349   // Specifies if the DeoptReason for the last uncommon trap was Reason_transfer_to_interpreter
 350   bool      _pending_transfer_to_interpreter;
 351 
 352   // An id of a speculation that JVMCI compiled code can use to further describe and
 353   // uniquely identify the speculative optimization guarded by an uncommon trap.
 354   // See JVMCINMethodData::SPECULATION_LENGTH_BITS for further details.
 355   jlong     _pending_failed_speculation;
 356 
 357   // These fields are mutually exclusive in terms of live ranges.
 358   union {
 359     // Communicates the pc at which the most recent implicit exception occurred
 360     // from the signal handler to a deoptimization stub.
 361     address   _implicit_exception_pc;
 362 
 363     // Communicates an alternative call target to an i2c stub from a JavaCall .
 364     address   _alternate_call_target;
 365   } _jvmci;
 366 
 367   // The JVMCIRuntime in a JVMCI shared library
 368   JVMCIRuntime* _libjvmci_runtime;
 369 
 370   // Support for high precision, thread sensitive counters in JVMCI compiled code.
 371   jlong*    _jvmci_counters;
 372 
 373   // Fast thread locals for use by JVMCI
 374   jlong      _jvmci_reserved0;
 375   jlong      _jvmci_reserved1;
 376   oop        _jvmci_reserved_oop0;
 377 
 378   // This field is used to keep an nmethod visible to the GC so that it and its contained oops can
 379   // be kept alive
 380   nmethod*  _live_nmethod;
 381 
 382  public:
 383   static jlong* _jvmci_old_thread_counters;
 384   static void collect_counters(jlong* array, int length);
 385 
 386   bool resize_counters(int current_size, int new_size);
 387 
 388   static bool resize_all_jvmci_counters(int new_size);
 389 
 390   void set_jvmci_reserved_oop0(oop value) {
 391     _jvmci_reserved_oop0 = value;
 392   }
 393 
 394   oop get_jvmci_reserved_oop0() {
 395     return _jvmci_reserved_oop0;
 396   }
 397 
 398   void set_jvmci_reserved0(jlong value) {
 399     _jvmci_reserved0 = value;
 400   }
 401 
 402   jlong get_jvmci_reserved0() {
 403     return _jvmci_reserved0;
 404   }
 405 
 406   void set_jvmci_reserved1(jlong value) {
 407     _jvmci_reserved1 = value;
 408   }
 409 
 410   jlong get_jvmci_reserved1() {
 411     return _jvmci_reserved1;
 412   }
 413 
 414   void set_live_nmethod(nmethod* nm) {
 415     assert(_live_nmethod == nullptr, "only one");
 416     _live_nmethod = nm;
 417   }
 418 
 419   void clear_live_nmethod() {
 420     _live_nmethod = nullptr;
 421   }
 422 
 423  private:
 424 #endif // INCLUDE_JVMCI
 425 
 426   StackOverflow    _stack_overflow_state;
 427 
 428   void pretouch_stack();
 429 
 430   // Compiler exception handling (NOTE: The _exception_oop is *NOT* the same as _pending_exception. It is
 431   // used to temp. parsing values into and out of the runtime system during exception handling for compiled
 432   // code)
 433   volatile oop     _exception_oop;               // Exception thrown in compiled code
 434   volatile address _exception_pc;                // PC where exception happened
 435   volatile address _exception_handler_pc;        // PC for handler of exception
 436   volatile int     _is_method_handle_return;     // true (== 1) if the current exception PC is a MethodHandle call site.
 437 
 438  private:
 439   // support for JNI critical regions
 440   jint    _jni_active_critical;                  // count of entries into JNI critical region
 441 
 442   // Checked JNI: function name requires exception check
 443   char* _pending_jni_exception_check_fn;
 444 
 445   // For deadlock detection.
 446   int _depth_first_number;
 447 
 448   // JVMTI PopFrame support
 449   // This is set to popframe_pending to signal that top Java frame should be popped immediately
 450   int _popframe_condition;
 451 
 452   // If reallocation of scalar replaced objects fails, we throw OOM
 453   // and during exception propagation, pop the top
 454   // _frames_to_pop_failed_realloc frames, the ones that reference
 455   // failed reallocations.
 456   int _frames_to_pop_failed_realloc;
 457 
 458   ContinuationEntry* _cont_entry;
 459   intptr_t* _cont_fastpath; // the sp of the oldest known interpreted/call_stub frame inside the
 460                             // continuation that we know about
 461   int _cont_fastpath_thread_state; // whether global thread state allows continuation fastpath (JVMTI)
 462 
 463   // It's signed for error detection.
 464   intx _held_monitor_count;  // used by continuations for fast lock detection
 465   intx _jni_monitor_count;
 466   ObjectMonitor* _unlocked_inflated_monitor;
 467 
 468 private:
 469 
 470   friend class VMThread;
 471   friend class ThreadWaitTransition;
 472   friend class VM_Exit;
 473 
 474   // Stack watermark barriers.
 475   StackWatermarks _stack_watermarks;
 476 
 477  public:
 478   inline StackWatermarks* stack_watermarks() { return &_stack_watermarks; }
 479 
 480  public:
 481   // Constructor
 482   JavaThread(MemTag mem_tag = mtThread);   // delegating constructor
 483   JavaThread(ThreadFunction entry_point, size_t stack_size = 0, MemTag mem_tag = mtThread);
 484   ~JavaThread();
 485 
 486   // Factory method to create a new JavaThread whose attach state is "is attaching"
 487   static JavaThread* create_attaching_thread();
 488 
 489 #ifdef ASSERT
 490   // verify this JavaThread hasn't be published in the Threads::list yet
 491   void verify_not_published();
 492 #endif // ASSERT
 493 
 494   StackOverflow* stack_overflow_state() { return &_stack_overflow_state; }
 495 
 496   //JNI functiontable getter/setter for JVMTI jni function table interception API.
 497   void set_jni_functions(struct JNINativeInterface_* functionTable) {
 498     _jni_environment.functions = functionTable;
 499   }
 500   struct JNINativeInterface_* get_jni_functions() {
 501     return (struct JNINativeInterface_ *)_jni_environment.functions;
 502   }
 503 
 504   // This function is called at thread creation to allow
 505   // platform specific thread variables to be initialized.
 506   void cache_global_variables();
 507 
 508   // Executes Shutdown.shutdown()
 509   void invoke_shutdown_hooks();
 510 
 511   // Cleanup on thread exit
 512   enum ExitType {
 513     normal_exit,
 514     jni_detach
 515   };
 516   void exit(bool destroy_vm, ExitType exit_type = normal_exit);
 517 
 518   void cleanup_failed_attach_current_thread(bool is_daemon);
 519 
 520   // Testers
 521   virtual bool is_Java_thread() const            { return true;  }
 522   virtual bool can_call_java() const             { return true; }
 523 
 524   virtual bool is_active_Java_thread() const;
 525 
 526   // Thread oop. threadObj() can be null for initial JavaThread
 527   // (or for threads attached via JNI)
 528   oop threadObj() const;
 529   void set_threadOopHandles(oop p);
 530   oop vthread() const;
 531   void set_vthread(oop p);
 532   oop scopedValueCache() const;
 533   void set_scopedValueCache(oop p);
 534   void clear_scopedValueBindings();
 535   oop jvmti_vthread() const;
 536   void set_jvmti_vthread(oop p);
 537   oop vthread_or_thread() const;
 538 
 539   // Prepare thread and add to priority queue.  If a priority is
 540   // not specified, use the priority of the thread object. Threads_lock
 541   // must be held while this function is called.
 542   void prepare(jobject jni_thread, ThreadPriority prio=NoPriority);
 543 
 544   void set_saved_exception_pc(address pc)        { _saved_exception_pc = pc; }
 545   address saved_exception_pc()                   { return _saved_exception_pc; }
 546 
 547   ThreadFunction entry_point() const             { return _entry_point; }
 548 
 549   // Allocates a new Java level thread object for this thread. thread_name may be null.
 550   void allocate_threadObj(Handle thread_group, const char* thread_name, bool daemon, TRAPS);
 551 
 552   // Last frame anchor routines
 553 
 554   JavaFrameAnchor* frame_anchor(void)            { return &_anchor; }
 555 
 556   // last_Java_sp
 557   bool has_last_Java_frame() const               { return _anchor.has_last_Java_frame(); }
 558   intptr_t* last_Java_sp() const                 { return _anchor.last_Java_sp(); }
 559 
 560   // last_Java_pc
 561 
 562   address last_Java_pc(void)                     { return _anchor.last_Java_pc(); }
 563 
 564   // Safepoint support
 565   inline JavaThreadState thread_state() const;
 566   inline void set_thread_state(JavaThreadState s);
 567   inline void set_thread_state_fence(JavaThreadState s);  // fence after setting thread state
 568   inline ThreadSafepointState* safepoint_state() const;
 569   inline void set_safepoint_state(ThreadSafepointState* state);
 570   inline bool is_at_poll_safepoint();
 571 
 572   // JavaThread termination and lifecycle support:
 573   void smr_delete();
 574   bool on_thread_list() const { return _on_thread_list; }
 575   void set_on_thread_list() { _on_thread_list = true; }
 576 
 577   // thread has called JavaThread::exit(), thread's GC barrier is detached
 578   // or thread is terminated
 579   bool is_exiting() const;
 580   // thread's GC barrier is NOT detached and thread is NOT terminated
 581   bool is_oop_safe() const;
 582   // thread is terminated (no longer on the threads list); the thread must
 583   // be protected by a ThreadsListHandle to avoid potential crashes.
 584   bool check_is_terminated(TerminatedTypes l_terminated) const {
 585     return l_terminated == _thread_terminated || l_terminated == _vm_exited;
 586   }
 587   bool is_terminated() const;
 588   void set_terminated(TerminatedTypes t);
 589 
 590   void block_if_vm_exited();
 591 
 592   bool doing_unsafe_access()                     { return _doing_unsafe_access; }
 593   void set_doing_unsafe_access(bool val)         { _doing_unsafe_access = val; }
 594 
 595   bool do_not_unlock_if_synchronized()             { return _do_not_unlock_if_synchronized; }
 596   void set_do_not_unlock_if_synchronized(bool val) { _do_not_unlock_if_synchronized = val; }
 597 
 598   SafepointMechanism::ThreadData* poll_data() { return &_poll_data; }
 599 
 600   static ByteSize polling_word_offset() {
 601     ByteSize offset = byte_offset_of(Thread, _poll_data) +
 602                       byte_offset_of(SafepointMechanism::ThreadData, _polling_word);
 603     // At least on x86_64, safepoint polls encode the offset as disp8 imm.
 604     assert(in_bytes(offset) < 128, "Offset >= 128");
 605     return offset;
 606   }
 607 
 608   static ByteSize polling_page_offset() {
 609     ByteSize offset = byte_offset_of(Thread, _poll_data) +
 610                       byte_offset_of(SafepointMechanism::ThreadData, _polling_page);
 611     // At least on x86_64, safepoint polls encode the offset as disp8 imm.
 612     assert(in_bytes(offset) < 128, "Offset >= 128");
 613     return offset;
 614   }
 615 
 616   void set_requires_cross_modify_fence(bool val) PRODUCT_RETURN NOT_PRODUCT({ _requires_cross_modify_fence = val; })
 617 
 618   // Continuation support
 619   ContinuationEntry* last_continuation() const { return _cont_entry; }
 620   void set_cont_fastpath(intptr_t* x)          { _cont_fastpath = x; }
 621   void push_cont_fastpath(intptr_t* sp)        { if (sp > _cont_fastpath) _cont_fastpath = sp; }
 622   void set_cont_fastpath_thread_state(bool x)  { _cont_fastpath_thread_state = (int)x; }
 623   intptr_t* raw_cont_fastpath() const          { return _cont_fastpath; }
 624   bool cont_fastpath() const                   { return _cont_fastpath == nullptr && _cont_fastpath_thread_state != 0; }
 625   bool cont_fastpath_thread_state() const      { return _cont_fastpath_thread_state != 0; }
 626 
 627   void inc_held_monitor_count(intx i = 1, bool jni = false);
 628   void dec_held_monitor_count(intx i = 1, bool jni = false);
 629 
 630   intx held_monitor_count() { return _held_monitor_count; }
 631   intx jni_monitor_count()  { return _jni_monitor_count;  }
 632   void clear_jni_monitor_count() { _jni_monitor_count = 0;   }
 633 
 634   // Support for SharedRuntime::monitor_exit_helper()
 635   ObjectMonitor* unlocked_inflated_monitor() const { return _unlocked_inflated_monitor; }
 636   void clear_unlocked_inflated_monitor() {
 637     _unlocked_inflated_monitor = nullptr;
 638   }
 639 
 640   inline bool is_vthread_mounted() const;
 641   inline const ContinuationEntry* vthread_continuation() const;
 642 
 643  private:
 644   DEBUG_ONLY(void verify_frame_info();)
 645 
 646   // Support for thread handshake operations
 647   HandshakeState _handshake;
 648  public:
 649   HandshakeState* handshake_state() { return &_handshake; }
 650 
 651   // A JavaThread can always safely operate on it self and other threads
 652   // can do it safely if they are the active handshaker.
 653   bool is_handshake_safe_for(Thread* th) const {
 654     return _handshake.active_handshaker() == th || this == th;
 655   }
 656 
 657   // Suspend/resume support for JavaThread
 658   // higher-level suspension/resume logic called by the public APIs
 659   bool java_suspend();
 660   bool java_resume();
 661   bool is_suspended()     { return _handshake.is_suspended(); }
 662 
 663   // Check for async exception in addition to safepoint.
 664   static void check_special_condition_for_native_trans(JavaThread *thread);
 665 
 666   // Synchronize with another thread that is deoptimizing objects of the
 667   // current thread, i.e. reverts optimizations based on escape analysis.
 668   void wait_for_object_deoptimization();
 669 
 670 #if INCLUDE_JVMTI
 671   inline void set_carrier_thread_suspended();
 672   inline void clear_carrier_thread_suspended();
 673 
 674   bool is_carrier_thread_suspended() const {
 675     return _carrier_thread_suspended;
 676   }
 677 
 678   bool is_in_VTMS_transition() const             { return _is_in_VTMS_transition; }
 679   bool is_in_tmp_VTMS_transition() const         { return _is_in_tmp_VTMS_transition; }
 680   bool is_in_any_VTMS_transition() const         { return _is_in_VTMS_transition || _is_in_tmp_VTMS_transition; }
 681 
 682   void set_is_in_VTMS_transition(bool val);
 683   void toggle_is_in_tmp_VTMS_transition()        { _is_in_tmp_VTMS_transition = !_is_in_tmp_VTMS_transition; };
 684 
 685   bool is_disable_suspend() const                { return _is_disable_suspend; }
 686   void toggle_is_disable_suspend()               { _is_disable_suspend = !_is_disable_suspend; };
 687 
 688   bool VTMS_transition_mark() const              { return Atomic::load(&_VTMS_transition_mark); }
 689   void set_VTMS_transition_mark(bool val)        { Atomic::store(&_VTMS_transition_mark, val); }
 690 
 691 #ifdef ASSERT
 692   bool is_VTMS_transition_disabler() const       { return _is_VTMS_transition_disabler; }
 693   void set_is_VTMS_transition_disabler(bool val);
 694 #endif
 695 #endif
 696 
 697   // Support for object deoptimization and JFR suspension
 698   void handle_special_runtime_exit_condition();
 699   bool has_special_runtime_exit_condition() {
 700     return (_suspend_flags & (_obj_deopt JFR_ONLY(| _trace_flag))) != 0;
 701   }
 702 
 703   // Stack-locking support (not for LM_LIGHTWEIGHT)
 704   bool is_lock_owned(address adr) const;
 705 
 706   // Accessors for vframe array top
 707   // The linked list of vframe arrays are sorted on sp. This means when we
 708   // unpack the head must contain the vframe array to unpack.
 709   void set_vframe_array_head(vframeArray* value) { _vframe_array_head = value; }
 710   vframeArray* vframe_array_head() const         { return _vframe_array_head;  }
 711 
 712   // Side structure for deferring update of java frame locals until deopt occurs
 713   JvmtiDeferredUpdates* deferred_updates() const      { return _jvmti_deferred_updates; }
 714   void set_deferred_updates(JvmtiDeferredUpdates* du) { _jvmti_deferred_updates = du; }
 715 
 716   // These only really exist to make debugging deopt problems simpler
 717 
 718   void set_vframe_array_last(vframeArray* value) { _vframe_array_last = value; }
 719   vframeArray* vframe_array_last() const         { return _vframe_array_last;  }
 720 
 721   // The special resourceMark used during deoptimization
 722 
 723   void set_deopt_mark(DeoptResourceMark* value)  { _deopt_mark = value; }
 724   DeoptResourceMark* deopt_mark(void)            { return _deopt_mark; }
 725 
 726   void set_deopt_compiled_method(nmethod* nm)    { _deopt_nmethod = nm; }
 727   nmethod* deopt_compiled_method()               { return _deopt_nmethod; }
 728 
 729   Method*    callee_target() const               { return _callee_target; }
 730   void set_callee_target  (Method* x)            { _callee_target   = x; }
 731 
 732   // Oop results of vm runtime calls
 733   oop  vm_result() const                         { return _vm_result; }
 734   void set_vm_result  (oop x)                    { _vm_result   = x; }
 735 
 736   void set_vm_result_2  (Metadata* x)            { _vm_result_2   = x; }
 737 
 738   oop return_buffered_value() const              { return _return_buffered_value; }
 739   void set_return_buffered_value(oop val)        { _return_buffered_value = val; }
 740 
 741   MemRegion deferred_card_mark() const           { return _deferred_card_mark; }
 742   void set_deferred_card_mark(MemRegion mr)      { _deferred_card_mark = mr;   }
 743 
 744   // Is thread in scope of an InternalOOMEMark?
 745   bool is_in_internal_oome_mark() const          { return _is_in_internal_oome_mark; }
 746   void set_is_in_internal_oome_mark(bool b)      { _is_in_internal_oome_mark = b;    }
 747 
 748 #if INCLUDE_JVMCI
 749   jlong pending_failed_speculation() const        { return _pending_failed_speculation; }
 750   void set_pending_monitorenter(bool b)           { _pending_monitorenter = b; }
 751   void set_pending_deoptimization(int reason)     { _pending_deoptimization = reason; }
 752   void set_pending_failed_speculation(jlong failed_speculation) { _pending_failed_speculation = failed_speculation; }
 753   void set_pending_transfer_to_interpreter(bool b) { _pending_transfer_to_interpreter = b; }
 754   void set_jvmci_alternate_call_target(address a) { assert(_jvmci._alternate_call_target == nullptr, "must be"); _jvmci._alternate_call_target = a; }
 755   void set_jvmci_implicit_exception_pc(address a) { assert(_jvmci._implicit_exception_pc == nullptr, "must be"); _jvmci._implicit_exception_pc = a; }
 756 
 757   JVMCIRuntime* libjvmci_runtime() const          { return _libjvmci_runtime; }
 758   void set_libjvmci_runtime(JVMCIRuntime* rt) {
 759     assert((_libjvmci_runtime == nullptr && rt != nullptr) || (_libjvmci_runtime != nullptr && rt == nullptr), "must be");
 760     _libjvmci_runtime = rt;
 761   }
 762 #endif // INCLUDE_JVMCI
 763 
 764   // Exception handling for compiled methods
 765   oop      exception_oop() const;
 766   address  exception_pc() const                  { return _exception_pc; }
 767 
 768   void set_exception_oop(oop o);
 769   void set_exception_pc(address a)               { _exception_pc = a; }
 770   void set_exception_handler_pc(address a)       { _exception_handler_pc = a; }
 771   void set_is_method_handle_return(bool value)   { _is_method_handle_return = value ? 1 : 0; }
 772 
 773   void clear_exception_oop_and_pc() {
 774     set_exception_oop(nullptr);
 775     set_exception_pc(nullptr);
 776   }
 777 
 778   // Check if address is in the usable part of the stack (excludes protected
 779   // guard pages). Can be applied to any thread and is an approximation for
 780   // using is_in_live_stack when the query has to happen from another thread.
 781   bool is_in_usable_stack(address adr) const {
 782     return is_in_stack_range_incl(adr, _stack_overflow_state.stack_reserved_zone_base());
 783   }
 784 
 785   // Misc. accessors/mutators
 786   static ByteSize scopedValueCache_offset()       { return byte_offset_of(JavaThread, _scopedValueCache); }
 787 
 788   // For assembly stub generation
 789   static ByteSize threadObj_offset()             { return byte_offset_of(JavaThread, _threadObj); }
 790   static ByteSize vthread_offset()               { return byte_offset_of(JavaThread, _vthread); }
 791   static ByteSize jni_environment_offset()       { return byte_offset_of(JavaThread, _jni_environment); }
 792   static ByteSize pending_jni_exception_check_fn_offset() {
 793     return byte_offset_of(JavaThread, _pending_jni_exception_check_fn);
 794   }
 795   static ByteSize last_Java_sp_offset() {
 796     return byte_offset_of(JavaThread, _anchor) + JavaFrameAnchor::last_Java_sp_offset();
 797   }
 798   static ByteSize last_Java_pc_offset() {
 799     return byte_offset_of(JavaThread, _anchor) + JavaFrameAnchor::last_Java_pc_offset();
 800   }
 801   static ByteSize frame_anchor_offset() {
 802     return byte_offset_of(JavaThread, _anchor);
 803   }
 804   static ByteSize callee_target_offset()         { return byte_offset_of(JavaThread, _callee_target); }
 805   static ByteSize vm_result_offset()             { return byte_offset_of(JavaThread, _vm_result); }
 806   static ByteSize vm_result_2_offset()           { return byte_offset_of(JavaThread, _vm_result_2); }
 807   static ByteSize return_buffered_value_offset() { return byte_offset_of(JavaThread, _return_buffered_value); }
 808   static ByteSize thread_state_offset()          { return byte_offset_of(JavaThread, _thread_state); }
 809   static ByteSize saved_exception_pc_offset()    { return byte_offset_of(JavaThread, _saved_exception_pc); }
 810   static ByteSize osthread_offset()              { return byte_offset_of(JavaThread, _osthread); }
 811 #if INCLUDE_JVMCI
 812   static ByteSize pending_deoptimization_offset() { return byte_offset_of(JavaThread, _pending_deoptimization); }
 813   static ByteSize pending_monitorenter_offset()  { return byte_offset_of(JavaThread, _pending_monitorenter); }
 814   static ByteSize jvmci_alternate_call_target_offset() { return byte_offset_of(JavaThread, _jvmci._alternate_call_target); }
 815   static ByteSize jvmci_implicit_exception_pc_offset() { return byte_offset_of(JavaThread, _jvmci._implicit_exception_pc); }
 816   static ByteSize jvmci_counters_offset()        { return byte_offset_of(JavaThread, _jvmci_counters); }
 817 #endif // INCLUDE_JVMCI
 818   static ByteSize exception_oop_offset()         { return byte_offset_of(JavaThread, _exception_oop); }
 819   static ByteSize exception_pc_offset()          { return byte_offset_of(JavaThread, _exception_pc); }
 820   static ByteSize exception_handler_pc_offset()  { return byte_offset_of(JavaThread, _exception_handler_pc); }
 821   static ByteSize is_method_handle_return_offset() { return byte_offset_of(JavaThread, _is_method_handle_return); }
 822 
 823   static ByteSize active_handles_offset()        { return byte_offset_of(JavaThread, _active_handles); }
 824 
 825   // StackOverflow offsets
 826   static ByteSize stack_overflow_limit_offset()  {
 827     return byte_offset_of(JavaThread, _stack_overflow_state._stack_overflow_limit);
 828   }
 829   static ByteSize stack_guard_state_offset()     {
 830     return byte_offset_of(JavaThread, _stack_overflow_state._stack_guard_state);
 831   }
 832   static ByteSize reserved_stack_activation_offset() {
 833     return byte_offset_of(JavaThread, _stack_overflow_state._reserved_stack_activation);
 834   }
 835   static ByteSize shadow_zone_safe_limit()  {
 836     return byte_offset_of(JavaThread, _stack_overflow_state._shadow_zone_safe_limit);
 837   }
 838   static ByteSize shadow_zone_growth_watermark()  {
 839     return byte_offset_of(JavaThread, _stack_overflow_state._shadow_zone_growth_watermark);
 840   }
 841 
 842   static ByteSize suspend_flags_offset()         { return byte_offset_of(JavaThread, _suspend_flags); }
 843 
 844   static ByteSize do_not_unlock_if_synchronized_offset() { return byte_offset_of(JavaThread, _do_not_unlock_if_synchronized); }
 845   static ByteSize should_post_on_exceptions_flag_offset() {
 846     return byte_offset_of(JavaThread, _should_post_on_exceptions_flag);
 847   }
 848   static ByteSize doing_unsafe_access_offset() { return byte_offset_of(JavaThread, _doing_unsafe_access); }
 849   NOT_PRODUCT(static ByteSize requires_cross_modify_fence_offset()  { return byte_offset_of(JavaThread, _requires_cross_modify_fence); })
 850 
 851   static ByteSize cont_entry_offset()         { return byte_offset_of(JavaThread, _cont_entry); }
 852   static ByteSize cont_fastpath_offset()      { return byte_offset_of(JavaThread, _cont_fastpath); }
 853   static ByteSize held_monitor_count_offset() { return byte_offset_of(JavaThread, _held_monitor_count); }
 854   static ByteSize jni_monitor_count_offset()  { return byte_offset_of(JavaThread, _jni_monitor_count); }
 855   static ByteSize unlocked_inflated_monitor_offset() { return byte_offset_of(JavaThread, _unlocked_inflated_monitor); }
 856 
 857 #if INCLUDE_JVMTI
 858   static ByteSize is_in_VTMS_transition_offset()     { return byte_offset_of(JavaThread, _is_in_VTMS_transition); }
 859   static ByteSize is_in_tmp_VTMS_transition_offset() { return byte_offset_of(JavaThread, _is_in_tmp_VTMS_transition); }
 860   static ByteSize is_disable_suspend_offset()        { return byte_offset_of(JavaThread, _is_disable_suspend); }
 861 #endif
 862 
 863   // Returns the jni environment for this thread
 864   JNIEnv* jni_environment()                      { return &_jni_environment; }
 865 
 866   // Returns the current thread as indicated by the given JNIEnv.
 867   // We don't assert it is Thread::current here as that is done at the
 868   // external JNI entry points where the JNIEnv is passed into the VM.
 869   static JavaThread* thread_from_jni_environment(JNIEnv* env) {
 870     JavaThread* current = reinterpret_cast<JavaThread*>(((intptr_t)env - in_bytes(jni_environment_offset())));
 871     // We can't normally get here in a thread that has completed its
 872     // execution and so "is_terminated", except when the call is from
 873     // AsyncGetCallTrace, which can be triggered by a signal at any point in
 874     // a thread's lifecycle. A thread is also considered terminated if the VM
 875     // has exited, so we have to check this and block in case this is a daemon
 876     // thread returning to the VM (the JNI DirectBuffer entry points rely on
 877     // this).
 878     if (current->is_terminated()) {
 879       current->block_if_vm_exited();
 880     }
 881     return current;
 882   }
 883 
 884   // JNI critical regions. These can nest.
 885   bool in_critical()    { return _jni_active_critical > 0; }
 886   bool in_last_critical()  { return _jni_active_critical == 1; }
 887   inline void enter_critical();
 888   void exit_critical() {
 889     assert(Thread::current() == this, "this must be current thread");
 890     _jni_active_critical--;
 891     assert(_jni_active_critical >= 0, "JNI critical nesting problem?");
 892   }
 893 
 894   // Checked JNI: is the programmer required to check for exceptions, if so specify
 895   // which function name. Returning to a Java frame should implicitly clear the
 896   // pending check, this is done for Native->Java transitions (i.e. user JNI code).
 897   // VM->Java transitions are not cleared, it is expected that JNI code enclosed
 898   // within ThreadToNativeFromVM makes proper exception checks (i.e. VM internal).
 899   bool is_pending_jni_exception_check() const { return _pending_jni_exception_check_fn != nullptr; }
 900   void clear_pending_jni_exception_check() { _pending_jni_exception_check_fn = nullptr; }
 901   const char* get_pending_jni_exception_check() const { return _pending_jni_exception_check_fn; }
 902   void set_pending_jni_exception_check(const char* fn_name) { _pending_jni_exception_check_fn = (char*) fn_name; }
 903 
 904   // For deadlock detection
 905   int depth_first_number() { return _depth_first_number; }
 906   void set_depth_first_number(int dfn) { _depth_first_number = dfn; }
 907 
 908  public:
 909   bool in_deopt_handler() const                  { return _in_deopt_handler > 0; }
 910   void inc_in_deopt_handler()                    { _in_deopt_handler++; }
 911   void dec_in_deopt_handler() {
 912     assert(_in_deopt_handler > 0, "mismatched deopt nesting");
 913     if (_in_deopt_handler > 0) { // robustness
 914       _in_deopt_handler--;
 915     }
 916   }
 917 
 918  private:
 919   void set_entry_point(ThreadFunction entry_point) { _entry_point = entry_point; }
 920 
 921   // factor out low-level mechanics for use in both normal and error cases
 922   const char* get_thread_name_string(char* buf = nullptr, int buflen = 0) const;
 923 
 924  public:
 925 
 926   // Frame iteration; calls the function f for all frames on the stack
 927   void frames_do(void f(frame*, const RegisterMap*));
 928 
 929   // Memory operations
 930   void oops_do_frames(OopClosure* f, NMethodClosure* cf);
 931   void oops_do_no_frames(OopClosure* f, NMethodClosure* cf);
 932 
 933   // GC operations
 934   virtual void nmethods_do(NMethodClosure* cf);
 935 
 936   // RedefineClasses Support
 937   void metadata_do(MetadataClosure* f);
 938 
 939   // Debug method asserting thread states are correct during a handshake operation.
 940   DEBUG_ONLY(void verify_states_for_handshake();)
 941 
 942   // Misc. operations
 943   const char* name() const;
 944   const char* name_raw() const;
 945   const char* type_name() const { return "JavaThread"; }
 946   static const char* name_for(oop thread_obj);
 947 
 948   void print_on(outputStream* st, bool print_extended_info) const;
 949   void print_on(outputStream* st) const { print_on(st, false); }
 950   void print() const;
 951   void print_thread_state_on(outputStream*) const;
 952   void print_on_error(outputStream* st, char* buf, int buflen) const;
 953   void print_name_on_error(outputStream* st, char* buf, int buflen) const;
 954   void verify();
 955 
 956   // Accessing frames
 957   frame last_frame() {
 958     _anchor.make_walkable();
 959     return pd_last_frame();
 960   }
 961   javaVFrame* last_java_vframe(RegisterMap* reg_map) { return last_java_vframe(last_frame(), reg_map); }
 962 
 963   frame carrier_last_frame(RegisterMap* reg_map);
 964   javaVFrame* carrier_last_java_vframe(RegisterMap* reg_map) { return last_java_vframe(carrier_last_frame(reg_map), reg_map); }
 965 
 966   frame vthread_last_frame();
 967   javaVFrame* vthread_last_java_vframe(RegisterMap* reg_map) { return last_java_vframe(vthread_last_frame(), reg_map); }
 968 
 969   frame platform_thread_last_frame(RegisterMap* reg_map);
 970   javaVFrame*  platform_thread_last_java_vframe(RegisterMap* reg_map) {
 971     return last_java_vframe(platform_thread_last_frame(reg_map), reg_map);
 972   }
 973 
 974   javaVFrame* last_java_vframe(const frame f, RegisterMap* reg_map);
 975 
 976   // Returns method at 'depth' java or native frames down the stack
 977   // Used for security checks
 978   Klass* security_get_caller_class(int depth);
 979 
 980   // Print stack trace in external format
 981   // These variants print carrier/platform thread information only.
 982   void print_stack_on(outputStream* st);
 983   void print_stack() { print_stack_on(tty); }
 984   // This prints the currently mounted virtual thread.
 985   void print_vthread_stack_on(outputStream* st);
 986   // This prints the active stack: either carrier/platform or virtual.
 987   void print_active_stack_on(outputStream* st);
 988   // Print current stack trace for checked JNI warnings and JNI fatal errors.
 989   // This is the external format from above, but selecting the platform
 990   // or vthread as applicable.
 991   void print_jni_stack();
 992 
 993   // Print stack traces in various internal formats
 994   void trace_stack()                             PRODUCT_RETURN;
 995   void trace_stack_from(vframe* start_vf)        PRODUCT_RETURN;
 996   void trace_frames()                            PRODUCT_RETURN;
 997 
 998   // Print an annotated view of the stack frames
 999   void print_frame_layout(int depth = 0, bool validate_only = false) NOT_DEBUG_RETURN;
1000   void validate_frame_layout() {
1001     print_frame_layout(0, true);
1002   }
1003 
1004   // Function for testing deoptimization
1005   void deoptimize();
1006   void make_zombies();
1007 
1008   void deoptimize_marked_methods();
1009 
1010  public:
1011   // Returns the running thread as a JavaThread
1012   static JavaThread* current() {
1013     return JavaThread::cast(Thread::current());
1014   }
1015 
1016   // Returns the current thread as a JavaThread, or nullptr if not attached
1017   static inline JavaThread* current_or_null();
1018 
1019   // Casts
1020   static JavaThread* cast(Thread* t) {
1021     assert(t->is_Java_thread(), "incorrect cast to JavaThread");
1022     return static_cast<JavaThread*>(t);
1023   }
1024 
1025   static const JavaThread* cast(const Thread* t) {
1026     assert(t->is_Java_thread(), "incorrect cast to const JavaThread");
1027     return static_cast<const JavaThread*>(t);
1028   }
1029 
1030   // Returns the active Java thread.  Do not use this if you know you are calling
1031   // from a JavaThread, as it's slower than JavaThread::current.  If called from
1032   // the VMThread, it also returns the JavaThread that instigated the VMThread's
1033   // operation.  You may not want that either.
1034   static JavaThread* active();
1035 
1036  protected:
1037   virtual void pre_run();
1038   virtual void run();
1039   void thread_main_inner();
1040   virtual void post_run();
1041 
1042  public:
1043   // Thread local information maintained by JVMTI.
1044   void set_jvmti_thread_state(JvmtiThreadState *value)                           { _jvmti_thread_state = value; }
1045   // A JvmtiThreadState is lazily allocated. This jvmti_thread_state()
1046   // getter is used to get this JavaThread's JvmtiThreadState if it has
1047   // one which means null can be returned. JvmtiThreadState::state_for()
1048   // is used to get the specified JavaThread's JvmtiThreadState if it has
1049   // one or it allocates a new JvmtiThreadState for the JavaThread and
1050   // returns it. JvmtiThreadState::state_for() will return null only if
1051   // the specified JavaThread is exiting.
1052   JvmtiThreadState *jvmti_thread_state() const                                   { return _jvmti_thread_state; }
1053   static ByteSize jvmti_thread_state_offset()                                    { return byte_offset_of(JavaThread, _jvmti_thread_state); }
1054 
1055 #if INCLUDE_JVMTI
1056   // Rebind JVMTI thread state from carrier to virtual or from virtual to carrier.
1057   JvmtiThreadState *rebind_to_jvmti_thread_state_of(oop thread_oop);
1058 #endif
1059 
1060   // JVMTI PopFrame support
1061   // Setting and clearing popframe_condition
1062   // All of these enumerated values are bits. popframe_pending
1063   // indicates that a PopFrame() has been requested and not yet been
1064   // completed. popframe_processing indicates that that PopFrame() is in
1065   // the process of being completed. popframe_force_deopt_reexecution_bit
1066   // indicates that special handling is required when returning to a
1067   // deoptimized caller.
1068   enum PopCondition {
1069     popframe_inactive                      = 0x00,
1070     popframe_pending_bit                   = 0x01,
1071     popframe_processing_bit                = 0x02,
1072     popframe_force_deopt_reexecution_bit   = 0x04
1073   };
1074   PopCondition popframe_condition()                   { return (PopCondition) _popframe_condition; }
1075   void set_popframe_condition(PopCondition c)         { _popframe_condition = c; }
1076   void set_popframe_condition_bit(PopCondition c)     { _popframe_condition |= c; }
1077   void clear_popframe_condition()                     { _popframe_condition = popframe_inactive; }
1078   static ByteSize popframe_condition_offset()         { return byte_offset_of(JavaThread, _popframe_condition); }
1079   bool has_pending_popframe()                         { return (popframe_condition() & popframe_pending_bit) != 0; }
1080   bool popframe_forcing_deopt_reexecution()           { return (popframe_condition() & popframe_force_deopt_reexecution_bit) != 0; }
1081 
1082   bool pop_frame_in_process(void)                     { return ((_popframe_condition & popframe_processing_bit) != 0); }
1083   void set_pop_frame_in_process(void)                 { _popframe_condition |= popframe_processing_bit; }
1084   void clr_pop_frame_in_process(void)                 { _popframe_condition &= ~popframe_processing_bit; }
1085 
1086   int frames_to_pop_failed_realloc() const            { return _frames_to_pop_failed_realloc; }
1087   void set_frames_to_pop_failed_realloc(int nb)       { _frames_to_pop_failed_realloc = nb; }
1088   void dec_frames_to_pop_failed_realloc()             { _frames_to_pop_failed_realloc--; }
1089 
1090  private:
1091   // Saved incoming arguments to popped frame.
1092   // Used only when popped interpreted frame returns to deoptimized frame.
1093   void*    _popframe_preserved_args;
1094   int      _popframe_preserved_args_size;
1095 
1096  public:
1097   void  popframe_preserve_args(ByteSize size_in_bytes, void* start);
1098   void* popframe_preserved_args();
1099   ByteSize popframe_preserved_args_size();
1100   WordSize popframe_preserved_args_size_in_words();
1101   void  popframe_free_preserved_args();
1102 
1103 
1104  private:
1105   JvmtiThreadState *_jvmti_thread_state;
1106 
1107   // Used by the interpreter in fullspeed mode for frame pop, method
1108   // entry, method exit and single stepping support. This field is
1109   // only set to non-zero at a safepoint or using a direct handshake
1110   // (see EnterInterpOnlyModeClosure).
1111   // It can be set to zero asynchronously to this threads execution (i.e., without
1112   // safepoint/handshake or a lock) so we have to be very careful.
1113   // Accesses by other threads are synchronized using JvmtiThreadState_lock though.
1114   int               _interp_only_mode;
1115 
1116  public:
1117   // used by the interpreter for fullspeed debugging support (see above)
1118   static ByteSize interp_only_mode_offset() { return byte_offset_of(JavaThread, _interp_only_mode); }
1119   bool is_interp_only_mode()                { return (_interp_only_mode != 0); }
1120   int get_interp_only_mode()                { return _interp_only_mode; }
1121   int set_interp_only_mode(int val)         { return _interp_only_mode = val; }
1122   void increment_interp_only_mode()         { ++_interp_only_mode; }
1123   void decrement_interp_only_mode()         { --_interp_only_mode; }
1124 
1125   // support for cached flag that indicates whether exceptions need to be posted for this thread
1126   // if this is false, we can avoid deoptimizing when events are thrown
1127   // this gets set to reflect whether jvmtiExport::post_exception_throw would actually do anything
1128  private:
1129   int    _should_post_on_exceptions_flag;
1130 
1131  public:
1132   void  set_should_post_on_exceptions_flag(int val)  { _should_post_on_exceptions_flag = val; }
1133 
1134  private:
1135   ThreadStatistics *_thread_stat;
1136 
1137  public:
1138   ThreadStatistics* get_thread_stat() const    { return _thread_stat; }
1139 
1140   // Return a blocker object for which this thread is blocked parking.
1141   oop current_park_blocker();
1142 
1143  private:
1144   static size_t _stack_size_at_create;
1145 
1146  public:
1147   static inline size_t stack_size_at_create(void) {
1148     return _stack_size_at_create;
1149   }
1150   static inline void set_stack_size_at_create(size_t value) {
1151     _stack_size_at_create = value;
1152   }
1153 
1154   // Machine dependent stuff
1155 #include OS_CPU_HEADER(javaThread)
1156 
1157   // JSR166 per-thread parker
1158  private:
1159   Parker _parker;
1160  public:
1161   Parker* parker() { return &_parker; }
1162 
1163  public:
1164   // clearing/querying jni attach status
1165   bool is_attaching_via_jni() const { return _jni_attach_state == _attaching_via_jni; }
1166   bool has_attached_via_jni() const { return is_attaching_via_jni() || _jni_attach_state == _attached_via_jni; }
1167   inline void set_done_attaching_via_jni();
1168 
1169   // Stack dump assistance:
1170   // Track the class we want to initialize but for which we have to wait
1171   // on its init_lock() because it is already being initialized.
1172   void set_class_to_be_initialized(InstanceKlass* k);
1173   InstanceKlass* class_to_be_initialized() const;
1174 
1175 private:
1176   InstanceKlass* _class_to_be_initialized;
1177 
1178   // java.lang.Thread.sleep support
1179   ParkEvent * _SleepEvent;
1180 public:
1181   bool sleep(jlong millis);
1182   bool sleep_nanos(jlong nanos);
1183 
1184   // java.lang.Thread interruption support
1185   void interrupt();
1186   bool is_interrupted(bool clear_interrupted);
1187 
1188   // This is only for use by JVMTI RawMonitorWait. It emulates the actions of
1189   // the Java code in Object::wait which are not present in RawMonitorWait.
1190   bool get_and_clear_interrupted();
1191 
1192 private:
1193   LockStack _lock_stack;
1194   OMCache _om_cache;
1195 
1196 public:
1197   LockStack& lock_stack() { return _lock_stack; }
1198 
1199   static ByteSize lock_stack_offset()      { return byte_offset_of(JavaThread, _lock_stack); }
1200   // Those offsets are used in code generators to access the LockStack that is embedded in this
1201   // JavaThread structure. Those accesses are relative to the current thread, which
1202   // is typically in a dedicated register.
1203   static ByteSize lock_stack_top_offset()  { return lock_stack_offset() + LockStack::top_offset(); }
1204   static ByteSize lock_stack_base_offset() { return lock_stack_offset() + LockStack::base_offset(); }
1205 
1206   static ByteSize om_cache_offset()        { return byte_offset_of(JavaThread, _om_cache); }
1207   static ByteSize om_cache_oops_offset()   { return om_cache_offset() + OMCache::entries_offset(); }
1208 
1209   void om_set_monitor_cache(ObjectMonitor* monitor);
1210   void om_clear_monitor_cache();
1211   ObjectMonitor* om_get_from_monitor_cache(oop obj);
1212 
1213   static OopStorage* thread_oop_storage();
1214 
1215   static void verify_cross_modify_fence_failure(JavaThread *thread) PRODUCT_RETURN;
1216 
1217   // Helper function to create the java.lang.Thread object for a
1218   // VM-internal thread. The thread will have the given name and be
1219   // part of the System ThreadGroup.
1220   static Handle create_system_thread_object(const char* name, TRAPS);
1221 
1222   // Helper function to start a VM-internal daemon thread.
1223   // E.g. ServiceThread, NotificationThread, CompilerThread etc.
1224   static void start_internal_daemon(JavaThread* current, JavaThread* target,
1225                                     Handle thread_oop, ThreadPriority prio);
1226 
1227   // Helper function to do vm_exit_on_initialization for osthread
1228   // resource allocation failure.
1229   static void vm_exit_on_osthread_failure(JavaThread* thread);
1230 
1231   // Deferred OopHandle release support
1232  private:
1233   // List of OopHandles to be released - guarded by the Service_lock.
1234   static OopHandleList* _oop_handle_list;
1235   // Add our OopHandles to the list for the service thread to release.
1236   void add_oop_handles_for_release();
1237   // Called by the ServiceThread to release the OopHandles.
1238   static void release_oop_handles();
1239   // Called by the ServiceThread to poll if there are any OopHandles to release.
1240   // Called when holding the Service_lock.
1241   static bool has_oop_handles_to_release() {
1242     return _oop_handle_list != nullptr;
1243   }
1244 };
1245 
1246 inline JavaThread* JavaThread::current_or_null() {
1247   Thread* current = Thread::current_or_null();
1248   return current != nullptr ? JavaThread::cast(current) : nullptr;
1249 }
1250 
1251 class UnlockFlagSaver {
1252   private:
1253     JavaThread* _thread;
1254     bool _do_not_unlock;
1255   public:
1256     UnlockFlagSaver(JavaThread* t) {
1257       _thread = t;
1258       _do_not_unlock = t->do_not_unlock_if_synchronized();
1259       t->set_do_not_unlock_if_synchronized(false);
1260     }
1261     ~UnlockFlagSaver() {
1262       _thread->set_do_not_unlock_if_synchronized(_do_not_unlock);
1263     }
1264 };
1265 
1266 class JNIHandleMark : public StackObj {
1267   JavaThread* _thread;
1268  public:
1269   JNIHandleMark(JavaThread* thread) : _thread(thread) {
1270     thread->push_jni_handle_block();
1271   }
1272   ~JNIHandleMark() { _thread->pop_jni_handle_block(); }
1273 };
1274 
1275 #endif // SHARE_RUNTIME_JAVATHREAD_HPP