1 /*
   2  * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #ifndef SHARE_VM_RUNTIME_THREAD_HPP
  26 #define SHARE_VM_RUNTIME_THREAD_HPP
  27 
  28 #include "jni.h"
  29 #include "code/compiledMethod.hpp"
  30 #include "gc/shared/gcThreadLocalData.hpp"
  31 #include "gc/shared/threadLocalAllocBuffer.hpp"
  32 #include "memory/allocation.hpp"
  33 #include "oops/oop.hpp"
  34 #include "prims/jvmtiExport.hpp"
  35 #include "runtime/frame.hpp"
  36 #include "runtime/globals.hpp"
  37 #include "runtime/handshake.hpp"
  38 #include "runtime/javaFrameAnchor.hpp"
  39 #include "runtime/jniHandles.hpp"
  40 #include "runtime/mutexLocker.hpp"
  41 #include "runtime/os.hpp"
  42 #include "runtime/osThread.hpp"
  43 #include "runtime/park.hpp"
  44 #include "runtime/stubRoutines.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/macros.hpp"
  52 #ifdef ZERO
  53 # include "stack_zero.hpp"
  54 #endif
  55 #if INCLUDE_JFR
  56 #include "jfr/support/jfrThreadExtension.hpp"
  57 #endif
  58 
  59 
  60 class SafeThreadsListPtr;
  61 class ThreadSafepointState;
  62 class ThreadsList;
  63 class ThreadsSMRSupport;
  64 
  65 class JvmtiThreadState;
  66 class ThreadStatistics;
  67 class ConcurrentLocksDump;
  68 class ParkEvent;
  69 class Parker;
  70 
  71 class ciEnv;
  72 class CompileThread;
  73 class CompileLog;
  74 class CompileTask;
  75 class CompileQueue;
  76 class CompilerCounters;
  77 class vframeArray;
  78 
  79 class DeoptResourceMark;
  80 class jvmtiDeferredLocalVariableSet;
  81 
  82 class GCTaskQueue;
  83 class ThreadClosure;
  84 class ICRefillVerifier;
  85 class IdealGraphPrinter;
  86 
  87 class Metadata;
  88 template <class T, MEMFLAGS F> class ChunkedList;
  89 typedef ChunkedList<Metadata*, mtInternal> MetadataOnStackBuffer;
  90 
  91 DEBUG_ONLY(class ResourceMark;)
  92 
  93 class WorkerThread;
  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 //         - GCTaskThread
 106 //     - WatcherThread
 107 //     - JfrThreadSampler
 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 class Thread: public ThreadShadow {
 114   friend class VMStructs;
 115   friend class JVMCIVMStructs;
 116  private:
 117 
 118 #ifndef USE_LIBRARY_BASED_TLS_ONLY
 119   // Current thread is maintained as a thread-local variable
 120   static THREAD_LOCAL_DECL Thread* _thr_current;
 121 #endif
 122 
 123  private:
 124   // Thread local data area available to the GC. The internal
 125   // structure and contents of this data area is GC-specific.
 126   // Only GC and GC barrier code should access this data area.
 127   GCThreadLocalData _gc_data;
 128 
 129  public:
 130   static ByteSize gc_data_offset() {
 131     return byte_offset_of(Thread, _gc_data);
 132   }
 133 
 134   template <typename T> T* gc_data() {
 135     STATIC_ASSERT(sizeof(T) <= sizeof(_gc_data));
 136     return reinterpret_cast<T*>(&_gc_data);
 137   }
 138 
 139   // Exception handling
 140   // (Note: _pending_exception and friends are in ThreadShadow)
 141   //oop       _pending_exception;                // pending exception for current thread
 142   // const char* _exception_file;                   // file information for exception (debugging only)
 143   // int         _exception_line;                   // line information for exception (debugging only)
 144  protected:
 145   // Support for forcing alignment of thread objects for biased locking
 146   void*       _real_malloc_address;
 147 
 148   // JavaThread lifecycle support:
 149   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
 150   friend class ScanHazardPtrGatherProtectedThreadsClosure;  // for cmpxchg_threads_hazard_ptr(), get_threads_hazard_ptr(), is_hazard_ptr_tagged() access
 151   friend class ScanHazardPtrGatherThreadsListClosure;  // for get_threads_hazard_ptr(), untag_hazard_ptr() access
 152   friend class ScanHazardPtrPrintMatchingThreadsClosure;  // for get_threads_hazard_ptr(), is_hazard_ptr_tagged() access
 153   friend class ThreadsSMRSupport;  // for _nested_threads_hazard_ptr_cnt, _threads_hazard_ptr, _threads_list_ptr access
 154 
 155   ThreadsList* volatile _threads_hazard_ptr;
 156   SafeThreadsListPtr*   _threads_list_ptr;
 157   ThreadsList*          cmpxchg_threads_hazard_ptr(ThreadsList* exchange_value, ThreadsList* compare_value);
 158   ThreadsList*          get_threads_hazard_ptr();
 159   void                  set_threads_hazard_ptr(ThreadsList* new_list);
 160   static bool           is_hazard_ptr_tagged(ThreadsList* list) {
 161     return (intptr_t(list) & intptr_t(1)) == intptr_t(1);
 162   }
 163   static ThreadsList*   tag_hazard_ptr(ThreadsList* list) {
 164     return (ThreadsList*)(intptr_t(list) | intptr_t(1));
 165   }
 166   static ThreadsList*   untag_hazard_ptr(ThreadsList* list) {
 167     return (ThreadsList*)(intptr_t(list) & ~intptr_t(1));
 168   }
 169   // This field is enabled via -XX:+EnableThreadSMRStatistics:
 170   uint _nested_threads_hazard_ptr_cnt;
 171   void dec_nested_threads_hazard_ptr_cnt() {
 172     assert(_nested_threads_hazard_ptr_cnt != 0, "mismatched {dec,inc}_nested_threads_hazard_ptr_cnt()");
 173     _nested_threads_hazard_ptr_cnt--;
 174   }
 175   void inc_nested_threads_hazard_ptr_cnt() {
 176     _nested_threads_hazard_ptr_cnt++;
 177   }
 178   uint nested_threads_hazard_ptr_cnt() {
 179     return _nested_threads_hazard_ptr_cnt;
 180   }
 181 
 182  public:
 183   void* operator new(size_t size) throw() { return allocate(size, true); }
 184   void* operator new(size_t size, const std::nothrow_t& nothrow_constant) throw() {
 185     return allocate(size, false); }
 186   void  operator delete(void* p);
 187 
 188  protected:
 189   static void* allocate(size_t size, bool throw_excpt, MEMFLAGS flags = mtThread);
 190  private:
 191 
 192   // ***************************************************************
 193   // Suspend and resume support
 194   // ***************************************************************
 195   //
 196   // VM suspend/resume no longer exists - it was once used for various
 197   // things including safepoints but was deprecated and finally removed
 198   // in Java 7. Because VM suspension was considered "internal" Java-level
 199   // suspension was considered "external", and this legacy naming scheme
 200   // remains.
 201   //
 202   // External suspend/resume requests come from JVM_SuspendThread,
 203   // JVM_ResumeThread, JVMTI SuspendThread, and finally JVMTI
 204   // ResumeThread. External
 205   // suspend requests cause _external_suspend to be set and external
 206   // resume requests cause _external_suspend to be cleared.
 207   // External suspend requests do not nest on top of other external
 208   // suspend requests. The higher level APIs reject suspend requests
 209   // for already suspended threads.
 210   //
 211   // The external_suspend
 212   // flag is checked by has_special_runtime_exit_condition() and java thread
 213   // will self-suspend when handle_special_runtime_exit_condition() is
 214   // called. Most uses of the _thread_blocked state in JavaThreads are
 215   // considered the same as being externally suspended; if the blocking
 216   // condition lifts, the JavaThread will self-suspend. Other places
 217   // where VM checks for external_suspend include:
 218   //   + mutex granting (do not enter monitors when thread is suspended)
 219   //   + state transitions from _thread_in_native
 220   //
 221   // In general, java_suspend() does not wait for an external suspend
 222   // request to complete. When it returns, the only guarantee is that
 223   // the _external_suspend field is true.
 224   //
 225   // wait_for_ext_suspend_completion() is used to wait for an external
 226   // suspend request to complete. External suspend requests are usually
 227   // followed by some other interface call that requires the thread to
 228   // be quiescent, e.g., GetCallTrace(). By moving the "wait time" into
 229   // the interface that requires quiescence, we give the JavaThread a
 230   // chance to self-suspend before we need it to be quiescent. This
 231   // improves overall suspend/query performance.
 232   //
 233   // _suspend_flags controls the behavior of java_ suspend/resume.
 234   // It must be set under the protection of SR_lock. Read from the flag is
 235   // OK without SR_lock as long as the value is only used as a hint.
 236   // (e.g., check _external_suspend first without lock and then recheck
 237   // inside SR_lock and finish the suspension)
 238   //
 239   // _suspend_flags is also overloaded for other "special conditions" so
 240   // that a single check indicates whether any special action is needed
 241   // eg. for async exceptions.
 242   // -------------------------------------------------------------------
 243   // Notes:
 244   // 1. The suspend/resume logic no longer uses ThreadState in OSThread
 245   // but we still update its value to keep other part of the system (mainly
 246   // JVMTI) happy. ThreadState is legacy code (see notes in
 247   // osThread.hpp).
 248   //
 249   // 2. It would be more natural if set_external_suspend() is private and
 250   // part of java_suspend(), but that probably would affect the suspend/query
 251   // performance. Need more investigation on this.
 252 
 253   // suspend/resume lock: used for self-suspend
 254   Monitor* _SR_lock;
 255 
 256  protected:
 257   enum SuspendFlags {
 258     // NOTE: avoid using the sign-bit as cc generates different test code
 259     //       when the sign-bit is used, and sometimes incorrectly - see CR 6398077
 260 
 261     _external_suspend       = 0x20000000U, // thread is asked to self suspend
 262     _ext_suspended          = 0x40000000U, // thread has self-suspended
 263     _deopt_suspend          = 0x10000000U, // thread needs to self suspend for deopt
 264 
 265     _has_async_exception    = 0x00000001U, // there is a pending async exception
 266     _critical_native_unlock = 0x00000002U, // Must call back to unlock JNI critical lock
 267 
 268     _trace_flag             = 0x00000004U  // call tracing backend
 269   };
 270 
 271   // various suspension related flags - atomically updated
 272   // overloaded for async exception checking in check_special_condition_for_native_trans.
 273   volatile uint32_t _suspend_flags;
 274 
 275  private:
 276   int _num_nested_signal;
 277 
 278   DEBUG_ONLY(bool _suspendible_thread;)
 279 
 280  public:
 281   void enter_signal_handler() { _num_nested_signal++; }
 282   void leave_signal_handler() { _num_nested_signal--; }
 283   bool is_inside_signal_handler() const { return _num_nested_signal > 0; }
 284 
 285   // Determines if a heap allocation failure will be retried
 286   // (e.g., by deoptimizing and re-executing in the interpreter).
 287   // In this case, the failed allocation must raise
 288   // Universe::out_of_memory_error_retry() and omit side effects
 289   // such as JVMTI events and handling -XX:+HeapDumpOnOutOfMemoryError
 290   // and -XX:OnOutOfMemoryError.
 291   virtual bool in_retryable_allocation() const { return false; }
 292 
 293 #ifdef ASSERT
 294   void set_suspendible_thread() {
 295     _suspendible_thread = true;
 296   }
 297 
 298   void clear_suspendible_thread() {
 299     _suspendible_thread = false;
 300   }
 301 
 302   bool is_suspendible_thread() { return _suspendible_thread; }
 303 #endif
 304 
 305  private:
 306   // Active_handles points to a block of handles
 307   JNIHandleBlock* _active_handles;
 308 
 309   // One-element thread local free list
 310   JNIHandleBlock* _free_handle_block;
 311 
 312   // Point to the last handle mark
 313   HandleMark* _last_handle_mark;
 314 
 315   // The parity of the last strong_roots iteration in which this thread was
 316   // claimed as a task.
 317   int _oops_do_parity;
 318 
 319   // Support for GlobalCounter
 320  private:
 321   volatile uintx _rcu_counter;
 322  public:
 323   volatile uintx* get_rcu_counter() {
 324     return &_rcu_counter;
 325   }
 326 
 327  public:
 328   void set_last_handle_mark(HandleMark* mark)   { _last_handle_mark = mark; }
 329   HandleMark* last_handle_mark() const          { return _last_handle_mark; }
 330  private:
 331 
 332 #ifdef ASSERT
 333   ICRefillVerifier* _missed_ic_stub_refill_verifier;
 334 
 335  public:
 336   ICRefillVerifier* missed_ic_stub_refill_verifier() {
 337     return _missed_ic_stub_refill_verifier;
 338   }
 339 
 340   void set_missed_ic_stub_refill_verifier(ICRefillVerifier* verifier) {
 341     _missed_ic_stub_refill_verifier = verifier;
 342   }
 343 #endif
 344 
 345  private:
 346 
 347   // debug support for checking if code does allow safepoints or not
 348   // GC points in the VM can happen because of allocation, invoking a VM operation, or blocking on
 349   // mutex, or blocking on an object synchronizer (Java locking).
 350   // If !allow_safepoint(), then an assertion failure will happen in any of the above cases
 351   // If !allow_allocation(), then an assertion failure will happen during allocation
 352   // (Hence, !allow_safepoint() => !allow_allocation()).
 353   //
 354   // The two classes NoSafepointVerifier and No_Allocation_Verifier are used to set these counters.
 355   //
 356   NOT_PRODUCT(int _allow_safepoint_count;)      // If 0, thread allow a safepoint to happen
 357   debug_only(int _allow_allocation_count;)     // If 0, the thread is allowed to allocate oops.
 358 
 359   // Used by SkipGCALot class.
 360   NOT_PRODUCT(bool _skip_gcalot;)               // Should we elide gc-a-lot?
 361 
 362   friend class NoAllocVerifier;
 363   friend class NoSafepointVerifier;
 364   friend class PauseNoSafepointVerifier;
 365   friend class GCLocker;
 366 
 367   volatile void* _polling_page;                 // Thread local polling page
 368 
 369   ThreadLocalAllocBuffer _tlab;                 // Thread-local eden
 370   jlong _allocated_bytes;                       // Cumulative number of bytes allocated on
 371                                                 // the Java heap
 372   ThreadHeapSampler _heap_sampler;              // For use when sampling the memory.
 373 
 374   ThreadStatisticalInfo _statistical_info;      // Statistics about the thread
 375 
 376   JFR_ONLY(DEFINE_THREAD_LOCAL_FIELD_JFR;)      // Thread-local data for jfr
 377 
 378   int   _vm_operation_started_count;            // VM_Operation support
 379   int   _vm_operation_completed_count;          // VM_Operation support
 380 
 381   ObjectMonitor* _current_pending_monitor;      // ObjectMonitor this thread
 382                                                 // is waiting to lock
 383   bool _current_pending_monitor_is_from_java;   // locking is from Java code
 384 
 385   // ObjectMonitor on which this thread called Object.wait()
 386   ObjectMonitor* _current_waiting_monitor;
 387 
 388   // Private thread-local objectmonitor list - a simple cache organized as a SLL.
 389  public:
 390   ObjectMonitor* omFreeList;
 391   int omFreeCount;                              // length of omFreeList
 392   int omFreeProvision;                          // reload chunk size
 393   ObjectMonitor* omInUseList;                   // SLL to track monitors in circulation
 394   int omInUseCount;                             // length of omInUseList
 395 
 396 #ifdef ASSERT
 397  private:
 398   bool _visited_for_critical_count;
 399 
 400  public:
 401   void set_visited_for_critical_count(bool z) { _visited_for_critical_count = z; }
 402   bool was_visited_for_critical_count() const   { return _visited_for_critical_count; }
 403 #endif
 404 
 405  public:
 406   enum {
 407     is_definitely_current_thread = true
 408   };
 409 
 410   // Constructor
 411   Thread();
 412   virtual ~Thread() = 0;        // Thread is abstract.
 413 
 414   // Manage Thread::current()
 415   void initialize_thread_current();
 416   static void clear_thread_current(); // TLS cleanup needed before threads terminate
 417 
 418  protected:
 419   // To be implemented by children.
 420   virtual void run() = 0;
 421 
 422  public:
 423   // invokes <ChildThreadClass>::run(), with common preparations and cleanups.
 424   void call_run();
 425 
 426   // Testers
 427   virtual bool is_VM_thread()       const            { return false; }
 428   virtual bool is_Java_thread()     const            { return false; }
 429   virtual bool is_Compiler_thread() const            { return false; }
 430   virtual bool is_Code_cache_sweeper_thread() const  { return false; }
 431   virtual bool is_hidden_from_external_view() const  { return false; }
 432   virtual bool is_jvmti_agent_thread() const         { return false; }
 433   // True iff the thread can perform GC operations at a safepoint.
 434   // Generally will be true only of VM thread and parallel GC WorkGang
 435   // threads.
 436   virtual bool is_GC_task_thread() const             { return false; }
 437   virtual bool is_Watcher_thread() const             { return false; }
 438   virtual bool is_ConcurrentGC_thread() const        { return false; }
 439   virtual bool is_Named_thread() const               { return false; }
 440   virtual bool is_Worker_thread() const              { return false; }
 441 
 442   // Can this thread make Java upcalls
 443   virtual bool can_call_java() const                 { return false; }
 444 
 445   // Casts
 446   virtual WorkerThread* as_Worker_thread() const     { return NULL; }
 447 
 448   virtual char* name() const { return (char*)"Unknown thread"; }
 449 
 450   // Returns the current thread (ASSERTS if NULL)
 451   static inline Thread* current();
 452   // Returns the current thread, or NULL if not attached
 453   static inline Thread* current_or_null();
 454   // Returns the current thread, or NULL if not attached, and is
 455   // safe for use from signal-handlers
 456   static inline Thread* current_or_null_safe();
 457 
 458   // Common thread operations
 459 #ifdef ASSERT
 460   static void check_for_dangling_thread_pointer(Thread *thread);
 461 #endif
 462   static void set_priority(Thread* thread, ThreadPriority priority);
 463   static ThreadPriority get_priority(const Thread* const thread);
 464   static void start(Thread* thread);
 465   static void interrupt(Thread* thr);
 466   static bool is_interrupted(Thread* thr, bool clear_interrupted);
 467 
 468   void set_native_thread_name(const char *name) {
 469     assert(Thread::current() == this, "set_native_thread_name can only be called on the current thread");
 470     os::set_native_thread_name(name);
 471   }
 472 
 473   ObjectMonitor** omInUseList_addr()             { return (ObjectMonitor **)&omInUseList; }
 474   Monitor* SR_lock() const                       { return _SR_lock; }
 475 
 476   bool has_async_exception() const { return (_suspend_flags & _has_async_exception) != 0; }
 477 
 478   inline void set_suspend_flag(SuspendFlags f);
 479   inline void clear_suspend_flag(SuspendFlags f);
 480 
 481   inline void set_has_async_exception();
 482   inline void clear_has_async_exception();
 483 
 484   bool do_critical_native_unlock() const { return (_suspend_flags & _critical_native_unlock) != 0; }
 485 
 486   inline void set_critical_native_unlock();
 487   inline void clear_critical_native_unlock();
 488 
 489   inline void set_trace_flag();
 490   inline void clear_trace_flag();
 491 
 492   // Support for Unhandled Oop detection
 493   // Add the field for both, fastdebug and debug, builds to keep
 494   // Thread's fields layout the same.
 495   // Note: CHECK_UNHANDLED_OOPS is defined only for fastdebug build.
 496 #ifdef CHECK_UNHANDLED_OOPS
 497  private:
 498   UnhandledOops* _unhandled_oops;
 499 #elif defined(ASSERT)
 500  private:
 501   void* _unhandled_oops;
 502 #endif
 503 #ifdef CHECK_UNHANDLED_OOPS
 504  public:
 505   UnhandledOops* unhandled_oops() { return _unhandled_oops; }
 506   // Mark oop safe for gc.  It may be stack allocated but won't move.
 507   void allow_unhandled_oop(oop *op) {
 508     if (CheckUnhandledOops) unhandled_oops()->allow_unhandled_oop(op);
 509   }
 510   // Clear oops at safepoint so crashes point to unhandled oop violator
 511   void clear_unhandled_oops() {
 512     if (CheckUnhandledOops) unhandled_oops()->clear_unhandled_oops();
 513   }
 514 #endif // CHECK_UNHANDLED_OOPS
 515 
 516  public:
 517 #ifndef PRODUCT
 518   bool skip_gcalot()           { return _skip_gcalot; }
 519   void set_skip_gcalot(bool v) { _skip_gcalot = v;    }
 520 #endif
 521 
 522   // Installs a pending exception to be inserted later
 523   static void send_async_exception(oop thread_oop, oop java_throwable);
 524 
 525   // Resource area
 526   ResourceArea* resource_area() const            { return _resource_area; }
 527   void set_resource_area(ResourceArea* area)     { _resource_area = area; }
 528 
 529   OSThread* osthread() const                     { return _osthread;   }
 530   void set_osthread(OSThread* thread)            { _osthread = thread; }
 531 
 532   // JNI handle support
 533   JNIHandleBlock* active_handles() const         { return _active_handles; }
 534   void set_active_handles(JNIHandleBlock* block) { _active_handles = block; }
 535   JNIHandleBlock* free_handle_block() const      { return _free_handle_block; }
 536   void set_free_handle_block(JNIHandleBlock* block) { _free_handle_block = block; }
 537 
 538   // Internal handle support
 539   HandleArea* handle_area() const                { return _handle_area; }
 540   void set_handle_area(HandleArea* area)         { _handle_area = area; }
 541 
 542   GrowableArray<Metadata*>* metadata_handles() const          { return _metadata_handles; }
 543   void set_metadata_handles(GrowableArray<Metadata*>* handles){ _metadata_handles = handles; }
 544 
 545   // Thread-Local Allocation Buffer (TLAB) support
 546   ThreadLocalAllocBuffer& tlab()                 { return _tlab; }
 547   void initialize_tlab() {
 548     if (UseTLAB) {
 549       tlab().initialize();
 550     }
 551   }
 552 
 553   jlong allocated_bytes()               { return _allocated_bytes; }
 554   void set_allocated_bytes(jlong value) { _allocated_bytes = value; }
 555   void incr_allocated_bytes(jlong size) { _allocated_bytes += size; }
 556   inline jlong cooked_allocated_bytes();
 557 
 558   ThreadHeapSampler& heap_sampler()     { return _heap_sampler; }
 559 
 560   ThreadStatisticalInfo& statistical_info() { return _statistical_info; }
 561 
 562   JFR_ONLY(DEFINE_THREAD_LOCAL_ACCESSOR_JFR;)
 563 
 564   bool is_trace_suspend()               { return (_suspend_flags & _trace_flag) != 0; }
 565 
 566   // VM operation support
 567   int vm_operation_ticket()                      { return ++_vm_operation_started_count; }
 568   int vm_operation_completed_count()             { return _vm_operation_completed_count; }
 569   void increment_vm_operation_completed_count()  { _vm_operation_completed_count++; }
 570 
 571   // For tracking the heavyweight monitor the thread is pending on.
 572   ObjectMonitor* current_pending_monitor() {
 573     return _current_pending_monitor;
 574   }
 575   void set_current_pending_monitor(ObjectMonitor* monitor) {
 576     _current_pending_monitor = monitor;
 577   }
 578   void set_current_pending_monitor_is_from_java(bool from_java) {
 579     _current_pending_monitor_is_from_java = from_java;
 580   }
 581   bool current_pending_monitor_is_from_java() {
 582     return _current_pending_monitor_is_from_java;
 583   }
 584 
 585   // For tracking the ObjectMonitor on which this thread called Object.wait()
 586   ObjectMonitor* current_waiting_monitor() {
 587     return _current_waiting_monitor;
 588   }
 589   void set_current_waiting_monitor(ObjectMonitor* monitor) {
 590     _current_waiting_monitor = monitor;
 591   }
 592 
 593   // GC support
 594   // Apply "f->do_oop" to all root oops in "this".
 595   //   Used by JavaThread::oops_do.
 596   // Apply "cf->do_code_blob" (if !NULL) to all code blobs active in frames
 597   virtual void oops_do(OopClosure* f, CodeBlobClosure* cf);
 598 
 599   // Handles the parallel case for the method below.
 600  private:
 601   bool claim_oops_do_par_case(int collection_parity);
 602  public:
 603   // Requires that "collection_parity" is that of the current roots
 604   // iteration.  If "is_par" is false, sets the parity of "this" to
 605   // "collection_parity", and returns "true".  If "is_par" is true,
 606   // uses an atomic instruction to set the current threads parity to
 607   // "collection_parity", if it is not already.  Returns "true" iff the
 608   // calling thread does the update, this indicates that the calling thread
 609   // has claimed the thread's stack as a root groop in the current
 610   // collection.
 611   bool claim_oops_do(bool is_par, int collection_parity) {
 612     if (!is_par) {
 613       _oops_do_parity = collection_parity;
 614       return true;
 615     } else {
 616       return claim_oops_do_par_case(collection_parity);
 617     }
 618   }
 619 
 620   // jvmtiRedefineClasses support
 621   void metadata_handles_do(void f(Metadata*));
 622 
 623   // Used by fast lock support
 624   virtual bool is_lock_owned(address adr) const;
 625 
 626   // Check if address is in the stack of the thread (not just for locks).
 627   // Warning: the method can only be used on the running thread
 628   bool is_in_stack(address adr) const;
 629   // Check if address is in the usable part of the stack (excludes protected
 630   // guard pages)
 631   bool is_in_usable_stack(address adr) const;
 632 
 633   // Sets this thread as starting thread. Returns failure if thread
 634   // creation fails due to lack of memory, too many threads etc.
 635   bool set_as_starting_thread();
 636 
 637 protected:
 638   // OS data associated with the thread
 639   OSThread* _osthread;  // Platform-specific thread information
 640 
 641   // Thread local resource area for temporary allocation within the VM
 642   ResourceArea* _resource_area;
 643 
 644   DEBUG_ONLY(ResourceMark* _current_resource_mark;)
 645 
 646   // Thread local handle area for allocation of handles within the VM
 647   HandleArea* _handle_area;
 648   GrowableArray<Metadata*>* _metadata_handles;
 649 
 650   // Support for stack overflow handling, get_thread, etc.
 651   address          _stack_base;
 652   size_t           _stack_size;
 653   uintptr_t        _self_raw_id;      // used by get_thread (mutable)
 654   int              _lgrp_id;
 655 
 656   volatile void** polling_page_addr() { return &_polling_page; }
 657 
 658  public:
 659   // Stack overflow support
 660   address stack_base() const           { assert(_stack_base != NULL,"Sanity check"); return _stack_base; }
 661   void    set_stack_base(address base) { _stack_base = base; }
 662   size_t  stack_size() const           { return _stack_size; }
 663   void    set_stack_size(size_t size)  { _stack_size = size; }
 664   address stack_end()  const           { return stack_base() - stack_size(); }
 665   void    record_stack_base_and_size();
 666   void    register_thread_stack_with_NMT() NOT_NMT_RETURN;
 667 
 668   bool    on_local_stack(address adr) const {
 669     // QQQ this has knowledge of direction, ought to be a stack method
 670     return (_stack_base >= adr && adr >= stack_end());
 671   }
 672 
 673   uintptr_t self_raw_id()                    { return _self_raw_id; }
 674   void      set_self_raw_id(uintptr_t value) { _self_raw_id = value; }
 675 
 676   int     lgrp_id() const        { return _lgrp_id; }
 677   void    set_lgrp_id(int value) { _lgrp_id = value; }
 678 
 679   // Printing
 680   void print_on(outputStream* st, bool print_extended_info) const;
 681   virtual void print_on(outputStream* st) const { print_on(st, false); }
 682   void print() const { print_on(tty); }
 683   virtual void print_on_error(outputStream* st, char* buf, int buflen) const;
 684   void print_value_on(outputStream* st) const;
 685 
 686   // Debug-only code
 687 #ifdef ASSERT
 688  private:
 689   // Deadlock detection support for Mutex locks. List of locks own by thread.
 690   Monitor* _owned_locks;
 691   // Mutex::set_owner_implementation is the only place where _owned_locks is modified,
 692   // thus the friendship
 693   friend class Mutex;
 694   friend class Monitor;
 695 
 696  public:
 697   void print_owned_locks_on(outputStream* st) const;
 698   void print_owned_locks() const                 { print_owned_locks_on(tty);    }
 699   Monitor* owned_locks() const                   { return _owned_locks;          }
 700   bool owns_locks() const                        { return owned_locks() != NULL; }
 701   bool owns_locks_but_compiled_lock() const;
 702   int oops_do_parity() const                     { return _oops_do_parity; }
 703 
 704   // Deadlock detection
 705   bool allow_allocation()                        { return _allow_allocation_count == 0; }
 706   ResourceMark* current_resource_mark()          { return _current_resource_mark; }
 707   void set_current_resource_mark(ResourceMark* rm) { _current_resource_mark = rm; }
 708 #endif
 709 
 710   void check_for_valid_safepoint_state(bool potential_vm_operation) PRODUCT_RETURN;
 711 
 712  private:
 713   volatile int _jvmti_env_iteration_count;
 714 
 715  public:
 716   void entering_jvmti_env_iteration()            { ++_jvmti_env_iteration_count; }
 717   void leaving_jvmti_env_iteration()             { --_jvmti_env_iteration_count; }
 718   bool is_inside_jvmti_env_iteration()           { return _jvmti_env_iteration_count > 0; }
 719 
 720   // Code generation
 721   static ByteSize exception_file_offset()        { return byte_offset_of(Thread, _exception_file); }
 722   static ByteSize exception_line_offset()        { return byte_offset_of(Thread, _exception_line); }
 723   static ByteSize active_handles_offset()        { return byte_offset_of(Thread, _active_handles); }
 724 
 725   static ByteSize stack_base_offset()            { return byte_offset_of(Thread, _stack_base); }
 726   static ByteSize stack_size_offset()            { return byte_offset_of(Thread, _stack_size); }
 727 
 728   static ByteSize polling_page_offset()          { return byte_offset_of(Thread, _polling_page); }
 729 
 730   static ByteSize tlab_start_offset()            { return byte_offset_of(Thread, _tlab) + ThreadLocalAllocBuffer::start_offset(); }
 731   static ByteSize tlab_end_offset()              { return byte_offset_of(Thread, _tlab) + ThreadLocalAllocBuffer::end_offset(); }
 732   static ByteSize tlab_top_offset()              { return byte_offset_of(Thread, _tlab) + ThreadLocalAllocBuffer::top_offset(); }
 733   static ByteSize tlab_pf_top_offset()           { return byte_offset_of(Thread, _tlab) + ThreadLocalAllocBuffer::pf_top_offset(); }
 734 
 735   static ByteSize allocated_bytes_offset()       { return byte_offset_of(Thread, _allocated_bytes); }
 736 
 737   JFR_ONLY(DEFINE_THREAD_LOCAL_OFFSET_JFR;)
 738 
 739  public:
 740   volatile intptr_t _Stalled;
 741   volatile int _TypeTag;
 742   ParkEvent * _ParkEvent;                     // for synchronized()
 743   ParkEvent * _SleepEvent;                    // for Thread.sleep
 744   ParkEvent * _MutexEvent;                    // for native internal Mutex/Monitor
 745   ParkEvent * _MuxEvent;                      // for low-level muxAcquire-muxRelease
 746   int NativeSyncRecursion;                    // diagnostic
 747 
 748   volatile int _OnTrap;                       // Resume-at IP delta
 749   jint _hashStateW;                           // Marsaglia Shift-XOR thread-local RNG
 750   jint _hashStateX;                           // thread-specific hashCode generator state
 751   jint _hashStateY;
 752   jint _hashStateZ;
 753 
 754   volatile jint rng[4];                      // RNG for spin loop
 755 
 756   // Low-level leaf-lock primitives used to implement synchronization
 757   // and native monitor-mutex infrastructure.
 758   // Not for general synchronization use.
 759   static void SpinAcquire(volatile int * Lock, const char * Name);
 760   static void SpinRelease(volatile int * Lock);
 761   static void muxAcquire(volatile intptr_t * Lock, const char * Name);
 762   static void muxAcquireW(volatile intptr_t * Lock, ParkEvent * ev);
 763   static void muxRelease(volatile intptr_t * Lock);
 764 };
 765 
 766 // Inline implementation of Thread::current()
 767 inline Thread* Thread::current() {
 768   Thread* current = current_or_null();
 769   assert(current != NULL, "Thread::current() called on detached thread");
 770   return current;
 771 }
 772 
 773 inline Thread* Thread::current_or_null() {
 774 #ifndef USE_LIBRARY_BASED_TLS_ONLY
 775   return _thr_current;
 776 #else
 777   if (ThreadLocalStorage::is_initialized()) {
 778     return ThreadLocalStorage::thread();
 779   }
 780   return NULL;
 781 #endif
 782 }
 783 
 784 inline Thread* Thread::current_or_null_safe() {
 785   if (ThreadLocalStorage::is_initialized()) {
 786     return ThreadLocalStorage::thread();
 787   }
 788   return NULL;
 789 }
 790 
 791 class NonJavaThread: public Thread {
 792   friend class VMStructs;
 793 
 794   NonJavaThread* volatile _next;
 795 
 796   class List;
 797   static List _the_list;
 798 
 799  public:
 800   NonJavaThread();
 801   ~NonJavaThread();
 802 
 803   class Iterator;
 804 };
 805 
 806 // Provides iteration over the list of NonJavaThreads.  Because list
 807 // management occurs in the NonJavaThread constructor and destructor,
 808 // entries in the list may not be fully constructed instances of a
 809 // derived class.  Threads created after an iterator is constructed
 810 // will not be visited by the iterator.  The scope of an iterator is a
 811 // critical section; there must be no safepoint checks in that scope.
 812 class NonJavaThread::Iterator : public StackObj {
 813   uint _protect_enter;
 814   NonJavaThread* _current;
 815 
 816   // Noncopyable.
 817   Iterator(const Iterator&);
 818   Iterator& operator=(const Iterator&);
 819 
 820 public:
 821   Iterator();
 822   ~Iterator();
 823 
 824   bool end() const { return _current == NULL; }
 825   NonJavaThread* current() const { return _current; }
 826   void step();
 827 };
 828 
 829 // Name support for threads.  non-JavaThread subclasses with multiple
 830 // uniquely named instances should derive from this.
 831 class NamedThread: public NonJavaThread {
 832   friend class VMStructs;
 833   enum {
 834     max_name_len = 64
 835   };
 836  private:
 837   char* _name;
 838   // log JavaThread being processed by oops_do
 839   JavaThread* _processed_thread;
 840   uint _gc_id; // The current GC id when a thread takes part in GC
 841 
 842  public:
 843   NamedThread();
 844   ~NamedThread();
 845   // May only be called once per thread.
 846   void set_name(const char* format, ...)  ATTRIBUTE_PRINTF(2, 3);
 847   void initialize_named_thread();
 848   virtual bool is_Named_thread() const { return true; }
 849   virtual char* name() const { return _name == NULL ? (char*)"Unknown Thread" : _name; }
 850   JavaThread *processed_thread() { return _processed_thread; }
 851   void set_processed_thread(JavaThread *thread) { _processed_thread = thread; }
 852   virtual void print_on(outputStream* st) const;
 853 
 854   void set_gc_id(uint gc_id) { _gc_id = gc_id; }
 855   uint gc_id() { return _gc_id; }
 856 };
 857 
 858 // Worker threads are named and have an id of an assigned work.
 859 class WorkerThread: public NamedThread {
 860  private:
 861   uint _id;
 862  public:
 863   WorkerThread() : _id(0)               { }
 864   virtual bool is_Worker_thread() const { return true; }
 865 
 866   virtual WorkerThread* as_Worker_thread() const {
 867     assert(is_Worker_thread(), "Dubious cast to WorkerThread*?");
 868     return (WorkerThread*) this;
 869   }
 870 
 871   void set_id(uint work_id)             { _id = work_id; }
 872   uint id() const                       { return _id; }
 873 };
 874 
 875 // A single WatcherThread is used for simulating timer interrupts.
 876 class WatcherThread: public NonJavaThread {
 877   friend class VMStructs;
 878  public:
 879   virtual void run();
 880 
 881  private:
 882   static WatcherThread* _watcher_thread;
 883 
 884   static bool _startable;
 885   // volatile due to at least one lock-free read
 886   volatile static bool _should_terminate;
 887  public:
 888   enum SomeConstants {
 889     delay_interval = 10                          // interrupt delay in milliseconds
 890   };
 891 
 892   // Constructor
 893   WatcherThread();
 894 
 895   // No destruction allowed
 896   ~WatcherThread() {
 897     guarantee(false, "WatcherThread deletion must fix the race with VM termination");
 898   }
 899 
 900   // Tester
 901   bool is_Watcher_thread() const                 { return true; }
 902 
 903   // Printing
 904   char* name() const { return (char*)"VM Periodic Task Thread"; }
 905   void print_on(outputStream* st) const;
 906   void unpark();
 907 
 908   // Returns the single instance of WatcherThread
 909   static WatcherThread* watcher_thread()         { return _watcher_thread; }
 910 
 911   // Create and start the single instance of WatcherThread, or stop it on shutdown
 912   static void start();
 913   static void stop();
 914   // Only allow start once the VM is sufficiently initialized
 915   // Otherwise the first task to enroll will trigger the start
 916   static void make_startable();
 917  private:
 918   int sleep() const;
 919 };
 920 
 921 
 922 class CompilerThread;
 923 
 924 typedef void (*ThreadFunction)(JavaThread*, TRAPS);
 925 
 926 class JavaThread: public Thread {
 927   friend class VMStructs;
 928   friend class JVMCIVMStructs;
 929   friend class WhiteBox;
 930  private:
 931   JavaThread*    _next;                          // The next thread in the Threads list
 932   bool           _on_thread_list;                // Is set when this JavaThread is added to the Threads list
 933   oop            _threadObj;                     // The Java level thread object
 934 
 935 #ifdef ASSERT
 936  private:
 937   int _java_call_counter;
 938 
 939  public:
 940   int  java_call_counter()                       { return _java_call_counter; }
 941   void inc_java_call_counter()                   { _java_call_counter++; }
 942   void dec_java_call_counter() {
 943     assert(_java_call_counter > 0, "Invalid nesting of JavaCallWrapper");
 944     _java_call_counter--;
 945   }
 946  private:  // restore original namespace restriction
 947 #endif  // ifdef ASSERT
 948 
 949 #ifndef PRODUCT
 950  public:
 951   enum {
 952     jump_ring_buffer_size = 16
 953   };
 954  private:  // restore original namespace restriction
 955 #endif
 956 
 957   JavaFrameAnchor _anchor;                       // Encapsulation of current java frame and it state
 958 
 959   ThreadFunction _entry_point;
 960 
 961   JNIEnv        _jni_environment;
 962 
 963   // Deopt support
 964   DeoptResourceMark*  _deopt_mark;               // Holds special ResourceMark for deoptimization
 965 
 966   intptr_t*      _must_deopt_id;                 // id of frame that needs to be deopted once we
 967                                                  // transition out of native
 968   CompiledMethod*       _deopt_nmethod;         // CompiledMethod that is currently being deoptimized
 969   vframeArray*  _vframe_array_head;              // Holds the heap of the active vframeArrays
 970   vframeArray*  _vframe_array_last;              // Holds last vFrameArray we popped
 971   // Because deoptimization is lazy we must save jvmti requests to set locals
 972   // in compiled frames until we deoptimize and we have an interpreter frame.
 973   // This holds the pointer to array (yeah like there might be more than one) of
 974   // description of compiled vframes that have locals that need to be updated.
 975   GrowableArray<jvmtiDeferredLocalVariableSet*>* _deferred_locals_updates;
 976 
 977   // Handshake value for fixing 6243940. We need a place for the i2c
 978   // adapter to store the callee Method*. This value is NEVER live
 979   // across a gc point so it does NOT have to be gc'd
 980   // The handshake is open ended since we can't be certain that it will
 981   // be NULLed. This is because we rarely ever see the race and end up
 982   // in handle_wrong_method which is the backend of the handshake. See
 983   // code in i2c adapters and handle_wrong_method.
 984 
 985   Method*       _callee_target;
 986 
 987   // Used to pass back results to the interpreter or generated code running Java code.
 988   oop           _vm_result;    // oop result is GC-preserved
 989   Metadata*     _vm_result_2;  // non-oop result
 990 
 991   // See ReduceInitialCardMarks: this holds the precise space interval of
 992   // the most recent slow path allocation for which compiled code has
 993   // elided card-marks for performance along the fast-path.
 994   MemRegion     _deferred_card_mark;
 995 
 996   MonitorChunk* _monitor_chunks;                 // Contains the off stack monitors
 997                                                  // allocated during deoptimization
 998                                                  // and by JNI_MonitorEnter/Exit
 999 
1000   // Async. requests support
1001   enum AsyncRequests {
1002     _no_async_condition = 0,
1003     _async_exception,
1004     _async_unsafe_access_error
1005   };
1006   AsyncRequests _special_runtime_exit_condition; // Enum indicating pending async. request
1007   oop           _pending_async_exception;
1008 
1009   // Safepoint support
1010  public:                                         // Expose _thread_state for SafeFetchInt()
1011   volatile JavaThreadState _thread_state;
1012  private:
1013   ThreadSafepointState* _safepoint_state;        // Holds information about a thread during a safepoint
1014   address               _saved_exception_pc;     // Saved pc of instruction where last implicit exception happened
1015 
1016   // JavaThread termination support
1017   enum TerminatedTypes {
1018     _not_terminated = 0xDEAD - 2,
1019     _thread_exiting,                             // JavaThread::exit() has been called for this thread
1020     _thread_terminated,                          // JavaThread is removed from thread list
1021     _vm_exited                                   // JavaThread is still executing native code, but VM is terminated
1022                                                  // only VM_Exit can set _vm_exited
1023   };
1024 
1025   // In general a JavaThread's _terminated field transitions as follows:
1026   //
1027   //   _not_terminated => _thread_exiting => _thread_terminated
1028   //
1029   // _vm_exited is a special value to cover the case of a JavaThread
1030   // executing native code after the VM itself is terminated.
1031   volatile TerminatedTypes _terminated;
1032   // suspend/resume support
1033   volatile bool         _suspend_equivalent;     // Suspend equivalent condition
1034   jint                  _in_deopt_handler;       // count of deoptimization
1035                                                  // handlers thread is in
1036   volatile bool         _doing_unsafe_access;    // Thread may fault due to unsafe access
1037   bool                  _do_not_unlock_if_synchronized;  // Do not unlock the receiver of a synchronized method (since it was
1038                                                          // never locked) when throwing an exception. Used by interpreter only.
1039 
1040   // JNI attach states:
1041   enum JNIAttachStates {
1042     _not_attaching_via_jni = 1,  // thread is not attaching via JNI
1043     _attaching_via_jni,          // thread is attaching via JNI
1044     _attached_via_jni            // thread has attached via JNI
1045   };
1046 
1047   // A regular JavaThread's _jni_attach_state is _not_attaching_via_jni.
1048   // A native thread that is attaching via JNI starts with a value
1049   // of _attaching_via_jni and transitions to _attached_via_jni.
1050   volatile JNIAttachStates _jni_attach_state;
1051 
1052  public:
1053   // State of the stack guard pages for this thread.
1054   enum StackGuardState {
1055     stack_guard_unused,         // not needed
1056     stack_guard_reserved_disabled,
1057     stack_guard_yellow_reserved_disabled,// disabled (temporarily) after stack overflow
1058     stack_guard_enabled         // enabled
1059   };
1060 
1061  private:
1062 
1063 #if INCLUDE_JVMCI
1064   // The _pending_* fields below are used to communicate extra information
1065   // from an uncommon trap in JVMCI compiled code to the uncommon trap handler.
1066 
1067   // Communicates the DeoptReason and DeoptAction of the uncommon trap
1068   int       _pending_deoptimization;
1069 
1070   // Specifies whether the uncommon trap is to bci 0 of a synchronized method
1071   // before the monitor has been acquired.
1072   bool      _pending_monitorenter;
1073 
1074   // Specifies if the DeoptReason for the last uncommon trap was Reason_transfer_to_interpreter
1075   bool      _pending_transfer_to_interpreter;
1076 
1077   // Guard for re-entrant call to JVMCIRuntime::adjust_comp_level
1078   bool      _adjusting_comp_level;
1079 
1080   // True if in a runtime call from compiled code that will deoptimize
1081   // and re-execute a failed heap allocation in the interpreter.
1082   bool      _in_retryable_allocation;
1083 
1084   // An id of a speculation that JVMCI compiled code can use to further describe and
1085   // uniquely identify the  speculative optimization guarded by the uncommon trap
1086   long       _pending_failed_speculation;
1087 
1088   // These fields are mutually exclusive in terms of live ranges.
1089   union {
1090     // Communicates the pc at which the most recent implicit exception occurred
1091     // from the signal handler to a deoptimization stub.
1092     address   _implicit_exception_pc;
1093 
1094     // Communicates an alternative call target to an i2c stub from a JavaCall .
1095     address   _alternate_call_target;
1096   } _jvmci;
1097 
1098   // Support for high precision, thread sensitive counters in JVMCI compiled code.
1099   jlong*    _jvmci_counters;
1100 
1101  public:
1102   static jlong* _jvmci_old_thread_counters;
1103   static void collect_counters(typeArrayOop array);
1104  private:
1105 #endif // INCLUDE_JVMCI
1106 
1107   StackGuardState  _stack_guard_state;
1108 
1109   // Precompute the limit of the stack as used in stack overflow checks.
1110   // We load it from here to simplify the stack overflow check in assembly.
1111   address          _stack_overflow_limit;
1112   address          _reserved_stack_activation;
1113 
1114   // Compiler exception handling (NOTE: The _exception_oop is *NOT* the same as _pending_exception. It is
1115   // used to temp. parsing values into and out of the runtime system during exception handling for compiled
1116   // code)
1117   volatile oop     _exception_oop;               // Exception thrown in compiled code
1118   volatile address _exception_pc;                // PC where exception happened
1119   volatile address _exception_handler_pc;        // PC for handler of exception
1120   volatile int     _is_method_handle_return;     // true (== 1) if the current exception PC is a MethodHandle call site.
1121 
1122  private:
1123   // support for JNI critical regions
1124   jint    _jni_active_critical;                  // count of entries into JNI critical region
1125 
1126   // Checked JNI: function name requires exception check
1127   char* _pending_jni_exception_check_fn;
1128 
1129   // For deadlock detection.
1130   int _depth_first_number;
1131 
1132   // JVMTI PopFrame support
1133   // This is set to popframe_pending to signal that top Java frame should be popped immediately
1134   int _popframe_condition;
1135 
1136   // If reallocation of scalar replaced objects fails, we throw OOM
1137   // and during exception propagation, pop the top
1138   // _frames_to_pop_failed_realloc frames, the ones that reference
1139   // failed reallocations.
1140   int _frames_to_pop_failed_realloc;
1141 
1142 #ifndef PRODUCT
1143   int _jmp_ring_index;
1144   struct {
1145     // We use intptr_t instead of address so debugger doesn't try and display strings
1146     intptr_t _target;
1147     intptr_t _instruction;
1148     const char*  _file;
1149     int _line;
1150   }   _jmp_ring[jump_ring_buffer_size];
1151 #endif // PRODUCT
1152 
1153   friend class VMThread;
1154   friend class ThreadWaitTransition;
1155   friend class VM_Exit;
1156 
1157   void initialize();                             // Initialized the instance variables
1158 
1159  public:
1160   // Constructor
1161   JavaThread(bool is_attaching_via_jni = false); // for main thread and JNI attached threads
1162   JavaThread(ThreadFunction entry_point, size_t stack_size = 0);
1163   ~JavaThread();
1164 
1165 #ifdef ASSERT
1166   // verify this JavaThread hasn't be published in the Threads::list yet
1167   void verify_not_published();
1168 #endif
1169 
1170   //JNI functiontable getter/setter for JVMTI jni function table interception API.
1171   void set_jni_functions(struct JNINativeInterface_* functionTable) {
1172     _jni_environment.functions = functionTable;
1173   }
1174   struct JNINativeInterface_* get_jni_functions() {
1175     return (struct JNINativeInterface_ *)_jni_environment.functions;
1176   }
1177 
1178   // This function is called at thread creation to allow
1179   // platform specific thread variables to be initialized.
1180   void cache_global_variables();
1181 
1182   // Executes Shutdown.shutdown()
1183   void invoke_shutdown_hooks();
1184 
1185   // Cleanup on thread exit
1186   enum ExitType {
1187     normal_exit,
1188     jni_detach
1189   };
1190   void exit(bool destroy_vm, ExitType exit_type = normal_exit);
1191 
1192   void cleanup_failed_attach_current_thread();
1193 
1194   // Testers
1195   virtual bool is_Java_thread() const            { return true;  }
1196   virtual bool can_call_java() const             { return true; }
1197 
1198   // Thread chain operations
1199   JavaThread* next() const                       { return _next; }
1200   void set_next(JavaThread* p)                   { _next = p; }
1201 
1202   // Thread oop. threadObj() can be NULL for initial JavaThread
1203   // (or for threads attached via JNI)
1204   oop threadObj() const                          { return _threadObj; }
1205   void set_threadObj(oop p)                      { _threadObj = p; }
1206 
1207   ThreadPriority java_priority() const;          // Read from threadObj()
1208 
1209   // Prepare thread and add to priority queue.  If a priority is
1210   // not specified, use the priority of the thread object. Threads_lock
1211   // must be held while this function is called.
1212   void prepare(jobject jni_thread, ThreadPriority prio=NoPriority);
1213 
1214   void set_saved_exception_pc(address pc)        { _saved_exception_pc = pc; }
1215   address saved_exception_pc()                   { return _saved_exception_pc; }
1216 
1217 
1218   ThreadFunction entry_point() const             { return _entry_point; }
1219 
1220   // Allocates a new Java level thread object for this thread. thread_name may be NULL.
1221   void allocate_threadObj(Handle thread_group, const char* thread_name, bool daemon, TRAPS);
1222 
1223   // Last frame anchor routines
1224 
1225   JavaFrameAnchor* frame_anchor(void)            { return &_anchor; }
1226 
1227   // last_Java_sp
1228   bool has_last_Java_frame() const               { return _anchor.has_last_Java_frame(); }
1229   intptr_t* last_Java_sp() const                 { return _anchor.last_Java_sp(); }
1230 
1231   // last_Java_pc
1232 
1233   address last_Java_pc(void)                     { return _anchor.last_Java_pc(); }
1234 
1235   // Safepoint support
1236 #if !(defined(PPC64) || defined(AARCH64))
1237   JavaThreadState thread_state() const           { return _thread_state; }
1238   void set_thread_state(JavaThreadState s)       { _thread_state = s;    }
1239 #else
1240   // Use membars when accessing volatile _thread_state. See
1241   // Threads::create_vm() for size checks.
1242   inline JavaThreadState thread_state() const;
1243   inline void set_thread_state(JavaThreadState s);
1244 #endif
1245   inline ThreadSafepointState* safepoint_state() const;
1246   inline void set_safepoint_state(ThreadSafepointState* state);
1247   inline bool is_at_poll_safepoint();
1248 
1249   // JavaThread termination and lifecycle support:
1250   void smr_delete();
1251   bool on_thread_list() const { return _on_thread_list; }
1252   void set_on_thread_list() { _on_thread_list = true; }
1253 
1254   // thread has called JavaThread::exit() or is terminated
1255   bool is_exiting() const;
1256   // thread is terminated (no longer on the threads list); we compare
1257   // against the two non-terminated values so that a freed JavaThread
1258   // will also be considered terminated.
1259   bool check_is_terminated(TerminatedTypes l_terminated) const {
1260     return l_terminated != _not_terminated && l_terminated != _thread_exiting;
1261   }
1262   bool is_terminated() const;
1263   void set_terminated(TerminatedTypes t);
1264   // special for Threads::remove() which is static:
1265   void set_terminated_value();
1266   void block_if_vm_exited();
1267 
1268   bool doing_unsafe_access()                     { return _doing_unsafe_access; }
1269   void set_doing_unsafe_access(bool val)         { _doing_unsafe_access = val; }
1270 
1271   bool do_not_unlock_if_synchronized()             { return _do_not_unlock_if_synchronized; }
1272   void set_do_not_unlock_if_synchronized(bool val) { _do_not_unlock_if_synchronized = val; }
1273 
1274   inline void set_polling_page_release(void* poll_value);
1275   inline void set_polling_page(void* poll_value);
1276   inline volatile void* get_polling_page();
1277 
1278  private:
1279   // Support for thread handshake operations
1280   HandshakeState _handshake;
1281  public:
1282   void set_handshake_operation(HandshakeOperation* op) {
1283     _handshake.set_operation(this, op);
1284   }
1285 
1286   bool has_handshake() const {
1287     return _handshake.has_operation();
1288   }
1289 
1290   void handshake_process_by_self() {
1291     _handshake.process_by_self(this);
1292   }
1293 
1294   void handshake_process_by_vmthread() {
1295     _handshake.process_by_vmthread(this);
1296   }
1297 
1298   // Suspend/resume support for JavaThread
1299  private:
1300   inline void set_ext_suspended();
1301   inline void clear_ext_suspended();
1302 
1303  public:
1304   void java_suspend();
1305   void java_resume();
1306   int  java_suspend_self();
1307 
1308   void check_and_wait_while_suspended() {
1309     assert(JavaThread::current() == this, "sanity check");
1310 
1311     bool do_self_suspend;
1312     do {
1313       // were we externally suspended while we were waiting?
1314       do_self_suspend = handle_special_suspend_equivalent_condition();
1315       if (do_self_suspend) {
1316         // don't surprise the thread that suspended us by returning
1317         java_suspend_self();
1318         set_suspend_equivalent();
1319       }
1320     } while (do_self_suspend);
1321   }
1322   static void check_safepoint_and_suspend_for_native_trans(JavaThread *thread);
1323   // Check for async exception in addition to safepoint and suspend request.
1324   static void check_special_condition_for_native_trans(JavaThread *thread);
1325 
1326   // Same as check_special_condition_for_native_trans but finishes the
1327   // transition into thread_in_Java mode so that it can potentially
1328   // block.
1329   static void check_special_condition_for_native_trans_and_transition(JavaThread *thread);
1330 
1331   bool is_ext_suspend_completed(bool called_by_wait, int delay, uint32_t *bits);
1332   bool is_ext_suspend_completed_with_lock(uint32_t *bits) {
1333     MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag);
1334     // Warning: is_ext_suspend_completed() may temporarily drop the
1335     // SR_lock to allow the thread to reach a stable thread state if
1336     // it is currently in a transient thread state.
1337     return is_ext_suspend_completed(false /* !called_by_wait */,
1338                                     SuspendRetryDelay, bits);
1339   }
1340 
1341   // We cannot allow wait_for_ext_suspend_completion() to run forever or
1342   // we could hang. SuspendRetryCount and SuspendRetryDelay are normally
1343   // passed as the count and delay parameters. Experiments with specific
1344   // calls to wait_for_ext_suspend_completion() can be done by passing
1345   // other values in the code. Experiments with all calls can be done
1346   // via the appropriate -XX options.
1347   bool wait_for_ext_suspend_completion(int count, int delay, uint32_t *bits);
1348 
1349   // test for suspend - most (all?) of these should go away
1350   bool is_thread_fully_suspended(bool wait_for_suspend, uint32_t *bits);
1351 
1352   inline void set_external_suspend();
1353   inline void clear_external_suspend();
1354 
1355   inline void set_deopt_suspend();
1356   inline void clear_deopt_suspend();
1357   bool is_deopt_suspend()         { return (_suspend_flags & _deopt_suspend) != 0; }
1358 
1359   bool is_external_suspend() const {
1360     return (_suspend_flags & _external_suspend) != 0;
1361   }
1362   // Whenever a thread transitions from native to vm/java it must suspend
1363   // if external|deopt suspend is present.
1364   bool is_suspend_after_native() const {
1365     return (_suspend_flags & (_external_suspend | _deopt_suspend)) != 0;
1366   }
1367 
1368   // external suspend request is completed
1369   bool is_ext_suspended() const {
1370     return (_suspend_flags & _ext_suspended) != 0;
1371   }
1372 
1373   bool is_external_suspend_with_lock() const {
1374     MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag);
1375     return is_external_suspend();
1376   }
1377 
1378   // Special method to handle a pending external suspend request
1379   // when a suspend equivalent condition lifts.
1380   bool handle_special_suspend_equivalent_condition() {
1381     assert(is_suspend_equivalent(),
1382            "should only be called in a suspend equivalence condition");
1383     MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag);
1384     bool ret = is_external_suspend();
1385     if (!ret) {
1386       // not about to self-suspend so clear suspend equivalence
1387       clear_suspend_equivalent();
1388     }
1389     // implied else:
1390     // We have a pending external suspend request so we leave the
1391     // suspend_equivalent flag set until java_suspend_self() sets
1392     // the ext_suspended flag and clears the suspend_equivalent
1393     // flag. This insures that wait_for_ext_suspend_completion()
1394     // will return consistent values.
1395     return ret;
1396   }
1397 
1398   // utility methods to see if we are doing some kind of suspension
1399   bool is_being_ext_suspended() const            {
1400     MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag);
1401     return is_ext_suspended() || is_external_suspend();
1402   }
1403 
1404   bool is_suspend_equivalent() const             { return _suspend_equivalent; }
1405 
1406   void set_suspend_equivalent()                  { _suspend_equivalent = true; }
1407   void clear_suspend_equivalent()                { _suspend_equivalent = false; }
1408 
1409   // Thread.stop support
1410   void send_thread_stop(oop throwable);
1411   AsyncRequests clear_special_runtime_exit_condition() {
1412     AsyncRequests x = _special_runtime_exit_condition;
1413     _special_runtime_exit_condition = _no_async_condition;
1414     return x;
1415   }
1416 
1417   // Are any async conditions present?
1418   bool has_async_condition() { return (_special_runtime_exit_condition != _no_async_condition); }
1419 
1420   void check_and_handle_async_exceptions(bool check_unsafe_error = true);
1421 
1422   // these next two are also used for self-suspension and async exception support
1423   void handle_special_runtime_exit_condition(bool check_asyncs = true);
1424 
1425   // Return true if JavaThread has an asynchronous condition or
1426   // if external suspension is requested.
1427   bool has_special_runtime_exit_condition() {
1428     // Because we don't use is_external_suspend_with_lock
1429     // it is possible that we won't see an asynchronous external suspend
1430     // request that has just gotten started, i.e., SR_lock grabbed but
1431     // _external_suspend field change either not made yet or not visible
1432     // yet. However, this is okay because the request is asynchronous and
1433     // we will see the new flag value the next time through. It's also
1434     // possible that the external suspend request is dropped after
1435     // we have checked is_external_suspend(), we will recheck its value
1436     // under SR_lock in java_suspend_self().
1437     return (_special_runtime_exit_condition != _no_async_condition) ||
1438             is_external_suspend() || is_trace_suspend();
1439   }
1440 
1441   void set_pending_unsafe_access_error()          { _special_runtime_exit_condition = _async_unsafe_access_error; }
1442 
1443   inline void set_pending_async_exception(oop e);
1444 
1445   // Fast-locking support
1446   bool is_lock_owned(address adr) const;
1447 
1448   // Accessors for vframe array top
1449   // The linked list of vframe arrays are sorted on sp. This means when we
1450   // unpack the head must contain the vframe array to unpack.
1451   void set_vframe_array_head(vframeArray* value) { _vframe_array_head = value; }
1452   vframeArray* vframe_array_head() const         { return _vframe_array_head;  }
1453 
1454   // Side structure for deferring update of java frame locals until deopt occurs
1455   GrowableArray<jvmtiDeferredLocalVariableSet*>* deferred_locals() const { return _deferred_locals_updates; }
1456   void set_deferred_locals(GrowableArray<jvmtiDeferredLocalVariableSet *>* vf) { _deferred_locals_updates = vf; }
1457 
1458   // These only really exist to make debugging deopt problems simpler
1459 
1460   void set_vframe_array_last(vframeArray* value) { _vframe_array_last = value; }
1461   vframeArray* vframe_array_last() const         { return _vframe_array_last;  }
1462 
1463   // The special resourceMark used during deoptimization
1464 
1465   void set_deopt_mark(DeoptResourceMark* value)  { _deopt_mark = value; }
1466   DeoptResourceMark* deopt_mark(void)            { return _deopt_mark; }
1467 
1468   intptr_t* must_deopt_id()                      { return _must_deopt_id; }
1469   void     set_must_deopt_id(intptr_t* id)       { _must_deopt_id = id; }
1470   void     clear_must_deopt_id()                 { _must_deopt_id = NULL; }
1471 
1472   void set_deopt_compiled_method(CompiledMethod* nm)  { _deopt_nmethod = nm; }
1473   CompiledMethod* deopt_compiled_method()        { return _deopt_nmethod; }
1474 
1475   Method*    callee_target() const               { return _callee_target; }
1476   void set_callee_target  (Method* x)          { _callee_target   = x; }
1477 
1478   // Oop results of vm runtime calls
1479   oop  vm_result() const                         { return _vm_result; }
1480   void set_vm_result  (oop x)                    { _vm_result   = x; }
1481 
1482   Metadata*    vm_result_2() const               { return _vm_result_2; }
1483   void set_vm_result_2  (Metadata* x)          { _vm_result_2   = x; }
1484 
1485   MemRegion deferred_card_mark() const           { return _deferred_card_mark; }
1486   void set_deferred_card_mark(MemRegion mr)      { _deferred_card_mark = mr;   }
1487 
1488 #if INCLUDE_JVMCI
1489   int  pending_deoptimization() const             { return _pending_deoptimization; }
1490   long pending_failed_speculation() const         { return _pending_failed_speculation; }
1491   bool adjusting_comp_level() const               { return _adjusting_comp_level; }
1492   void set_adjusting_comp_level(bool b)           { _adjusting_comp_level = b; }
1493   bool has_pending_monitorenter() const           { return _pending_monitorenter; }
1494   void set_pending_monitorenter(bool b)           { _pending_monitorenter = b; }
1495   void set_pending_deoptimization(int reason)     { _pending_deoptimization = reason; }
1496   void set_pending_failed_speculation(long failed_speculation) { _pending_failed_speculation = failed_speculation; }
1497   void set_pending_transfer_to_interpreter(bool b) { _pending_transfer_to_interpreter = b; }
1498   void set_jvmci_alternate_call_target(address a) { assert(_jvmci._alternate_call_target == NULL, "must be"); _jvmci._alternate_call_target = a; }
1499   void set_jvmci_implicit_exception_pc(address a) { assert(_jvmci._implicit_exception_pc == NULL, "must be"); _jvmci._implicit_exception_pc = a; }
1500 
1501   virtual bool in_retryable_allocation() const    { return _in_retryable_allocation; }
1502   void set_in_retryable_allocation(bool b)        { _in_retryable_allocation = b; }
1503 #endif // INCLUDE_JVMCI
1504 
1505   // Exception handling for compiled methods
1506   oop      exception_oop() const                 { return _exception_oop; }
1507   address  exception_pc() const                  { return _exception_pc; }
1508   address  exception_handler_pc() const          { return _exception_handler_pc; }
1509   bool     is_method_handle_return() const       { return _is_method_handle_return == 1; }
1510 
1511   void set_exception_oop(oop o)                  { (void)const_cast<oop&>(_exception_oop = o); }
1512   void set_exception_pc(address a)               { _exception_pc = a; }
1513   void set_exception_handler_pc(address a)       { _exception_handler_pc = a; }
1514   void set_is_method_handle_return(bool value)   { _is_method_handle_return = value ? 1 : 0; }
1515 
1516   void clear_exception_oop_and_pc() {
1517     set_exception_oop(NULL);
1518     set_exception_pc(NULL);
1519   }
1520 
1521   // Stack overflow support
1522   //
1523   //  (small addresses)
1524   //
1525   //  --  <-- stack_end()                   ---
1526   //  |                                      |
1527   //  |  red pages                           |
1528   //  |                                      |
1529   //  --  <-- stack_red_zone_base()          |
1530   //  |                                      |
1531   //  |                                     guard
1532   //  |  yellow pages                       zone
1533   //  |                                      |
1534   //  |                                      |
1535   //  --  <-- stack_yellow_zone_base()       |
1536   //  |                                      |
1537   //  |                                      |
1538   //  |  reserved pages                      |
1539   //  |                                      |
1540   //  --  <-- stack_reserved_zone_base()    ---      ---
1541   //                                                 /|\  shadow     <--  stack_overflow_limit() (somewhere in here)
1542   //                                                  |   zone
1543   //                                                 \|/  size
1544   //  some untouched memory                          ---
1545   //
1546   //
1547   //  --
1548   //  |
1549   //  |  shadow zone
1550   //  |
1551   //  --
1552   //  x    frame n
1553   //  --
1554   //  x    frame n-1
1555   //  x
1556   //  --
1557   //  ...
1558   //
1559   //  --
1560   //  x    frame 0
1561   //  --  <-- stack_base()
1562   //
1563   //  (large addresses)
1564   //
1565 
1566  private:
1567   // These values are derived from flags StackRedPages, StackYellowPages,
1568   // StackReservedPages and StackShadowPages. The zone size is determined
1569   // ergonomically if page_size > 4K.
1570   static size_t _stack_red_zone_size;
1571   static size_t _stack_yellow_zone_size;
1572   static size_t _stack_reserved_zone_size;
1573   static size_t _stack_shadow_zone_size;
1574  public:
1575   inline size_t stack_available(address cur_sp);
1576 
1577   static size_t stack_red_zone_size() {
1578     assert(_stack_red_zone_size > 0, "Don't call this before the field is initialized.");
1579     return _stack_red_zone_size;
1580   }
1581   static void set_stack_red_zone_size(size_t s) {
1582     assert(is_aligned(s, os::vm_page_size()),
1583            "We can not protect if the red zone size is not page aligned.");
1584     assert(_stack_red_zone_size == 0, "This should be called only once.");
1585     _stack_red_zone_size = s;
1586   }
1587   address stack_red_zone_base() {
1588     return (address)(stack_end() + stack_red_zone_size());
1589   }
1590   bool in_stack_red_zone(address a) {
1591     return a <= stack_red_zone_base() && a >= stack_end();
1592   }
1593 
1594   static size_t stack_yellow_zone_size() {
1595     assert(_stack_yellow_zone_size > 0, "Don't call this before the field is initialized.");
1596     return _stack_yellow_zone_size;
1597   }
1598   static void set_stack_yellow_zone_size(size_t s) {
1599     assert(is_aligned(s, os::vm_page_size()),
1600            "We can not protect if the yellow zone size is not page aligned.");
1601     assert(_stack_yellow_zone_size == 0, "This should be called only once.");
1602     _stack_yellow_zone_size = s;
1603   }
1604 
1605   static size_t stack_reserved_zone_size() {
1606     // _stack_reserved_zone_size may be 0. This indicates the feature is off.
1607     return _stack_reserved_zone_size;
1608   }
1609   static void set_stack_reserved_zone_size(size_t s) {
1610     assert(is_aligned(s, os::vm_page_size()),
1611            "We can not protect if the reserved zone size is not page aligned.");
1612     assert(_stack_reserved_zone_size == 0, "This should be called only once.");
1613     _stack_reserved_zone_size = s;
1614   }
1615   address stack_reserved_zone_base() {
1616     return (address)(stack_end() +
1617                      (stack_red_zone_size() + stack_yellow_zone_size() + stack_reserved_zone_size()));
1618   }
1619   bool in_stack_reserved_zone(address a) {
1620     return (a <= stack_reserved_zone_base()) &&
1621            (a >= (address)((intptr_t)stack_reserved_zone_base() - stack_reserved_zone_size()));
1622   }
1623 
1624   static size_t stack_yellow_reserved_zone_size() {
1625     return _stack_yellow_zone_size + _stack_reserved_zone_size;
1626   }
1627   bool in_stack_yellow_reserved_zone(address a) {
1628     return (a <= stack_reserved_zone_base()) && (a >= stack_red_zone_base());
1629   }
1630 
1631   // Size of red + yellow + reserved zones.
1632   static size_t stack_guard_zone_size() {
1633     return stack_red_zone_size() + stack_yellow_reserved_zone_size();
1634   }
1635 
1636   static size_t stack_shadow_zone_size() {
1637     assert(_stack_shadow_zone_size > 0, "Don't call this before the field is initialized.");
1638     return _stack_shadow_zone_size;
1639   }
1640   static void set_stack_shadow_zone_size(size_t s) {
1641     // The shadow area is not allocated or protected, so
1642     // it needs not be page aligned.
1643     // But the stack bang currently assumes that it is a
1644     // multiple of page size. This guarantees that the bang
1645     // loop touches all pages in the shadow zone.
1646     // This can be guaranteed differently, as well.  E.g., if
1647     // the page size is a multiple of 4K, banging in 4K steps
1648     // suffices to touch all pages. (Some pages are banged
1649     // several times, though.)
1650     assert(is_aligned(s, os::vm_page_size()),
1651            "Stack bang assumes multiple of page size.");
1652     assert(_stack_shadow_zone_size == 0, "This should be called only once.");
1653     _stack_shadow_zone_size = s;
1654   }
1655 
1656   void create_stack_guard_pages();
1657   void remove_stack_guard_pages();
1658 
1659   void enable_stack_reserved_zone();
1660   void disable_stack_reserved_zone();
1661   void enable_stack_yellow_reserved_zone();
1662   void disable_stack_yellow_reserved_zone();
1663   void enable_stack_red_zone();
1664   void disable_stack_red_zone();
1665 
1666   inline bool stack_guard_zone_unused();
1667   inline bool stack_yellow_reserved_zone_disabled();
1668   inline bool stack_reserved_zone_disabled();
1669   inline bool stack_guards_enabled();
1670 
1671   address reserved_stack_activation() const { return _reserved_stack_activation; }
1672   void set_reserved_stack_activation(address addr) {
1673     assert(_reserved_stack_activation == stack_base()
1674             || _reserved_stack_activation == NULL
1675             || addr == stack_base(), "Must not be set twice");
1676     _reserved_stack_activation = addr;
1677   }
1678 
1679   // Attempt to reguard the stack after a stack overflow may have occurred.
1680   // Returns true if (a) guard pages are not needed on this thread, (b) the
1681   // pages are already guarded, or (c) the pages were successfully reguarded.
1682   // Returns false if there is not enough stack space to reguard the pages, in
1683   // which case the caller should unwind a frame and try again.  The argument
1684   // should be the caller's (approximate) sp.
1685   bool reguard_stack(address cur_sp);
1686   // Similar to above but see if current stackpoint is out of the guard area
1687   // and reguard if possible.
1688   bool reguard_stack(void);
1689 
1690   address stack_overflow_limit() { return _stack_overflow_limit; }
1691   void set_stack_overflow_limit() {
1692     _stack_overflow_limit =
1693       stack_end() + MAX2(JavaThread::stack_guard_zone_size(), JavaThread::stack_shadow_zone_size());
1694   }
1695 
1696   // Misc. accessors/mutators
1697   void set_do_not_unlock(void)                   { _do_not_unlock_if_synchronized = true; }
1698   void clr_do_not_unlock(void)                   { _do_not_unlock_if_synchronized = false; }
1699   bool do_not_unlock(void)                       { return _do_not_unlock_if_synchronized; }
1700 
1701 #ifndef PRODUCT
1702   void record_jump(address target, address instr, const char* file, int line);
1703 #endif // PRODUCT
1704 
1705   // For assembly stub generation
1706   static ByteSize threadObj_offset()             { return byte_offset_of(JavaThread, _threadObj); }
1707 #ifndef PRODUCT
1708   static ByteSize jmp_ring_index_offset()        { return byte_offset_of(JavaThread, _jmp_ring_index); }
1709   static ByteSize jmp_ring_offset()              { return byte_offset_of(JavaThread, _jmp_ring); }
1710 #endif // PRODUCT
1711   static ByteSize jni_environment_offset()       { return byte_offset_of(JavaThread, _jni_environment); }
1712   static ByteSize pending_jni_exception_check_fn_offset() {
1713     return byte_offset_of(JavaThread, _pending_jni_exception_check_fn);
1714   }
1715   static ByteSize last_Java_sp_offset() {
1716     return byte_offset_of(JavaThread, _anchor) + JavaFrameAnchor::last_Java_sp_offset();
1717   }
1718   static ByteSize last_Java_pc_offset() {
1719     return byte_offset_of(JavaThread, _anchor) + JavaFrameAnchor::last_Java_pc_offset();
1720   }
1721   static ByteSize frame_anchor_offset() {
1722     return byte_offset_of(JavaThread, _anchor);
1723   }
1724   static ByteSize callee_target_offset()         { return byte_offset_of(JavaThread, _callee_target); }
1725   static ByteSize vm_result_offset()             { return byte_offset_of(JavaThread, _vm_result); }
1726   static ByteSize vm_result_2_offset()           { return byte_offset_of(JavaThread, _vm_result_2); }
1727   static ByteSize thread_state_offset()          { return byte_offset_of(JavaThread, _thread_state); }
1728   static ByteSize saved_exception_pc_offset()    { return byte_offset_of(JavaThread, _saved_exception_pc); }
1729   static ByteSize osthread_offset()              { return byte_offset_of(JavaThread, _osthread); }
1730 #if INCLUDE_JVMCI
1731   static ByteSize pending_deoptimization_offset() { return byte_offset_of(JavaThread, _pending_deoptimization); }
1732   static ByteSize pending_monitorenter_offset()  { return byte_offset_of(JavaThread, _pending_monitorenter); }
1733   static ByteSize pending_failed_speculation_offset() { return byte_offset_of(JavaThread, _pending_failed_speculation); }
1734   static ByteSize jvmci_alternate_call_target_offset() { return byte_offset_of(JavaThread, _jvmci._alternate_call_target); }
1735   static ByteSize jvmci_implicit_exception_pc_offset() { return byte_offset_of(JavaThread, _jvmci._implicit_exception_pc); }
1736   static ByteSize jvmci_counters_offset()        { return byte_offset_of(JavaThread, _jvmci_counters); }
1737 #endif // INCLUDE_JVMCI
1738   static ByteSize exception_oop_offset()         { return byte_offset_of(JavaThread, _exception_oop); }
1739   static ByteSize exception_pc_offset()          { return byte_offset_of(JavaThread, _exception_pc); }
1740   static ByteSize exception_handler_pc_offset()  { return byte_offset_of(JavaThread, _exception_handler_pc); }
1741   static ByteSize stack_overflow_limit_offset()  { return byte_offset_of(JavaThread, _stack_overflow_limit); }
1742   static ByteSize is_method_handle_return_offset() { return byte_offset_of(JavaThread, _is_method_handle_return); }
1743   static ByteSize stack_guard_state_offset()     { return byte_offset_of(JavaThread, _stack_guard_state); }
1744   static ByteSize reserved_stack_activation_offset() { return byte_offset_of(JavaThread, _reserved_stack_activation); }
1745   static ByteSize suspend_flags_offset()         { return byte_offset_of(JavaThread, _suspend_flags); }
1746 
1747   static ByteSize do_not_unlock_if_synchronized_offset() { return byte_offset_of(JavaThread, _do_not_unlock_if_synchronized); }
1748   static ByteSize should_post_on_exceptions_flag_offset() {
1749     return byte_offset_of(JavaThread, _should_post_on_exceptions_flag);
1750   }
1751 
1752   // Returns the jni environment for this thread
1753   JNIEnv* jni_environment()                      { return &_jni_environment; }
1754 
1755   static JavaThread* thread_from_jni_environment(JNIEnv* env) {
1756     JavaThread *thread_from_jni_env = (JavaThread*)((intptr_t)env - in_bytes(jni_environment_offset()));
1757     // Only return NULL if thread is off the thread list; starting to
1758     // exit should not return NULL.
1759     if (thread_from_jni_env->is_terminated()) {
1760       thread_from_jni_env->block_if_vm_exited();
1761       return NULL;
1762     } else {
1763       return thread_from_jni_env;
1764     }
1765   }
1766 
1767   // JNI critical regions. These can nest.
1768   bool in_critical()    { return _jni_active_critical > 0; }
1769   bool in_last_critical()  { return _jni_active_critical == 1; }
1770   inline void enter_critical();
1771   void exit_critical() {
1772     assert(Thread::current() == this, "this must be current thread");
1773     _jni_active_critical--;
1774     assert(_jni_active_critical >= 0, "JNI critical nesting problem?");
1775   }
1776 
1777   // Checked JNI: is the programmer required to check for exceptions, if so specify
1778   // which function name. Returning to a Java frame should implicitly clear the
1779   // pending check, this is done for Native->Java transitions (i.e. user JNI code).
1780   // VM->Java transistions are not cleared, it is expected that JNI code enclosed
1781   // within ThreadToNativeFromVM makes proper exception checks (i.e. VM internal).
1782   bool is_pending_jni_exception_check() const { return _pending_jni_exception_check_fn != NULL; }
1783   void clear_pending_jni_exception_check() { _pending_jni_exception_check_fn = NULL; }
1784   const char* get_pending_jni_exception_check() const { return _pending_jni_exception_check_fn; }
1785   void set_pending_jni_exception_check(const char* fn_name) { _pending_jni_exception_check_fn = (char*) fn_name; }
1786 
1787   // For deadlock detection
1788   int depth_first_number() { return _depth_first_number; }
1789   void set_depth_first_number(int dfn) { _depth_first_number = dfn; }
1790 
1791  private:
1792   void set_monitor_chunks(MonitorChunk* monitor_chunks) { _monitor_chunks = monitor_chunks; }
1793 
1794  public:
1795   MonitorChunk* monitor_chunks() const           { return _monitor_chunks; }
1796   void add_monitor_chunk(MonitorChunk* chunk);
1797   void remove_monitor_chunk(MonitorChunk* chunk);
1798   bool in_deopt_handler() const                  { return _in_deopt_handler > 0; }
1799   void inc_in_deopt_handler()                    { _in_deopt_handler++; }
1800   void dec_in_deopt_handler() {
1801     assert(_in_deopt_handler > 0, "mismatched deopt nesting");
1802     if (_in_deopt_handler > 0) { // robustness
1803       _in_deopt_handler--;
1804     }
1805   }
1806 
1807  private:
1808   void set_entry_point(ThreadFunction entry_point) { _entry_point = entry_point; }
1809 
1810  public:
1811 
1812   // Frame iteration; calls the function f for all frames on the stack
1813   void frames_do(void f(frame*, const RegisterMap*));
1814 
1815   // Memory operations
1816   void oops_do(OopClosure* f, CodeBlobClosure* cf);
1817 
1818   // Sweeper operations
1819   virtual void nmethods_do(CodeBlobClosure* cf);
1820 
1821   // RedefineClasses Support
1822   void metadata_do(void f(Metadata*));
1823 
1824   // Misc. operations
1825   char* name() const { return (char*)get_thread_name(); }
1826   void print_on(outputStream* st, bool print_extended_info) const;
1827   void print_on(outputStream* st) const { print_on(st, false); }
1828   void print_value();
1829   void print_thread_state_on(outputStream*) const      PRODUCT_RETURN;
1830   void print_thread_state() const                      PRODUCT_RETURN;
1831   void print_on_error(outputStream* st, char* buf, int buflen) const;
1832   void print_name_on_error(outputStream* st, char* buf, int buflen) const;
1833   void verify();
1834   const char* get_thread_name() const;
1835  private:
1836   // factor out low-level mechanics for use in both normal and error cases
1837   const char* get_thread_name_string(char* buf = NULL, int buflen = 0) const;
1838  public:
1839   const char* get_threadgroup_name() const;
1840   const char* get_parent_name() const;
1841 
1842   // Accessing frames
1843   frame last_frame() {
1844     _anchor.make_walkable(this);
1845     return pd_last_frame();
1846   }
1847   javaVFrame* last_java_vframe(RegisterMap* reg_map);
1848 
1849   // Returns method at 'depth' java or native frames down the stack
1850   // Used for security checks
1851   Klass* security_get_caller_class(int depth);
1852 
1853   // Print stack trace in external format
1854   void print_stack_on(outputStream* st);
1855   void print_stack() { print_stack_on(tty); }
1856 
1857   // Print stack traces in various internal formats
1858   void trace_stack()                             PRODUCT_RETURN;
1859   void trace_stack_from(vframe* start_vf)        PRODUCT_RETURN;
1860   void trace_frames()                            PRODUCT_RETURN;
1861   void trace_oops()                              PRODUCT_RETURN;
1862 
1863   // Print an annotated view of the stack frames
1864   void print_frame_layout(int depth = 0, bool validate_only = false) NOT_DEBUG_RETURN;
1865   void validate_frame_layout() {
1866     print_frame_layout(0, true);
1867   }
1868 
1869   // Returns the number of stack frames on the stack
1870   int depth() const;
1871 
1872   // Function for testing deoptimization
1873   void deoptimize();
1874   void make_zombies();
1875 
1876   void deoptimized_wrt_marked_nmethods();
1877 
1878  public:
1879   // Returns the running thread as a JavaThread
1880   static inline JavaThread* current();
1881 
1882   // Returns the active Java thread.  Do not use this if you know you are calling
1883   // from a JavaThread, as it's slower than JavaThread::current.  If called from
1884   // the VMThread, it also returns the JavaThread that instigated the VMThread's
1885   // operation.  You may not want that either.
1886   static JavaThread* active();
1887 
1888   inline CompilerThread* as_CompilerThread();
1889 
1890  public:
1891   virtual void run();
1892   void thread_main_inner();
1893 
1894  private:
1895   GrowableArray<oop>* _array_for_gc;
1896  public:
1897 
1898   void register_array_for_gc(GrowableArray<oop>* array) { _array_for_gc = array; }
1899 
1900  public:
1901   // Thread local information maintained by JVMTI.
1902   void set_jvmti_thread_state(JvmtiThreadState *value)                           { _jvmti_thread_state = value; }
1903   // A JvmtiThreadState is lazily allocated. This jvmti_thread_state()
1904   // getter is used to get this JavaThread's JvmtiThreadState if it has
1905   // one which means NULL can be returned. JvmtiThreadState::state_for()
1906   // is used to get the specified JavaThread's JvmtiThreadState if it has
1907   // one or it allocates a new JvmtiThreadState for the JavaThread and
1908   // returns it. JvmtiThreadState::state_for() will return NULL only if
1909   // the specified JavaThread is exiting.
1910   JvmtiThreadState *jvmti_thread_state() const                                   { return _jvmti_thread_state; }
1911   static ByteSize jvmti_thread_state_offset()                                    { return byte_offset_of(JavaThread, _jvmti_thread_state); }
1912 
1913   // JVMTI PopFrame support
1914   // Setting and clearing popframe_condition
1915   // All of these enumerated values are bits. popframe_pending
1916   // indicates that a PopFrame() has been requested and not yet been
1917   // completed. popframe_processing indicates that that PopFrame() is in
1918   // the process of being completed. popframe_force_deopt_reexecution_bit
1919   // indicates that special handling is required when returning to a
1920   // deoptimized caller.
1921   enum PopCondition {
1922     popframe_inactive                      = 0x00,
1923     popframe_pending_bit                   = 0x01,
1924     popframe_processing_bit                = 0x02,
1925     popframe_force_deopt_reexecution_bit   = 0x04
1926   };
1927   PopCondition popframe_condition()                   { return (PopCondition) _popframe_condition; }
1928   void set_popframe_condition(PopCondition c)         { _popframe_condition = c; }
1929   void set_popframe_condition_bit(PopCondition c)     { _popframe_condition |= c; }
1930   void clear_popframe_condition()                     { _popframe_condition = popframe_inactive; }
1931   static ByteSize popframe_condition_offset()         { return byte_offset_of(JavaThread, _popframe_condition); }
1932   bool has_pending_popframe()                         { return (popframe_condition() & popframe_pending_bit) != 0; }
1933   bool popframe_forcing_deopt_reexecution()           { return (popframe_condition() & popframe_force_deopt_reexecution_bit) != 0; }
1934   void clear_popframe_forcing_deopt_reexecution()     { _popframe_condition &= ~popframe_force_deopt_reexecution_bit; }
1935 #ifdef CC_INTERP
1936   bool pop_frame_pending(void)                        { return ((_popframe_condition & popframe_pending_bit) != 0); }
1937   void clr_pop_frame_pending(void)                    { _popframe_condition = popframe_inactive; }
1938   bool pop_frame_in_process(void)                     { return ((_popframe_condition & popframe_processing_bit) != 0); }
1939   void set_pop_frame_in_process(void)                 { _popframe_condition |= popframe_processing_bit; }
1940   void clr_pop_frame_in_process(void)                 { _popframe_condition &= ~popframe_processing_bit; }
1941 #endif
1942 
1943   int frames_to_pop_failed_realloc() const            { return _frames_to_pop_failed_realloc; }
1944   void set_frames_to_pop_failed_realloc(int nb)       { _frames_to_pop_failed_realloc = nb; }
1945   void dec_frames_to_pop_failed_realloc()             { _frames_to_pop_failed_realloc--; }
1946 
1947  private:
1948   // Saved incoming arguments to popped frame.
1949   // Used only when popped interpreted frame returns to deoptimized frame.
1950   void*    _popframe_preserved_args;
1951   int      _popframe_preserved_args_size;
1952 
1953  public:
1954   void  popframe_preserve_args(ByteSize size_in_bytes, void* start);
1955   void* popframe_preserved_args();
1956   ByteSize popframe_preserved_args_size();
1957   WordSize popframe_preserved_args_size_in_words();
1958   void  popframe_free_preserved_args();
1959 
1960 
1961  private:
1962   JvmtiThreadState *_jvmti_thread_state;
1963 
1964   // Used by the interpreter in fullspeed mode for frame pop, method
1965   // entry, method exit and single stepping support. This field is
1966   // only set to non-zero by the VM_EnterInterpOnlyMode VM operation.
1967   // It can be set to zero asynchronously (i.e., without a VM operation
1968   // or a lock) so we have to be very careful.
1969   int               _interp_only_mode;
1970 
1971  public:
1972   // used by the interpreter for fullspeed debugging support (see above)
1973   static ByteSize interp_only_mode_offset() { return byte_offset_of(JavaThread, _interp_only_mode); }
1974   bool is_interp_only_mode()                { return (_interp_only_mode != 0); }
1975   int get_interp_only_mode()                { return _interp_only_mode; }
1976   void increment_interp_only_mode()         { ++_interp_only_mode; }
1977   void decrement_interp_only_mode()         { --_interp_only_mode; }
1978 
1979   // support for cached flag that indicates whether exceptions need to be posted for this thread
1980   // if this is false, we can avoid deoptimizing when events are thrown
1981   // this gets set to reflect whether jvmtiExport::post_exception_throw would actually do anything
1982  private:
1983   int    _should_post_on_exceptions_flag;
1984 
1985  public:
1986   int   should_post_on_exceptions_flag()  { return _should_post_on_exceptions_flag; }
1987   void  set_should_post_on_exceptions_flag(int val)  { _should_post_on_exceptions_flag = val; }
1988 
1989  private:
1990   ThreadStatistics *_thread_stat;
1991 
1992  public:
1993   ThreadStatistics* get_thread_stat() const    { return _thread_stat; }
1994 
1995   // Return a blocker object for which this thread is blocked parking.
1996   oop current_park_blocker();
1997 
1998  private:
1999   static size_t _stack_size_at_create;
2000 
2001  public:
2002   static inline size_t stack_size_at_create(void) {
2003     return _stack_size_at_create;
2004   }
2005   static inline void set_stack_size_at_create(size_t value) {
2006     _stack_size_at_create = value;
2007   }
2008 
2009   // Machine dependent stuff
2010 #include OS_CPU_HEADER(thread)
2011 
2012  public:
2013   void set_blocked_on_compilation(bool value) {
2014     _blocked_on_compilation = value;
2015   }
2016 
2017   bool blocked_on_compilation() {
2018     return _blocked_on_compilation;
2019   }
2020  protected:
2021   bool         _blocked_on_compilation;
2022 
2023 
2024   // JSR166 per-thread parker
2025  private:
2026   Parker*    _parker;
2027  public:
2028   Parker*     parker() { return _parker; }
2029 
2030   // Biased locking support
2031  private:
2032   GrowableArray<MonitorInfo*>* _cached_monitor_info;
2033  public:
2034   GrowableArray<MonitorInfo*>* cached_monitor_info() { return _cached_monitor_info; }
2035   void set_cached_monitor_info(GrowableArray<MonitorInfo*>* info) { _cached_monitor_info = info; }
2036 
2037   // clearing/querying jni attach status
2038   bool is_attaching_via_jni() const { return _jni_attach_state == _attaching_via_jni; }
2039   bool has_attached_via_jni() const { return is_attaching_via_jni() || _jni_attach_state == _attached_via_jni; }
2040   inline void set_done_attaching_via_jni();
2041 };
2042 
2043 // Inline implementation of JavaThread::current
2044 inline JavaThread* JavaThread::current() {
2045   Thread* thread = Thread::current();
2046   assert(thread->is_Java_thread(), "just checking");
2047   return (JavaThread*)thread;
2048 }
2049 
2050 inline CompilerThread* JavaThread::as_CompilerThread() {
2051   assert(is_Compiler_thread(), "just checking");
2052   return (CompilerThread*)this;
2053 }
2054 
2055 // Dedicated thread to sweep the code cache
2056 class CodeCacheSweeperThread : public JavaThread {
2057   CompiledMethod*       _scanned_compiled_method; // nmethod being scanned by the sweeper
2058  public:
2059   CodeCacheSweeperThread();
2060   // Track the nmethod currently being scanned by the sweeper
2061   void set_scanned_compiled_method(CompiledMethod* cm) {
2062     assert(_scanned_compiled_method == NULL || cm == NULL, "should reset to NULL before writing a new value");
2063     _scanned_compiled_method = cm;
2064   }
2065 
2066   // Hide sweeper thread from external view.
2067   bool is_hidden_from_external_view() const { return true; }
2068 
2069   bool is_Code_cache_sweeper_thread() const { return true; }
2070 
2071   // Prevent GC from unloading _scanned_compiled_method
2072   void oops_do(OopClosure* f, CodeBlobClosure* cf);
2073   void nmethods_do(CodeBlobClosure* cf);
2074 };
2075 
2076 // A thread used for Compilation.
2077 class CompilerThread : public JavaThread {
2078   friend class VMStructs;
2079  private:
2080   CompilerCounters* _counters;
2081 
2082   ciEnv*                _env;
2083   CompileLog*           _log;
2084   CompileTask* volatile _task;  // print_threads_compiling can read this concurrently.
2085   CompileQueue*         _queue;
2086   BufferBlob*           _buffer_blob;
2087 
2088   AbstractCompiler*     _compiler;
2089   TimeStamp             _idle_time;
2090 
2091  public:
2092 
2093   static CompilerThread* current();
2094 
2095   CompilerThread(CompileQueue* queue, CompilerCounters* counters);
2096   ~CompilerThread();
2097 
2098   bool is_Compiler_thread() const                { return true; }
2099 
2100   virtual bool can_call_java() const;
2101 
2102   // Hide native compiler threads from external view.
2103   bool is_hidden_from_external_view() const      { return !can_call_java(); }
2104 
2105   void set_compiler(AbstractCompiler* c)         { _compiler = c; }
2106   AbstractCompiler* compiler() const             { return _compiler; }
2107 
2108   CompileQueue* queue()        const             { return _queue; }
2109   CompilerCounters* counters() const             { return _counters; }
2110 
2111   // Get/set the thread's compilation environment.
2112   ciEnv*        env()                            { return _env; }
2113   void          set_env(ciEnv* env)              { _env = env; }
2114 
2115   BufferBlob*   get_buffer_blob() const          { return _buffer_blob; }
2116   void          set_buffer_blob(BufferBlob* b)   { _buffer_blob = b; }
2117 
2118   // Get/set the thread's logging information
2119   CompileLog*   log()                            { return _log; }
2120   void          init_log(CompileLog* log) {
2121     // Set once, for good.
2122     assert(_log == NULL, "set only once");
2123     _log = log;
2124   }
2125 
2126   void start_idle_timer()                        { _idle_time.update(); }
2127   jlong idle_time_millis() {
2128     return TimeHelper::counter_to_millis(_idle_time.ticks_since_update());
2129   }
2130 
2131 #ifndef PRODUCT
2132  private:
2133   IdealGraphPrinter *_ideal_graph_printer;
2134  public:
2135   IdealGraphPrinter *ideal_graph_printer()           { return _ideal_graph_printer; }
2136   void set_ideal_graph_printer(IdealGraphPrinter *n) { _ideal_graph_printer = n; }
2137 #endif
2138 
2139   // Get/set the thread's current task
2140   CompileTask* task()                      { return _task; }
2141   void         set_task(CompileTask* task) { _task = task; }
2142 };
2143 
2144 inline CompilerThread* CompilerThread::current() {
2145   return JavaThread::current()->as_CompilerThread();
2146 }
2147 
2148 // The active thread queue. It also keeps track of the current used
2149 // thread priorities.
2150 class Threads: AllStatic {
2151   friend class VMStructs;
2152  private:
2153   static JavaThread* _thread_list;
2154   static int         _number_of_threads;
2155   static int         _number_of_non_daemon_threads;
2156   static int         _return_code;
2157   static int         _thread_claim_parity;
2158 #ifdef ASSERT
2159   static bool        _vm_complete;
2160 #endif
2161 
2162   static void initialize_java_lang_classes(JavaThread* main_thread, TRAPS);
2163   static void initialize_jsr292_core_classes(TRAPS);
2164 
2165  public:
2166   // Thread management
2167   // force_daemon is a concession to JNI, where we may need to add a
2168   // thread to the thread list before allocating its thread object
2169   static void add(JavaThread* p, bool force_daemon = false);
2170   static void remove(JavaThread* p);
2171   static void non_java_threads_do(ThreadClosure* tc);
2172   static void java_threads_do(ThreadClosure* tc);
2173   static void java_threads_and_vm_thread_do(ThreadClosure* tc);
2174   static void threads_do(ThreadClosure* tc);
2175   static void possibly_parallel_threads_do(bool is_par, ThreadClosure* tc);
2176 
2177   // Initializes the vm and creates the vm thread
2178   static jint create_vm(JavaVMInitArgs* args, bool* canTryAgain);
2179   static void convert_vm_init_libraries_to_agents();
2180   static void create_vm_init_libraries();
2181   static void create_vm_init_agents();
2182   static void shutdown_vm_agents();
2183   static bool destroy_vm();
2184   // Supported VM versions via JNI
2185   // Includes JNI_VERSION_1_1
2186   static jboolean is_supported_jni_version_including_1_1(jint version);
2187   // Does not include JNI_VERSION_1_1
2188   static jboolean is_supported_jni_version(jint version);
2189 
2190   // The "thread claim parity" provides a way for threads to be claimed
2191   // by parallel worker tasks.
2192   //
2193   // Each thread contains a a "parity" field. A task will claim the
2194   // thread only if its parity field is the same as the global parity,
2195   // which is updated by calling change_thread_claim_parity().
2196   //
2197   // For this to work change_thread_claim_parity() needs to be called
2198   // exactly once in sequential code before starting parallel tasks
2199   // that should claim threads.
2200   //
2201   // New threads get their parity set to 0 and change_thread_claim_parity()
2202   // never set the global parity to 0.
2203   static int thread_claim_parity() { return _thread_claim_parity; }
2204   static void change_thread_claim_parity();
2205   static void assert_all_threads_claimed() NOT_DEBUG_RETURN;
2206 
2207   // Apply "f->do_oop" to all root oops in all threads.
2208   // This version may only be called by sequential code.
2209   static void oops_do(OopClosure* f, CodeBlobClosure* cf);
2210   // This version may be called by sequential or parallel code.
2211   static void possibly_parallel_oops_do(bool is_par, OopClosure* f, CodeBlobClosure* cf);
2212 
2213   // Apply "f->do_oop" to roots in all threads that
2214   // are part of compiled frames
2215   static void compiled_frame_oops_do(OopClosure* f, CodeBlobClosure* cf);
2216 
2217   static void convert_hcode_pointers();
2218   static void restore_hcode_pointers();
2219 
2220   // Sweeper
2221   static void nmethods_do(CodeBlobClosure* cf);
2222 
2223   // RedefineClasses support
2224   static void metadata_do(void f(Metadata*));
2225   static void metadata_handles_do(void f(Metadata*));
2226 
2227 #ifdef ASSERT
2228   static bool is_vm_complete() { return _vm_complete; }
2229 #endif // ASSERT
2230 
2231   // Verification
2232   static void verify();
2233   static void print_on(outputStream* st, bool print_stacks, bool internal_format, bool print_concurrent_locks, bool print_extended_info);
2234   static void print(bool print_stacks, bool internal_format) {
2235     // this function is only used by debug.cpp
2236     print_on(tty, print_stacks, internal_format, false /* no concurrent lock printed */, false /* simple format */);
2237   }
2238   static void print_on_error(outputStream* st, Thread* current, char* buf, int buflen);
2239   static void print_on_error(Thread* this_thread, outputStream* st, Thread* current, char* buf,
2240                              int buflen, bool* found_current);
2241   static void print_threads_compiling(outputStream* st, char* buf, int buflen);
2242 
2243   // Get Java threads that are waiting to enter a monitor.
2244   static GrowableArray<JavaThread*>* get_pending_threads(ThreadsList * t_list,
2245                                                          int count, address monitor);
2246 
2247   // Get owning Java thread from the monitor's owner field.
2248   static JavaThread *owning_thread_from_monitor_owner(ThreadsList * t_list,
2249                                                       address owner);
2250 
2251   // Number of threads on the active threads list
2252   static int number_of_threads()                 { return _number_of_threads; }
2253   // Number of non-daemon threads on the active threads list
2254   static int number_of_non_daemon_threads()      { return _number_of_non_daemon_threads; }
2255 
2256   // Deoptimizes all frames tied to marked nmethods
2257   static void deoptimized_wrt_marked_nmethods();
2258 };
2259 
2260 
2261 // Thread iterator
2262 class ThreadClosure: public StackObj {
2263  public:
2264   virtual void do_thread(Thread* thread) = 0;
2265 };
2266 
2267 class SignalHandlerMark: public StackObj {
2268  private:
2269   Thread* _thread;
2270  public:
2271   SignalHandlerMark(Thread* t) {
2272     _thread = t;
2273     if (_thread) _thread->enter_signal_handler();
2274   }
2275   ~SignalHandlerMark() {
2276     if (_thread) _thread->leave_signal_handler();
2277     _thread = NULL;
2278   }
2279 };
2280 
2281 
2282 #endif // SHARE_VM_RUNTIME_THREAD_HPP