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