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