1 /*
2 * Copyright (c) 1997, 2026, 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_JAVATHREAD_HPP
27 #define SHARE_RUNTIME_JAVATHREAD_HPP
28
29 #ifndef PRODUCT
30 #include "interpreter/bytecodeTracer.hpp"
31 #endif // PRODUCT
32 #include "jni.h"
33 #include "memory/allocation.hpp"
34 #include "oops/oop.hpp"
35 #include "oops/oopHandle.hpp"
36 #include "runtime/continuationEntry.hpp"
37 #include "runtime/frame.hpp"
38 #include "runtime/globals.hpp"
39 #include "runtime/handshake.hpp"
40 #include "runtime/javaFrameAnchor.hpp"
41 #include "runtime/lockStack.hpp"
42 #include "runtime/park.hpp"
43 #include "runtime/safepointMechanism.hpp"
44 #include "runtime/stackOverflow.hpp"
45 #include "runtime/stackWatermarkSet.hpp"
46 #include "runtime/suspendResumeManager.hpp"
47 #include "runtime/thread.hpp"
48 #include "runtime/threadHeapSampler.hpp"
49 #include "runtime/threadIdentifier.hpp"
50 #include "runtime/threadStatisticalInfo.hpp"
51 #include "utilities/exceptions.hpp"
52 #include "utilities/globalDefinitions.hpp"
53 #include "utilities/macros.hpp"
54 #if INCLUDE_JFR
55 #include "jfr/support/jfrThreadExtension.hpp"
56 #include "utilities/ticks.hpp"
57 #endif
58
59 class AsyncExceptionHandshakeClosure;
60 class DeoptResourceMark;
61 class InternalOOMEMark;
62 class JNIHandleBlock;
63 class JVMCIRuntime;
64
65 class JvmtiDeferredUpdates;
66 class JvmtiSampledObjectAllocEventCollector;
67 class JvmtiThreadState;
68
69 class Metadata;
70 class ObjectMonitor;
71 class OopHandleList;
72 class OopStorage;
73 class OSThread;
74
75 class ThreadsList;
76 class ThreadSafepointState;
77 class ThreadStatistics;
78
79 class vframeArray;
80 class vframe;
81 class javaVFrame;
82
83 class JavaThread;
84 typedef void (*ThreadFunction)(JavaThread*, TRAPS);
85
86 class EventVirtualThreadPinned;
87 class ThreadWXEnable;
88
89 class JavaThread: public Thread {
90 friend class VMStructs;
91 friend class JVMCIVMStructs;
92 friend class WhiteBox;
93 friend class ThreadsSMRSupport; // to access _threadObj for exiting_threads_oops_do
94 friend class HandshakeState;
95 friend class Continuation;
96 friend class Threads;
97 friend class ServiceThread; // for deferred OopHandle release access
98 private:
99 bool _on_thread_list; // Is set when this JavaThread is added to the Threads list
100
101 // All references to Java objects managed via OopHandles. These
102 // have to be released by the ServiceThread after the JavaThread has
103 // terminated - see add_oop_handles_for_release().
104 OopHandle _threadObj; // The Java level thread object
105 OopHandle _vthread; // the value returned by Thread.currentThread(): the virtual thread, if mounted, otherwise _threadObj
106 OopHandle _jvmti_vthread;
107 OopHandle _scopedValueCache;
108
109 static OopStorage* _thread_oop_storage;
110
111 #ifdef ASSERT
112 private:
113 int _java_call_counter;
114
115 public:
116 int java_call_counter() { return _java_call_counter; }
117 void inc_java_call_counter() { _java_call_counter++; }
118 void dec_java_call_counter() {
119 assert(_java_call_counter > 0, "Invalid nesting of JavaCallWrapper");
120 _java_call_counter--;
121 }
122 private: // restore original namespace restriction
123 #endif // ifdef ASSERT
124
125 JavaFrameAnchor _anchor; // Encapsulation of current java frame and it state
126
127 ThreadFunction _entry_point;
128
129 JNIEnv _jni_environment;
130
131 // Deopt support
132 DeoptResourceMark* _deopt_mark; // Holds special ResourceMark for deoptimization
133
134 nmethod* _deopt_nmethod; // nmethod that is currently being deoptimized
135 vframeArray* _vframe_array_head; // Holds the heap of the active vframeArrays
136 vframeArray* _vframe_array_last; // Holds last vFrameArray we popped
137 // Holds updates by JVMTI agents for compiled frames that cannot be performed immediately. They
138 // will be carried out as soon as possible which, in most cases, is just before deoptimization of
139 // the frame, when control returns to it.
140 JvmtiDeferredUpdates* _jvmti_deferred_updates;
141
142 // Handshake value for fixing 6243940. We need a place for the i2c
143 // adapter to store the callee Method*. This value is NEVER live
144 // across a gc point so it does NOT have to be gc'd
145 // The handshake is open ended since we can't be certain that it will
146 // be nulled. This is because we rarely ever see the race and end up
147 // in handle_wrong_method which is the backend of the handshake. See
148 // code in i2c adapters and handle_wrong_method.
149
150 Method* _callee_target;
151
152 // Used to pass back results to the interpreter or generated code running Java code.
153 oop _vm_result_oop; // oop result is GC-preserved
154 Metadata* _vm_result_metadata; // non-oop result
155 oop _return_buffered_value; // buffered value being returned
156
157 ObjectMonitor* volatile _current_pending_monitor; // ObjectMonitor this thread is waiting to lock
158 bool _current_pending_monitor_is_from_java; // locking is from Java code
159 ObjectMonitor* volatile _current_waiting_monitor; // ObjectMonitor on which this thread called Object.wait()
160
161 // Active_handles points to a block of handles
162 JNIHandleBlock* _active_handles;
163
164 // One-element thread local free list
165 JNIHandleBlock* _free_handle_block;
166
167 // ID used as owner for inflated monitors. Same as the j.l.Thread.tid of the
168 // current _vthread object, except during creation of the primordial and JNI
169 // attached thread cases where this field can have a temporary value.
170 int64_t _monitor_owner_id;
171
172 public:
173 void set_monitor_owner_id(int64_t id) {
174 ThreadIdentifier::verify_id(id);
175 _monitor_owner_id = id;
176 }
177 int64_t monitor_owner_id() const {
178 int64_t id = _monitor_owner_id;
179 ThreadIdentifier::verify_id(id);
180 return id;
181 }
182
183 // For tracking the heavyweight monitor the thread is pending on.
184 ObjectMonitor* current_pending_monitor() {
185 // Use AtomicAccess::load() to prevent data race between concurrent modification and
186 // concurrent readers, e.g. ThreadService::get_current_contended_monitor().
187 // Especially, reloading pointer from thread after null check must be prevented.
188 return AtomicAccess::load(&_current_pending_monitor);
189 }
190 void set_current_pending_monitor(ObjectMonitor* monitor) {
191 AtomicAccess::store(&_current_pending_monitor, monitor);
192 }
193 void set_current_pending_monitor_is_from_java(bool from_java) {
194 _current_pending_monitor_is_from_java = from_java;
195 }
196 bool current_pending_monitor_is_from_java() {
197 return _current_pending_monitor_is_from_java;
198 }
199 ObjectMonitor* current_waiting_monitor() {
200 // See the comment in current_pending_monitor() above.
201 return AtomicAccess::load(&_current_waiting_monitor);
202 }
203 void set_current_waiting_monitor(ObjectMonitor* monitor) {
204 AtomicAccess::store(&_current_waiting_monitor, monitor);
205 }
206
207 // JNI handle support
208 JNIHandleBlock* active_handles() const { return _active_handles; }
209 void set_active_handles(JNIHandleBlock* block) { _active_handles = block; }
210 JNIHandleBlock* free_handle_block() const { return _free_handle_block; }
211 void set_free_handle_block(JNIHandleBlock* block) { _free_handle_block = block; }
212
213 void push_jni_handle_block();
214 void pop_jni_handle_block();
215
216 private:
217 enum SuspendFlags {
218 // NOTE: avoid using the sign-bit as cc generates different test code
219 // when the sign-bit is used, and sometimes incorrectly - see CR 6398077
220 _obj_deopt = 0x00000008U // suspend for object reallocation and relocking for JVMTI agent
221 };
222
223 // various suspension related flags - atomically updated
224 volatile uint32_t _suspend_flags;
225
226 inline void set_suspend_flag(SuspendFlags f);
227 inline void clear_suspend_flag(SuspendFlags f);
228
229 public:
230 inline void set_obj_deopt_flag();
231 inline void clear_obj_deopt_flag();
232 bool is_obj_deopt_suspend() { return (_suspend_flags & _obj_deopt) != 0; }
233
234 // Asynchronous exception support
235 private:
236 friend class InstallAsyncExceptionHandshakeClosure;
237 friend class AsyncExceptionHandshakeClosure;
238 friend class HandshakeState;
239
240 void handle_async_exception(oop java_throwable);
241 public:
242 void install_async_exception(AsyncExceptionHandshakeClosure* aec = nullptr);
243 bool has_async_exception_condition();
244 inline void set_pending_unsafe_access_error();
245 static void send_async_exception(JavaThread* jt, oop java_throwable);
246
247 class NoAsyncExceptionDeliveryMark : public StackObj {
248 friend JavaThread;
249 JavaThread *_target;
250 inline NoAsyncExceptionDeliveryMark(JavaThread *t);
251 inline ~NoAsyncExceptionDeliveryMark();
252 };
253
254 // Safepoint support
255 public: // Expose _thread_state for SafeFetchInt()
256 volatile JavaThreadState _thread_state;
257 ThreadSafepointState* _safepoint_state; // Holds information about a thread during a safepoint
258 address _saved_exception_pc; // Saved pc of instruction where last implicit exception happened
259 NOT_PRODUCT(bool _requires_cross_modify_fence;) // State used by VerifyCrossModifyFence
260 #ifdef ASSERT
261 // Debug support for checking if code allows safepoints or not.
262 // Safepoints in the VM can happen because of allocation, invoking a VM operation, or blocking on
263 // mutex, or blocking on an object synchronizer (Java locking).
264 // If _no_safepoint_count is non-zero, then an assertion failure will happen in any of
265 // the above cases. The class NoSafepointVerifier is used to set this counter.
266 int _no_safepoint_count; // If 0, thread allow a safepoint to happen
267
268 public:
269 void inc_no_safepoint_count() { _no_safepoint_count++; }
270 void dec_no_safepoint_count() { _no_safepoint_count--; }
271 bool is_in_no_safepoint_scope() { return _no_safepoint_count > 0; }
272 #endif // ASSERT
273 public:
274 // These functions check conditions before possibly going to a safepoint.
275 // including NoSafepointVerifier.
276 void check_for_valid_safepoint_state() NOT_DEBUG_RETURN;
277 void check_possible_safepoint() NOT_DEBUG_RETURN;
278
279 #ifdef ASSERT
280 private:
281 volatile uint64_t _visited_for_critical_count;
282
283 public:
284 void set_visited_for_critical_count(uint64_t safepoint_id) {
285 assert(_visited_for_critical_count == 0, "Must be reset before set");
286 assert((safepoint_id & 0x1) == 1, "Must be odd");
287 _visited_for_critical_count = safepoint_id;
288 }
289 void reset_visited_for_critical_count(uint64_t safepoint_id) {
290 assert(_visited_for_critical_count == safepoint_id, "Was not visited");
291 _visited_for_critical_count = 0;
292 }
293 bool was_visited_for_critical_count(uint64_t safepoint_id) const {
294 return _visited_for_critical_count == safepoint_id;
295 }
296 #endif // ASSERT
297
298 #ifndef PRODUCT
299 private:
300 BytecodeTracerData _bytecode_tracer_data;
301
302 public:
303 BytecodeTracerData* bytecode_tracer_data() {
304 return &_bytecode_tracer_data;
305 }
306 #endif // PRODUCT
307
308 // JavaThread termination support
309 public:
310 enum TerminatedTypes {
311 _not_terminated = 0xDEAD - 3,
312 _thread_exiting, // JavaThread::exit() has been called for this thread
313 _thread_gc_barrier_detached, // thread's GC barrier has been detached
314 _thread_terminated, // JavaThread is removed from thread list
315 _vm_exited // JavaThread is still executing native code, but VM is terminated
316 // only VM_Exit can set _vm_exited
317 };
318
319 private:
320 // In general a JavaThread's _terminated field transitions as follows:
321 //
322 // _not_terminated => _thread_exiting => _thread_gc_barrier_detached => _thread_terminated
323 //
324 // _vm_exited is a special value to cover the case of a JavaThread
325 // executing native code after the VM itself is terminated.
326 //
327 // A JavaThread that fails to JNI attach has these _terminated field transitions:
328 // _not_terminated => _thread_terminated
329 //
330 volatile TerminatedTypes _terminated;
331
332 jint _in_deopt_handler; // count of deoptimization
333 // handlers thread is in
334 volatile bool _doing_unsafe_access; // Thread may fault due to unsafe access
335 volatile bool _throwing_unsafe_access_error; // Thread has faulted and is throwing an exception
336 bool _do_not_unlock_if_synchronized; // Do not unlock the receiver of a synchronized method (since it was
337 // never locked) when throwing an exception. Used by interpreter only.
338 #if INCLUDE_JVMTI
339 volatile bool _carrier_thread_suspended; // Carrier thread is externally suspended
340 bool _is_disable_suspend; // JVMTI suspend is temporarily disabled; used on current thread only
341 bool _is_in_java_upcall; // JVMTI is doing a Java upcall, so JVMTI events must be hidden
342 int _jvmti_events_disabled; // JVMTI events disabled manually
343 bool _on_monitor_waited_event; // Avoid callee arg processing for enterSpecial when posting waited event
344 ObjectMonitor* _contended_entered_monitor; // Monitor for pending monitor_contended_entered callback
345 #endif
346
347 // JNI attach states:
348 enum JNIAttachStates {
349 _not_attaching_via_jni = 1, // thread is not attaching via JNI
350 _attaching_via_jni, // thread is attaching via JNI
351 _attached_via_jni // thread has attached via JNI
352 };
353
354 // A regular JavaThread's _jni_attach_state is _not_attaching_via_jni.
355 // A native thread that is attaching via JNI starts with a value
356 // of _attaching_via_jni and transitions to _attached_via_jni.
357 volatile JNIAttachStates _jni_attach_state;
358
359 // In scope of an InternalOOMEMark?
360 bool _is_in_internal_oome_mark;
361
362 #if INCLUDE_JVMCI
363 // The _pending_* fields below are used to communicate extra information
364 // from an uncommon trap in JVMCI compiled code to the uncommon trap handler.
365
366 // Communicates the DeoptReason and DeoptAction of the uncommon trap
367 int _pending_deoptimization;
368
369 // Specifies whether the uncommon trap is to bci 0 of a synchronized method
370 // before the monitor has been acquired.
371 bool _pending_monitorenter;
372
373 // Specifies if the DeoptReason for the last uncommon trap was Reason_transfer_to_interpreter
374 bool _pending_transfer_to_interpreter;
375
376 // An id of a speculation that JVMCI compiled code can use to further describe and
377 // uniquely identify the speculative optimization guarded by an uncommon trap.
378 // See JVMCINMethodData::SPECULATION_LENGTH_BITS for further details.
379 jlong _pending_failed_speculation;
380
381 // These fields are mutually exclusive in terms of live ranges.
382 union {
383 // Communicates the pc at which the most recent implicit exception occurred
384 // from the signal handler to a deoptimization stub.
385 address _implicit_exception_pc;
386
387 // Communicates an alternative call target to an i2c stub from a JavaCall .
388 address _alternate_call_target;
389 } _jvmci;
390
391 // The JVMCIRuntime in a JVMCI shared library
392 JVMCIRuntime* _libjvmci_runtime;
393
394 // Support for high precision, thread sensitive counters in JVMCI compiled code.
395 jlong* _jvmci_counters;
396
397 // Fast thread locals for use by JVMCI
398 jlong _jvmci_reserved0;
399 jlong _jvmci_reserved1;
400 oop _jvmci_reserved_oop0;
401
402 // This field is used to keep an nmethod visible to the GC so that it and its contained oops can
403 // be kept alive
404 nmethod* _live_nmethod;
405
406 public:
407 static jlong* _jvmci_old_thread_counters;
408 static void collect_counters(jlong* array, int length);
409
410 bool resize_counters(int current_size, int new_size);
411
412 static bool resize_all_jvmci_counters(int new_size);
413
414 void set_jvmci_reserved_oop0(oop value) {
415 _jvmci_reserved_oop0 = value;
416 }
417
418 oop get_jvmci_reserved_oop0() {
419 return _jvmci_reserved_oop0;
420 }
421
422 void set_jvmci_reserved0(jlong value) {
423 _jvmci_reserved0 = value;
424 }
425
426 jlong get_jvmci_reserved0() {
427 return _jvmci_reserved0;
428 }
429
430 void set_jvmci_reserved1(jlong value) {
431 _jvmci_reserved1 = value;
432 }
433
434 jlong get_jvmci_reserved1() {
435 return _jvmci_reserved1;
436 }
437
438 void set_live_nmethod(nmethod* nm) {
439 assert(_live_nmethod == nullptr, "only one");
440 _live_nmethod = nm;
441 }
442
443 void clear_live_nmethod() {
444 _live_nmethod = nullptr;
445 }
446
447 private:
448 #endif // INCLUDE_JVMCI
449
450 StackOverflow _stack_overflow_state;
451
452 void pretouch_stack();
453
454 // Compiler exception handling (NOTE: The _exception_oop is *NOT* the same as _pending_exception. It is
455 // used to temp. parsing values into and out of the runtime system during exception handling for compiled
456 // code)
457 volatile oop _exception_oop; // Exception thrown in compiled code
458 volatile address _exception_pc; // PC where exception happened
459 volatile address _exception_handler_pc; // PC for handler of exception
460
461 private:
462 // support for JNI critical regions
463 jint _jni_active_critical; // count of entries into JNI critical region
464
465 // Checked JNI: function name requires exception check
466 char* _pending_jni_exception_check_fn;
467
468 // For deadlock detection.
469 int _depth_first_number;
470
471 // JVMTI PopFrame support
472 // This is set to popframe_pending to signal that top Java frame should be popped immediately
473 int _popframe_condition;
474
475 // If reallocation of scalar replaced objects fails, we throw OOM
476 // and during exception propagation, pop the top
477 // _frames_to_pop_failed_realloc frames, the ones that reference
478 // failed reallocations.
479 int _frames_to_pop_failed_realloc;
480
481 ContinuationEntry* _cont_entry;
482 intptr_t* _cont_fastpath; // the sp of the oldest known interpreted/call_stub/upcall_stub/native_wrapper
483 // frame inside the continuation that we know about
484 int _cont_fastpath_thread_state; // whether global thread state allows continuation fastpath (JVMTI)
485
486 ObjectMonitor* _unlocked_inflated_monitor;
487
488 // This is the field we poke in the interpreter and native
489 // wrapper (Object.wait) to check for preemption.
490 address _preempt_alternate_return;
491 // When preempting on monitorenter we could have acquired the
492 // monitor after freezing all vthread frames. In that case we
493 // set this field so that in the preempt stub we call thaw again
494 // instead of unmounting.
495 bool _preemption_cancelled;
496 // For Object.wait() we set this field to know if we need to
497 // throw IE at the end of thawing before returning to Java.
498 bool _pending_interrupted_exception;
499 // We allow preemption on some klass initialization calls.
500 // We use this boolean to mark such calls.
501 bool _at_preemptable_init;
502
503 public:
504 bool preemption_cancelled() { return _preemption_cancelled; }
505 void set_preemption_cancelled(bool b) { _preemption_cancelled = b; }
506
507 bool pending_interrupted_exception() { return _pending_interrupted_exception; }
508 void set_pending_interrupted_exception(bool b) { _pending_interrupted_exception = b; }
509
510 bool preempting() { return _preempt_alternate_return != nullptr; }
511 void set_preempt_alternate_return(address val) { _preempt_alternate_return = val; }
512
513 bool at_preemptable_init() { return _at_preemptable_init; }
514 void set_at_preemptable_init(bool b) { _at_preemptable_init = b; }
515
516 #ifdef ASSERT
517 // Used for extra logging with -Xlog:continuation+preempt
518 InstanceKlass* _preempt_init_klass;
519
520 InstanceKlass* preempt_init_klass() { return _preempt_init_klass; }
521 void set_preempt_init_klass(InstanceKlass* ik) { _preempt_init_klass = ik; }
522
523 int _interp_at_preemptable_vmcall_cnt;
524 int interp_at_preemptable_vmcall_cnt() { return _interp_at_preemptable_vmcall_cnt; }
525
526 bool _interp_redoing_vm_call;
527 bool interp_redoing_vm_call() const { return _interp_redoing_vm_call; };
528
529 class AtRedoVMCall : public StackObj {
530 JavaThread* _thread;
531 public:
532 AtRedoVMCall(JavaThread* t) : _thread(t) {
533 assert(!_thread->_interp_redoing_vm_call, "");
534 _thread->_interp_redoing_vm_call = true;
535 _thread->_interp_at_preemptable_vmcall_cnt++;
536 assert(_thread->_interp_at_preemptable_vmcall_cnt > 0, "Unexpected count: %d",
537 _thread->_interp_at_preemptable_vmcall_cnt);
538 }
539 ~AtRedoVMCall() {
540 assert(_thread->_interp_redoing_vm_call, "");
541 _thread->_interp_redoing_vm_call = false;
542 _thread->_interp_at_preemptable_vmcall_cnt--;
543 assert(_thread->_interp_at_preemptable_vmcall_cnt >= 0, "Unexpected count: %d",
544 _thread->_interp_at_preemptable_vmcall_cnt);
545 }
546 };
547 #endif // ASSERT
548
549 private:
550 friend class VMThread;
551 friend class ThreadWaitTransition;
552 friend class VM_Exit;
553
554 // Stack watermark barriers.
555 StackWatermarks _stack_watermarks;
556
557 public:
558 inline StackWatermarks* stack_watermarks() { return &_stack_watermarks; }
559
560 public:
561 // Constructor
562 JavaThread(MemTag mem_tag = mtThread); // delegating constructor
563 JavaThread(ThreadFunction entry_point, size_t stack_size = 0, MemTag mem_tag = mtThread);
564 ~JavaThread();
565
566 // Factory method to create a new JavaThread whose attach state is "is attaching"
567 static JavaThread* create_attaching_thread();
568
569 #ifdef ASSERT
570 // verify this JavaThread hasn't be published in the Threads::list yet
571 void verify_not_published();
572 #endif // ASSERT
573
574 StackOverflow* stack_overflow_state() { return &_stack_overflow_state; }
575
576 //JNI functiontable getter/setter for JVMTI jni function table interception API.
577 void set_jni_functions(struct JNINativeInterface_* functionTable) {
578 _jni_environment.functions = functionTable;
579 }
580 struct JNINativeInterface_* get_jni_functions() {
581 return (struct JNINativeInterface_ *)_jni_environment.functions;
582 }
583
584 // This function is called at thread creation to allow
585 // platform specific thread variables to be initialized.
586 void cache_global_variables();
587
588 // Executes Shutdown.shutdown()
589 void invoke_shutdown_hooks();
590
591 // Cleanup on thread exit
592 enum ExitType {
593 normal_exit,
594 jni_detach
595 };
596 void exit(bool destroy_vm, ExitType exit_type = normal_exit);
597
598 void cleanup_failed_attach_current_thread(bool is_daemon);
599
600 // Testers
601 virtual bool is_Java_thread() const { return true; }
602 virtual bool can_call_java() const { return true; }
603
604 virtual bool is_active_Java_thread() const;
605
606 // Thread oop. threadObj() can be null for initial JavaThread
607 // (or for threads attached via JNI)
608 oop threadObj() const;
609 void set_threadOopHandles(oop p);
610 oop vthread() const;
611 void set_vthread(oop p);
612 oop scopedValueCache() const;
613 void set_scopedValueCache(oop p);
614 void clear_scopedValueBindings();
615 oop jvmti_vthread() const;
616 void set_jvmti_vthread(oop p);
617 oop vthread_or_thread() const;
618
619 // Prepare thread and add to priority queue. If a priority is
620 // not specified, use the priority of the thread object. Threads_lock
621 // must be held while this function is called.
622 void prepare(jobject jni_thread, ThreadPriority prio=NoPriority);
623
624 void set_saved_exception_pc(address pc) { _saved_exception_pc = pc; }
625 address saved_exception_pc() { return _saved_exception_pc; }
626
627 ThreadFunction entry_point() const { return _entry_point; }
628
629 // Allocates a new Java level thread object for this thread. thread_name may be null.
630 void allocate_threadObj(Handle thread_group, const char* thread_name, bool daemon, TRAPS);
631
632 // Last frame anchor routines
633
634 JavaFrameAnchor* frame_anchor(void) { return &_anchor; }
635
636 // last_Java_sp
637 bool has_last_Java_frame() const { return _anchor.has_last_Java_frame(); }
638 intptr_t* last_Java_sp() const { return _anchor.last_Java_sp(); }
639
640 // last_Java_pc
641
642 address last_Java_pc(void) { return _anchor.last_Java_pc(); }
643
644 // Safepoint support
645 inline JavaThreadState thread_state() const;
646 inline void set_thread_state(JavaThreadState s);
647 inline void set_thread_state_fence(JavaThreadState s); // fence after setting thread state
648 inline ThreadSafepointState* safepoint_state() const;
649 inline void set_safepoint_state(ThreadSafepointState* state);
650 inline bool is_at_poll_safepoint();
651
652 // JavaThread termination and lifecycle support:
653 void smr_delete();
654 bool on_thread_list() const { return _on_thread_list; }
655 void set_on_thread_list() { _on_thread_list = true; }
656
657 // thread has called JavaThread::exit(), thread's GC barrier is detached
658 // or thread is terminated
659 bool is_exiting() const;
660 // thread's GC barrier is NOT detached and thread is NOT terminated
661 bool is_oop_safe() const;
662 // thread is terminated (no longer on the threads list); the thread must
663 // be protected by a ThreadsListHandle to avoid potential crashes.
664 bool check_is_terminated(TerminatedTypes l_terminated) const {
665 return l_terminated == _thread_terminated || l_terminated == _vm_exited;
666 }
667 bool is_terminated() const;
668 void set_terminated(TerminatedTypes t);
669
670 void block_if_vm_exited();
671
672 bool doing_unsafe_access() { return _doing_unsafe_access; }
673 void set_doing_unsafe_access(bool val) { _doing_unsafe_access = val; }
674
675 bool is_throwing_unsafe_access_error() { return _throwing_unsafe_access_error; }
676 void set_throwing_unsafe_access_error(bool val) { _throwing_unsafe_access_error = val; }
677
678 bool do_not_unlock_if_synchronized() { return _do_not_unlock_if_synchronized; }
679 void set_do_not_unlock_if_synchronized(bool val) { _do_not_unlock_if_synchronized = val; }
680
681 SafepointMechanism::ThreadData* poll_data() { return &_poll_data; }
682
683 static ByteSize polling_word_offset() {
684 ByteSize offset = byte_offset_of(Thread, _poll_data) +
685 byte_offset_of(SafepointMechanism::ThreadData, _polling_word);
686 // At least on x86_64, safepoint polls encode the offset as disp8 imm.
687 assert(in_bytes(offset) < 128, "Offset >= 128");
688 return offset;
689 }
690
691 static ByteSize polling_page_offset() {
692 ByteSize offset = byte_offset_of(Thread, _poll_data) +
693 byte_offset_of(SafepointMechanism::ThreadData, _polling_page);
694 // At least on x86_64, safepoint polls encode the offset as disp8 imm.
695 assert(in_bytes(offset) < 128, "Offset >= 128");
696 return offset;
697 }
698
699 void set_requires_cross_modify_fence(bool val) PRODUCT_RETURN NOT_PRODUCT({ _requires_cross_modify_fence = val; })
700
701 // Continuation support
702 ContinuationEntry* last_continuation() const { return _cont_entry; }
703 void set_cont_fastpath(intptr_t* x) { _cont_fastpath = x; }
704 void push_cont_fastpath(intptr_t* sp) { if (sp > _cont_fastpath) _cont_fastpath = sp; }
705 void set_cont_fastpath_thread_state(bool x) { _cont_fastpath_thread_state = (int)x; }
706 intptr_t* raw_cont_fastpath() const { return _cont_fastpath; }
707 bool cont_fastpath() const { return _cont_fastpath == nullptr && _cont_fastpath_thread_state != 0; }
708 bool cont_fastpath_thread_state() const { return _cont_fastpath_thread_state != 0; }
709
710 // Support for SharedRuntime::monitor_exit_helper()
711 ObjectMonitor* unlocked_inflated_monitor() const { return _unlocked_inflated_monitor; }
712 void clear_unlocked_inflated_monitor() {
713 _unlocked_inflated_monitor = nullptr;
714 }
715
716 inline bool is_vthread_mounted() const;
717 inline const ContinuationEntry* vthread_continuation() const;
718
719 private:
720 DEBUG_ONLY(void verify_frame_info();)
721
722 // Support for thread handshake operations
723 HandshakeState _handshake;
724 public:
725 HandshakeState* handshake_state() { return &_handshake; }
726
727 // A JavaThread can always safely operate on it self and other threads
728 // can do it safely if they are the active handshaker.
729 bool is_handshake_safe_for(Thread* th) const {
730 return _handshake.active_handshaker() == th || this == th;
731 }
732
733 // Suspend/resume support for JavaThread
734 // higher-level suspension/resume logic called by the public APIs
735 private:
736 SuspendResumeManager _suspend_resume_manager;
737 public:
738 bool java_suspend(bool register_vthread_SR);
739 bool java_resume(bool register_vthread_SR);
740 bool is_suspended() { return _suspend_resume_manager.is_suspended(); }
741 SuspendResumeManager* suspend_resume_manager() { return &_suspend_resume_manager; }
742
743 // Check for async exception in addition to safepoint.
744 static void check_special_condition_for_native_trans(JavaThread *thread);
745
746 // Synchronize with another thread that is deoptimizing objects of the
747 // current thread, i.e. reverts optimizations based on escape analysis.
748 void wait_for_object_deoptimization();
749
750 private:
751 bool _is_in_vthread_transition; // thread is in virtual thread mount state transition
752 JVMTI_ONLY(bool _is_vthread_transition_disabler;) // thread currently disabled vthread transitions
753 DEBUG_ONLY(bool _is_disabler_at_start;) // thread at process of disabling vthread transitions
754 public:
755 bool is_in_vthread_transition() const;
756 void set_is_in_vthread_transition(bool val);
757 JVMTI_ONLY(bool is_vthread_transition_disabler() const { return _is_vthread_transition_disabler; })
758 JVMTI_ONLY(void set_is_vthread_transition_disabler(bool val);)
759 #ifdef ASSERT
760 bool is_disabler_at_start() const { return _is_disabler_at_start; }
761 void set_is_disabler_at_start(bool val);
762 #endif
763
764 #if INCLUDE_JVMTI
765 inline bool set_carrier_thread_suspended();
766 inline bool clear_carrier_thread_suspended();
767
768 bool is_carrier_thread_suspended() const {
769 return AtomicAccess::load(&_carrier_thread_suspended);
770 }
771
772 bool is_disable_suspend() const { return _is_disable_suspend; }
773 void toggle_is_disable_suspend() { _is_disable_suspend = !_is_disable_suspend; }
774
775 bool is_in_java_upcall() const { return _is_in_java_upcall; }
776 void toggle_is_in_java_upcall() { _is_in_java_upcall = !_is_in_java_upcall; }
777
778 void disable_jvmti_events() { _jvmti_events_disabled++; }
779 void enable_jvmti_events() { _jvmti_events_disabled--; }
780
781 // Temporarily skip posting JVMTI events for safety reasons when executions is in a critical section:
782 // - is in a vthread transition (_is_in_vthread_transition)
783 // - is in an interruptLock or similar critical section (_is_disable_suspend)
784 // - JVMTI is making a Java upcall (_is_in_java_upcall)
785 bool should_hide_jvmti_events() const {
786 return _is_in_vthread_transition || _is_disable_suspend || _is_in_java_upcall || _jvmti_events_disabled != 0;
787 }
788
789 bool on_monitor_waited_event() { return _on_monitor_waited_event; }
790 void set_on_monitor_waited_event(bool val) { _on_monitor_waited_event = val; }
791
792 bool pending_contended_entered_event() { return _contended_entered_monitor != nullptr; }
793 ObjectMonitor* contended_entered_monitor() { return _contended_entered_monitor; }
794 #endif
795
796 void set_contended_entered_monitor(ObjectMonitor* val) NOT_JVMTI_RETURN JVMTI_ONLY({ _contended_entered_monitor = val; })
797
798 // Support for object deoptimization and JFR suspension
799 void handle_special_runtime_exit_condition();
800 bool has_special_runtime_exit_condition() {
801 return (_suspend_flags & _obj_deopt) != 0;
802 }
803
804 // Accessors for vframe array top
805 // The linked list of vframe arrays are sorted on sp. This means when we
806 // unpack the head must contain the vframe array to unpack.
807 void set_vframe_array_head(vframeArray* value) { _vframe_array_head = value; }
808 vframeArray* vframe_array_head() const { return _vframe_array_head; }
809
810 // Side structure for deferring update of java frame locals until deopt occurs
811 JvmtiDeferredUpdates* deferred_updates() const { return _jvmti_deferred_updates; }
812 void set_deferred_updates(JvmtiDeferredUpdates* du) { _jvmti_deferred_updates = du; }
813
814 // These only really exist to make debugging deopt problems simpler
815
816 void set_vframe_array_last(vframeArray* value) { _vframe_array_last = value; }
817 vframeArray* vframe_array_last() const { return _vframe_array_last; }
818
819 // The special resourceMark used during deoptimization
820
821 void set_deopt_mark(DeoptResourceMark* value) { _deopt_mark = value; }
822 DeoptResourceMark* deopt_mark(void) { return _deopt_mark; }
823
824 void set_deopt_compiled_method(nmethod* nm) { _deopt_nmethod = nm; }
825 nmethod* deopt_compiled_method() { return _deopt_nmethod; }
826
827 Method* callee_target() const { return _callee_target; }
828 void set_callee_target (Method* x) { _callee_target = x; }
829
830 // Oop results of vm runtime calls
831 oop vm_result_oop() const { return _vm_result_oop; }
832 void set_vm_result_oop(oop x) { _vm_result_oop = x; }
833
834 void set_vm_result_metadata(Metadata* x) { _vm_result_metadata = x; }
835
836 oop return_buffered_value() const { return _return_buffered_value; }
837 void set_return_buffered_value(oop val) { _return_buffered_value = val; }
838
839 // Is thread in scope of an InternalOOMEMark?
840 bool is_in_internal_oome_mark() const { return _is_in_internal_oome_mark; }
841 void set_is_in_internal_oome_mark(bool b) { _is_in_internal_oome_mark = b; }
842
843 #if INCLUDE_JVMCI
844 jlong pending_failed_speculation() const { return _pending_failed_speculation; }
845 void set_pending_monitorenter(bool b) { _pending_monitorenter = b; }
846 void set_pending_deoptimization(int reason) { _pending_deoptimization = reason; }
847 void set_pending_failed_speculation(jlong failed_speculation) { _pending_failed_speculation = failed_speculation; }
848 void set_pending_transfer_to_interpreter(bool b) { _pending_transfer_to_interpreter = b; }
849 void set_jvmci_alternate_call_target(address a) { assert(_jvmci._alternate_call_target == nullptr, "must be"); _jvmci._alternate_call_target = a; }
850 void set_jvmci_implicit_exception_pc(address a) { assert(_jvmci._implicit_exception_pc == nullptr, "must be"); _jvmci._implicit_exception_pc = a; }
851
852 JVMCIRuntime* libjvmci_runtime() const { return _libjvmci_runtime; }
853 void set_libjvmci_runtime(JVMCIRuntime* rt) {
854 assert((_libjvmci_runtime == nullptr && rt != nullptr) || (_libjvmci_runtime != nullptr && rt == nullptr), "must be");
855 _libjvmci_runtime = rt;
856 }
857 #endif // INCLUDE_JVMCI
858
859 // Exception handling for compiled methods
860 oop exception_oop() const;
861 address exception_pc() const { return _exception_pc; }
862
863 void set_exception_oop(oop o);
864 void set_exception_pc(address a) { _exception_pc = a; }
865 void set_exception_handler_pc(address a) { _exception_handler_pc = a; }
866
867 void clear_exception_oop_and_pc() {
868 set_exception_oop(nullptr);
869 set_exception_pc(nullptr);
870 }
871
872 // Check if address is in the usable part of the stack (excludes protected
873 // guard pages). Can be applied to any thread and is an approximation for
874 // using is_in_live_stack when the query has to happen from another thread.
875 bool is_in_usable_stack(address adr) const {
876 return is_in_stack_range_incl(adr, _stack_overflow_state.stack_reserved_zone_base());
877 }
878
879 // Misc. accessors/mutators
880 static ByteSize scopedValueCache_offset() { return byte_offset_of(JavaThread, _scopedValueCache); }
881
882 // For assembly stub generation
883 static ByteSize threadObj_offset() { return byte_offset_of(JavaThread, _threadObj); }
884 static ByteSize vthread_offset() { return byte_offset_of(JavaThread, _vthread); }
885 static ByteSize jni_environment_offset() { return byte_offset_of(JavaThread, _jni_environment); }
886 static ByteSize pending_jni_exception_check_fn_offset() {
887 return byte_offset_of(JavaThread, _pending_jni_exception_check_fn);
888 }
889 static ByteSize last_Java_sp_offset() {
890 return byte_offset_of(JavaThread, _anchor) + JavaFrameAnchor::last_Java_sp_offset();
891 }
892 static ByteSize last_Java_pc_offset() {
893 return byte_offset_of(JavaThread, _anchor) + JavaFrameAnchor::last_Java_pc_offset();
894 }
895 static ByteSize frame_anchor_offset() {
896 return byte_offset_of(JavaThread, _anchor);
897 }
898 static ByteSize callee_target_offset() { return byte_offset_of(JavaThread, _callee_target); }
899 static ByteSize vm_result_oop_offset() { return byte_offset_of(JavaThread, _vm_result_oop); }
900 static ByteSize vm_result_metadata_offset() { return byte_offset_of(JavaThread, _vm_result_metadata); }
901 static ByteSize return_buffered_value_offset() { return byte_offset_of(JavaThread, _return_buffered_value); }
902 static ByteSize thread_state_offset() { return byte_offset_of(JavaThread, _thread_state); }
903 static ByteSize saved_exception_pc_offset() { return byte_offset_of(JavaThread, _saved_exception_pc); }
904 static ByteSize osthread_offset() { return byte_offset_of(JavaThread, _osthread); }
905 #if INCLUDE_JVMCI
906 static ByteSize pending_deoptimization_offset() { return byte_offset_of(JavaThread, _pending_deoptimization); }
907 static ByteSize pending_monitorenter_offset() { return byte_offset_of(JavaThread, _pending_monitorenter); }
908 static ByteSize jvmci_alternate_call_target_offset() { return byte_offset_of(JavaThread, _jvmci._alternate_call_target); }
909 static ByteSize jvmci_implicit_exception_pc_offset() { return byte_offset_of(JavaThread, _jvmci._implicit_exception_pc); }
910 static ByteSize jvmci_counters_offset() { return byte_offset_of(JavaThread, _jvmci_counters); }
911 #endif // INCLUDE_JVMCI
912 static ByteSize exception_oop_offset() { return byte_offset_of(JavaThread, _exception_oop); }
913 static ByteSize exception_pc_offset() { return byte_offset_of(JavaThread, _exception_pc); }
914 static ByteSize exception_handler_pc_offset() { return byte_offset_of(JavaThread, _exception_handler_pc); }
915
916 static ByteSize active_handles_offset() { return byte_offset_of(JavaThread, _active_handles); }
917
918 // StackOverflow offsets
919 static ByteSize stack_overflow_limit_offset() {
920 return byte_offset_of(JavaThread, _stack_overflow_state._stack_overflow_limit);
921 }
922 static ByteSize stack_guard_state_offset() {
923 return byte_offset_of(JavaThread, _stack_overflow_state._stack_guard_state);
924 }
925 static ByteSize reserved_stack_activation_offset() {
926 return byte_offset_of(JavaThread, _stack_overflow_state._reserved_stack_activation);
927 }
928 static ByteSize shadow_zone_safe_limit() {
929 return byte_offset_of(JavaThread, _stack_overflow_state._shadow_zone_safe_limit);
930 }
931 static ByteSize shadow_zone_growth_watermark() {
932 return byte_offset_of(JavaThread, _stack_overflow_state._shadow_zone_growth_watermark);
933 }
934
935 static ByteSize suspend_flags_offset() { return byte_offset_of(JavaThread, _suspend_flags); }
936
937 static ByteSize do_not_unlock_if_synchronized_offset() { return byte_offset_of(JavaThread, _do_not_unlock_if_synchronized); }
938 static ByteSize should_post_on_exceptions_flag_offset() {
939 return byte_offset_of(JavaThread, _should_post_on_exceptions_flag);
940 }
941 static ByteSize doing_unsafe_access_offset() { return byte_offset_of(JavaThread, _doing_unsafe_access); }
942 NOT_PRODUCT(static ByteSize requires_cross_modify_fence_offset() { return byte_offset_of(JavaThread, _requires_cross_modify_fence); })
943
944 static ByteSize monitor_owner_id_offset() { return byte_offset_of(JavaThread, _monitor_owner_id); }
945
946 static ByteSize cont_entry_offset() { return byte_offset_of(JavaThread, _cont_entry); }
947 static ByteSize cont_fastpath_offset() { return byte_offset_of(JavaThread, _cont_fastpath); }
948 static ByteSize preemption_cancelled_offset() { return byte_offset_of(JavaThread, _preemption_cancelled); }
949 static ByteSize preempt_alternate_return_offset() { return byte_offset_of(JavaThread, _preempt_alternate_return); }
950 DEBUG_ONLY(static ByteSize interp_at_preemptable_vmcall_cnt_offset() { return byte_offset_of(JavaThread, _interp_at_preemptable_vmcall_cnt); })
951 static ByteSize unlocked_inflated_monitor_offset() { return byte_offset_of(JavaThread, _unlocked_inflated_monitor); }
952 static ByteSize is_in_vthread_transition_offset() { return byte_offset_of(JavaThread, _is_in_vthread_transition); }
953
954 #if INCLUDE_JVMTI
955 static ByteSize is_disable_suspend_offset() { return byte_offset_of(JavaThread, _is_disable_suspend); }
956 #endif
957
958 // Returns the jni environment for this thread
959 JNIEnv* jni_environment() { return &_jni_environment; }
960
961 // Returns the current thread as indicated by the given JNIEnv.
962 // We don't assert it is Thread::current here as that is done at the
963 // external JNI entry points where the JNIEnv is passed into the VM.
964 static JavaThread* thread_from_jni_environment(JNIEnv* env) {
965 JavaThread* current = reinterpret_cast<JavaThread*>(((intptr_t)env - in_bytes(jni_environment_offset())));
966 // We can't normally get here in a thread that has completed its
967 // execution and so "is_terminated", except when the call is from
968 // AsyncGetCallTrace, which can be triggered by a signal at any point in
969 // a thread's lifecycle. A thread is also considered terminated if the VM
970 // has exited, so we have to check this and block in case this is a daemon
971 // thread returning to the VM (the JNI DirectBuffer entry points rely on
972 // this).
973 if (current->is_terminated()) {
974 current->block_if_vm_exited();
975 }
976 return current;
977 }
978
979 // JNI critical regions. These can nest.
980 bool in_critical() { return _jni_active_critical > 0; }
981 bool in_last_critical() { return _jni_active_critical == 1; }
982 inline void enter_critical();
983 void exit_critical() {
984 assert(Thread::current() == this, "this must be current thread");
985 _jni_active_critical--;
986 assert(_jni_active_critical >= 0, "JNI critical nesting problem?");
987 }
988
989 // Atomic version; invoked by a thread other than the owning thread.
990 bool in_critical_atomic() { return AtomicAccess::load(&_jni_active_critical) > 0; }
991
992 // Checked JNI: is the programmer required to check for exceptions, if so specify
993 // which function name. Returning to a Java frame should implicitly clear the
994 // pending check, this is done for Native->Java transitions (i.e. user JNI code).
995 // VM->Java transitions are not cleared, it is expected that JNI code enclosed
996 // within ThreadToNativeFromVM makes proper exception checks (i.e. VM internal).
997 bool is_pending_jni_exception_check() const { return _pending_jni_exception_check_fn != nullptr; }
998 void clear_pending_jni_exception_check() { _pending_jni_exception_check_fn = nullptr; }
999 const char* get_pending_jni_exception_check() const { return _pending_jni_exception_check_fn; }
1000 void set_pending_jni_exception_check(const char* fn_name) { _pending_jni_exception_check_fn = (char*) fn_name; }
1001
1002 // For deadlock detection
1003 int depth_first_number() { return _depth_first_number; }
1004 void set_depth_first_number(int dfn) { _depth_first_number = dfn; }
1005
1006 public:
1007 bool in_deopt_handler() const { return _in_deopt_handler > 0; }
1008 void inc_in_deopt_handler() { _in_deopt_handler++; }
1009 void dec_in_deopt_handler() {
1010 assert(_in_deopt_handler > 0, "mismatched deopt nesting");
1011 if (_in_deopt_handler > 0) { // robustness
1012 _in_deopt_handler--;
1013 }
1014 }
1015
1016 private:
1017 void set_entry_point(ThreadFunction entry_point) { _entry_point = entry_point; }
1018
1019 // factor out low-level mechanics for use in both normal and error cases
1020 const char* get_thread_name_string(char* buf = nullptr, int buflen = 0) const;
1021
1022 public:
1023
1024 // Frame iteration; calls the function f for all frames on the stack
1025 void frames_do(void f(frame*, const RegisterMap*));
1026
1027 // Memory operations
1028 void oops_do_frames(OopClosure* f, NMethodClosure* cf);
1029 void oops_do_no_frames(OopClosure* f, NMethodClosure* cf);
1030
1031 // GC operations
1032 virtual void nmethods_do(NMethodClosure* cf);
1033
1034 // RedefineClasses Support
1035 void metadata_do(MetadataClosure* f);
1036
1037 // Debug method asserting thread states are correct during a handshake operation.
1038 DEBUG_ONLY(void verify_states_for_handshake();)
1039
1040 // Misc. operations
1041 const char* name() const;
1042 const char* name_raw() const;
1043 const char* type_name() const { return "JavaThread"; }
1044 static const char* name_for(oop thread_obj);
1045
1046 void print_on(outputStream* st, bool print_extended_info) const;
1047 void print_on(outputStream* st) const { print_on(st, false); }
1048 void print() const;
1049 void print_thread_state_on(outputStream*) const;
1050 void print_on_error(outputStream* st, char* buf, int buflen) const;
1051 void print_name_on_error(outputStream* st, char* buf, int buflen) const;
1052 void verify();
1053
1054 // Accessing frames
1055 frame last_frame() {
1056 _anchor.make_walkable();
1057 return pd_last_frame();
1058 }
1059 javaVFrame* last_java_vframe(RegisterMap* reg_map) { return last_java_vframe(last_frame(), reg_map); }
1060
1061 frame carrier_last_frame(RegisterMap* reg_map);
1062 javaVFrame* carrier_last_java_vframe(RegisterMap* reg_map) { return last_java_vframe(carrier_last_frame(reg_map), reg_map); }
1063
1064 frame vthread_last_frame();
1065 javaVFrame* vthread_last_java_vframe(RegisterMap* reg_map) { return last_java_vframe(vthread_last_frame(), reg_map); }
1066
1067 frame platform_thread_last_frame(RegisterMap* reg_map);
1068 javaVFrame* platform_thread_last_java_vframe(RegisterMap* reg_map) {
1069 return last_java_vframe(platform_thread_last_frame(reg_map), reg_map);
1070 }
1071
1072 javaVFrame* last_java_vframe(const frame f, RegisterMap* reg_map);
1073
1074 // Returns method at 'depth' java or native frames down the stack
1075 // Used for security checks
1076 Klass* security_get_caller_class(int depth);
1077
1078 // Print stack trace in external format
1079 // These variants print carrier/platform thread information only.
1080 void print_stack_on(outputStream* st);
1081 void print_stack() { print_stack_on(tty); }
1082 // This prints the currently mounted virtual thread.
1083 void print_vthread_stack_on(outputStream* st);
1084 // This prints the active stack: either carrier/platform or virtual.
1085 void print_active_stack_on(outputStream* st);
1086 // Print current stack trace for checked JNI warnings and JNI fatal errors.
1087 // This is the external format from above, but selecting the platform
1088 // or vthread as applicable.
1089 void print_jni_stack();
1090
1091 // Print stack traces in various internal formats
1092 void trace_stack() PRODUCT_RETURN;
1093 void trace_stack_from(vframe* start_vf) PRODUCT_RETURN;
1094 void trace_frames() PRODUCT_RETURN;
1095
1096 // Print an annotated view of the stack frames
1097 void print_frame_layout(int depth = 0, bool validate_only = false) NOT_DEBUG_RETURN;
1098 void validate_frame_layout() {
1099 print_frame_layout(0, true);
1100 }
1101
1102 // Function for testing deoptimization
1103 void deoptimize();
1104 void make_zombies();
1105
1106 void deoptimize_marked_methods();
1107
1108 public:
1109 // Returns the running thread as a JavaThread
1110 static JavaThread* current() {
1111 return JavaThread::cast(Thread::current());
1112 }
1113
1114 // Returns the current thread as a JavaThread, or nullptr if not attached
1115 static inline JavaThread* current_or_null();
1116
1117 // Casts
1118 static JavaThread* cast(Thread* t) {
1119 assert(t->is_Java_thread(), "incorrect cast to JavaThread");
1120 return static_cast<JavaThread*>(t);
1121 }
1122
1123 static const JavaThread* cast(const Thread* t) {
1124 assert(t->is_Java_thread(), "incorrect cast to const JavaThread");
1125 return static_cast<const JavaThread*>(t);
1126 }
1127
1128 // Returns the active Java thread. Do not use this if you know you are calling
1129 // from a JavaThread, as it's slower than JavaThread::current. If called from
1130 // the VMThread, it also returns the JavaThread that instigated the VMThread's
1131 // operation. You may not want that either.
1132 static JavaThread* active();
1133
1134 protected:
1135 virtual void pre_run();
1136 virtual void run();
1137 void thread_main_inner();
1138 virtual void post_run();
1139
1140 public:
1141 // Thread local information maintained by JVMTI.
1142 void set_jvmti_thread_state(JvmtiThreadState *value) { _jvmti_thread_state = value; }
1143 // A JvmtiThreadState is lazily allocated. This jvmti_thread_state()
1144 // getter is used to get this JavaThread's JvmtiThreadState if it has
1145 // one which means null can be returned. JvmtiThreadState::state_for()
1146 // is used to get the specified JavaThread's JvmtiThreadState if it has
1147 // one or it allocates a new JvmtiThreadState for the JavaThread and
1148 // returns it. JvmtiThreadState::state_for() will return null only if
1149 // the specified JavaThread is exiting.
1150 JvmtiThreadState *jvmti_thread_state() const { return _jvmti_thread_state; }
1151 static ByteSize jvmti_thread_state_offset() { return byte_offset_of(JavaThread, _jvmti_thread_state); }
1152
1153 #if INCLUDE_JVMTI
1154 // Rebind JVMTI thread state from carrier to virtual or from virtual to carrier.
1155 JvmtiThreadState *rebind_to_jvmti_thread_state_of(oop thread_oop);
1156 #endif
1157
1158 // JVMTI PopFrame support
1159 // Setting and clearing popframe_condition
1160 // All of these enumerated values are bits. popframe_pending
1161 // indicates that a PopFrame() has been requested and not yet been
1162 // completed. popframe_processing indicates that that PopFrame() is in
1163 // the process of being completed. popframe_force_deopt_reexecution_bit
1164 // indicates that special handling is required when returning to a
1165 // deoptimized caller.
1166 enum PopCondition {
1167 popframe_inactive = 0x00,
1168 popframe_pending_bit = 0x01,
1169 popframe_processing_bit = 0x02,
1170 popframe_force_deopt_reexecution_bit = 0x04
1171 };
1172 PopCondition popframe_condition() { return (PopCondition) _popframe_condition; }
1173 void set_popframe_condition(PopCondition c) { _popframe_condition = c; }
1174 void set_popframe_condition_bit(PopCondition c) { _popframe_condition |= c; }
1175 void clear_popframe_condition() { _popframe_condition = popframe_inactive; }
1176 static ByteSize popframe_condition_offset() { return byte_offset_of(JavaThread, _popframe_condition); }
1177 bool has_pending_popframe() { return (popframe_condition() & popframe_pending_bit) != 0; }
1178 bool popframe_forcing_deopt_reexecution() { return (popframe_condition() & popframe_force_deopt_reexecution_bit) != 0; }
1179
1180 bool pop_frame_in_process(void) { return ((_popframe_condition & popframe_processing_bit) != 0); }
1181 void set_pop_frame_in_process(void) { _popframe_condition |= popframe_processing_bit; }
1182 void clr_pop_frame_in_process(void) { _popframe_condition &= ~popframe_processing_bit; }
1183
1184 int frames_to_pop_failed_realloc() const { return _frames_to_pop_failed_realloc; }
1185 void set_frames_to_pop_failed_realloc(int nb) { _frames_to_pop_failed_realloc = nb; }
1186 void dec_frames_to_pop_failed_realloc() { _frames_to_pop_failed_realloc--; }
1187
1188 private:
1189 // Saved incoming arguments to popped frame.
1190 // Used only when popped interpreted frame returns to deoptimized frame.
1191 void* _popframe_preserved_args;
1192 int _popframe_preserved_args_size;
1193
1194 public:
1195 void popframe_preserve_args(ByteSize size_in_bytes, void* start);
1196 void* popframe_preserved_args();
1197 ByteSize popframe_preserved_args_size();
1198 WordSize popframe_preserved_args_size_in_words();
1199 void popframe_free_preserved_args();
1200
1201
1202 private:
1203 JvmtiThreadState *_jvmti_thread_state;
1204
1205 // Used by the interpreter in fullspeed mode for frame pop, method
1206 // entry, method exit and single stepping support. This field is
1207 // only set to non-zero at a safepoint or using a direct handshake
1208 // (see EnterInterpOnlyModeHandshakeClosure).
1209 // It can be set to zero asynchronously to this threads execution (i.e., without
1210 // safepoint/handshake or a lock) so we have to be very careful.
1211 // Accesses by other threads are synchronized using JvmtiThreadState_lock though.
1212 // This field is checked by the interpreter which expects it to be an integer.
1213 int _interp_only_mode;
1214
1215 public:
1216 // used by the interpreter for fullspeed debugging support (see above)
1217 static ByteSize interp_only_mode_offset() { return byte_offset_of(JavaThread, _interp_only_mode); }
1218 bool is_interp_only_mode() { return (_interp_only_mode != 0); }
1219 void set_interp_only_mode(bool val) { _interp_only_mode = val ? 1 : 0; }
1220
1221 // support for cached flag that indicates whether exceptions need to be posted for this thread
1222 // if this is false, we can avoid deoptimizing when events are thrown
1223 // this gets set to reflect whether jvmtiExport::post_exception_throw would actually do anything
1224 private:
1225 int _should_post_on_exceptions_flag;
1226
1227 public:
1228 void set_should_post_on_exceptions_flag(int val) { _should_post_on_exceptions_flag = val; }
1229
1230 private:
1231 ThreadStatistics *_thread_stat;
1232
1233 public:
1234 ThreadStatistics* get_thread_stat() const { return _thread_stat; }
1235
1236 // Return a blocker object for which this thread is blocked parking.
1237 oop current_park_blocker();
1238
1239 private:
1240 static size_t _stack_size_at_create;
1241
1242 public:
1243 static inline size_t stack_size_at_create(void) {
1244 return _stack_size_at_create;
1245 }
1246 static inline void set_stack_size_at_create(size_t value) {
1247 _stack_size_at_create = value;
1248 }
1249
1250 // Machine dependent stuff
1251 #include OS_CPU_HEADER(javaThread)
1252
1253 // JSR166 per-thread parker
1254 private:
1255 Parker _parker;
1256 public:
1257 Parker* parker() { return &_parker; }
1258
1259 public:
1260 // clearing/querying jni attach status
1261 bool is_attaching_via_jni() const { return _jni_attach_state == _attaching_via_jni; }
1262 bool has_attached_via_jni() const { return is_attaching_via_jni() || _jni_attach_state == _attached_via_jni; }
1263 inline void set_done_attaching_via_jni();
1264
1265 // Stack dump assistance:
1266 // Track the class we want to initialize but for which we have to wait
1267 // on its init_lock() because it is already being initialized.
1268 void set_class_to_be_initialized(InstanceKlass* k);
1269 InstanceKlass* class_to_be_initialized() const;
1270
1271 // Track executing class initializer, see ThreadInClassInitializer
1272 void set_class_being_initialized(InstanceKlass* k);
1273 InstanceKlass* class_being_initialized() const;
1274
1275 private:
1276 InstanceKlass* _class_to_be_initialized;
1277 InstanceKlass* _class_being_initialized;
1278
1279 // java.lang.Thread.sleep support
1280 ParkEvent * _SleepEvent;
1281
1282 #if INCLUDE_JFR
1283 // Support for jdk.VirtualThreadPinned event
1284 freeze_result _last_freeze_fail_result;
1285 Ticks _last_freeze_fail_time;
1286 #endif
1287
1288 public:
1289 bool sleep(jlong millis);
1290 bool sleep_nanos(jlong nanos);
1291
1292 // java.lang.Thread interruption support
1293 void interrupt();
1294 bool is_interrupted(bool clear_interrupted);
1295
1296 #if INCLUDE_JFR
1297 // Support for jdk.VirtualThreadPinned event
1298 freeze_result last_freeze_fail_result() { return _last_freeze_fail_result; }
1299 Ticks& last_freeze_fail_time() { return _last_freeze_fail_time; }
1300 void set_last_freeze_fail_result(freeze_result result);
1301 #endif
1302 void post_vthread_pinned_event(EventVirtualThreadPinned* event, const char* op, freeze_result result) NOT_JFR_RETURN();
1303
1304
1305 // This is only for use by JVMTI RawMonitorWait. It emulates the actions of
1306 // the Java code in Object::wait which are not present in RawMonitorWait.
1307 bool get_and_clear_interrupted();
1308
1309 private:
1310
1311 #ifdef MACOS_AARCH64
1312 friend class ThreadWXEnable;
1313 friend class PosixSignals;
1314
1315 ThreadWXEnable* _cur_wx_enable;
1316 WXMode* _cur_wx_mode;
1317 #endif
1318
1319 LockStack _lock_stack;
1320 OMCache _om_cache;
1321
1322 public:
1323 LockStack& lock_stack() { return _lock_stack; }
1324
1325 static ByteSize lock_stack_offset() { return byte_offset_of(JavaThread, _lock_stack); }
1326 // Those offsets are used in code generators to access the LockStack that is embedded in this
1327 // JavaThread structure. Those accesses are relative to the current thread, which
1328 // is typically in a dedicated register.
1329 static ByteSize lock_stack_top_offset() { return lock_stack_offset() + LockStack::top_offset(); }
1330 static ByteSize lock_stack_base_offset() { return lock_stack_offset() + LockStack::base_offset(); }
1331
1332 static ByteSize om_cache_offset() { return byte_offset_of(JavaThread, _om_cache); }
1333 static ByteSize om_cache_oops_offset() { return om_cache_offset() + OMCache::entries_offset(); }
1334
1335 void om_set_monitor_cache(ObjectMonitor* monitor);
1336 void om_clear_monitor_cache();
1337 ObjectMonitor* om_get_from_monitor_cache(oop obj);
1338
1339 static OopStorage* thread_oop_storage();
1340
1341 static void verify_cross_modify_fence_failure(JavaThread *thread) PRODUCT_RETURN;
1342
1343 // Helper function to create the java.lang.Thread object for a
1344 // VM-internal thread. The thread will have the given name and be
1345 // part of the System ThreadGroup.
1346 static Handle create_system_thread_object(const char* name, TRAPS);
1347
1348 // Helper function to start a VM-internal daemon thread.
1349 // E.g. ServiceThread, NotificationThread, CompilerThread etc.
1350 static void start_internal_daemon(JavaThread* current, JavaThread* target,
1351 Handle thread_oop, ThreadPriority prio);
1352
1353 // Helper function to do vm_exit_on_initialization for osthread
1354 // resource allocation failure.
1355 static void vm_exit_on_osthread_failure(JavaThread* thread);
1356
1357 // Deferred OopHandle release support
1358 private:
1359 // List of OopHandles to be released - guarded by the Service_lock.
1360 static OopHandleList* _oop_handle_list;
1361 // Add our OopHandles to the list for the service thread to release.
1362 void add_oop_handles_for_release();
1363 // Called by the ServiceThread to release the OopHandles.
1364 static void release_oop_handles();
1365 // Called by the ServiceThread to poll if there are any OopHandles to release.
1366 // Called when holding the Service_lock.
1367 static bool has_oop_handles_to_release() {
1368 return _oop_handle_list != nullptr;
1369 }
1370 };
1371
1372 inline JavaThread* JavaThread::current_or_null() {
1373 Thread* current = Thread::current_or_null();
1374 return current != nullptr ? JavaThread::cast(current) : nullptr;
1375 }
1376
1377 class UnlockFlagSaver {
1378 private:
1379 JavaThread* _thread;
1380 bool _do_not_unlock;
1381 public:
1382 UnlockFlagSaver(JavaThread* t) {
1383 _thread = t;
1384 _do_not_unlock = t->do_not_unlock_if_synchronized();
1385 t->set_do_not_unlock_if_synchronized(false);
1386 }
1387 ~UnlockFlagSaver() {
1388 _thread->set_do_not_unlock_if_synchronized(_do_not_unlock);
1389 }
1390 };
1391
1392 class JNIHandleMark : public StackObj {
1393 JavaThread* _thread;
1394 public:
1395 JNIHandleMark(JavaThread* thread) : _thread(thread) {
1396 thread->push_jni_handle_block();
1397 }
1398 ~JNIHandleMark() { _thread->pop_jni_handle_block(); }
1399 };
1400
1401 class NoPreemptMark {
1402 ContinuationEntry* _ce;
1403 bool _unpin;
1404 public:
1405 NoPreemptMark(JavaThread* thread, bool ignore_mark = false) : _ce(thread->last_continuation()), _unpin(false) {
1406 if (_ce != nullptr && !ignore_mark) _unpin = _ce->pin();
1407 }
1408 ~NoPreemptMark() { if (_unpin) _ce->unpin(); }
1409 };
1410
1411 class ThreadOnMonitorWaitedEvent {
1412 JavaThread* _thread;
1413 public:
1414 ThreadOnMonitorWaitedEvent(JavaThread* thread) : _thread(thread) {
1415 JVMTI_ONLY(_thread->set_on_monitor_waited_event(true);)
1416 }
1417 ~ThreadOnMonitorWaitedEvent() { JVMTI_ONLY(_thread->set_on_monitor_waited_event(false);) }
1418 };
1419
1420 class ThreadInClassInitializer : public StackObj {
1421 JavaThread* _thread;
1422 InstanceKlass* _previous;
1423 public:
1424 ThreadInClassInitializer(JavaThread* thread, InstanceKlass* ik) : _thread(thread) {
1425 _previous = _thread->class_being_initialized();
1426 _thread->set_class_being_initialized(ik);
1427 }
1428 ~ThreadInClassInitializer() {
1429 _thread->set_class_being_initialized(_previous);
1430 }
1431 };
1432
1433 class ThrowingUnsafeAccessError : public StackObj {
1434 JavaThread* _thread;
1435 bool _prev;
1436 public:
1437 ThrowingUnsafeAccessError(JavaThread* thread) :
1438 _thread(thread),
1439 _prev(thread->is_throwing_unsafe_access_error()) {
1440 _thread->set_throwing_unsafe_access_error(true);
1441 }
1442 ~ThrowingUnsafeAccessError() {
1443 _thread->set_throwing_unsafe_access_error(_prev);
1444 }
1445 };
1446
1447 #endif // SHARE_RUNTIME_JAVATHREAD_HPP