1 /*
  2  * Copyright (c) 2003, 2026, Oracle and/or its affiliates. All rights reserved.
  3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4  *
  5  * This code is free software; you can redistribute it and/or modify it
  6  * under the terms of the GNU General Public License version 2 only, as
  7  * published by the Free Software Foundation.
  8  *
  9  * This code is distributed in the hope that it will be useful, but WITHOUT
 10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 12  * version 2 for more details (a copy is included in the LICENSE file that
 13  * accompanied this code).
 14  *
 15  * You should have received a copy of the GNU General Public License version
 16  * 2 along with this work; if not, write to the Free Software Foundation,
 17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 18  *
 19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 20  * or visit www.oracle.com if you need additional information or have any
 21  * questions.
 22  *
 23  */
 24 
 25 #ifndef SHARE_PRIMS_JVMTIENVBASE_HPP
 26 #define SHARE_PRIMS_JVMTIENVBASE_HPP
 27 
 28 #include "oops/oopHandle.hpp"
 29 #include "prims/jvmtiEnvThreadState.hpp"
 30 #include "prims/jvmtiEventController.hpp"
 31 #include "prims/jvmtiThreadState.hpp"
 32 #include "runtime/atomicAccess.hpp"
 33 #include "runtime/fieldDescriptor.hpp"
 34 #include "runtime/frame.hpp"
 35 #include "runtime/javaThread.hpp"
 36 #include "runtime/threads.hpp"
 37 #include "runtime/vmOperation.hpp"
 38 #include "utilities/growableArray.hpp"
 39 #include "utilities/macros.hpp"
 40 
 41 //
 42 // Forward Declarations
 43 //
 44 
 45 class JvmtiEnv;
 46 class JvmtiThreadState;
 47 class JvmtiRawMonitor; // for jvmtiEnv.hpp
 48 class JvmtiEventControllerPrivate;
 49 class JvmtiTagMap;
 50 
 51 
 52 
 53 // One JvmtiEnv object is created per jvmti attachment;
 54 // done via JNI GetEnv() call. Multiple attachments are
 55 // allowed in jvmti.
 56 
 57 class JvmtiEnvBase : public CHeapObj<mtInternal> {
 58 
 59  private:
 60 
 61 #if INCLUDE_JVMTI
 62   static JvmtiEnvBase*     _head_environment;  // head of environment list
 63 #endif // INCLUDE_JVMTI
 64 
 65   static bool              _globally_initialized;
 66   static jvmtiPhase        _phase;
 67   static volatile int      _dying_thread_env_iteration_count;
 68 
 69  public:
 70 
 71   enum {
 72     JDK15_JVMTI_VERSION = JVMTI_VERSION_1_0 +  33,  /* version: 1.0.33  */
 73     JDK16_JVMTI_VERSION = JVMTI_VERSION_1_1 + 102,  /* version: 1.1.102 */
 74     JDK17_JVMTI_VERSION = JVMTI_VERSION_1_2 +   2   /* version: 1.2.2   */
 75   };
 76 
 77   static jvmtiPhase  get_phase()                    { return _phase; }
 78   static jvmtiPhase  get_phase(jvmtiEnv* env)       { return ((JvmtiEnvBase*)JvmtiEnv_from_jvmti_env(env))->phase(); }
 79   static void  set_phase(jvmtiPhase phase)          { _phase = phase; }
 80   static bool is_vm_live()                          { return _phase == JVMTI_PHASE_LIVE; }
 81 
 82   static void entering_dying_thread_env_iteration() { ++_dying_thread_env_iteration_count; }
 83   static void leaving_dying_thread_env_iteration()  { --_dying_thread_env_iteration_count; }
 84   static bool is_inside_dying_thread_env_iteration(){ return _dying_thread_env_iteration_count > 0; }
 85 
 86   // This function is to support agents loaded into running VM.
 87   static bool enable_virtual_threads_notify_jvmti();
 88 
 89   // This function is used in WhiteBox, only needed to test the function above.
 90   // It is unsafe to use this function when virtual threads are executed.
 91   static bool disable_virtual_threads_notify_jvmti();
 92 
 93   static jvmtiError suspend_thread(oop thread_oop, JavaThread* java_thread, bool single_suspend);
 94   static jvmtiError resume_thread(oop thread_oop, JavaThread* java_thread, bool single_resume);
 95   static jvmtiError check_thread_list(jint count, const jthread* list);
 96   static bool is_in_thread_list(jint count, const jthread* list, oop jt_oop);
 97 
 98   // check if thread_oop represents a thread carrying a virtual thread
 99   static bool is_thread_carrying_vthread(JavaThread* java_thread, oop thread_oop) {
100     return java_thread != nullptr && java_thread->jvmti_vthread() != nullptr
101                                && java_thread->jvmti_vthread() != thread_oop
102                                && java_thread->threadObj() == thread_oop;
103   }
104 
105  private:
106 
107   enum {
108       JVMTI_MAGIC    = 0x71EE,
109       DISPOSED_MAGIC = 0xDEFC,
110       BAD_MAGIC      = 0xDEAD
111   };
112 
113   jvmtiEnv _jvmti_external;
114   jint _magic;
115   jint _version;  // version value passed to JNI GetEnv()
116   JvmtiEnvBase* _next;
117   bool _is_retransformable;
118   const void *_env_local_storage;     // per env agent allocated data.
119   jvmtiEventCallbacks _event_callbacks;
120   jvmtiExtEventCallbacks _ext_event_callbacks;
121   JvmtiTagMap* volatile _tag_map;
122   JvmtiEnvEventEnable _env_event_enable;
123   jvmtiCapabilities _current_capabilities;
124   jvmtiCapabilities _prohibited_capabilities;
125   volatile bool _class_file_load_hook_ever_enabled;
126   static volatile bool _needs_clean_up;
127   char** _native_method_prefixes;
128   int    _native_method_prefix_count;
129 
130  protected:
131   JvmtiEnvBase(jint version);
132   ~JvmtiEnvBase();
133   void dispose();
134   void env_dispose();
135 
136   void set_env_local_storage(const void* data)     { _env_local_storage = data; }
137 
138   void record_class_file_load_hook_enabled();
139   void record_first_time_class_file_load_hook_enabled();
140 
141   char** get_native_method_prefixes()              { return _native_method_prefixes; }
142   int    get_native_method_prefix_count()          { return _native_method_prefix_count; }
143   jvmtiError set_native_method_prefixes(jint prefix_count, char** prefixes);
144 
145  private:
146   friend class JvmtiEventControllerPrivate;
147   void initialize();
148   void set_event_callbacks(const jvmtiEventCallbacks* callbacks, jint size_of_callbacks);
149   static void globally_initialize();
150   static void periodic_clean_up();
151 
152   friend class JvmtiEnvIterator;
153   JvmtiEnv* next_environment()                     { return (JvmtiEnv*)_next; }
154   void set_next_environment(JvmtiEnvBase* env)     { _next = env; }
155   static JvmtiEnv* head_environment()              {
156     JVMTI_ONLY(return (JvmtiEnv*)_head_environment);
157     NOT_JVMTI(return nullptr);
158   }
159 
160  public:
161 
162   jvmtiPhase  phase();
163   bool is_valid();
164 
165   bool use_version_1_0_semantics();  // agent asked for version 1.0
166   bool use_version_1_1_semantics();  // agent asked for version 1.1
167   bool use_version_1_2_semantics();  // agent asked for version 1.2
168 
169   bool is_retransformable()                        { return _is_retransformable; }
170 
171   const void* get_env_local_storage() { return _env_local_storage; }
172 
173   static ByteSize jvmti_external_offset() {
174     return byte_offset_of(JvmtiEnvBase, _jvmti_external);
175   };
176 
177   // If (thread == nullptr) then return current thread object.
178   // Otherwise return JNIHandles::resolve_external_guard(thread).
179   static oop current_thread_obj_or_resolve_external_guard(jthread thread);
180 
181   // Return true if the thread identified with a pair <jt,thr_obj> is current.
182   // A thread carrying a virtual thread is not treated as current.
183   static bool is_JavaThread_current(JavaThread* jt, oop thr_obj) {
184     JavaThread* current = JavaThread::current();
185     // jt can be null in case of a virtual thread
186     if (jt == nullptr || jt != current) {
187       return false;
188     }
189     oop cur_obj = current->jvmti_vthread();
190 
191     // cur_obj == nullptr is true for normal platform threads only
192     // otherwise it can be virtual or carrier thread.
193     return cur_obj == nullptr || cur_obj == thr_obj;
194   }
195 
196   static jvmtiError get_JavaThread(ThreadsList* tlist, jthread thread, JavaThread** jt_pp) {
197     jvmtiError err = JVMTI_ERROR_NONE;
198     if (thread == nullptr) {
199       *jt_pp = JavaThread::current();
200     } else {
201       err = JvmtiExport::cv_external_thread_to_JavaThread(tlist, thread, jt_pp, nullptr);
202     }
203     return err;
204   }
205 
206   // If there is a virtual thread mounted on the JavaThread* then
207   // return virtual thread oop. Otherwise, return thread oop.
208   static oop get_vthread_or_thread_oop(JavaThread* jt) {
209     oop result = jt->threadObj();
210     if (jt->jvmti_vthread() != nullptr) {
211       result = jt->jvmti_vthread();
212     }
213     return result;
214   }
215 
216   static jvmtiError get_threadOop_and_JavaThread(ThreadsList* t_list, jthread thread, JavaThread* cur_thread,
217                                                  JavaThread** jt_pp, oop* thread_oop_p);
218 
219   // Return true if java thread is a carrier thread with a mounted virtual thread.
220   static bool is_cthread_with_mounted_vthread(JavaThread* jt);
221   static bool is_cthread_with_continuation(JavaThread* jt);
222 
223   // Check if VirtualThread or BoundVirtualThread is suspended.
224   static bool is_vthread_suspended(oop vt_oop, JavaThread* jt);
225 
226   // Check for JVMTI_ERROR_NOT_SUSPENDED and JVMTI_ERROR_OPAQUE_FRAME errors.
227   // Used in PopFrame and ForceEarlyReturn implementations.
228   static jvmtiError check_non_suspended_or_opaque_frame(JavaThread* jt, oop thr_obj, bool self);
229 
230   static JvmtiEnv* JvmtiEnv_from_jvmti_env(jvmtiEnv *env) {
231     return (JvmtiEnv*)((intptr_t)env - in_bytes(jvmti_external_offset()));
232   };
233 
234   jvmtiCapabilities *get_capabilities()             { return &_current_capabilities; }
235 
236   jvmtiCapabilities *get_prohibited_capabilities()  { return &_prohibited_capabilities; }
237 
238   bool early_class_hook_env() {
239     return get_capabilities()->can_generate_early_class_hook_events != 0
240         && get_capabilities()->can_generate_all_class_hook_events != 0;
241   }
242 
243   bool early_vmstart_env() {
244     return get_capabilities()->can_generate_early_vmstart != 0;
245   }
246 
247   static char** get_all_native_method_prefixes(int* count_ptr);
248 
249   // This test will answer true when all environments have been disposed and some have
250   // not yet been deallocated.  As a result, this test should only be used as an
251   // optimization for the no environment case.
252   static bool environments_might_exist() {
253     return head_environment() != nullptr;
254   }
255 
256   static void check_for_periodic_clean_up();
257 
258   JvmtiEnvEventEnable *env_event_enable() {
259     return &_env_event_enable;
260   }
261 
262   jvmtiError allocate(jlong size, unsigned char** mem_ptr) {
263     if (size < 0) {
264       return JVMTI_ERROR_ILLEGAL_ARGUMENT;
265     }
266     if (size == 0) {
267       *mem_ptr = nullptr;
268     } else {
269       *mem_ptr = (unsigned char *)os::malloc((size_t)size, mtInternal);
270       if (*mem_ptr == nullptr) {
271         return JVMTI_ERROR_OUT_OF_MEMORY;
272       }
273     }
274     return JVMTI_ERROR_NONE;
275   }
276 
277   jvmtiError deallocate(unsigned char* mem) {
278     if (mem != nullptr) {
279       os::free(mem);
280     }
281     return JVMTI_ERROR_NONE;
282   }
283 
284 
285   // Memory functions
286   unsigned char* jvmtiMalloc(jlong size);  // don't use this - call allocate
287 
288   // method to create a local handle
289   jobject jni_reference(Handle hndl);
290 
291   // method to create a local handle.
292   // This function allows caller to specify which
293   // threads local handle table to use.
294   jobject jni_reference(JavaThread *thread, Handle hndl);
295 
296   // method to destroy a local handle
297   void destroy_jni_reference(jobject jobj);
298 
299   // method to destroy a local handle.
300   // This function allows caller to specify which
301   // threads local handle table to use.
302   void destroy_jni_reference(JavaThread *thread, jobject jobj);
303 
304   jvmtiEnv* jvmti_external() { return &_jvmti_external; };
305 
306 // Event Dispatch
307 
308   bool has_callback(jvmtiEvent event_type) {
309     assert(event_type >= JVMTI_MIN_EVENT_TYPE_VAL &&
310            event_type <= JVMTI_MAX_EVENT_TYPE_VAL, "checking");
311     return ((void**)&_event_callbacks)[event_type-JVMTI_MIN_EVENT_TYPE_VAL] != nullptr;
312   }
313 
314   jvmtiEventCallbacks* callbacks() {
315     return &_event_callbacks;
316   }
317 
318   jvmtiExtEventCallbacks* ext_callbacks() {
319     return &_ext_event_callbacks;
320   }
321 
322   void set_tag_map(JvmtiTagMap* tag_map) {
323     _tag_map = tag_map;
324   }
325 
326   JvmtiTagMap* tag_map() {
327     return _tag_map;
328   }
329 
330   JvmtiTagMap* tag_map_acquire() {
331     return AtomicAccess::load_acquire(&_tag_map);
332   }
333 
334   void release_set_tag_map(JvmtiTagMap* tag_map) {
335     AtomicAccess::release_store(&_tag_map, tag_map);
336   }
337 
338   // return true if event is enabled globally or for any thread
339   // True only if there is a callback for it.
340   bool is_enabled(jvmtiEvent event_type) {
341     return _env_event_enable.is_enabled(event_type);
342   }
343 
344 // Random Utilities
345 
346  protected:
347   // helper methods for creating arrays of global JNI Handles from local Handles
348   // allocated into environment specific storage
349   jthread * new_jthreadArray(int length, Handle *handles);
350   jthreadGroup * new_jthreadGroupArray(int length, objArrayHandle groups);
351 
352   // convert to a jni jclass from a non-null Klass*
353   jclass get_jni_class_non_null(Klass* k);
354 
355   jint count_locked_objects(JavaThread *java_thread, Handle hobj);
356   jvmtiError get_locked_objects_in_frame(JavaThread *calling_thread,
357                                    JavaThread* java_thread,
358                                    javaVFrame *jvf,
359                                    GrowableArray<jvmtiMonitorStackDepthInfo*>* owned_monitors_list,
360                                    jint depth, oop vthread = nullptr);
361  public:
362   static javaVFrame* jvf_for_thread_and_depth(JavaThread* java_thread, jint depth);
363 
364   // get a field descriptor for the specified class and field
365   static bool get_field_descriptor(Klass* k, jfieldID field, fieldDescriptor* fd);
366 
367   // check and skip frames hidden in mount/unmount transitions
368   static javaVFrame* skip_yield_frames_for_unmounted_vthread(oop vthread, javaVFrame* jvf);
369   static javaVFrame* check_and_skip_hidden_frames(bool is_in_VTMS_transition, javaVFrame* jvf);
370   static javaVFrame* check_and_skip_hidden_frames(JavaThread* jt, javaVFrame* jvf);
371 
372   // check if virtual thread is not terminated (alive)
373   static bool is_vthread_alive(oop vt);
374 
375   // return JavaThread if virtual thread is mounted, null otherwise
376   static JavaThread* get_JavaThread_or_null(oop vthread);
377 
378   // get virtual thread last java vframe
379   static javaVFrame* get_vthread_jvf(oop vthread);
380 
381   // get carrier thread last java vframe
382   static javaVFrame* get_cthread_last_java_vframe(JavaThread* jt, RegisterMap* reg_map);
383 
384   // get platform thread state
385   static jint get_thread_state_base(oop thread_oop, JavaThread* jt);
386   static jint get_thread_state(oop thread_oop, JavaThread* jt);
387 
388   // get virtual thread state
389   static jint get_vthread_state(oop thread_oop, JavaThread* jt);
390 
391   // get platform or virtual thread state
392   static jint get_thread_or_vthread_state(oop thread_oop, JavaThread* jt);
393 
394   // enumerates the live threads in the given thread group
395   static jvmtiError get_live_threads(JavaThread* current_thread, Handle group_hdl, jint *count_ptr, Handle **thread_objs_p);
396 
397   // enumerates the subgroups in the given thread group
398   static jvmtiError get_subgroups(JavaThread* current_thread, Handle group_hdl, jint *count_ptr, objArrayHandle *group_objs_p);
399 
400   // JVMTI API helper functions which are called when target thread is suspended
401   // or at safepoint / thread local handshake.
402   static jint get_frame_count(javaVFrame* jvf);
403   jvmtiError get_frame_count(JavaThread* java_thread, jint *count_ptr);
404   jvmtiError get_frame_count(oop frame_oop, jint *count_ptr);
405   jvmtiError get_frame_location(javaVFrame* jvf, jint depth,
406                                 jmethodID* method_ptr, jlocation* location_ptr);
407   jvmtiError get_frame_location(JavaThread* java_thread, jint depth,
408                                 jmethodID* method_ptr, jlocation* location_ptr);
409   jvmtiError get_frame_location(oop vthread_oop, jint depth,
410                                 jmethodID* method_ptr, jlocation* location_ptr);
411   jvmtiError set_frame_pop(JvmtiThreadState* state, javaVFrame* jvf, jint depth);
412   jvmtiError clear_all_frame_pops(JvmtiThreadState* state);
413   jvmtiError get_object_monitor_usage(JavaThread* calling_thread,
414                                       jobject object, jvmtiMonitorUsage* info_ptr);
415   jvmtiError get_stack_trace(javaVFrame* jvf,
416                              jint stack_depth, jint max_count,
417                              jvmtiFrameInfo* frame_buffer, jint* count_ptr);
418   jvmtiError get_stack_trace(JavaThread* java_thread,
419                              jint stack_depth, jint max_count,
420                              jvmtiFrameInfo* frame_buffer, jint* count_ptr);
421   jvmtiError get_current_contended_monitor(JavaThread* calling_thread, JavaThread* java_thread,
422                                            jobject* monitor_ptr, bool is_virtual);
423   jvmtiError get_owned_monitors(JavaThread* calling_thread, JavaThread* java_thread,
424                                 GrowableArray<jvmtiMonitorStackDepthInfo*> *owned_monitors_list);
425   jvmtiError get_owned_monitors(JavaThread* calling_thread, JavaThread* carrier, javaVFrame* jvf,
426                                 GrowableArray<jvmtiMonitorStackDepthInfo*> *owned_monitors_list, oop vthread);
427   static jvmtiError check_top_frame(Thread* current_thread, JavaThread* java_thread,
428                                     jvalue value, TosState tos, Handle* ret_ob_h);
429   jvmtiError force_early_return(jthread thread, jvalue value, TosState tos);
430 };
431 
432 // This class is the only safe means of iterating through environments.
433 // Note that this iteratation includes invalid environments pending
434 // deallocation -- in fact, some uses depend on this behavior.
435 
436 class JvmtiEnvIterator : public StackObj {
437  private:
438   bool _entry_was_marked;
439  public:
440   JvmtiEnvIterator() {
441     if (Threads::number_of_threads() == 0) {
442       _entry_was_marked = false; // we are single-threaded, no need
443     } else {
444       Thread::current()->entering_jvmti_env_iteration();
445       _entry_was_marked = true;
446     }
447   }
448   ~JvmtiEnvIterator() {
449     if (_entry_was_marked) {
450       Thread::current()->leaving_jvmti_env_iteration();
451     }
452   }
453   JvmtiEnv* first()                 { return JvmtiEnvBase::head_environment(); }
454   JvmtiEnv* next(JvmtiEnvBase* env) { return env->next_environment(); }
455 };
456 
457 #if INCLUDE_JVMTI
458 
459 // This helper class marks current thread as making a Java upcall.
460 // It is needed to hide JVMTI events during JVMTI operation.
461 class JvmtiJavaUpcallMark : public StackObj {
462  private:
463   JavaThread* _current;
464  public:
465   JvmtiJavaUpcallMark(JavaThread* current) {
466     _current = current;
467     assert(!_current->is_in_java_upcall(), "sanity check");
468     _current->toggle_is_in_java_upcall();
469   }
470 
471   ~JvmtiJavaUpcallMark() {
472     assert(_current->is_in_java_upcall(), "sanity check");
473     _current->toggle_is_in_java_upcall();
474   }
475 };
476 #endif // INCLUDE_JVMTI
477 
478 // Used in combination with the JvmtiHandshake class.
479 // It is intended to support both platform and virtual threads.
480 class JvmtiUnitedHandshakeClosure : public HandshakeClosure {
481  protected:
482   jvmtiError _result;
483   // the fields below are set by the JvmtiHandshake::execute
484   JavaThread* _target_jt;
485   bool _is_virtual;
486   bool _self;
487  public:
488   JvmtiUnitedHandshakeClosure(const char* name)
489     : HandshakeClosure(name),
490       _result(JVMTI_ERROR_THREAD_NOT_ALIVE),
491       _target_jt(nullptr),
492       _is_virtual(false),
493       _self(false) {}
494 
495   void set_result(jvmtiError err) { _result = err; }
496   void set_target_jt(JavaThread* target_jt) { _target_jt = target_jt; }
497   void set_is_virtual(bool val) { _is_virtual = val; }
498   void set_self(bool val) { _self = val; }
499   jvmtiError result() { return _result; }
500   virtual void do_vthread(Handle target_h) = 0;
501 };
502 
503 // The JvmtiHandshake supports virtual threads.
504 class JvmtiHandshake : public Handshake {
505  public:
506   static void execute(JvmtiUnitedHandshakeClosure* hs_cl, ThreadsListHandle* tlh,
507                       JavaThread* target_jt, Handle target_h);
508   static void execute(JvmtiUnitedHandshakeClosure* hs_cl, jthread target);
509 };
510 
511 class SetForceEarlyReturn : public JvmtiUnitedHandshakeClosure {
512 private:
513   JvmtiThreadState* _state;
514   jvalue _value;
515   TosState _tos;
516 public:
517   SetForceEarlyReturn(JvmtiThreadState* state, jvalue value, TosState tos)
518     : JvmtiUnitedHandshakeClosure("SetForceEarlyReturn"),
519      _state(state),
520      _value(value),
521      _tos(tos) {}
522   void doit(Thread *target);
523   void do_thread(Thread *target) {
524     doit(target);
525   }
526   void do_vthread(Handle target_h) {
527     assert(_target_jt != nullptr, "sanity check");
528     // Use jvmti_vthread() instead of vthread() as target could have temporarily changed
529     // identity to carrier thread (see VirtualThread.switchToCarrierThread).
530     assert(_target_jt->jvmti_vthread() == target_h(), "sanity check");
531     doit(_target_jt); // mounted virtual thread
532   }
533 };
534 
535 // HandshakeClosure to send an asynchronous exception to target.
536 class StopThreadClosure : public JvmtiUnitedHandshakeClosure {
537  private:
538   Handle _exception;
539  public:
540   StopThreadClosure(JavaThread* current_thread, oop exception);
541   void doit(JavaThread* target);
542   void do_thread(Thread* target);
543   void do_vthread(Handle target_h);
544 };
545 
546 // HandshakeClosure to update for pop top frame.
547 class UpdateForPopTopFrameClosure : public JvmtiUnitedHandshakeClosure {
548 private:
549   JvmtiThreadState* _state;
550 
551 public:
552   UpdateForPopTopFrameClosure(JvmtiThreadState* state)
553     : JvmtiUnitedHandshakeClosure("UpdateForPopTopFrame"),
554      _state(state) {}
555   void doit(Thread *target);
556   void do_thread(Thread *target) {
557     doit(target);
558   }
559   void do_vthread(Handle target_h) {
560     assert(_target_jt != nullptr, "sanity check");
561     // Use jvmti_vthread() instead of vthread() as target could have temporarily changed
562     // identity to carrier thread (see VirtualThread.switchToCarrierThread).
563     assert(_target_jt->jvmti_vthread() == target_h(), "sanity check");
564     doit(_target_jt); // mounted virtual thread
565   }
566 };
567 
568 // HandshakeClosure to set frame pop.
569 class SetOrClearFramePopClosure : public JvmtiUnitedHandshakeClosure {
570 private:
571   JvmtiEnvBase *_env;
572   JvmtiThreadState* _state;
573   bool _set;
574   jint _depth; // used for NotiftyFramePop only
575 
576 public:
577   SetOrClearFramePopClosure(JvmtiEnv *env, JvmtiThreadState* state, bool set, jint depth = 0)
578     : JvmtiUnitedHandshakeClosure("SetOrClearFramePopClosure"),
579       _env((JvmtiEnvBase*)env),
580       _state(state),
581       _set(set),
582       _depth(depth) {}
583   void do_thread(Thread *target);
584   void do_vthread(Handle target_h);
585 };
586 
587 // HandshakeClosure to get monitor information with stack depth.
588 class GetOwnedMonitorInfoClosure : public JvmtiUnitedHandshakeClosure {
589 private:
590   JvmtiEnv *_env;
591   JavaThread* _calling_thread;
592   GrowableArray<jvmtiMonitorStackDepthInfo*> *_owned_monitors_list;
593 
594 public:
595   GetOwnedMonitorInfoClosure(JvmtiEnv* env,
596                              JavaThread* calling_thread,
597                              GrowableArray<jvmtiMonitorStackDepthInfo*>* owned_monitors_list)
598     : JvmtiUnitedHandshakeClosure("GetOwnedMonitorInfo"),
599       _env(env),
600       _calling_thread(calling_thread),
601       _owned_monitors_list(owned_monitors_list) {}
602 
603   void do_thread(Thread *target);
604   void do_vthread(Handle target_h);
605 };
606 
607 // VM operation to get object monitor usage.
608 class VM_GetObjectMonitorUsage : public VM_Operation {
609 private:
610   JvmtiEnv *_env;
611   jobject _object;
612   JavaThread* _calling_thread;
613   jvmtiMonitorUsage* _info_ptr;
614   jvmtiError _result;
615 
616 public:
617   VM_GetObjectMonitorUsage(JvmtiEnv *env, JavaThread* calling_thread, jobject object, jvmtiMonitorUsage* info_ptr) {
618     _env = env;
619     _object = object;
620     _calling_thread = calling_thread;
621     _info_ptr = info_ptr;
622   }
623   VMOp_Type type() const { return VMOp_GetObjectMonitorUsage; }
624   jvmtiError result() { return _result; }
625   void doit() {
626     _result = ((JvmtiEnvBase*) _env)->get_object_monitor_usage(_calling_thread, _object, _info_ptr);
627   }
628 
629 };
630 
631 // HandshakeClosure to get current contended monitor. It is used for both platform and virtual threads.
632 class GetCurrentContendedMonitorClosure : public JvmtiUnitedHandshakeClosure {
633 private:
634   JvmtiEnv *_env;
635   JavaThread *_calling_thread;
636   jobject *_owned_monitor_ptr;
637 
638 public:
639   GetCurrentContendedMonitorClosure(JvmtiEnv *env,
640                                     JavaThread* calling_thread,
641                                     jobject *owned_monitor_ptr)
642     : JvmtiUnitedHandshakeClosure("GetCurrentContendedMonitor"),
643       _env(env),
644       _calling_thread(calling_thread),
645       _owned_monitor_ptr(owned_monitor_ptr) {}
646   void do_thread(Thread *target);
647   void do_vthread(Handle target_h);
648 };
649 
650 // HandshakeClosure to get stack trace.
651 class GetStackTraceClosure : public JvmtiUnitedHandshakeClosure {
652 private:
653   JvmtiEnv *_env;
654   jint _start_depth;
655   jint _max_count;
656   jvmtiFrameInfo *_frame_buffer;
657   jint *_count_ptr;
658 
659 public:
660   GetStackTraceClosure(JvmtiEnv *env, jint start_depth, jint max_count,
661                        jvmtiFrameInfo* frame_buffer, jint* count_ptr)
662     : JvmtiUnitedHandshakeClosure("GetStackTrace"),
663       _env(env),
664       _start_depth(start_depth),
665       _max_count(max_count),
666       _frame_buffer(frame_buffer),
667       _count_ptr(count_ptr) {}
668   void do_thread(Thread *target);
669   void do_vthread(Handle target_h);
670 };
671 
672 #ifdef ASSERT
673 // HandshakeClosure to print stack trace in JvmtiVTMSTransitionDisabler error handling.
674 class PrintStackTraceClosure : public HandshakeClosure {
675  public:
676   static void do_thread_impl(Thread *target);
677 
678   PrintStackTraceClosure()
679       : HandshakeClosure("PrintStackTraceClosure") {}
680   void do_thread(Thread *target);
681 };
682 #endif
683 
684 // Forward declaration.
685 struct StackInfoNode;
686 
687 // Get stack trace at safepoint or at direct handshake.
688 class MultipleStackTracesCollector {
689 private:
690   friend class VM_GetThreadListStackTraces;
691   JvmtiEnv *_env;
692   jint _max_frame_count;
693   jvmtiStackInfo *_stack_info;
694   jvmtiError _result;
695   int _frame_count_total;
696   struct StackInfoNode *_head;
697 
698   JvmtiEnvBase *env()                 { return (JvmtiEnvBase *)_env; }
699   jint max_frame_count()              { return _max_frame_count; }
700   struct StackInfoNode *head()        { return _head; }
701   void set_head(StackInfoNode *head)  { _head = head; }
702 
703 public:
704   MultipleStackTracesCollector(JvmtiEnv *env, jint max_frame_count)
705     : _env(env),
706       _max_frame_count(max_frame_count),
707       _stack_info(nullptr),
708       _result(JVMTI_ERROR_NONE),
709       _frame_count_total(0),
710       _head(nullptr) {
711   }
712   void set_result(jvmtiError result)  { _result = result; }
713   void fill_frames(jthread jt, JavaThread *thr, oop thread_oop);
714   void allocate_and_fill_stacks(jint thread_count);
715   jvmtiStackInfo *stack_info()       { return _stack_info; }
716   jvmtiError result()                { return _result; }
717 };
718 
719 
720 // VM operation to get stack trace at safepoint.
721 class VM_GetAllStackTraces : public VM_Operation {
722 private:
723   JavaThread *_calling_thread;
724   jint _final_thread_count;
725   MultipleStackTracesCollector _collector;
726 
727 public:
728   VM_GetAllStackTraces(JvmtiEnv *env, JavaThread *calling_thread,
729                        jint max_frame_count)
730       : _calling_thread(calling_thread),
731         _final_thread_count(0),
732         _collector(env, max_frame_count) {
733   }
734   VMOp_Type type() const          { return VMOp_GetAllStackTraces; }
735   void doit();
736   jint final_thread_count()       { return _final_thread_count; }
737   jvmtiStackInfo *stack_info()    { return _collector.stack_info(); }
738   jvmtiError result()             { return _collector.result(); }
739 };
740 
741 // VM operation to get stack trace at safepoint.
742 class VM_GetThreadListStackTraces : public VM_Operation {
743 private:
744   jint _thread_count;
745   const jthread* _thread_list;
746   MultipleStackTracesCollector _collector;
747 
748   JvmtiEnvBase *env() { return _collector.env(); }
749 
750 public:
751   VM_GetThreadListStackTraces(JvmtiEnv *env, jint thread_count, const jthread* thread_list, jint max_frame_count)
752       : _thread_count(thread_count),
753         _thread_list(thread_list),
754         _collector(env, max_frame_count) {
755   }
756   VMOp_Type type() const { return VMOp_GetThreadListStackTraces; }
757   void doit();
758   jvmtiStackInfo *stack_info()    { return _collector.stack_info(); }
759   jvmtiError result()             { return _collector.result(); }
760 };
761 
762 // HandshakeClosure to get single stack trace.
763 class GetSingleStackTraceClosure : public JvmtiUnitedHandshakeClosure {
764 private:
765   JavaThread *_calling_thread;
766   jthread _jthread;
767   MultipleStackTracesCollector _collector;
768 
769 public:
770   GetSingleStackTraceClosure(JvmtiEnv *env, JavaThread *calling_thread,
771                              jthread thread, jint max_frame_count)
772     : JvmtiUnitedHandshakeClosure("GetSingleStackTrace"),
773       _calling_thread(calling_thread),
774       _jthread(thread),
775       _collector(env, max_frame_count) {
776   }
777   void do_thread(Thread *target);
778   void do_vthread(Handle target_h);
779   void doit();
780   jvmtiStackInfo *stack_info()    { return _collector.stack_info(); }
781   jvmtiError result()             { return _result; }
782 };
783 
784 // HandshakeClosure to count stack frames.
785 class GetFrameCountClosure : public JvmtiUnitedHandshakeClosure {
786 private:
787   JvmtiEnv *_env;
788   jint *_count_ptr;
789 
790 public:
791   GetFrameCountClosure(JvmtiEnv *env, jint *count_ptr)
792     : JvmtiUnitedHandshakeClosure("GetFrameCount"),
793       _env(env),
794       _count_ptr(count_ptr) {}
795   void do_thread(Thread *target);
796   void do_vthread(Handle target_h);
797 };
798 
799 // HandshakeClosure to get frame location.
800 class GetFrameLocationClosure : public JvmtiUnitedHandshakeClosure {
801 private:
802   JvmtiEnv *_env;
803   jint _depth;
804   jmethodID* _method_ptr;
805   jlocation* _location_ptr;
806 
807 public:
808   GetFrameLocationClosure(JvmtiEnv *env, jint depth,
809                           jmethodID* method_ptr, jlocation* location_ptr)
810     : JvmtiUnitedHandshakeClosure("GetFrameLocation"),
811       _env(env),
812       _depth(depth),
813       _method_ptr(method_ptr),
814       _location_ptr(location_ptr) {}
815   void do_thread(Thread *target);
816   void do_vthread(Handle target_h);
817 };
818 
819 // ResourceTracker
820 //
821 // ResourceTracker works a little like a ResourceMark. All allocates
822 // using the resource tracker are recorded. If an allocate using the
823 // resource tracker fails the destructor will free any resources
824 // that were allocated using the tracker.
825 // The motive for this class is to avoid messy error recovery code
826 // in situations where multiple allocations are done in sequence. If
827 // the second or subsequent allocation fails it avoids any code to
828 // release memory allocated in the previous calls.
829 //
830 // Usage :-
831 //   ResourceTracker rt(env);
832 //   :
833 //   err = rt.allocate(1024, &ptr);
834 
835 class ResourceTracker : public StackObj {
836  private:
837   JvmtiEnv* _env;
838   GrowableArray<unsigned char*> *_allocations;
839   bool _failed;
840  public:
841   ResourceTracker(JvmtiEnv* env);
842   ~ResourceTracker();
843   jvmtiError allocate(jlong size, unsigned char** mem_ptr);
844   unsigned char* allocate(jlong size);
845   char* strdup(const char* str);
846 };
847 
848 
849 // Jvmti monitor closure to collect off stack monitors.
850 class JvmtiMonitorClosure: public MonitorClosure {
851  private:
852   JavaThread *_calling_thread;
853   GrowableArray<jvmtiMonitorStackDepthInfo*> *_owned_monitors_list;
854   jvmtiError _error;
855   JvmtiEnvBase *_env;
856 
857  public:
858   JvmtiMonitorClosure(JavaThread *calling_thread,
859                       GrowableArray<jvmtiMonitorStackDepthInfo*> *owned_monitors,
860                       JvmtiEnvBase *env) {
861     _calling_thread = calling_thread;
862     _owned_monitors_list = owned_monitors;
863     _error = JVMTI_ERROR_NONE;
864     _env = env;
865   }
866   void do_monitor(ObjectMonitor* mon);
867   jvmtiError error() { return _error;}
868 };
869 
870 
871 // Jvmti module closure to collect all modules loaded to the system.
872 class JvmtiModuleClosure : public StackObj {
873 private:
874   static GrowableArray<OopHandle> *_tbl; // Protected with Module_lock
875 
876   static void do_module(ModuleEntry* entry);
877 public:
878   jvmtiError get_all_modules(JvmtiEnv* env, jint* module_count_ptr, jobject** modules_ptr);
879 };
880 
881 #endif // SHARE_PRIMS_JVMTIENVBASE_HPP