1 /*
  2  * Copyright (c) 1997, 2025, Oracle and/or its affiliates. All rights reserved.
  3  * Copyright (c) 2021, Azul Systems, Inc. All rights reserved.
  4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  5  *
  6  * This code is free software; you can redistribute it and/or modify it
  7  * under the terms of the GNU General Public License version 2 only, as
  8  * published by the Free Software Foundation.
  9  *
 10  * This code is distributed in the hope that it will be useful, but WITHOUT
 11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 13  * version 2 for more details (a copy is included in the LICENSE file that
 14  * accompanied this code).
 15  *
 16  * You should have received a copy of the GNU General Public License version
 17  * 2 along with this work; if not, write to the Free Software Foundation,
 18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 19  *
 20  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 21  * or visit www.oracle.com if you need additional information or have any
 22  * questions.
 23  *
 24  */
 25 
 26 #ifndef SHARE_RUNTIME_THREAD_HPP
 27 #define SHARE_RUNTIME_THREAD_HPP
 28 
 29 #include "gc/shared/gcThreadLocalData.hpp"
 30 #include "gc/shared/threadLocalAllocBuffer.hpp"
 31 #include "jni.h"
 32 #include "memory/allocation.hpp"
 33 #include "runtime/atomic.hpp"
 34 #include "runtime/globals.hpp"
 35 #include "runtime/os.hpp"
 36 #include "runtime/safepointMechanism.hpp"
 37 #include "runtime/threadHeapSampler.hpp"
 38 #include "runtime/threadLocalStorage.hpp"
 39 #include "runtime/threadStatisticalInfo.hpp"
 40 #include "runtime/unhandledOops.hpp"
 41 #include "utilities/globalDefinitions.hpp"
 42 #include "utilities/macros.hpp"
 43 #if INCLUDE_JFR
 44 #include "jfr/support/jfrThreadExtension.hpp"
 45 #endif
 46 
 47 class CompilerThread;
 48 class HandleArea;
 49 class HandleMark;
 50 class JvmtiRawMonitor;
 51 class NMethodClosure;
 52 class Metadata;
 53 class OopClosure;
 54 class OSThread;
 55 class ParkEvent;
 56 class ResourceArea;
 57 class SafeThreadsListPtr;
 58 class ThreadClosure;
 59 class ThreadsList;
 60 class ThreadsSMRSupport;
 61 class VMErrorCallback;
 62 
 63 
 64 DEBUG_ONLY(class ResourceMark;)
 65 
 66 class WorkerThread;
 67 
 68 class JavaThread;
 69 
 70 // Class hierarchy
 71 // - Thread
 72 //   - JavaThread
 73 //     - various subclasses eg CompilerThread, ServiceThread
 74 //   - NonJavaThread
 75 //     - NamedThread
 76 //       - VMThread
 77 //       - ConcurrentGCThread
 78 //       - WorkerThread
 79 //     - WatcherThread
 80 //     - JfrThreadSampler
 81 //     - LogAsyncWriter
 82 //
 83 // All Thread subclasses must be either JavaThread or NonJavaThread.
 84 // This means !t->is_Java_thread() iff t is a NonJavaThread, or t is
 85 // a partially constructed/destroyed Thread.
 86 
 87 // Thread execution sequence and actions:
 88 // All threads:
 89 //  - thread_native_entry  // per-OS native entry point
 90 //    - stack initialization
 91 //    - other OS-level initialization (signal masks etc)
 92 //    - handshake with creating thread (if not started suspended)
 93 //    - this->call_run()  // common shared entry point
 94 //      - shared common initialization
 95 //      - this->pre_run()  // virtual per-thread-type initialization
 96 //      - this->run()      // virtual per-thread-type "main" logic
 97 //      - shared common tear-down
 98 //      - this->post_run()  // virtual per-thread-type tear-down
 99 //      - // 'this' no longer referenceable
100 //    - OS-level tear-down (minimal)
101 //    - final logging
102 //
103 // For JavaThread:
104 //   - this->run()  // virtual but not normally overridden
105 //     - this->thread_main_inner()  // extra call level to ensure correct stack calculations
106 //       - this->entry_point()  // set differently for each kind of JavaThread
107 
108 class Thread: public ThreadShadow {
109   friend class VMError;
110   friend class VMErrorCallbackMark;
111   friend class VMStructs;
112   friend class JVMCIVMStructs;
113   friend class JavaThread;
114  private:
115 
116   // Current thread is maintained as a thread-local variable
117   static THREAD_LOCAL Thread* _thr_current;
118 
119   // On AArch64, the high order 32 bits are used by a "patching epoch" number
120   // which reflects if this thread has executed the required fences, after
121   // an nmethod gets disarmed. The low order 32 bits denote the disarmed value.
122   uint64_t _nmethod_disarmed_guard_value;
123 
124  public:
125   void set_nmethod_disarmed_guard_value(int value) {
126     _nmethod_disarmed_guard_value = (uint64_t)(uint32_t)value;
127   }
128 
129   static ByteSize nmethod_disarmed_guard_value_offset() {
130     ByteSize offset = byte_offset_of(Thread, _nmethod_disarmed_guard_value);
131     // At least on x86_64, nmethod entry barrier encodes disarmed value offset
132     // in instruction as disp8 immed
133     assert(in_bytes(offset) < 128, "Offset >= 128");
134     return offset;
135   }
136 
137  private:
138   // Poll data is used in generated code for safepoint polls.
139   // It is important for performance to put this at lower offset
140   // in Thread. The accessors are in JavaThread.
141   SafepointMechanism::ThreadData _poll_data;
142 
143   // Thread local data area available to the GC. The internal
144   // structure and contents of this data area is GC-specific.
145   // Only GC and GC barrier code should access this data area.
146   GCThreadLocalData _gc_data;
147 
148  public:
149   static ByteSize gc_data_offset() {
150     return byte_offset_of(Thread, _gc_data);
151   }
152 
153   template <typename T> T* gc_data() {
154     STATIC_ASSERT(sizeof(T) <= sizeof(_gc_data));
155     return reinterpret_cast<T*>(&_gc_data);
156   }
157 
158   // Exception handling
159   // (Note: _pending_exception and friends are in ThreadShadow)
160   //oop       _pending_exception;                // pending exception for current thread
161   // const char* _exception_file;                   // file information for exception (debugging only)
162   // int         _exception_line;                   // line information for exception (debugging only)
163  protected:
164   // JavaThread lifecycle support:
165   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
166   friend class ScanHazardPtrGatherProtectedThreadsClosure;  // for cmpxchg_threads_hazard_ptr(), get_threads_hazard_ptr(), is_hazard_ptr_tagged() access
167   friend class ScanHazardPtrGatherThreadsListClosure;  // for get_threads_hazard_ptr(), untag_hazard_ptr() access
168   friend class ScanHazardPtrPrintMatchingThreadsClosure;  // for get_threads_hazard_ptr(), is_hazard_ptr_tagged() access
169   friend class ThreadsSMRSupport;  // for _nested_threads_hazard_ptr_cnt, _threads_hazard_ptr, _threads_list_ptr access
170   friend class ThreadsListHandleTest;  // for _nested_threads_hazard_ptr_cnt, _threads_hazard_ptr, _threads_list_ptr access
171   friend class ValidateHazardPtrsClosure;  // for get_threads_hazard_ptr(), untag_hazard_ptr() access
172 
173   ThreadsList* volatile _threads_hazard_ptr;
174   SafeThreadsListPtr*   _threads_list_ptr;
175   ThreadsList*          cmpxchg_threads_hazard_ptr(ThreadsList* exchange_value, ThreadsList* compare_value);
176   ThreadsList*          get_threads_hazard_ptr() const;
177   void                  set_threads_hazard_ptr(ThreadsList* new_list);
178   static bool           is_hazard_ptr_tagged(ThreadsList* list) {
179     return (intptr_t(list) & intptr_t(1)) == intptr_t(1);
180   }
181   static ThreadsList*   tag_hazard_ptr(ThreadsList* list) {
182     return (ThreadsList*)(intptr_t(list) | intptr_t(1));
183   }
184   static ThreadsList*   untag_hazard_ptr(ThreadsList* list) {
185     return (ThreadsList*)(intptr_t(list) & ~intptr_t(1));
186   }
187   // This field is enabled via -XX:+EnableThreadSMRStatistics:
188   uint _nested_threads_hazard_ptr_cnt;
189   void dec_nested_threads_hazard_ptr_cnt() {
190     assert(_nested_threads_hazard_ptr_cnt != 0, "mismatched {dec,inc}_nested_threads_hazard_ptr_cnt()");
191     _nested_threads_hazard_ptr_cnt--;
192   }
193   void inc_nested_threads_hazard_ptr_cnt() {
194     _nested_threads_hazard_ptr_cnt++;
195   }
196   uint nested_threads_hazard_ptr_cnt() {
197     return _nested_threads_hazard_ptr_cnt;
198   }
199 
200  public:
201   // Is the target JavaThread protected by the calling Thread or by some other
202   // mechanism?
203   static bool is_JavaThread_protected(const JavaThread* target);
204   // Is the target JavaThread protected by a ThreadsListHandle (TLH) associated
205   // with the calling Thread?
206   static bool is_JavaThread_protected_by_TLH(const JavaThread* target);
207 
208  private:
209   DEBUG_ONLY(static Thread* _starting_thread;)
210   DEBUG_ONLY(bool _suspendible_thread;)
211   DEBUG_ONLY(bool _indirectly_suspendible_thread;)
212   DEBUG_ONLY(bool _indirectly_safepoint_thread;)
213 
214  public:
215 #ifdef ASSERT
216   static bool is_starting_thread(const Thread* t);
217 
218   void set_suspendible_thread()   { _suspendible_thread = true; }
219   void clear_suspendible_thread() { _suspendible_thread = false; }
220   bool is_suspendible_thread()    { return _suspendible_thread; }
221 
222   void set_indirectly_suspendible_thread()   { _indirectly_suspendible_thread = true; }
223   void clear_indirectly_suspendible_thread() { _indirectly_suspendible_thread = false; }
224   bool is_indirectly_suspendible_thread()    { return _indirectly_suspendible_thread; }
225 
226   void set_indirectly_safepoint_thread()   { _indirectly_safepoint_thread = true; }
227   void clear_indirectly_safepoint_thread() { _indirectly_safepoint_thread = false; }
228   bool is_indirectly_safepoint_thread()    { return _indirectly_safepoint_thread; }
229 #endif
230 
231  private:
232   // Point to the last handle mark
233   HandleMark* _last_handle_mark;
234 
235   // Claim value for parallel iteration over threads.
236   uintx _threads_do_token;
237 
238   // Support for GlobalCounter
239  private:
240   volatile uintx _rcu_counter;
241  public:
242   volatile uintx* get_rcu_counter() {
243     return &_rcu_counter;
244   }
245 
246  public:
247   void set_last_handle_mark(HandleMark* mark)   { _last_handle_mark = mark; }
248   HandleMark* last_handle_mark() const          { return _last_handle_mark; }
249 
250  private:
251   // Used by SkipGCALot class.
252   NOT_PRODUCT(bool _skip_gcalot;)               // Should we elide gc-a-lot?
253 
254   friend class GCLocker;
255 
256  private:
257   ThreadLocalAllocBuffer _tlab;                 // Thread-local eden
258   jlong _allocated_bytes;                       // Cumulative number of bytes allocated on
259                                                 // the Java heap
260   ThreadHeapSampler _heap_sampler;              // For use when sampling the memory.
261 
262   ThreadStatisticalInfo _statistical_info;      // Statistics about the thread
263 
264   JFR_ONLY(DEFINE_THREAD_LOCAL_FIELD_JFR;)      // Thread-local data for jfr
265 
266   JvmtiRawMonitor* _current_pending_raw_monitor; // JvmtiRawMonitor this thread
267                                                  // is waiting to lock
268  public:
269   // Constructor
270   Thread(MemTag mem_tag = mtThread);
271   virtual ~Thread() = 0;        // Thread is abstract.
272 
273   // Manage Thread::current()
274   void initialize_thread_current();
275   static void clear_thread_current(); // TLS cleanup needed before threads terminate
276 
277  protected:
278   // To be implemented by children.
279   virtual void run() = 0;
280   virtual void pre_run() = 0;
281   virtual void post_run() = 0;  // Note: Thread must not be deleted prior to calling this!
282 
283 #ifdef ASSERT
284   enum RunState {
285     PRE_CALL_RUN,
286     CALL_RUN,
287     PRE_RUN,
288     RUN,
289     POST_RUN
290     // POST_CALL_RUN - can't define this one as 'this' may be deleted when we want to set it
291   };
292   RunState _run_state;  // for lifecycle checks
293 #endif
294 
295 
296  public:
297   // invokes <ChildThreadClass>::run(), with common preparations and cleanups.
298   void call_run();
299 
300   // Testers
301   virtual bool is_VM_thread()       const            { return false; }
302   virtual bool is_Java_thread()     const            { return false; }
303   virtual bool is_Compiler_thread() const            { return false; }
304   virtual bool is_service_thread() const             { return false; }
305   virtual bool is_hidden_from_external_view() const  { return false; }
306   virtual bool is_jvmti_agent_thread() const         { return false; }
307   virtual bool is_Watcher_thread() const             { return false; }
308   virtual bool is_ConcurrentGC_thread() const        { return false; }
309   virtual bool is_Named_thread() const               { return false; }
310   virtual bool is_Worker_thread() const              { return false; }
311   virtual bool is_JfrSampler_thread() const          { return false; }
312   virtual bool is_JfrRecorder_thread() const         { return false; }
313   virtual bool is_AttachListener_thread() const      { return false; }
314   virtual bool is_monitor_deflation_thread() const   { return false; }
315 
316   // Convenience cast functions
317   CompilerThread* as_Compiler_thread() const {
318     assert(is_Compiler_thread(), "Must be compiler thread");
319     return (CompilerThread*)this;
320   }
321 
322   // Can this thread make Java upcalls
323   virtual bool can_call_java() const                 { return false; }
324 
325   // Is this a JavaThread that is on the VM's current ThreadsList?
326   // If so it must participate in the safepoint protocol.
327   virtual bool is_active_Java_thread() const         { return false; }
328 
329   // All threads are given names. For singleton subclasses we can
330   // just hard-wire the known name of the instance. JavaThreads and
331   // NamedThreads support multiple named instances, and dynamic
332   // changing of the name of an instance.
333   virtual const char* name() const { return "Unknown thread"; }
334 
335   // A thread's type name is also made available for debugging
336   // and logging.
337   virtual const char* type_name() const { return "Thread"; }
338 
339   // Returns the current thread (ASSERTS if null)
340   static inline Thread* current();
341   // Returns the current thread, or null if not attached
342   static inline Thread* current_or_null();
343   // Returns the current thread, or null if not attached, and is
344   // safe for use from signal-handlers
345   static inline Thread* current_or_null_safe();
346 
347   // Common thread operations
348 #ifdef ASSERT
349   static void check_for_dangling_thread_pointer(Thread *thread);
350 #endif
351   static void set_priority(Thread* thread, ThreadPriority priority);
352   static void start(Thread* thread);
353 
354   void set_native_thread_name(const char *name) {
355     assert(Thread::current() == this, "set_native_thread_name can only be called on the current thread");
356     os::set_native_thread_name(name);
357   }
358 
359   // Support for Unhandled Oop detection
360   // Add the field for both, fastdebug and debug, builds to keep
361   // Thread's fields layout the same.
362   // Note: CHECK_UNHANDLED_OOPS is defined only for fastdebug build.
363 #ifdef CHECK_UNHANDLED_OOPS
364  private:
365   UnhandledOops* _unhandled_oops;
366 #elif defined(ASSERT)
367  private:
368   void* _unhandled_oops;
369 #endif
370 #ifdef CHECK_UNHANDLED_OOPS
371  public:
372   UnhandledOops* unhandled_oops() { return _unhandled_oops; }
373   // Mark oop safe for gc.  It may be stack allocated but won't move.
374   void allow_unhandled_oop(oop *op) {
375     if (CheckUnhandledOops) unhandled_oops()->allow_unhandled_oop(op);
376   }
377   // Clear oops at safepoint so crashes point to unhandled oop violator
378   void clear_unhandled_oops() {
379     if (CheckUnhandledOops) unhandled_oops()->clear_unhandled_oops();
380   }
381 #endif // CHECK_UNHANDLED_OOPS
382 
383  public:
384 #ifndef PRODUCT
385   bool skip_gcalot()           { return _skip_gcalot; }
386   void set_skip_gcalot(bool v) { _skip_gcalot = v;    }
387 #endif
388 
389   // Resource area
390   ResourceArea* resource_area() const            { return _resource_area; }
391   void set_resource_area(ResourceArea* area)     { _resource_area = area; }
392 
393   OSThread* osthread() const                     { return _osthread;   }
394   void set_osthread(OSThread* thread)            { _osthread = thread; }
395 
396   // Internal handle support
397   HandleArea* handle_area() const                { return _handle_area; }
398   void set_handle_area(HandleArea* area)         { _handle_area = area; }
399 
400   GrowableArray<Metadata*>* metadata_handles() const          { return _metadata_handles; }
401   void set_metadata_handles(GrowableArray<Metadata*>* handles){ _metadata_handles = handles; }
402 
403   // Thread-Local Allocation Buffer (TLAB) support
404   ThreadLocalAllocBuffer& tlab()                 { return _tlab; }
405   void initialize_tlab();
406   void retire_tlab(ThreadLocalAllocStats* stats = nullptr);
407   void fill_tlab(HeapWord* start, size_t pre_reserved, size_t new_size);
408 
409   jlong allocated_bytes()               { return _allocated_bytes; }
410   void set_allocated_bytes(jlong value) { _allocated_bytes = value; }
411   void incr_allocated_bytes(jlong size) { _allocated_bytes += size; }
412   inline jlong cooked_allocated_bytes();
413 
414   ThreadHeapSampler& heap_sampler()     { return _heap_sampler; }
415 
416   ThreadStatisticalInfo& statistical_info() { return _statistical_info; }
417 
418   JFR_ONLY(DEFINE_THREAD_LOCAL_ACCESSOR_JFR;)
419 
420   // For tracking the Jvmti raw monitor the thread is pending on.
421   JvmtiRawMonitor* current_pending_raw_monitor() {
422     return _current_pending_raw_monitor;
423   }
424   void set_current_pending_raw_monitor(JvmtiRawMonitor* monitor) {
425     _current_pending_raw_monitor = monitor;
426   }
427 
428   // GC support
429   // Apply "f->do_oop" to all root oops in "this".
430   //   Used by JavaThread::oops_do.
431   // Apply "cf->do_nmethod" (if !nullptr) to all nmethods active in frames
432   virtual void oops_do_no_frames(OopClosure* f, NMethodClosure* cf);
433   virtual void oops_do_frames(OopClosure* f, NMethodClosure* cf) {}
434   void oops_do(OopClosure* f, NMethodClosure* cf);
435 
436   // Handles the parallel case for claim_threads_do.
437  private:
438   bool claim_par_threads_do(uintx claim_token);
439  public:
440   // Requires that "claim_token" is that of the current iteration.
441   // If "is_par" is false, sets the token of "this" to
442   // "claim_token", and returns "true".  If "is_par" is true,
443   // uses an atomic instruction to set the current thread's token to
444   // "claim_token", if it is not already.  Returns "true" iff the
445   // calling thread does the update, this indicates that the calling thread
446   // has claimed the thread in the current iteration.
447   bool claim_threads_do(bool is_par, uintx claim_token) {
448     if (!is_par) {
449       _threads_do_token = claim_token;
450       return true;
451     } else {
452       return claim_par_threads_do(claim_token);
453     }
454   }
455 
456   uintx threads_do_token() const { return _threads_do_token; }
457 
458   // jvmtiRedefineClasses support
459   void metadata_handles_do(void f(Metadata*));
460 
461  private:
462   // Check if address is within the given range of this thread's
463   // stack:  stack_base() > adr >/>= limit
464   // The check is inclusive of limit if passed true, else exclusive.
465   bool is_in_stack_range(address adr, address limit, bool inclusive) const {
466     assert(stack_base() > limit && limit >= stack_end(), "limit is outside of stack");
467     return stack_base() > adr && (inclusive ? adr >= limit : adr > limit);
468   }
469 
470  public:
471   // Check if address is within the given range of this thread's
472   // stack:  stack_base() > adr >= limit
473   bool is_in_stack_range_incl(address adr, address limit) const {
474     return is_in_stack_range(adr, limit, true);
475   }
476 
477   // Check if address is within the given range of this thread's
478   // stack:  stack_base() > adr > limit
479   bool is_in_stack_range_excl(address adr, address limit) const {
480     return is_in_stack_range(adr, limit, false);
481   }
482 
483   // Check if address is in the stack mapped to this thread. Used mainly in
484   // error reporting (so has to include guard zone) and frame printing.
485   // Expects _stack_base to be initialized - checked with assert.
486   bool is_in_full_stack_checked(address adr) const {
487     return is_in_stack_range_incl(adr, stack_end());
488   }
489 
490   // Like is_in_full_stack_checked but without the assertions as this
491   // may be called in a thread before _stack_base is initialized.
492   bool is_in_full_stack(address adr) const {
493     address stack_end = _stack_base - _stack_size;
494     return _stack_base > adr && adr >= stack_end;
495   }
496 
497   // Check if address is in the live stack of this thread (not just for locks).
498   // Warning: can only be called by the current thread on itself.
499   bool is_in_live_stack(address adr) const {
500     assert(Thread::current() == this, "is_in_live_stack can only be called from current thread");
501     return is_in_stack_range_incl(adr, os::current_stack_pointer());
502   }
503 
504   // Sets the argument thread as starting thread. Returns failure if thread
505   // creation fails due to lack of memory, too many threads etc.
506   static bool set_as_starting_thread(JavaThread* jt);
507 
508 protected:
509   // OS data associated with the thread
510   OSThread* _osthread;  // Platform-specific thread information
511 
512   // Thread local resource area for temporary allocation within the VM
513   ResourceArea* _resource_area;
514 
515   DEBUG_ONLY(ResourceMark* _current_resource_mark;)
516 
517   // Thread local handle area for allocation of handles within the VM
518   HandleArea* _handle_area;
519   GrowableArray<Metadata*>* _metadata_handles;
520 
521   // Support for stack overflow handling, get_thread, etc.
522   address          _stack_base;
523   size_t           _stack_size;
524   int              _lgrp_id;
525 
526  public:
527   // Stack overflow support
528   address stack_base() const DEBUG_ONLY(;) NOT_DEBUG({ return _stack_base; })
529   // Needed for code that can query a new thread before the stack has been set.
530   address stack_base_or_null() const   { return _stack_base; }
531   void    set_stack_base(address base) { _stack_base = base; }
532   size_t  stack_size() const           { return _stack_size; }
533   void    set_stack_size(size_t size)  { _stack_size = size; }
534   address stack_end()  const           { return stack_base() - stack_size(); }
535   void    record_stack_base_and_size();
536   void    register_thread_stack_with_NMT();
537   void    unregister_thread_stack_with_NMT();
538 
539   int     lgrp_id() const        { return _lgrp_id; }
540   void    set_lgrp_id(int value) { _lgrp_id = value; }
541 
542   // Printing
543   void print_on(outputStream* st, bool print_extended_info) const;
544   virtual void print_on(outputStream* st) const { print_on(st, false); }
545   void print() const;
546   virtual void print_on_error(outputStream* st, char* buf, int buflen) const;
547   // Basic, non-virtual, printing support that is simple and always safe.
548   void print_value_on(outputStream* st) const;
549 
550   // Debug-only code
551 #ifdef ASSERT
552  private:
553   // Deadlock detection support for Mutex locks. List of locks own by thread.
554   Mutex* _owned_locks;
555   // Mutex::set_owner_implementation is the only place where _owned_locks is modified,
556   // thus the friendship
557   friend class Mutex;
558   friend class Monitor;
559 
560  public:
561   void print_owned_locks_on(outputStream* st) const;
562   void print_owned_locks() const                 { print_owned_locks_on(tty);    }
563   Mutex* owned_locks() const                     { return _owned_locks;          }
564   bool owns_locks() const                        { return owned_locks() != nullptr; }
565 
566   // Deadlock detection
567   ResourceMark* current_resource_mark()          { return _current_resource_mark; }
568   void set_current_resource_mark(ResourceMark* rm) { _current_resource_mark = rm; }
569 #endif // ASSERT
570 
571  private:
572   volatile int _jvmti_env_iteration_count;
573 
574  public:
575   void entering_jvmti_env_iteration()            { ++_jvmti_env_iteration_count; }
576   void leaving_jvmti_env_iteration()             { --_jvmti_env_iteration_count; }
577   bool is_inside_jvmti_env_iteration()           { return _jvmti_env_iteration_count > 0; }
578 
579   // Code generation
580   static ByteSize exception_file_offset()        { return byte_offset_of(Thread, _exception_file); }
581   static ByteSize exception_line_offset()        { return byte_offset_of(Thread, _exception_line); }
582 
583   static ByteSize stack_base_offset()            { return byte_offset_of(Thread, _stack_base); }
584   static ByteSize stack_size_offset()            { return byte_offset_of(Thread, _stack_size); }
585 
586   static ByteSize tlab_start_offset()            { return byte_offset_of(Thread, _tlab) + ThreadLocalAllocBuffer::start_offset(); }
587   static ByteSize tlab_end_offset()              { return byte_offset_of(Thread, _tlab) + ThreadLocalAllocBuffer::end_offset(); }
588   static ByteSize tlab_top_offset()              { return byte_offset_of(Thread, _tlab) + ThreadLocalAllocBuffer::top_offset(); }
589   static ByteSize tlab_pf_top_offset()           { return byte_offset_of(Thread, _tlab) + ThreadLocalAllocBuffer::pf_top_offset(); }
590 
591   JFR_ONLY(DEFINE_THREAD_LOCAL_OFFSET_JFR;)
592 
593  public:
594   ParkEvent * volatile _ParkEvent;            // for Object monitors, JVMTI raw monitors,
595                                               // and ObjectSynchronizer::read_stable_mark
596 
597   // Termination indicator used by the signal handler.
598   // _ParkEvent is just a convenient field we can null out after setting the JavaThread termination state
599   // (which can't itself be read from the signal handler if a signal hits during the Thread destructor).
600   bool has_terminated()                       { return Atomic::load(&_ParkEvent) == nullptr; };
601 
602   jint _hashStateW;                           // Marsaglia Shift-XOR thread-local RNG
603   jint _hashStateX;                           // thread-specific hashCode generator state
604   jint _hashStateY;
605   jint _hashStateZ;
606 
607   // Low-level leaf-lock primitives used to implement synchronization.
608   // Not for general synchronization use.
609   static void SpinAcquire(volatile int * Lock);
610   static void SpinRelease(volatile int * Lock);
611 
612 #if defined(__APPLE__) && defined(AARCH64)
613  private:
614   DEBUG_ONLY(bool _wx_init);
615   WXMode _wx_state;
616  public:
617   void init_wx();
618   WXMode enable_wx(WXMode new_state);
619 
620   void assert_wx_state(WXMode expected) {
621     assert(_wx_state == expected, "wrong state");
622   }
623 #endif // __APPLE__ && AARCH64
624 
625  private:
626   bool _in_asgct = false;
627  public:
628   bool in_asgct() const { return _in_asgct; }
629   void set_in_asgct(bool value) { _in_asgct = value; }
630   static bool current_in_asgct() {
631     Thread *cur = Thread::current_or_null_safe();
632     return cur != nullptr && cur->in_asgct();
633   }
634 
635  private:
636   VMErrorCallback* _vm_error_callbacks;
637 };
638 
639 class ThreadInAsgct {
640  private:
641   Thread* _thread;
642   bool _saved_in_asgct;
643  public:
644   ThreadInAsgct(Thread* thread) : _thread(thread) {
645     assert(thread != nullptr, "invariant");
646     // Allow AsyncGetCallTrace to be reentrant - save the previous state.
647     _saved_in_asgct = thread->in_asgct();
648     thread->set_in_asgct(true);
649   }
650   ~ThreadInAsgct() {
651     assert(_thread->in_asgct(), "invariant");
652     _thread->set_in_asgct(_saved_in_asgct);
653   }
654 };
655 
656 // Inline implementation of Thread::current()
657 inline Thread* Thread::current() {
658   Thread* current = current_or_null();
659   assert(current != nullptr, "Thread::current() called on detached thread");
660   return current;
661 }
662 
663 inline Thread* Thread::current_or_null() {
664   return _thr_current;
665 }
666 
667 inline Thread* Thread::current_or_null_safe() {
668   if (ThreadLocalStorage::is_initialized()) {
669     return ThreadLocalStorage::thread();
670   }
671   return nullptr;
672 }
673 
674 #endif // SHARE_RUNTIME_THREAD_HPP