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