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