1 /*
   2  * Copyright (c) 1997, 2021, Oracle and/or its affiliates. All rights reserved.
   3  * Copyright (c) 2021, Azul Systems, Inc. All rights reserved.
   4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   5  *
   6  * This code is free software; you can redistribute it and/or modify it
   7  * under the terms of the GNU General Public License version 2 only, as
   8  * published by the Free Software Foundation.
   9  *
  10  * This code is distributed in the hope that it will be useful, but WITHOUT
  11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  13  * version 2 for more details (a copy is included in the LICENSE file that
  14  * accompanied this code).
  15  *
  16  * You should have received a copy of the GNU General Public License version
  17  * 2 along with this work; if not, write to the Free Software Foundation,
  18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  19  *
  20  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  21  * or visit www.oracle.com if you need additional information or have any
  22  * questions.
  23  *
  24  */
  25 
  26 #ifndef SHARE_RUNTIME_THREAD_HPP
  27 #define SHARE_RUNTIME_THREAD_HPP
  28 
  29 #include "jni.h"
  30 #include "gc/shared/gcThreadLocalData.hpp"
  31 #include "gc/shared/threadLocalAllocBuffer.hpp"
  32 #include "memory/allocation.hpp"
  33 #include "oops/oop.hpp"
  34 #include "oops/oopHandle.hpp"
  35 #include "oops/weakHandle.hpp"
  36 #include "runtime/continuation.hpp"
  37 #include "runtime/frame.hpp"
  38 #include "runtime/globals.hpp"
  39 #include "runtime/handshake.hpp"
  40 #include "runtime/javaFrameAnchor.hpp"
  41 #include "runtime/mutexLocker.hpp"
  42 #include "runtime/os.hpp"
  43 #include "runtime/park.hpp"
  44 #include "runtime/safepointMechanism.hpp"
  45 #include "runtime/stackWatermarkSet.hpp"
  46 #include "runtime/stackOverflow.hpp"
  47 #include "runtime/threadHeapSampler.hpp"
  48 #include "runtime/threadLocalStorage.hpp"
  49 #include "runtime/threadStatisticalInfo.hpp"
  50 #include "runtime/unhandledOops.hpp"
  51 #include "utilities/align.hpp"
  52 #include "utilities/exceptions.hpp"
  53 #include "utilities/globalDefinitions.hpp"
  54 #include "utilities/macros.hpp"
  55 #if INCLUDE_JFR
  56 #include "jfr/support/jfrThreadExtension.hpp"
  57 #endif
  58 
  59 class SafeThreadsListPtr;
  60 class ThreadSafepointState;
  61 class ThreadsList;
  62 class ThreadsSMRSupport;
  63 
  64 class JNIHandleBlock;
  65 class JvmtiRawMonitor;
  66 class JvmtiSampledObjectAllocEventCollector;
  67 class JvmtiThreadState;
  68 class JvmtiVMObjectAllocEventCollector;
  69 class OSThread;
  70 class ThreadStatistics;
  71 class ConcurrentLocksDump;
  72 class MonitorInfo;
  73 
  74 class vframeArray;
  75 class vframe;
  76 class javaVFrame;
  77 
  78 class DeoptResourceMark;
  79 class JvmtiDeferredUpdates;
  80 
  81 class ThreadClosure;
  82 class ICRefillVerifier;
  83 
  84 class Metadata;
  85 class ResourceArea;
  86 
  87 class OopStorage;
  88 
  89 DEBUG_ONLY(class ResourceMark;)
  90 
  91 class WorkerThread;
  92 
  93 class JavaThread;
  94 
  95 // Class hierarchy
  96 // - Thread
  97 //   - JavaThread
  98 //     - various subclasses eg CompilerThread, ServiceThread
  99 //   - NonJavaThread
 100 //     - NamedThread
 101 //       - VMThread
 102 //       - ConcurrentGCThread
 103 //       - WorkerThread
 104 //         - GangWorker
 105 //     - WatcherThread
 106 //     - JfrThreadSampler
 107 //     - LogAsyncWriter
 108 //
 109 // All Thread subclasses must be either JavaThread or NonJavaThread.
 110 // This means !t->is_Java_thread() iff t is a NonJavaThread, or t is
 111 // a partially constructed/destroyed Thread.
 112 
 113 // Thread execution sequence and actions:
 114 // All threads:
 115 //  - thread_native_entry  // per-OS native entry point
 116 //    - stack initialization
 117 //    - other OS-level initialization (signal masks etc)
 118 //    - handshake with creating thread (if not started suspended)
 119 //    - this->call_run()  // common shared entry point
 120 //      - shared common initialization
 121 //      - this->pre_run()  // virtual per-thread-type initialization
 122 //      - this->run()      // virtual per-thread-type "main" logic
 123 //      - shared common tear-down
 124 //      - this->post_run()  // virtual per-thread-type tear-down
 125 //      - // 'this' no longer referenceable
 126 //    - OS-level tear-down (minimal)
 127 //    - final logging
 128 //
 129 // For JavaThread:
 130 //   - this->run()  // virtual but not normally overridden
 131 //     - this->thread_main_inner()  // extra call level to ensure correct stack calculations
 132 //       - this->entry_point()  // set differently for each kind of JavaThread
 133 
 134 class Thread: public ThreadShadow {
 135   friend class VMStructs;
 136   friend class JVMCIVMStructs;
 137  private:
 138 
 139 #ifndef USE_LIBRARY_BASED_TLS_ONLY
 140   // Current thread is maintained as a thread-local variable
 141   static THREAD_LOCAL Thread* _thr_current;
 142 #endif
 143 
 144   int _nmethod_disarm_value;
 145 
 146  public:
 147   int nmethod_disarm_value() {
 148     return _nmethod_disarm_value;
 149   }
 150 
 151   void set_nmethod_disarm_value(int value) {
 152     _nmethod_disarm_value = value;
 153   }
 154 
 155   static ByteSize nmethod_disarmed_offset() {
 156     return byte_offset_of(Thread, _nmethod_disarm_value);
 157   }
 158 
 159  private:
 160   // Thread local data area available to the GC. The internal
 161   // structure and contents of this data area is GC-specific.
 162   // Only GC and GC barrier code should access this data area.
 163   GCThreadLocalData _gc_data;
 164 
 165  public:
 166   static ByteSize gc_data_offset() {
 167     return byte_offset_of(Thread, _gc_data);
 168   }
 169 
 170   template <typename T> T* gc_data() {
 171     STATIC_ASSERT(sizeof(T) <= sizeof(_gc_data));
 172     return reinterpret_cast<T*>(&_gc_data);
 173   }
 174 
 175   // Exception handling
 176   // (Note: _pending_exception and friends are in ThreadShadow)
 177   //oop       _pending_exception;                // pending exception for current thread
 178   // const char* _exception_file;                   // file information for exception (debugging only)
 179   // int         _exception_line;                   // line information for exception (debugging only)
 180  protected:
 181 
 182   DEBUG_ONLY(static Thread* _starting_thread;)
 183 
 184   // JavaThread lifecycle support:
 185   friend class SafeThreadsListPtr;  // for _threads_list_ptr, cmpxchg_threads_hazard_ptr(), {dec_,inc_,}nested_threads_hazard_ptr_cnt(), {g,s}et_threads_hazard_ptr(), inc_nested_handle_cnt(), tag_hazard_ptr() access
 186   friend class ScanHazardPtrGatherProtectedThreadsClosure;  // for cmpxchg_threads_hazard_ptr(), get_threads_hazard_ptr(), is_hazard_ptr_tagged() access
 187   friend class ScanHazardPtrGatherThreadsListClosure;  // for get_threads_hazard_ptr(), untag_hazard_ptr() access
 188   friend class ScanHazardPtrPrintMatchingThreadsClosure;  // for get_threads_hazard_ptr(), is_hazard_ptr_tagged() access
 189   friend class ThreadsSMRSupport;  // for _nested_threads_hazard_ptr_cnt, _threads_hazard_ptr, _threads_list_ptr access
 190   friend class ThreadsListHandleTest;  // for _nested_threads_hazard_ptr_cnt, _threads_hazard_ptr, _threads_list_ptr access
 191   friend class ValidateHazardPtrsClosure;  // for get_threads_hazard_ptr(), untag_hazard_ptr() access
 192 
 193   ThreadsList* volatile _threads_hazard_ptr;
 194   SafeThreadsListPtr*   _threads_list_ptr;
 195   ThreadsList*          cmpxchg_threads_hazard_ptr(ThreadsList* exchange_value, ThreadsList* compare_value);
 196   ThreadsList*          get_threads_hazard_ptr() const;
 197   void                  set_threads_hazard_ptr(ThreadsList* new_list);
 198   static bool           is_hazard_ptr_tagged(ThreadsList* list) {
 199     return (intptr_t(list) & intptr_t(1)) == intptr_t(1);
 200   }
 201   static ThreadsList*   tag_hazard_ptr(ThreadsList* list) {
 202     return (ThreadsList*)(intptr_t(list) | intptr_t(1));
 203   }
 204   static ThreadsList*   untag_hazard_ptr(ThreadsList* list) {
 205     return (ThreadsList*)(intptr_t(list) & ~intptr_t(1));
 206   }
 207   // This field is enabled via -XX:+EnableThreadSMRStatistics:
 208   uint _nested_threads_hazard_ptr_cnt;
 209   void dec_nested_threads_hazard_ptr_cnt() {
 210     assert(_nested_threads_hazard_ptr_cnt != 0, "mismatched {dec,inc}_nested_threads_hazard_ptr_cnt()");
 211     _nested_threads_hazard_ptr_cnt--;
 212   }
 213   void inc_nested_threads_hazard_ptr_cnt() {
 214     _nested_threads_hazard_ptr_cnt++;
 215   }
 216   uint nested_threads_hazard_ptr_cnt() {
 217     return _nested_threads_hazard_ptr_cnt;
 218   }
 219 
 220  public:
 221   // Is the target JavaThread protected by the calling Thread
 222   // or by some other mechanism:
 223   static bool is_JavaThread_protected(const JavaThread* p);
 224 
 225   void* operator new(size_t size) throw() { return allocate(size, true); }
 226   void* operator new(size_t size, const std::nothrow_t& nothrow_constant) throw() {
 227     return allocate(size, false); }
 228   void  operator delete(void* p);
 229 
 230  protected:
 231   static void* allocate(size_t size, bool throw_excpt, MEMFLAGS flags = mtThread);
 232 
 233  private:
 234   DEBUG_ONLY(bool _suspendible_thread;)
 235 
 236  public:
 237   // Determines if a heap allocation failure will be retried
 238   // (e.g., by deoptimizing and re-executing in the interpreter).
 239   // In this case, the failed allocation must raise
 240   // Universe::out_of_memory_error_retry() and omit side effects
 241   // such as JVMTI events and handling -XX:+HeapDumpOnOutOfMemoryError
 242   // and -XX:OnOutOfMemoryError.
 243   virtual bool in_retryable_allocation() const { return false; }
 244 
 245 #ifdef ASSERT
 246   void set_suspendible_thread() {
 247     _suspendible_thread = true;
 248   }
 249 
 250   void clear_suspendible_thread() {
 251     _suspendible_thread = false;
 252   }
 253 
 254   bool is_suspendible_thread() { return _suspendible_thread; }
 255 #endif
 256 
 257  private:
 258   // Active_handles points to a block of handles
 259   JNIHandleBlock* _active_handles;
 260 
 261   // One-element thread local free list
 262   JNIHandleBlock* _free_handle_block;
 263 
 264   // Point to the last handle mark
 265   HandleMark* _last_handle_mark;
 266 
 267   // Claim value for parallel iteration over threads.
 268   uintx _threads_do_token;
 269 
 270   // Support for GlobalCounter
 271  private:
 272   volatile uintx _rcu_counter;
 273  public:
 274   volatile uintx* get_rcu_counter() {
 275     return &_rcu_counter;
 276   }
 277 
 278  public:
 279   void set_last_handle_mark(HandleMark* mark)   { _last_handle_mark = mark; }
 280   HandleMark* last_handle_mark() const          { return _last_handle_mark; }
 281  private:
 282 
 283 #ifdef ASSERT
 284   ICRefillVerifier* _missed_ic_stub_refill_verifier;
 285 
 286  public:
 287   ICRefillVerifier* missed_ic_stub_refill_verifier() {
 288     return _missed_ic_stub_refill_verifier;
 289   }
 290 
 291   void set_missed_ic_stub_refill_verifier(ICRefillVerifier* verifier) {
 292     _missed_ic_stub_refill_verifier = verifier;
 293   }
 294 #endif // ASSERT
 295 
 296  private:
 297   // Used by SkipGCALot class.
 298   NOT_PRODUCT(bool _skip_gcalot;)               // Should we elide gc-a-lot?
 299 
 300   friend class GCLocker;
 301 
 302  private:
 303   ThreadLocalAllocBuffer _tlab;                 // Thread-local eden
 304   jlong _allocated_bytes;                       // Cumulative number of bytes allocated on
 305                                                 // the Java heap
 306   ThreadHeapSampler _heap_sampler;              // For use when sampling the memory.
 307 
 308   ThreadStatisticalInfo _statistical_info;      // Statistics about the thread
 309 
 310   JFR_ONLY(DEFINE_THREAD_LOCAL_FIELD_JFR;)      // Thread-local data for jfr
 311 
 312   JvmtiRawMonitor* _current_pending_raw_monitor; // JvmtiRawMonitor this thread
 313                                                  // is waiting to lock
 314  public:
 315   // Constructor
 316   Thread();
 317   virtual ~Thread() = 0;        // Thread is abstract.
 318 
 319   // Manage Thread::current()
 320   void initialize_thread_current();
 321   static void clear_thread_current(); // TLS cleanup needed before threads terminate
 322 
 323  protected:
 324   // To be implemented by children.
 325   virtual void run() = 0;
 326   virtual void pre_run() = 0;
 327   virtual void post_run() = 0;  // Note: Thread must not be deleted prior to calling this!
 328 
 329 #ifdef ASSERT
 330   enum RunState {
 331     PRE_CALL_RUN,
 332     CALL_RUN,
 333     PRE_RUN,
 334     RUN,
 335     POST_RUN
 336     // POST_CALL_RUN - can't define this one as 'this' may be deleted when we want to set it
 337   };
 338   RunState _run_state;  // for lifecycle checks
 339 #endif
 340 
 341 
 342  public:
 343   // invokes <ChildThreadClass>::run(), with common preparations and cleanups.
 344   void call_run();
 345 
 346   // Testers
 347   virtual bool is_VM_thread()       const            { return false; }
 348   virtual bool is_Java_thread()     const            { return false; }
 349   virtual bool is_Compiler_thread() const            { return false; }
 350   virtual bool is_Code_cache_sweeper_thread() const  { return false; }
 351   virtual bool is_service_thread() const             { return false; }
 352   virtual bool is_monitor_deflation_thread() const   { return false; }
 353   virtual bool is_hidden_from_external_view() const  { return false; }
 354   virtual bool is_jvmti_agent_thread() const         { return false; }
 355   virtual bool is_Watcher_thread() const             { return false; }
 356   virtual bool is_ConcurrentGC_thread() const        { return false; }
 357   virtual bool is_Named_thread() const               { return false; }
 358   virtual bool is_Worker_thread() const              { return false; }
 359   virtual bool is_JfrSampler_thread() const          { return false; }
 360 
 361   // Can this thread make Java upcalls
 362   virtual bool can_call_java() const                 { return false; }
 363 
 364   // Is this a JavaThread that is on the VM's current ThreadsList?
 365   // If so it must participate in the safepoint protocol.
 366   virtual bool is_active_Java_thread() const         { return false; }
 367 
 368   // All threads are given names. For singleton subclasses we can
 369   // just hard-wire the known name of the instance. JavaThreads and
 370   // NamedThreads support multiple named instances, and dynamic
 371   // changing of the name of an instance.
 372   virtual const char* name() const { return "Unknown thread"; }
 373 
 374   // A thread's type name is also made available for debugging
 375   // and logging.
 376   virtual const char* type_name() const { return "Thread"; }
 377 
 378   // Returns the current thread (ASSERTS if NULL)
 379   static inline Thread* current();
 380   // Returns the current thread, or NULL if not attached
 381   static inline Thread* current_or_null();
 382   // Returns the current thread, or NULL if not attached, and is
 383   // safe for use from signal-handlers
 384   static inline Thread* current_or_null_safe();
 385 
 386   // Common thread operations
 387 #ifdef ASSERT
 388   static void check_for_dangling_thread_pointer(Thread *thread);
 389 #endif
 390   static void set_priority(Thread* thread, ThreadPriority priority);
 391   static ThreadPriority get_priority(const Thread* const thread);
 392   static void start(Thread* thread);
 393 
 394   void set_native_thread_name(const char *name) {
 395     assert(Thread::current() == this, "set_native_thread_name can only be called on the current thread");
 396     os::set_native_thread_name(name);
 397   }
 398 
 399   // Support for Unhandled Oop detection
 400   // Add the field for both, fastdebug and debug, builds to keep
 401   // Thread's fields layout the same.
 402   // Note: CHECK_UNHANDLED_OOPS is defined only for fastdebug build.
 403 #ifdef CHECK_UNHANDLED_OOPS
 404  private:
 405   UnhandledOops* _unhandled_oops;
 406 #elif defined(ASSERT)
 407  private:
 408   void* _unhandled_oops;
 409 #endif
 410 #ifdef CHECK_UNHANDLED_OOPS
 411  public:
 412   UnhandledOops* unhandled_oops() { return _unhandled_oops; }
 413   // Mark oop safe for gc.  It may be stack allocated but won't move.
 414   void allow_unhandled_oop(oop *op) {
 415     if (CheckUnhandledOops) unhandled_oops()->allow_unhandled_oop(op);
 416   }
 417   // Clear oops at safepoint so crashes point to unhandled oop violator
 418   void clear_unhandled_oops() {
 419     if (CheckUnhandledOops) unhandled_oops()->clear_unhandled_oops();
 420   }
 421 #endif // CHECK_UNHANDLED_OOPS
 422 
 423  public:
 424 #ifndef PRODUCT
 425   bool skip_gcalot()           { return _skip_gcalot; }
 426   void set_skip_gcalot(bool v) { _skip_gcalot = v;    }
 427 #endif
 428 
 429   // Resource area
 430   ResourceArea* resource_area() const            { return _resource_area; }
 431   void set_resource_area(ResourceArea* area)     { _resource_area = area; }
 432 
 433   OSThread* osthread() const                     { return _osthread;   }
 434   void set_osthread(OSThread* thread)            { _osthread = thread; }
 435 
 436   // JNI handle support
 437   JNIHandleBlock* active_handles() const         { return _active_handles; }
 438   void set_active_handles(JNIHandleBlock* block) { _active_handles = block; }
 439   JNIHandleBlock* free_handle_block() const      { return _free_handle_block; }
 440   void set_free_handle_block(JNIHandleBlock* block) { _free_handle_block = block; }
 441 
 442   // Internal handle support
 443   HandleArea* handle_area() const                { return _handle_area; }
 444   void set_handle_area(HandleArea* area)         { _handle_area = area; }
 445 
 446   GrowableArray<Metadata*>* metadata_handles() const          { return _metadata_handles; }
 447   void set_metadata_handles(GrowableArray<Metadata*>* handles){ _metadata_handles = handles; }
 448 
 449   // Thread-Local Allocation Buffer (TLAB) support
 450   ThreadLocalAllocBuffer& tlab()                 { return _tlab; }
 451   void initialize_tlab();
 452 
 453   jlong allocated_bytes()               { return _allocated_bytes; }
 454   void set_allocated_bytes(jlong value) { _allocated_bytes = value; }
 455   void incr_allocated_bytes(jlong size) { _allocated_bytes += size; }
 456   inline jlong cooked_allocated_bytes();
 457 
 458   ThreadHeapSampler& heap_sampler()     { return _heap_sampler; }
 459 
 460   ThreadStatisticalInfo& statistical_info() { return _statistical_info; }
 461 
 462   JFR_ONLY(DEFINE_THREAD_LOCAL_ACCESSOR_JFR;)
 463 
 464   // For tracking the Jvmti raw monitor the thread is pending on.
 465   JvmtiRawMonitor* current_pending_raw_monitor() {
 466     return _current_pending_raw_monitor;
 467   }
 468   void set_current_pending_raw_monitor(JvmtiRawMonitor* monitor) {
 469     _current_pending_raw_monitor = monitor;
 470   }
 471 
 472   // GC support
 473   // Apply "f->do_oop" to all root oops in "this".
 474   //   Used by JavaThread::oops_do.
 475   // Apply "cf->do_code_blob" (if !NULL) to all code blobs active in frames
 476   virtual void oops_do_no_frames(OopClosure* f, CodeBlobClosure* cf);
 477   virtual void oops_do_frames(OopClosure* f, CodeBlobClosure* cf) {}
 478   void oops_do(OopClosure* f, CodeBlobClosure* cf);
 479 
 480   // Handles the parallel case for claim_threads_do.
 481  private:
 482   bool claim_par_threads_do(uintx claim_token);
 483  public:
 484   // Requires that "claim_token" is that of the current iteration.
 485   // If "is_par" is false, sets the token of "this" to
 486   // "claim_token", and returns "true".  If "is_par" is true,
 487   // uses an atomic instruction to set the current thread's token to
 488   // "claim_token", if it is not already.  Returns "true" iff the
 489   // calling thread does the update, this indicates that the calling thread
 490   // has claimed the thread in the current iteration.
 491   bool claim_threads_do(bool is_par, uintx claim_token) {
 492     if (!is_par) {
 493       _threads_do_token = claim_token;
 494       return true;
 495     } else {
 496       return claim_par_threads_do(claim_token);
 497     }
 498   }
 499 
 500   uintx threads_do_token() const { return _threads_do_token; }
 501 
 502   // jvmtiRedefineClasses support
 503   void metadata_handles_do(void f(Metadata*));
 504 
 505  private:
 506   // Check if address is within the given range of this thread's
 507   // stack:  stack_base() > adr >/>= limit
 508   // The check is inclusive of limit if passed true, else exclusive.
 509   bool is_in_stack_range(address adr, address limit, bool inclusive) const {
 510     assert(stack_base() > limit && limit >= stack_end(), "limit is outside of stack");
 511     return stack_base() > adr && (inclusive ? adr >= limit : adr > limit);
 512   }
 513 
 514  public:
 515   // Used by fast lock support
 516   virtual bool is_lock_owned(address adr) const;
 517 
 518   // Check if address is within the given range of this thread's
 519   // stack:  stack_base() > adr >= limit
 520   bool is_in_stack_range_incl(address adr, address limit) const {
 521     return is_in_stack_range(adr, limit, true);
 522   }
 523 
 524   // Check if address is within the given range of this thread's
 525   // stack:  stack_base() > adr > limit
 526   bool is_in_stack_range_excl(address adr, address limit) const {
 527     return is_in_stack_range(adr, limit, false);
 528   }
 529 
 530   // Check if address is in the stack mapped to this thread. Used mainly in
 531   // error reporting (so has to include guard zone) and frame printing.
 532   // Expects _stack_base to be initialized - checked with assert.
 533   bool is_in_full_stack_checked(address adr) const {
 534     return is_in_stack_range_incl(adr, stack_end());
 535   }
 536 
 537   // Like is_in_full_stack_checked but without the assertions as this
 538   // may be called in a thread before _stack_base is initialized.
 539   bool is_in_full_stack(address adr) const {
 540     address stack_end = _stack_base - _stack_size;
 541     return _stack_base > adr && adr >= stack_end;
 542   }
 543 
 544   // Check if address is in the live stack of this thread (not just for locks).
 545   // Warning: can only be called by the current thread on itself.
 546   bool is_in_live_stack(address adr) const {
 547     assert(Thread::current() == this, "is_in_live_stack can only be called from current thread");
 548     return is_in_stack_range_incl(adr, os::current_stack_pointer());
 549   }
 550 
 551   // Sets this thread as starting thread. Returns failure if thread
 552   // creation fails due to lack of memory, too many threads etc.
 553   bool set_as_starting_thread();
 554 
 555 protected:
 556   // OS data associated with the thread
 557   OSThread* _osthread;  // Platform-specific thread information
 558 
 559   // Thread local resource area for temporary allocation within the VM
 560   ResourceArea* _resource_area;
 561 
 562   DEBUG_ONLY(ResourceMark* _current_resource_mark;)
 563 
 564   // Thread local handle area for allocation of handles within the VM
 565   HandleArea* _handle_area;
 566   GrowableArray<Metadata*>* _metadata_handles;
 567 
 568   // Support for stack overflow handling, get_thread, etc.
 569   address          _stack_base;
 570   size_t           _stack_size;
 571   int              _lgrp_id;
 572 
 573  public:
 574   // Stack overflow support
 575   address stack_base() const           { assert(_stack_base != NULL,"Sanity check"); return _stack_base; }
 576   void    set_stack_base(address base) { _stack_base = base; }
 577   size_t  stack_size() const           { return _stack_size; }
 578   void    set_stack_size(size_t size)  { _stack_size = size; }
 579   address stack_end()  const           { return stack_base() - stack_size(); }
 580   void    record_stack_base_and_size();
 581   void    register_thread_stack_with_NMT() NOT_NMT_RETURN;
 582   void    unregister_thread_stack_with_NMT() NOT_NMT_RETURN;
 583 
 584   int     lgrp_id() const        { return _lgrp_id; }
 585   void    set_lgrp_id(int value) { _lgrp_id = value; }
 586 
 587   // Printing
 588   void print_on(outputStream* st, bool print_extended_info) const;
 589   virtual void print_on(outputStream* st) const { print_on(st, false); }
 590   void print() const;
 591   virtual void print_on_error(outputStream* st, char* buf, int buflen) const;
 592   // Basic, non-virtual, printing support that is simple and always safe.
 593   void print_value_on(outputStream* st) const;
 594 
 595   // Debug-only code
 596 #ifdef ASSERT
 597  private:
 598   // Deadlock detection support for Mutex locks. List of locks own by thread.
 599   Mutex* _owned_locks;
 600   // Mutex::set_owner_implementation is the only place where _owned_locks is modified,
 601   // thus the friendship
 602   friend class Mutex;
 603   friend class Monitor;
 604 
 605  public:
 606   void print_owned_locks_on(outputStream* st) const;
 607   void print_owned_locks() const                 { print_owned_locks_on(tty);    }
 608   Mutex* owned_locks() const                     { return _owned_locks;          }
 609   bool owns_locks() const                        { return owned_locks() != NULL; }
 610 
 611   // Deadlock detection
 612   ResourceMark* current_resource_mark()          { return _current_resource_mark; }
 613   void set_current_resource_mark(ResourceMark* rm) { _current_resource_mark = rm; }
 614 #endif // ASSERT
 615 
 616  private:
 617   volatile int _jvmti_env_iteration_count;
 618 
 619  public:
 620   void entering_jvmti_env_iteration()            { ++_jvmti_env_iteration_count; }
 621   void leaving_jvmti_env_iteration()             { --_jvmti_env_iteration_count; }
 622   bool is_inside_jvmti_env_iteration()           { return _jvmti_env_iteration_count > 0; }
 623 
 624   // Code generation
 625   static ByteSize exception_file_offset()        { return byte_offset_of(Thread, _exception_file); }
 626   static ByteSize exception_line_offset()        { return byte_offset_of(Thread, _exception_line); }
 627   static ByteSize active_handles_offset()        { return byte_offset_of(Thread, _active_handles); }
 628 
 629   static ByteSize stack_base_offset()            { return byte_offset_of(Thread, _stack_base); }
 630   static ByteSize stack_size_offset()            { return byte_offset_of(Thread, _stack_size); }
 631 
 632   static ByteSize tlab_start_offset()            { return byte_offset_of(Thread, _tlab) + ThreadLocalAllocBuffer::start_offset(); }
 633   static ByteSize tlab_end_offset()              { return byte_offset_of(Thread, _tlab) + ThreadLocalAllocBuffer::end_offset(); }
 634   static ByteSize tlab_top_offset()              { return byte_offset_of(Thread, _tlab) + ThreadLocalAllocBuffer::top_offset(); }
 635   static ByteSize tlab_pf_top_offset()           { return byte_offset_of(Thread, _tlab) + ThreadLocalAllocBuffer::pf_top_offset(); }
 636 
 637   static ByteSize allocated_bytes_offset()       { return byte_offset_of(Thread, _allocated_bytes); }
 638 
 639   JFR_ONLY(DEFINE_THREAD_LOCAL_OFFSET_JFR;)
 640 
 641  public:
 642   ParkEvent * volatile _ParkEvent;            // for Object monitors, JVMTI raw monitors,
 643                                               // and ObjectSynchronizer::read_stable_mark
 644 
 645   // Termination indicator used by the signal handler.
 646   // _ParkEvent is just a convenient field we can NULL out after setting the JavaThread termination state
 647   // (which can't itself be read from the signal handler if a signal hits during the Thread destructor).
 648   bool has_terminated()                       { return Atomic::load(&_ParkEvent) == NULL; };
 649 
 650   jint _hashStateW;                           // Marsaglia Shift-XOR thread-local RNG
 651   jint _hashStateX;                           // thread-specific hashCode generator state
 652   jint _hashStateY;
 653   jint _hashStateZ;
 654 
 655   // Low-level leaf-lock primitives used to implement synchronization.
 656   // Not for general synchronization use.
 657   static void SpinAcquire(volatile int * Lock, const char * Name);
 658   static void SpinRelease(volatile int * Lock);
 659 
 660 #if defined(__APPLE__) && defined(AARCH64)
 661  private:
 662   DEBUG_ONLY(bool _wx_init);
 663   WXMode _wx_state;
 664  public:
 665   void init_wx();
 666   WXMode enable_wx(WXMode new_state);
 667 
 668   void assert_wx_state(WXMode expected) {
 669     assert(_wx_state == expected, "wrong state");
 670   }
 671 #endif // __APPLE__ && AARCH64
 672 };
 673 
 674 // Inline implementation of Thread::current()
 675 inline Thread* Thread::current() {
 676   Thread* current = current_or_null();
 677   assert(current != NULL, "Thread::current() called on detached thread");
 678   return current;
 679 }
 680 
 681 inline Thread* Thread::current_or_null() {
 682 #ifndef USE_LIBRARY_BASED_TLS_ONLY
 683   return _thr_current;
 684 #else
 685   if (ThreadLocalStorage::is_initialized()) {
 686     return ThreadLocalStorage::thread();
 687   }
 688   return NULL;
 689 #endif
 690 }
 691 
 692 inline Thread* Thread::current_or_null_safe() {
 693   if (ThreadLocalStorage::is_initialized()) {
 694     return ThreadLocalStorage::thread();
 695   }
 696   return NULL;
 697 }
 698 
 699 class CompilerThread;
 700 
 701 typedef void (*ThreadFunction)(JavaThread*, TRAPS);
 702 
 703 class JavaThread: public Thread {
 704   friend class VMStructs;
 705   friend class JVMCIVMStructs;
 706   friend class WhiteBox;
 707   friend class ThreadsSMRSupport; // to access _threadObj for exiting_threads_oops_do
 708   friend class HandshakeState;
 709   friend class Continuation;
 710  private:
 711   bool           _on_thread_list;                // Is set when this JavaThread is added to the Threads list
 712   OopHandle      _threadObj;                     // The Java level thread object
 713   OopHandle      _vthread;
 714   OopHandle      _scopeLocalCache;
 715 
 716 #ifdef ASSERT
 717  private:
 718   int _java_call_counter;
 719 
 720  public:
 721   int  java_call_counter()                       { return _java_call_counter; }
 722   void inc_java_call_counter()                   { _java_call_counter++; }
 723   void dec_java_call_counter() {
 724     assert(_java_call_counter > 0, "Invalid nesting of JavaCallWrapper");
 725     _java_call_counter--;
 726   }
 727  private:  // restore original namespace restriction
 728 #endif  // ifdef ASSERT
 729 
 730   JavaFrameAnchor _anchor;                       // Encapsulation of current java frame and it state
 731 
 732   ThreadFunction _entry_point;
 733 
 734   JNIEnv        _jni_environment;
 735 
 736   // Deopt support
 737   DeoptResourceMark*  _deopt_mark;               // Holds special ResourceMark for deoptimization
 738 
 739   CompiledMethod*       _deopt_nmethod;         // CompiledMethod that is currently being deoptimized
 740   vframeArray*  _vframe_array_head;              // Holds the heap of the active vframeArrays
 741   vframeArray*  _vframe_array_last;              // Holds last vFrameArray we popped
 742   // Holds updates by JVMTI agents for compiled frames that cannot be performed immediately. They
 743   // will be carried out as soon as possible which, in most cases, is just before deoptimization of
 744   // the frame, when control returns to it.
 745   JvmtiDeferredUpdates* _jvmti_deferred_updates;
 746   GrowableArray<WeakHandle>* _keepalive_cleanup;
 747 
 748   // Handshake value for fixing 6243940. We need a place for the i2c
 749   // adapter to store the callee Method*. This value is NEVER live
 750   // across a gc point so it does NOT have to be gc'd
 751   // The handshake is open ended since we can't be certain that it will
 752   // be NULLed. This is because we rarely ever see the race and end up
 753   // in handle_wrong_method which is the backend of the handshake. See
 754   // code in i2c adapters and handle_wrong_method.
 755 
 756   Method*       _callee_target;
 757 
 758   // Used to pass back results to the interpreter or generated code running Java code.
 759   oop           _vm_result;    // oop result is GC-preserved
 760   Metadata*     _vm_result_2;  // non-oop result
 761 
 762   // See ReduceInitialCardMarks: this holds the precise space interval of
 763   // the most recent slow path allocation for which compiled code has
 764   // elided card-marks for performance along the fast-path.
 765   MemRegion     _deferred_card_mark;
 766 
 767   ObjectMonitor* volatile _current_pending_monitor;     // ObjectMonitor this thread is waiting to lock
 768   bool           _current_pending_monitor_is_from_java; // locking is from Java code
 769   ObjectMonitor* volatile _current_waiting_monitor;     // ObjectMonitor on which this thread called Object.wait()
 770  public:
 771   volatile intptr_t _Stalled;
 772 
 773   // For tracking the heavyweight monitor the thread is pending on.
 774   ObjectMonitor* current_pending_monitor() {
 775     // Use Atomic::load() to prevent data race between concurrent modification and
 776     // concurrent readers, e.g. ThreadService::get_current_contended_monitor().
 777     // Especially, reloading pointer from thread after NULL check must be prevented.
 778     return Atomic::load(&_current_pending_monitor);
 779   }
 780   void set_current_pending_monitor(ObjectMonitor* monitor) {
 781     Atomic::store(&_current_pending_monitor, monitor);
 782   }
 783   void set_current_pending_monitor_is_from_java(bool from_java) {
 784     _current_pending_monitor_is_from_java = from_java;
 785   }
 786   bool current_pending_monitor_is_from_java() {
 787     return _current_pending_monitor_is_from_java;
 788   }
 789   ObjectMonitor* current_waiting_monitor() {
 790     // See the comment in current_pending_monitor() above.
 791     return Atomic::load(&_current_waiting_monitor);
 792   }
 793   void set_current_waiting_monitor(ObjectMonitor* monitor) {
 794     Atomic::store(&_current_waiting_monitor, monitor);
 795   }
 796 
 797  private:
 798   MonitorChunk* _monitor_chunks;              // Contains the off stack monitors
 799                                               // allocated during deoptimization
 800                                               // and by JNI_MonitorEnter/Exit
 801 
 802   enum SuspendFlags {
 803     // NOTE: avoid using the sign-bit as cc generates different test code
 804     //       when the sign-bit is used, and sometimes incorrectly - see CR 6398077
 805     _has_async_exception    = 0x00000001U, // there is a pending async exception
 806     _trace_flag             = 0x00000004U, // call tracing backend
 807     _obj_deopt              = 0x00000008U, // suspend for object reallocation and relocking for JVMTI agent
 808     _thread_suspended       = 0x00000010U  // non-virtual thread is externally suspended
 809   };
 810 
 811   // various suspension related flags - atomically updated
 812   // overloaded with async exceptions so that we do a single check when transitioning from native->Java
 813   volatile uint32_t _suspend_flags;
 814 
 815   inline void set_suspend_flag(SuspendFlags f);
 816   inline void clear_suspend_flag(SuspendFlags f);
 817 
 818  public:
 819   inline void set_trace_flag();
 820   inline void clear_trace_flag();
 821   inline void set_obj_deopt_flag();
 822   inline void clear_obj_deopt_flag();
 823   bool is_trace_suspend()      { return (_suspend_flags & _trace_flag) != 0; }
 824   bool is_obj_deopt_suspend()  { return (_suspend_flags & _obj_deopt) != 0; }
 825 
 826   // Asynchronous exceptions support
 827  private:
 828   oop     _pending_async_exception;
 829 #ifdef ASSERT
 830   bool    _is_unsafe_access_error;
 831 #endif
 832 
 833   inline bool clear_async_exception_condition();
 834  public:
 835   bool has_async_exception_condition() {
 836     return (_suspend_flags & _has_async_exception) != 0;
 837   }
 838   inline void set_pending_async_exception(oop e);
 839   inline void set_pending_unsafe_access_error();
 840   static void send_async_exception(JavaThread* jt, oop java_throwable);
 841   void send_thread_stop(oop throwable);
 842   void check_and_handle_async_exceptions();
 843 
 844   // Safepoint support
 845  public:                                                        // Expose _thread_state for SafeFetchInt()
 846   volatile JavaThreadState _thread_state;
 847  private:
 848   SafepointMechanism::ThreadData _poll_data;
 849   ThreadSafepointState*          _safepoint_state;              // Holds information about a thread during a safepoint
 850   address                        _saved_exception_pc;           // Saved pc of instruction where last implicit exception happened
 851   NOT_PRODUCT(bool               _requires_cross_modify_fence;) // State used by VerifyCrossModifyFence
 852 #ifdef ASSERT
 853   // Debug support for checking if code allows safepoints or not.
 854   // Safepoints in the VM can happen because of allocation, invoking a VM operation, or blocking on
 855   // mutex, or blocking on an object synchronizer (Java locking).
 856   // If _no_safepoint_count is non-zero, then an assertion failure will happen in any of
 857   // the above cases. The class NoSafepointVerifier is used to set this counter.
 858   int _no_safepoint_count;                             // If 0, thread allow a safepoint to happen
 859 
 860  public:
 861   void inc_no_safepoint_count() { _no_safepoint_count++; }
 862   void dec_no_safepoint_count() { _no_safepoint_count--; }
 863 #endif // ASSERT
 864  public:
 865   // These functions check conditions before possibly going to a safepoint.
 866   // including NoSafepointVerifier.
 867   void check_for_valid_safepoint_state() NOT_DEBUG_RETURN;
 868   void check_possible_safepoint()        NOT_DEBUG_RETURN;
 869 
 870 #ifdef ASSERT
 871  private:
 872   volatile uint64_t _visited_for_critical_count;
 873 
 874  public:
 875   void set_visited_for_critical_count(uint64_t safepoint_id) {
 876     assert(_visited_for_critical_count == 0, "Must be reset before set");
 877     assert((safepoint_id & 0x1) == 1, "Must be odd");
 878     _visited_for_critical_count = safepoint_id;
 879   }
 880   void reset_visited_for_critical_count(uint64_t safepoint_id) {
 881     assert(_visited_for_critical_count == safepoint_id, "Was not visited");
 882     _visited_for_critical_count = 0;
 883   }
 884   bool was_visited_for_critical_count(uint64_t safepoint_id) const {
 885     return _visited_for_critical_count == safepoint_id;
 886   }
 887 #endif // ASSERT
 888 
 889   // JavaThread termination support
 890  public:
 891   enum TerminatedTypes {
 892     _not_terminated = 0xDEAD - 2,
 893     _thread_exiting,                             // JavaThread::exit() has been called for this thread
 894     _thread_terminated,                          // JavaThread is removed from thread list
 895     _vm_exited                                   // JavaThread is still executing native code, but VM is terminated
 896                                                  // only VM_Exit can set _vm_exited
 897   };
 898 
 899  private:
 900   // In general a JavaThread's _terminated field transitions as follows:
 901   //
 902   //   _not_terminated => _thread_exiting => _thread_terminated
 903   //
 904   // _vm_exited is a special value to cover the case of a JavaThread
 905   // executing native code after the VM itself is terminated.
 906   volatile TerminatedTypes _terminated;
 907 
 908   jint                  _in_deopt_handler;       // count of deoptimization
 909                                                  // handlers thread is in
 910   volatile bool         _doing_unsafe_access;    // Thread may fault due to unsafe access
 911   bool                  _do_not_unlock_if_synchronized;  // Do not unlock the receiver of a synchronized method (since it was
 912                                                          // never locked) when throwing an exception. Used by interpreter only.
 913 #if INCLUDE_JVMTI
 914   bool                  _is_in_VTMT;             // thread is in virtual thread mount transition
 915   bool                  _is_VTMT_disabler;       // thread currently disabled VTMT
 916 #endif
 917 
 918   // JNI attach states:
 919   enum JNIAttachStates {
 920     _not_attaching_via_jni = 1,  // thread is not attaching via JNI
 921     _attaching_via_jni,          // thread is attaching via JNI
 922     _attached_via_jni            // thread has attached via JNI
 923   };
 924 
 925   // A regular JavaThread's _jni_attach_state is _not_attaching_via_jni.
 926   // A native thread that is attaching via JNI starts with a value
 927   // of _attaching_via_jni and transitions to _attached_via_jni.
 928   volatile JNIAttachStates _jni_attach_state;
 929 
 930 
 931 #if INCLUDE_JVMCI
 932   // The _pending_* fields below are used to communicate extra information
 933   // from an uncommon trap in JVMCI compiled code to the uncommon trap handler.
 934 
 935   // Communicates the DeoptReason and DeoptAction of the uncommon trap
 936   int       _pending_deoptimization;
 937 
 938   // Specifies whether the uncommon trap is to bci 0 of a synchronized method
 939   // before the monitor has been acquired.
 940   bool      _pending_monitorenter;
 941 
 942   // Specifies if the DeoptReason for the last uncommon trap was Reason_transfer_to_interpreter
 943   bool      _pending_transfer_to_interpreter;
 944 
 945   // True if in a runtime call from compiled code that will deoptimize
 946   // and re-execute a failed heap allocation in the interpreter.
 947   bool      _in_retryable_allocation;
 948 
 949   // An id of a speculation that JVMCI compiled code can use to further describe and
 950   // uniquely identify the speculative optimization guarded by an uncommon trap.
 951   // See JVMCINMethodData::SPECULATION_LENGTH_BITS for further details.
 952   jlong     _pending_failed_speculation;
 953 
 954   // These fields are mutually exclusive in terms of live ranges.
 955   union {
 956     // Communicates the pc at which the most recent implicit exception occurred
 957     // from the signal handler to a deoptimization stub.
 958     address   _implicit_exception_pc;
 959 
 960     // Communicates an alternative call target to an i2c stub from a JavaCall .
 961     address   _alternate_call_target;
 962   } _jvmci;
 963 
 964   // Support for high precision, thread sensitive counters in JVMCI compiled code.
 965   jlong*    _jvmci_counters;
 966 
 967   // Fast thread locals for use by JVMCI
 968   jlong      _jvmci_reserved0;
 969   jlong      _jvmci_reserved1;
 970   oop        _jvmci_reserved_oop0;
 971 
 972  public:
 973   static jlong* _jvmci_old_thread_counters;
 974   static void collect_counters(jlong* array, int length);
 975 
 976   bool resize_counters(int current_size, int new_size);
 977 
 978   static bool resize_all_jvmci_counters(int new_size);
 979 
 980   void set_jvmci_reserved_oop0(oop value) {
 981     _jvmci_reserved_oop0 = value;
 982   }
 983 
 984   oop get_jvmci_reserved_oop0() {
 985     return _jvmci_reserved_oop0;
 986   }
 987 
 988   void set_jvmci_reserved0(jlong value) {
 989     _jvmci_reserved0 = value;
 990   }
 991 
 992   jlong get_jvmci_reserved0() {
 993     return _jvmci_reserved0;
 994   }
 995 
 996   void set_jvmci_reserved1(jlong value) {
 997     _jvmci_reserved1 = value;
 998   }
 999 
1000   jlong get_jvmci_reserved1() {
1001     return _jvmci_reserved1;
1002   }
1003 
1004  private:
1005 #endif // INCLUDE_JVMCI
1006 
1007   StackOverflow    _stack_overflow_state;
1008 
1009   // Compiler exception handling (NOTE: The _exception_oop is *NOT* the same as _pending_exception. It is
1010   // used to temp. parsing values into and out of the runtime system during exception handling for compiled
1011   // code)
1012   volatile oop     _exception_oop;               // Exception thrown in compiled code
1013   volatile address _exception_pc;                // PC where exception happened
1014   volatile address _exception_handler_pc;        // PC for handler of exception
1015   volatile int     _is_method_handle_return;     // true (== 1) if the current exception PC is a MethodHandle call site.
1016 
1017  private:
1018   // support for JNI critical regions
1019   jint    _jni_active_critical;                  // count of entries into JNI critical region
1020 
1021   // Checked JNI: function name requires exception check
1022   char* _pending_jni_exception_check_fn;
1023 
1024   // For deadlock detection.
1025   int _depth_first_number;
1026 
1027   // JVMTI PopFrame support
1028   // This is set to popframe_pending to signal that top Java frame should be popped immediately
1029   int _popframe_condition;
1030 
1031   // If reallocation of scalar replaced objects fails, we throw OOM
1032   // and during exception propagation, pop the top
1033   // _frames_to_pop_failed_realloc frames, the ones that reference
1034   // failed reallocations.
1035   int _frames_to_pop_failed_realloc;
1036 
1037   ContinuationEntry* _cont_entry;
1038   bool _cont_yield; // a continuation yield is in progress
1039   bool _cont_preempt;
1040   int _cont_fastpath_thread_state; // whether global thread state allows continuation fastpath (JVMTI)
1041   intptr_t* _cont_fastpath; // the sp of the oldest known interpreted/call_stub frame inside the continuation that we know about
1042   int _held_monitor_count; // used by continuations for fast lock detection
1043 private:
1044 
1045   friend class VMThread;
1046   friend class ThreadWaitTransition;
1047   friend class VM_Exit;
1048 
1049   // Stack watermark barriers.
1050   StackWatermarks _stack_watermarks;
1051 
1052  public:
1053   inline StackWatermarks* stack_watermarks() { return &_stack_watermarks; }
1054 
1055  public:
1056   oop _mounted_vthread;
1057   jlong _scopeLocal_hash_table_shift;
1058 
1059   void allocate_scopeLocal_hash_table(int count);
1060 
1061  public:
1062   // Constructor
1063   JavaThread();                            // delegating constructor
1064   JavaThread(bool is_attaching_via_jni);   // for main thread and JNI attached threads
1065   JavaThread(ThreadFunction entry_point, size_t stack_size = 0);
1066   ~JavaThread();
1067 
1068 #ifdef ASSERT
1069   // verify this JavaThread hasn't be published in the Threads::list yet
1070   void verify_not_published();
1071 #endif // ASSERT
1072 
1073   StackOverflow* stack_overflow_state() { return &_stack_overflow_state; }
1074 
1075   //JNI functiontable getter/setter for JVMTI jni function table interception API.
1076   void set_jni_functions(struct JNINativeInterface_* functionTable) {
1077     _jni_environment.functions = functionTable;
1078   }
1079   struct JNINativeInterface_* get_jni_functions() {
1080     return (struct JNINativeInterface_ *)_jni_environment.functions;
1081   }
1082 
1083   // This function is called at thread creation to allow
1084   // platform specific thread variables to be initialized.
1085   void cache_global_variables();
1086 
1087   // Executes Shutdown.shutdown()
1088   void invoke_shutdown_hooks();
1089 
1090   // Cleanup on thread exit
1091   enum ExitType {
1092     normal_exit,
1093     jni_detach
1094   };
1095   void exit(bool destroy_vm, ExitType exit_type = normal_exit);
1096 
1097   void cleanup_failed_attach_current_thread(bool is_daemon);
1098 
1099   // Testers
1100   virtual bool is_Java_thread() const            { return true;  }
1101   virtual bool can_call_java() const             { return true; }
1102 
1103   virtual bool is_active_Java_thread() const {
1104     return on_thread_list() && !is_terminated();
1105   }
1106 
1107   // Thread oop. threadObj() can be NULL for initial JavaThread
1108   // (or for threads attached via JNI)
1109   oop threadObj() const;
1110   void set_threadOopHandles(oop p);
1111   oop vthread() const;
1112   void set_vthread(oop p);
1113   oop scopeLocalCache() const;
1114   void set_scopeLocalCache(oop p);
1115   oop mounted_vthread() const                    { return _mounted_vthread; }
1116   void set_mounted_vthread(oop p)                { _mounted_vthread = p; }
1117 
1118   // Prepare thread and add to priority queue.  If a priority is
1119   // not specified, use the priority of the thread object. Threads_lock
1120   // must be held while this function is called.
1121   void prepare(jobject jni_thread, ThreadPriority prio=NoPriority);
1122 
1123   void set_saved_exception_pc(address pc)        { _saved_exception_pc = pc; }
1124   address saved_exception_pc()                   { return _saved_exception_pc; }
1125 
1126   ThreadFunction entry_point() const             { return _entry_point; }
1127 
1128   // Allocates a new Java level thread object for this thread. thread_name may be NULL.
1129   void allocate_threadObj(Handle thread_group, const char* thread_name, bool daemon, TRAPS);
1130 
1131   // Last frame anchor routines
1132 
1133   JavaFrameAnchor* frame_anchor(void)            { return &_anchor; }
1134 
1135   // last_Java_sp
1136   bool has_last_Java_frame() const               { return _anchor.has_last_Java_frame(); }
1137   intptr_t* last_Java_sp() const                 { return _anchor.last_Java_sp(); }
1138 
1139   // last_Java_pc
1140 
1141   address last_Java_pc(void)                     { return _anchor.last_Java_pc(); }
1142 
1143   // Safepoint support
1144   inline JavaThreadState thread_state() const;
1145   inline void set_thread_state(JavaThreadState s);
1146   inline void set_thread_state_fence(JavaThreadState s);  // fence after setting thread state
1147   inline ThreadSafepointState* safepoint_state() const;
1148   inline void set_safepoint_state(ThreadSafepointState* state);
1149   inline bool is_at_poll_safepoint();
1150 
1151   // JavaThread termination and lifecycle support:
1152   void smr_delete();
1153   bool on_thread_list() const { return _on_thread_list; }
1154   void set_on_thread_list() { _on_thread_list = true; }
1155 
1156   // thread has called JavaThread::exit() or is terminated
1157   bool is_exiting() const;
1158   // thread is terminated (no longer on the threads list); we compare
1159   // against the two non-terminated values so that a freed JavaThread
1160   // will also be considered terminated.
1161   bool check_is_terminated(TerminatedTypes l_terminated) const {
1162     return l_terminated != _not_terminated && l_terminated != _thread_exiting;
1163   }
1164   bool is_terminated() const;
1165   void set_terminated(TerminatedTypes t);
1166 
1167   void block_if_vm_exited();
1168 
1169   bool doing_unsafe_access()                     { return _doing_unsafe_access; }
1170   void set_doing_unsafe_access(bool val)         { _doing_unsafe_access = val; }
1171 
1172   bool do_not_unlock_if_synchronized()             { return _do_not_unlock_if_synchronized; }
1173   void set_do_not_unlock_if_synchronized(bool val) { _do_not_unlock_if_synchronized = val; }
1174 
1175   SafepointMechanism::ThreadData* poll_data() { return &_poll_data; }
1176 
1177   void set_requires_cross_modify_fence(bool val) PRODUCT_RETURN NOT_PRODUCT({ _requires_cross_modify_fence = val; })
1178 
1179   // Continuation support
1180   ContinuationEntry* last_continuation() const { return _cont_entry; }
1181   ContinuationEntry* last_continuation(oop cont_scope) const { return Continuation::last_continuation(this, cont_scope); }
1182   bool cont_yield() { return _cont_yield; }
1183   void set_cont_yield(bool x) { _cont_yield = x; }
1184   void set_cont_fastpath(intptr_t* x) { _cont_fastpath = x; }
1185   void push_cont_fastpath(intptr_t* sp) { if (sp > _cont_fastpath) _cont_fastpath = sp; }
1186   void set_cont_fastpath_thread_state(bool x) { _cont_fastpath_thread_state = (int)x; }
1187   intptr_t* raw_cont_fastpath() { return _cont_fastpath; }
1188   bool cont_fastpath() { return ((_cont_fastpath == NULL) & _cont_fastpath_thread_state) != 0; }
1189   bool cont_fastpath_thread_state() { return _cont_fastpath_thread_state != 0; }
1190   bool cont_preempt() { return _cont_preempt; }
1191   void set_cont_preempt(bool x) { _cont_preempt = x; }
1192   int held_monitor_count() { return _held_monitor_count; }
1193   void reset_held_monitor_count() { _held_monitor_count = 0; }
1194   void inc_held_monitor_count() { _held_monitor_count++; }
1195   void dec_held_monitor_count() { assert (_held_monitor_count > 0, ""); _held_monitor_count--; }
1196 
1197  private:
1198   DEBUG_ONLY(void verify_frame_info();)
1199 
1200   // Support for thread handshake operations
1201   HandshakeState _handshake;
1202  public:
1203   HandshakeState* handshake_state() { return &_handshake; }
1204 
1205   // A JavaThread can always safely operate on it self and other threads
1206   // can do it safely if they are the active handshaker.
1207   bool is_handshake_safe_for(Thread* th) const {
1208     return _handshake.active_handshaker() == th || this == th;
1209   }
1210 
1211   // Suspend/resume support for JavaThread
1212   // higher-level suspension/resume logic called by the public APIs
1213   bool java_suspend();
1214   bool java_resume();
1215   bool is_suspended()     { return _handshake.is_suspended(); }
1216 
1217   // lower-level blocking logic called by the JVM.  The caller suspends this
1218   // thread, does something, and then releases it.
1219   bool block_suspend(JavaThread* caller);
1220   bool continue_resume(JavaThread* caller);
1221 
1222   // Check for async exception in addition to safepoint.
1223   static void check_special_condition_for_native_trans(JavaThread *thread);
1224 
1225   // Synchronize with another thread that is deoptimizing objects of the
1226   // current thread, i.e. reverts optimizations based on escape analysis.
1227   void wait_for_object_deoptimization();
1228 
1229   inline void set_thread_suspended();
1230   inline void clear_thread_suspended();
1231 
1232   bool is_thread_suspended() const {
1233     return (_suspend_flags & _thread_suspended) != 0;
1234   }
1235 
1236 #if INCLUDE_JVMTI
1237   bool is_VTMT_disabler() const                  { return _is_VTMT_disabler; }
1238   bool is_in_VTMT() const                        { return _is_in_VTMT; }
1239 
1240   void set_is_in_VTMT(bool val);
1241   void set_is_VTMT_disabler(bool val);
1242 #endif
1243 
1244   bool is_cont_force_yield() { return cont_preempt(); }
1245 
1246   // these next two are also used for self-suspension and async exception support
1247   void handle_special_runtime_exit_condition(bool check_asyncs = true);
1248 
1249   // Return true if JavaThread has an asynchronous condition or
1250   // if external suspension is requested.
1251   bool has_special_runtime_exit_condition() {
1252     return (_suspend_flags & (_has_async_exception | _obj_deopt JFR_ONLY(| _trace_flag))) != 0
1253            || is_cont_force_yield();
1254   }
1255 
1256   // Fast-locking support
1257   bool is_lock_owned(address adr) const;
1258 
1259   // Accessors for vframe array top
1260   // The linked list of vframe arrays are sorted on sp. This means when we
1261   // unpack the head must contain the vframe array to unpack.
1262   void set_vframe_array_head(vframeArray* value) { _vframe_array_head = value; }
1263   vframeArray* vframe_array_head() const         { return _vframe_array_head;  }
1264 
1265   // Side structure for deferring update of java frame locals until deopt occurs
1266   JvmtiDeferredUpdates* deferred_updates() const      { return _jvmti_deferred_updates; }
1267   void set_deferred_updates(JvmtiDeferredUpdates* du) { _jvmti_deferred_updates = du; }
1268 
1269   void set_keepalive_cleanup(GrowableArray<WeakHandle>* lst) { _keepalive_cleanup = lst; }
1270   GrowableArray<WeakHandle>* keepalive_cleanup() const { return _keepalive_cleanup; }
1271 
1272   // These only really exist to make debugging deopt problems simpler
1273 
1274   void set_vframe_array_last(vframeArray* value) { _vframe_array_last = value; }
1275   vframeArray* vframe_array_last() const         { return _vframe_array_last;  }
1276 
1277   // The special resourceMark used during deoptimization
1278 
1279   void set_deopt_mark(DeoptResourceMark* value)  { _deopt_mark = value; }
1280   DeoptResourceMark* deopt_mark(void)            { return _deopt_mark; }
1281 
1282   void set_deopt_compiled_method(CompiledMethod* nm)  { _deopt_nmethod = nm; }
1283   CompiledMethod* deopt_compiled_method()        { return _deopt_nmethod; }
1284 
1285   Method*    callee_target() const               { return _callee_target; }
1286   void set_callee_target  (Method* x)          { _callee_target   = x; }
1287 
1288   // Oop results of vm runtime calls
1289   oop  vm_result() const                         { return _vm_result; }
1290   void set_vm_result  (oop x)                    { _vm_result   = x; }
1291 
1292   Metadata*    vm_result_2() const               { return _vm_result_2; }
1293   void set_vm_result_2  (Metadata* x)          { _vm_result_2   = x; }
1294 
1295   MemRegion deferred_card_mark() const           { return _deferred_card_mark; }
1296   void set_deferred_card_mark(MemRegion mr)      { _deferred_card_mark = mr;   }
1297 
1298 #if INCLUDE_JVMCI
1299   int  pending_deoptimization() const             { return _pending_deoptimization; }
1300   jlong pending_failed_speculation() const        { return _pending_failed_speculation; }
1301   bool has_pending_monitorenter() const           { return _pending_monitorenter; }
1302   void set_pending_monitorenter(bool b)           { _pending_monitorenter = b; }
1303   void set_pending_deoptimization(int reason)     { _pending_deoptimization = reason; }
1304   void set_pending_failed_speculation(jlong failed_speculation) { _pending_failed_speculation = failed_speculation; }
1305   void set_pending_transfer_to_interpreter(bool b) { _pending_transfer_to_interpreter = b; }
1306   void set_jvmci_alternate_call_target(address a) { assert(_jvmci._alternate_call_target == NULL, "must be"); _jvmci._alternate_call_target = a; }
1307   void set_jvmci_implicit_exception_pc(address a) { assert(_jvmci._implicit_exception_pc == NULL, "must be"); _jvmci._implicit_exception_pc = a; }
1308 
1309   virtual bool in_retryable_allocation() const    { return _in_retryable_allocation; }
1310   void set_in_retryable_allocation(bool b)        { _in_retryable_allocation = b; }
1311 #endif // INCLUDE_JVMCI
1312 
1313   // Exception handling for compiled methods
1314   oop      exception_oop() const;
1315   address  exception_pc() const                  { return _exception_pc; }
1316   address  exception_handler_pc() const          { return _exception_handler_pc; }
1317   bool     is_method_handle_return() const       { return _is_method_handle_return == 1; }
1318 
1319   void set_exception_oop(oop o);
1320   void set_exception_pc(address a)               { _exception_pc = a; }
1321   void set_exception_handler_pc(address a)       { _exception_handler_pc = a; }
1322   void set_is_method_handle_return(bool value)   { _is_method_handle_return = value ? 1 : 0; }
1323 
1324   void clear_exception_oop_and_pc() {
1325     set_exception_oop(NULL);
1326     set_exception_pc(NULL);
1327   }
1328 
1329   // Check if address is in the usable part of the stack (excludes protected
1330   // guard pages). Can be applied to any thread and is an approximation for
1331   // using is_in_live_stack when the query has to happen from another thread.
1332   bool is_in_usable_stack(address adr) const {
1333     return is_in_stack_range_incl(adr, _stack_overflow_state.stack_reserved_zone_base());
1334   }
1335 
1336   // Misc. accessors/mutators
1337   void set_do_not_unlock(void)                   { _do_not_unlock_if_synchronized = true; }
1338   void clr_do_not_unlock(void)                   { _do_not_unlock_if_synchronized = false; }
1339   bool do_not_unlock(void)                       { return _do_not_unlock_if_synchronized; }
1340 
1341   static ByteSize scopeLocalCache_offset()       { return byte_offset_of(JavaThread, _scopeLocalCache); }
1342 
1343   // For assembly stub generation
1344   static ByteSize threadObj_offset()             { return byte_offset_of(JavaThread, _threadObj); }
1345   static ByteSize vthread_offset()               { return byte_offset_of(JavaThread, _vthread); }
1346   static ByteSize jni_environment_offset()       { return byte_offset_of(JavaThread, _jni_environment); }
1347   static ByteSize pending_jni_exception_check_fn_offset() {
1348     return byte_offset_of(JavaThread, _pending_jni_exception_check_fn);
1349   }
1350   static ByteSize last_Java_sp_offset() {
1351     return byte_offset_of(JavaThread, _anchor) + JavaFrameAnchor::last_Java_sp_offset();
1352   }
1353   static ByteSize last_Java_pc_offset() {
1354     return byte_offset_of(JavaThread, _anchor) + JavaFrameAnchor::last_Java_pc_offset();
1355   }
1356   static ByteSize frame_anchor_offset() {
1357     return byte_offset_of(JavaThread, _anchor);
1358   }
1359   static ByteSize callee_target_offset()         { return byte_offset_of(JavaThread, _callee_target); }
1360   static ByteSize vm_result_offset()             { return byte_offset_of(JavaThread, _vm_result); }
1361   static ByteSize vm_result_2_offset()           { return byte_offset_of(JavaThread, _vm_result_2); }
1362   static ByteSize thread_state_offset()          { return byte_offset_of(JavaThread, _thread_state); }
1363   static ByteSize polling_word_offset()          { return byte_offset_of(JavaThread, _poll_data) + byte_offset_of(SafepointMechanism::ThreadData, _polling_word);}
1364   static ByteSize polling_page_offset()          { return byte_offset_of(JavaThread, _poll_data) + byte_offset_of(SafepointMechanism::ThreadData, _polling_page);}
1365   static ByteSize saved_exception_pc_offset()    { return byte_offset_of(JavaThread, _saved_exception_pc); }
1366   static ByteSize osthread_offset()              { return byte_offset_of(JavaThread, _osthread); }
1367 #if INCLUDE_JVMCI
1368   static ByteSize pending_deoptimization_offset() { return byte_offset_of(JavaThread, _pending_deoptimization); }
1369   static ByteSize pending_monitorenter_offset()  { return byte_offset_of(JavaThread, _pending_monitorenter); }
1370   static ByteSize pending_failed_speculation_offset() { return byte_offset_of(JavaThread, _pending_failed_speculation); }
1371   static ByteSize jvmci_alternate_call_target_offset() { return byte_offset_of(JavaThread, _jvmci._alternate_call_target); }
1372   static ByteSize jvmci_implicit_exception_pc_offset() { return byte_offset_of(JavaThread, _jvmci._implicit_exception_pc); }
1373   static ByteSize jvmci_counters_offset()        { return byte_offset_of(JavaThread, _jvmci_counters); }
1374 #endif // INCLUDE_JVMCI
1375   static ByteSize exception_oop_offset()         { return byte_offset_of(JavaThread, _exception_oop); }
1376   static ByteSize exception_pc_offset()          { return byte_offset_of(JavaThread, _exception_pc); }
1377   static ByteSize exception_handler_pc_offset()  { return byte_offset_of(JavaThread, _exception_handler_pc); }
1378   static ByteSize is_method_handle_return_offset() { return byte_offset_of(JavaThread, _is_method_handle_return); }
1379 
1380   // StackOverflow offsets
1381   static ByteSize stack_overflow_limit_offset()  {
1382     return byte_offset_of(JavaThread, _stack_overflow_state._stack_overflow_limit);
1383   }
1384   static ByteSize stack_guard_state_offset()     {
1385     return byte_offset_of(JavaThread, _stack_overflow_state._stack_guard_state);
1386   }
1387   static ByteSize reserved_stack_activation_offset() {
1388     return byte_offset_of(JavaThread, _stack_overflow_state._reserved_stack_activation);
1389   }
1390 
1391   static ByteSize suspend_flags_offset()         { return byte_offset_of(JavaThread, _suspend_flags); }
1392 
1393   static ByteSize do_not_unlock_if_synchronized_offset() { return byte_offset_of(JavaThread, _do_not_unlock_if_synchronized); }
1394   static ByteSize should_post_on_exceptions_flag_offset() {
1395     return byte_offset_of(JavaThread, _should_post_on_exceptions_flag);
1396   }
1397   static ByteSize doing_unsafe_access_offset() { return byte_offset_of(JavaThread, _doing_unsafe_access); }
1398   NOT_PRODUCT(static ByteSize requires_cross_modify_fence_offset()  { return byte_offset_of(JavaThread, _requires_cross_modify_fence); })
1399 
1400   static ByteSize cont_entry_offset()         { return byte_offset_of(JavaThread, _cont_entry); }
1401   static ByteSize cont_fastpath_offset()      { return byte_offset_of(JavaThread, _cont_fastpath); }
1402   static ByteSize cont_preempt_offset()       { return byte_offset_of(JavaThread, _cont_preempt); }
1403   static ByteSize held_monitor_count_offset() { return byte_offset_of(JavaThread, _held_monitor_count); }
1404 
1405   // Returns the jni environment for this thread
1406   JNIEnv* jni_environment()                      { return &_jni_environment; }
1407 
1408   static JavaThread* thread_from_jni_environment(JNIEnv* env) {
1409     JavaThread *thread_from_jni_env = (JavaThread*)((intptr_t)env - in_bytes(jni_environment_offset()));
1410     // Only return NULL if thread is off the thread list; starting to
1411     // exit should not return NULL.
1412     if (thread_from_jni_env->is_terminated()) {
1413       thread_from_jni_env->block_if_vm_exited();
1414       return NULL;
1415     } else {
1416       return thread_from_jni_env;
1417     }
1418   }
1419 
1420   // JNI critical regions. These can nest.
1421   bool in_critical()    { return _jni_active_critical > 0; }
1422   bool in_last_critical()  { return _jni_active_critical == 1; }
1423   inline void enter_critical();
1424   void exit_critical() {
1425     assert(Thread::current() == this, "this must be current thread");
1426     _jni_active_critical--;
1427     assert(_jni_active_critical >= 0, "JNI critical nesting problem?");
1428   }
1429 
1430   // Checked JNI: is the programmer required to check for exceptions, if so specify
1431   // which function name. Returning to a Java frame should implicitly clear the
1432   // pending check, this is done for Native->Java transitions (i.e. user JNI code).
1433   // VM->Java transistions are not cleared, it is expected that JNI code enclosed
1434   // within ThreadToNativeFromVM makes proper exception checks (i.e. VM internal).
1435   bool is_pending_jni_exception_check() const { return _pending_jni_exception_check_fn != NULL; }
1436   void clear_pending_jni_exception_check() { _pending_jni_exception_check_fn = NULL; }
1437   const char* get_pending_jni_exception_check() const { return _pending_jni_exception_check_fn; }
1438   void set_pending_jni_exception_check(const char* fn_name) { _pending_jni_exception_check_fn = (char*) fn_name; }
1439 
1440   // For deadlock detection
1441   int depth_first_number() { return _depth_first_number; }
1442   void set_depth_first_number(int dfn) { _depth_first_number = dfn; }
1443 
1444  private:
1445   void set_monitor_chunks(MonitorChunk* monitor_chunks) { _monitor_chunks = monitor_chunks; }
1446 
1447  public:
1448   MonitorChunk* monitor_chunks() const           { return _monitor_chunks; }
1449   void add_monitor_chunk(MonitorChunk* chunk);
1450   void remove_monitor_chunk(MonitorChunk* chunk);
1451   bool in_deopt_handler() const                  { return _in_deopt_handler > 0; }
1452   void inc_in_deopt_handler()                    { _in_deopt_handler++; }
1453   void dec_in_deopt_handler() {
1454     assert(_in_deopt_handler > 0, "mismatched deopt nesting");
1455     if (_in_deopt_handler > 0) { // robustness
1456       _in_deopt_handler--;
1457     }
1458   }
1459 
1460  private:
1461   void set_entry_point(ThreadFunction entry_point) { _entry_point = entry_point; }
1462 
1463   // factor out low-level mechanics for use in both normal and error cases
1464   const char* get_thread_name_string(char* buf = NULL, int buflen = 0) const;
1465 
1466  public:
1467 
1468   // Frame iteration; calls the function f for all frames on the stack
1469   void frames_do(void f(frame*, const RegisterMap*));
1470 
1471   // Memory operations
1472   void oops_do_frames(OopClosure* f, CodeBlobClosure* cf);
1473   void oops_do_no_frames(OopClosure* f, CodeBlobClosure* cf);
1474 
1475   // Sweeper operations
1476   virtual void nmethods_do(CodeBlobClosure* cf);
1477 
1478   // RedefineClasses Support
1479   void metadata_do(MetadataClosure* f);
1480 
1481   // Debug method asserting thread states are correct during a handshake operation.
1482   DEBUG_ONLY(void verify_states_for_handshake();)
1483 
1484   // Misc. operations
1485   const char* name() const;
1486   const char* type_name() const { return "JavaThread"; }
1487   static const char* name_for(oop thread_obj);
1488 
1489   void print_on(outputStream* st, bool print_extended_info) const;
1490   void print_on(outputStream* st) const { print_on(st, false); }
1491   void print() const;
1492   void print_thread_state_on(outputStream*) const;
1493   const char* thread_state_name() const;
1494   void print_on_error(outputStream* st, char* buf, int buflen) const;
1495   void print_name_on_error(outputStream* st, char* buf, int buflen) const;
1496   void verify();
1497 
1498   // Accessing frames
1499   frame last_frame() {
1500     _anchor.make_walkable(this);
1501     return pd_last_frame();
1502   }
1503   javaVFrame* last_java_vframe(RegisterMap* reg_map) { return last_java_vframe(last_frame(), reg_map); }
1504 
1505   frame vthread_carrier_last_frame(RegisterMap* reg_map);
1506   javaVFrame* vthread_carrier_last_java_vframe(RegisterMap* reg_map) { return last_java_vframe(vthread_carrier_last_frame(reg_map), reg_map); }
1507 
1508   javaVFrame* last_java_vframe(const frame f, RegisterMap* reg_map);
1509 
1510   // Returns method at 'depth' java or native frames down the stack
1511   // Used for security checks
1512   Klass* security_get_caller_class(int depth);
1513 
1514   // Print stack trace in external format
1515   void print_stack_on(outputStream* st);
1516   void print_stack() { print_stack_on(tty); }
1517 
1518   // Print stack traces in various internal formats
1519   void trace_stack()                             PRODUCT_RETURN;
1520   void trace_stack_from(vframe* start_vf)        PRODUCT_RETURN;
1521   void trace_frames()                            PRODUCT_RETURN;
1522 
1523   // Print an annotated view of the stack frames
1524   void print_frame_layout(int depth = 0, bool validate_only = false) NOT_DEBUG_RETURN;
1525   void validate_frame_layout() {
1526     print_frame_layout(0, true);
1527   }
1528 
1529   // Function for testing deoptimization
1530   void deoptimize();
1531   void make_zombies();
1532 
1533   void deoptimize_marked_methods();
1534   void deoptimize_marked_methods_only_anchors();
1535 
1536  public:
1537   // Returns the running thread as a JavaThread
1538   static JavaThread* current() {
1539     return JavaThread::cast(Thread::current());
1540   }
1541 
1542   // Returns the current thread as a JavaThread, or NULL if not attached
1543   static inline JavaThread* current_or_null();
1544 
1545   // Casts
1546   static JavaThread* cast(Thread* t) {
1547     assert(t->is_Java_thread(), "incorrect cast to JavaThread");
1548     return static_cast<JavaThread*>(t);
1549   }
1550 
1551   static const JavaThread* cast(const Thread* t) {
1552     assert(t->is_Java_thread(), "incorrect cast to const JavaThread");
1553     return static_cast<const JavaThread*>(t);
1554   }
1555 
1556   // Returns the active Java thread.  Do not use this if you know you are calling
1557   // from a JavaThread, as it's slower than JavaThread::current.  If called from
1558   // the VMThread, it also returns the JavaThread that instigated the VMThread's
1559   // operation.  You may not want that either.
1560   static JavaThread* active();
1561 
1562  protected:
1563   virtual void pre_run();
1564   virtual void run();
1565   void thread_main_inner();
1566   virtual void post_run();
1567 
1568  public:
1569   // Thread local information maintained by JVMTI.
1570   void set_jvmti_thread_state(JvmtiThreadState *value)                           { _jvmti_thread_state = value; }
1571   // A JvmtiThreadState is lazily allocated. This jvmti_thread_state()
1572   // getter is used to get this JavaThread's JvmtiThreadState if it has
1573   // one which means NULL can be returned. JvmtiThreadState::state_for()
1574   // is used to get the specified JavaThread's JvmtiThreadState if it has
1575   // one or it allocates a new JvmtiThreadState for the JavaThread and
1576   // returns it. JvmtiThreadState::state_for() will return NULL only if
1577   // the specified JavaThread is exiting.
1578   JvmtiThreadState *jvmti_thread_state() const                                   { return _jvmti_thread_state; }
1579   static ByteSize jvmti_thread_state_offset()                                    { return byte_offset_of(JavaThread, _jvmti_thread_state); }
1580 
1581 #if INCLUDE_JVMTI
1582   // Rebind JVMTI thread state from carrier to virtual or from virtual to carrier.
1583   JvmtiThreadState *rebind_to_jvmti_thread_state_of(oop thread_oop);
1584 #endif
1585 
1586   // JVMTI PopFrame support
1587   // Setting and clearing popframe_condition
1588   // All of these enumerated values are bits. popframe_pending
1589   // indicates that a PopFrame() has been requested and not yet been
1590   // completed. popframe_processing indicates that that PopFrame() is in
1591   // the process of being completed. popframe_force_deopt_reexecution_bit
1592   // indicates that special handling is required when returning to a
1593   // deoptimized caller.
1594   enum PopCondition {
1595     popframe_inactive                      = 0x00,
1596     popframe_pending_bit                   = 0x01,
1597     popframe_processing_bit                = 0x02,
1598     popframe_force_deopt_reexecution_bit   = 0x04
1599   };
1600   PopCondition popframe_condition()                   { return (PopCondition) _popframe_condition; }
1601   void set_popframe_condition(PopCondition c)         { _popframe_condition = c; }
1602   void set_popframe_condition_bit(PopCondition c)     { _popframe_condition |= c; }
1603   void clear_popframe_condition()                     { _popframe_condition = popframe_inactive; }
1604   static ByteSize popframe_condition_offset()         { return byte_offset_of(JavaThread, _popframe_condition); }
1605   bool has_pending_popframe()                         { return (popframe_condition() & popframe_pending_bit) != 0; }
1606   bool popframe_forcing_deopt_reexecution()           { return (popframe_condition() & popframe_force_deopt_reexecution_bit) != 0; }
1607   void clear_popframe_forcing_deopt_reexecution()     { _popframe_condition &= ~popframe_force_deopt_reexecution_bit; }
1608 
1609   bool pop_frame_in_process(void)                     { return ((_popframe_condition & popframe_processing_bit) != 0); }
1610   void set_pop_frame_in_process(void)                 { _popframe_condition |= popframe_processing_bit; }
1611   void clr_pop_frame_in_process(void)                 { _popframe_condition &= ~popframe_processing_bit; }
1612 
1613   int frames_to_pop_failed_realloc() const            { return _frames_to_pop_failed_realloc; }
1614   void set_frames_to_pop_failed_realloc(int nb)       { _frames_to_pop_failed_realloc = nb; }
1615   void dec_frames_to_pop_failed_realloc()             { _frames_to_pop_failed_realloc--; }
1616 
1617  private:
1618   // Saved incoming arguments to popped frame.
1619   // Used only when popped interpreted frame returns to deoptimized frame.
1620   void*    _popframe_preserved_args;
1621   int      _popframe_preserved_args_size;
1622 
1623  public:
1624   void  popframe_preserve_args(ByteSize size_in_bytes, void* start);
1625   void* popframe_preserved_args();
1626   ByteSize popframe_preserved_args_size();
1627   WordSize popframe_preserved_args_size_in_words();
1628   void  popframe_free_preserved_args();
1629 
1630 
1631  private:
1632   JvmtiThreadState *_jvmti_thread_state;
1633 
1634   // Used by the interpreter in fullspeed mode for frame pop, method
1635   // entry, method exit and single stepping support. This field is
1636   // only set to non-zero at a safepoint or using a direct handshake
1637   // (see EnterInterpOnlyModeClosure).
1638   // It can be set to zero asynchronously to this threads execution (i.e., without
1639   // safepoint/handshake or a lock) so we have to be very careful.
1640   // Accesses by other threads are synchronized using JvmtiThreadState_lock though.
1641   int               _interp_only_mode;
1642 
1643  public:
1644   // used by the interpreter for fullspeed debugging support (see above)
1645   static ByteSize interp_only_mode_offset() { return byte_offset_of(JavaThread, _interp_only_mode); }
1646   bool is_interp_only_mode()                { return (_interp_only_mode != 0); }
1647   int get_interp_only_mode()                { return _interp_only_mode; }
1648   int set_interp_only_mode(int val)         { return _interp_only_mode = val; }
1649   void increment_interp_only_mode()         { ++_interp_only_mode; }
1650   void decrement_interp_only_mode()         { --_interp_only_mode; }
1651 
1652   // support for cached flag that indicates whether exceptions need to be posted for this thread
1653   // if this is false, we can avoid deoptimizing when events are thrown
1654   // this gets set to reflect whether jvmtiExport::post_exception_throw would actually do anything
1655  private:
1656   int    _should_post_on_exceptions_flag;
1657 
1658  public:
1659   int   should_post_on_exceptions_flag()  { return _should_post_on_exceptions_flag; }
1660   void  set_should_post_on_exceptions_flag(int val)  { _should_post_on_exceptions_flag = val; }
1661 
1662  private:
1663   ThreadStatistics *_thread_stat;
1664 
1665  public:
1666   ThreadStatistics* get_thread_stat() const    { return _thread_stat; }
1667 
1668   // Return a blocker object for which this thread is blocked parking.
1669   oop current_park_blocker();
1670 
1671  private:
1672   static size_t _stack_size_at_create;
1673 
1674  public:
1675   static inline size_t stack_size_at_create(void) {
1676     return _stack_size_at_create;
1677   }
1678   static inline void set_stack_size_at_create(size_t value) {
1679     _stack_size_at_create = value;
1680   }
1681 
1682   // Machine dependent stuff
1683 #include OS_CPU_HEADER(thread)
1684 
1685   // JSR166 per-thread parker
1686  private:
1687   Parker _parker;
1688  public:
1689   Parker* parker() { return &_parker; }
1690 
1691  public:
1692   // clearing/querying jni attach status
1693   bool is_attaching_via_jni() const { return _jni_attach_state == _attaching_via_jni; }
1694   bool has_attached_via_jni() const { return is_attaching_via_jni() || _jni_attach_state == _attached_via_jni; }
1695   inline void set_done_attaching_via_jni();
1696 
1697   // Stack dump assistance:
1698   // Track the class we want to initialize but for which we have to wait
1699   // on its init_lock() because it is already being initialized.
1700   void set_class_to_be_initialized(InstanceKlass* k);
1701   InstanceKlass* class_to_be_initialized() const;
1702 
1703 private:
1704   InstanceKlass* _class_to_be_initialized;
1705 
1706   // java.lang.Thread.sleep support
1707   ParkEvent * _SleepEvent;
1708 public:
1709   bool sleep(jlong millis);
1710 
1711   // java.lang.Thread interruption support
1712   void interrupt();
1713   bool is_interrupted(bool clear_interrupted);
1714 
1715   static OopStorage* thread_oop_storage();
1716 
1717   static void verify_cross_modify_fence_failure(JavaThread *thread) PRODUCT_RETURN;
1718 
1719   // Helper function to create the java.lang.Thread object for a
1720   // VM-internal thread. The thread will have the given name, be
1721   // part of the System ThreadGroup and if is_visible is true will be
1722   // discoverable via the system ThreadGroup.
1723   static Handle create_system_thread_object(const char* name, bool is_visible, TRAPS);
1724 
1725   // Helper function to start a VM-internal daemon thread.
1726   // E.g. ServiceThread, NotificationThread, CompilerThread etc.
1727   static void start_internal_daemon(JavaThread* current, JavaThread* target,
1728                                     Handle thread_oop, ThreadPriority prio);
1729 
1730   // Helper function to do vm_exit_on_initialization for osthread
1731   // resource allocation failure.
1732   static void vm_exit_on_osthread_failure(JavaThread* thread);
1733 };
1734 
1735 inline JavaThread* JavaThread::current_or_null() {
1736   Thread* current = Thread::current_or_null();
1737   return current != nullptr ? JavaThread::cast(current) : nullptr;
1738 }
1739 
1740 // The active thread queue. It also keeps track of the current used
1741 // thread priorities.
1742 class Threads: AllStatic {
1743   friend class VMStructs;
1744  private:
1745   static int         _number_of_threads;
1746   static int         _number_of_non_daemon_threads;
1747   static int         _return_code;
1748   static uintx       _thread_claim_token;
1749 #ifdef ASSERT
1750   static bool        _vm_complete;
1751 #endif
1752 
1753   static void initialize_java_lang_classes(JavaThread* main_thread, TRAPS);
1754   static void initialize_jsr292_core_classes(TRAPS);
1755 
1756  public:
1757   // Thread management
1758   // force_daemon is a concession to JNI, where we may need to add a
1759   // thread to the thread list before allocating its thread object
1760   static void add(JavaThread* p, bool force_daemon = false);
1761   static void remove(JavaThread* p, bool is_daemon);
1762   static void non_java_threads_do(ThreadClosure* tc);
1763   static void java_threads_do(ThreadClosure* tc);
1764   static void java_threads_and_vm_thread_do(ThreadClosure* tc);
1765   static void threads_do(ThreadClosure* tc);
1766   static void possibly_parallel_threads_do(bool is_par, ThreadClosure* tc);
1767 
1768   // Initializes the vm and creates the vm thread
1769   static jint create_vm(JavaVMInitArgs* args, bool* canTryAgain);
1770   static void convert_vm_init_libraries_to_agents();
1771   static void create_vm_init_libraries();
1772   static void create_vm_init_agents();
1773   static void shutdown_vm_agents();
1774   static void destroy_vm();
1775   // Supported VM versions via JNI
1776   // Includes JNI_VERSION_1_1
1777   static jboolean is_supported_jni_version_including_1_1(jint version);
1778   // Does not include JNI_VERSION_1_1
1779   static jboolean is_supported_jni_version(jint version);
1780 
1781   // The "thread claim token" provides a way for threads to be claimed
1782   // by parallel worker tasks.
1783   //
1784   // Each thread contains a "token" field. A task will claim the
1785   // thread only if its token is different from the global token,
1786   // which is updated by calling change_thread_claim_token().  When
1787   // a thread is claimed, it's token is set to the global token value
1788   // so other threads in the same iteration pass won't claim it.
1789   //
1790   // For this to work change_thread_claim_token() needs to be called
1791   // exactly once in sequential code before starting parallel tasks
1792   // that should claim threads.
1793   //
1794   // New threads get their token set to 0 and change_thread_claim_token()
1795   // never sets the global token to 0.
1796   static uintx thread_claim_token() { return _thread_claim_token; }
1797   static void change_thread_claim_token();
1798   static void assert_all_threads_claimed() NOT_DEBUG_RETURN;
1799 
1800   // Apply "f->do_oop" to all root oops in all threads.
1801   // This version may only be called by sequential code.
1802   static void oops_do(OopClosure* f, CodeBlobClosure* cf);
1803   // This version may be called by sequential or parallel code.
1804   static void possibly_parallel_oops_do(bool is_par, OopClosure* f, CodeBlobClosure* cf);
1805 
1806   // RedefineClasses support
1807   static void metadata_do(MetadataClosure* f);
1808   static void metadata_handles_do(void f(Metadata*));
1809 
1810 #ifdef ASSERT
1811   static bool is_vm_complete() { return _vm_complete; }
1812 #endif // ASSERT
1813 
1814   // Verification
1815   static void verify();
1816   static void print_on(outputStream* st, bool print_stacks, bool internal_format, bool print_concurrent_locks, bool print_extended_info);
1817   static void print(bool print_stacks, bool internal_format) {
1818     // this function is only used by debug.cpp
1819     print_on(tty, print_stacks, internal_format, false /* no concurrent lock printed */, false /* simple format */);
1820   }
1821   static void print_on_error(outputStream* st, Thread* current, char* buf, int buflen);
1822   static void print_on_error(Thread* this_thread, outputStream* st, Thread* current, char* buf,
1823                              int buflen, bool* found_current);
1824   static void print_threads_compiling(outputStream* st, char* buf, int buflen, bool short_form = false);
1825 
1826   // Get Java threads that are waiting to enter a monitor.
1827   static GrowableArray<JavaThread*>* get_pending_threads(ThreadsList * t_list,
1828                                                          int count, address monitor);
1829 
1830   // Get owning Java thread from the monitor's owner field.
1831   static JavaThread *owning_thread_from_monitor_owner(ThreadsList * t_list,
1832                                                       address owner);
1833 
1834   // Number of threads on the active threads list
1835   static int number_of_threads()                 { return _number_of_threads; }
1836   // Number of non-daemon threads on the active threads list
1837   static int number_of_non_daemon_threads()      { return _number_of_non_daemon_threads; }
1838 
1839   // Deoptimizes all frames tied to marked nmethods
1840   static void deoptimized_wrt_marked_nmethods();
1841 
1842   struct Test;                  // For private gtest access.
1843 };
1844 
1845 class UnlockFlagSaver {
1846   private:
1847     JavaThread* _thread;
1848     bool _do_not_unlock;
1849   public:
1850     UnlockFlagSaver(JavaThread* t) {
1851       _thread = t;
1852       _do_not_unlock = t->do_not_unlock_if_synchronized();
1853       t->set_do_not_unlock_if_synchronized(false);
1854     }
1855     ~UnlockFlagSaver() {
1856       _thread->set_do_not_unlock_if_synchronized(_do_not_unlock);
1857     }
1858 };
1859 
1860 #endif // SHARE_RUNTIME_THREAD_HPP