1 /*
  2  * Copyright (c) 2003, 2024, 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);
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 state
392   static jint get_vthread_state(oop thread_oop, JavaThread* jt);
393 
394   // get platform or virtual thread state
395   static jint get_thread_or_vthread_state(oop thread_oop, JavaThread* jt);
396 
397   // enumerates the live threads in the given thread group
398   static jvmtiError get_live_threads(JavaThread* current_thread, Handle group_hdl, jint *count_ptr, Handle **thread_objs_p);
399 
400   // enumerates the subgroups in the given thread group
401   static jvmtiError get_subgroups(JavaThread* current_thread, Handle group_hdl, jint *count_ptr, objArrayHandle *group_objs_p);
402 
403   // JVMTI API helper functions which are called when target thread is suspended
404   // or at safepoint / thread local handshake.
405   static jint get_frame_count(javaVFrame* jvf);
406   jvmtiError get_frame_count(JavaThread* java_thread, jint *count_ptr);
407   jvmtiError get_frame_count(oop frame_oop, jint *count_ptr);
408   jvmtiError get_frame_location(javaVFrame* jvf, jint depth,
409                                 jmethodID* method_ptr, jlocation* location_ptr);
410   jvmtiError get_frame_location(JavaThread* java_thread, jint depth,
411                                 jmethodID* method_ptr, jlocation* location_ptr);
412   jvmtiError get_frame_location(oop vthread_oop, jint depth,
413                                 jmethodID* method_ptr, jlocation* location_ptr);
414   jvmtiError set_frame_pop(JvmtiThreadState* state, javaVFrame* jvf, jint depth);
415   jvmtiError get_object_monitor_usage(JavaThread* calling_thread,
416                                       jobject object, jvmtiMonitorUsage* info_ptr);
417   jvmtiError get_stack_trace(javaVFrame* jvf,
418                              jint stack_depth, jint max_count,
419                              jvmtiFrameInfo* frame_buffer, jint* count_ptr);
420   jvmtiError get_stack_trace(JavaThread* java_thread,
421                              jint stack_depth, jint max_count,
422                              jvmtiFrameInfo* frame_buffer, jint* count_ptr);
423   jvmtiError get_current_contended_monitor(JavaThread* calling_thread, JavaThread* java_thread,
424                                            jobject* monitor_ptr, bool is_virtual);
425   jvmtiError get_owned_monitors(JavaThread* calling_thread, JavaThread* java_thread,
426                                 GrowableArray<jvmtiMonitorStackDepthInfo*> *owned_monitors_list);
427   jvmtiError get_owned_monitors(JavaThread* calling_thread, JavaThread* java_thread, javaVFrame* jvf,
428                                 GrowableArray<jvmtiMonitorStackDepthInfo*> *owned_monitors_list);
429   static jvmtiError check_top_frame(Thread* current_thread, JavaThread* java_thread,
430                                     jvalue value, TosState tos, Handle* ret_ob_h);
431   jvmtiError force_early_return(jthread thread, jvalue value, TosState tos);
432 };
433 
434 // This class is the only safe means of iterating through environments.
435 // Note that this iteratation includes invalid environments pending
436 // deallocation -- in fact, some uses depend on this behavior.
437 
438 class JvmtiEnvIterator : public StackObj {
439  private:
440   bool _entry_was_marked;
441  public:
442   JvmtiEnvIterator() {
443     if (Threads::number_of_threads() == 0) {
444       _entry_was_marked = false; // we are single-threaded, no need
445     } else {
446       Thread::current()->entering_jvmti_env_iteration();
447       _entry_was_marked = true;
448     }
449   }
450   ~JvmtiEnvIterator() {
451     if (_entry_was_marked) {
452       Thread::current()->leaving_jvmti_env_iteration();
453     }
454   }
455   JvmtiEnv* first()                 { return JvmtiEnvBase::head_environment(); }
456   JvmtiEnv* next(JvmtiEnvBase* env) { return env->next_environment(); }
457 };
458 
459 // Used in combination with the JvmtiHandshake class.
460 // It is intended to support both platform and virtual threads.
461 class JvmtiUnitedHandshakeClosure : public HandshakeClosure {
462  protected:
463   jvmtiError _result;
464   // the fields below are set by the JvmtiHandshake::execute
465   JavaThread* _target_jt;
466   bool _is_virtual;
467   bool _self;
468  public:
469   JvmtiUnitedHandshakeClosure(const char* name)
470     : HandshakeClosure(name),
471       _result(JVMTI_ERROR_THREAD_NOT_ALIVE),
472       _target_jt(nullptr),
473       _is_virtual(false),
474       _self(false) {}
475 
476   void set_result(jvmtiError err) { _result = err; }
477   void set_target_jt(JavaThread* target_jt) { _target_jt = target_jt; }
478   void set_is_virtual(bool val) { _is_virtual = val; }
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 JvmtiUnitedHandshakeClosure {
493 private:
494   JvmtiThreadState* _state;
495   jvalue _value;
496   TosState _tos;
497 public:
498   SetForceEarlyReturn(JvmtiThreadState* state, jvalue value, TosState tos)
499     : JvmtiUnitedHandshakeClosure("SetForceEarlyReturn"),
500      _state(state),
501      _value(value),
502      _tos(tos) {}
503   void doit(Thread *target);
504   void do_thread(Thread *target) {
505     doit(target);
506   }
507   void do_vthread(Handle target_h) {
508     assert(_target_jt != nullptr, "sanity check");
509     assert(_target_jt->vthread() == target_h(), "sanity check");
510     doit(_target_jt); // mounted virtual thread
511   }
512 };
513 
514 // HandshakeClosure to update for pop top frame.
515 class UpdateForPopTopFrameClosure : public JvmtiUnitedHandshakeClosure {
516 private:
517   JvmtiThreadState* _state;
518 
519 public:
520   UpdateForPopTopFrameClosure(JvmtiThreadState* state)
521     : JvmtiUnitedHandshakeClosure("UpdateForPopTopFrame"),
522      _state(state) {}
523   void doit(Thread *target);
524   void do_thread(Thread *target) {
525     doit(target);
526   }
527   void do_vthread(Handle target_h) {
528     assert(_target_jt != nullptr, "sanity check");
529     assert(_target_jt->vthread() == target_h(), "sanity check");
530     doit(_target_jt); // mounted virtual thread
531   }
532 };
533 
534 // HandshakeClosure to set frame pop.
535 class SetFramePopClosure : public JvmtiUnitedHandshakeClosure {
536 private:
537   JvmtiEnv *_env;
538   JvmtiThreadState* _state;
539   jint _depth;
540 
541 public:
542   SetFramePopClosure(JvmtiEnv *env, JvmtiThreadState* state, jint depth)
543     : JvmtiUnitedHandshakeClosure("SetFramePopClosure"),
544       _env(env),
545       _state(state),
546       _depth(depth) {}
547   void do_thread(Thread *target);
548   void do_vthread(Handle target_h);
549 };
550 
551 // HandshakeClosure to get monitor information with stack depth.
552 class GetOwnedMonitorInfoClosure : public JvmtiUnitedHandshakeClosure {
553 private:
554   JvmtiEnv *_env;
555   JavaThread* _calling_thread;
556   GrowableArray<jvmtiMonitorStackDepthInfo*> *_owned_monitors_list;
557 
558 public:
559   GetOwnedMonitorInfoClosure(JvmtiEnv* env,
560                              JavaThread* calling_thread,
561                              GrowableArray<jvmtiMonitorStackDepthInfo*>* owned_monitors_list)
562     : JvmtiUnitedHandshakeClosure("GetOwnedMonitorInfo"),
563       _env(env),
564       _calling_thread(calling_thread),
565       _owned_monitors_list(owned_monitors_list) {}
566 
567   void do_thread(Thread *target);
568   void do_vthread(Handle target_h);
569 };
570 
571 // VM operation to get object monitor usage.
572 class VM_GetObjectMonitorUsage : public VM_Operation {
573 private:
574   JvmtiEnv *_env;
575   jobject _object;
576   JavaThread* _calling_thread;
577   jvmtiMonitorUsage* _info_ptr;
578   jvmtiError _result;
579 
580 public:
581   VM_GetObjectMonitorUsage(JvmtiEnv *env, JavaThread* calling_thread, jobject object, jvmtiMonitorUsage* info_ptr) {
582     _env = env;
583     _object = object;
584     _calling_thread = calling_thread;
585     _info_ptr = info_ptr;
586   }
587   VMOp_Type type() const { return VMOp_GetObjectMonitorUsage; }
588   jvmtiError result() { return _result; }
589   void doit() {
590     _result = ((JvmtiEnvBase*) _env)->get_object_monitor_usage(_calling_thread, _object, _info_ptr);
591   }
592 
593 };
594 
595 // HandshakeClosure to get current contended monitor. It is used for both platform and virtual threads.
596 class GetCurrentContendedMonitorClosure : public JvmtiUnitedHandshakeClosure {
597 private:
598   JvmtiEnv *_env;
599   JavaThread *_calling_thread;
600   jobject *_owned_monitor_ptr;
601 
602 public:
603   GetCurrentContendedMonitorClosure(JvmtiEnv *env,
604                                     JavaThread* calling_thread,
605                                     jobject *owned_monitor_ptr)
606     : JvmtiUnitedHandshakeClosure("GetCurrentContendedMonitor"),
607       _env(env),
608       _calling_thread(calling_thread),
609       _owned_monitor_ptr(owned_monitor_ptr) {}
610   void do_thread(Thread *target);
611   void do_vthread(Handle target_h);
612 };
613 
614 // HandshakeClosure to get stack trace.
615 class GetStackTraceClosure : public JvmtiUnitedHandshakeClosure {
616 private:
617   JvmtiEnv *_env;
618   jint _start_depth;
619   jint _max_count;
620   jvmtiFrameInfo *_frame_buffer;
621   jint *_count_ptr;
622 
623 public:
624   GetStackTraceClosure(JvmtiEnv *env, jint start_depth, jint max_count,
625                        jvmtiFrameInfo* frame_buffer, jint* count_ptr)
626     : JvmtiUnitedHandshakeClosure("GetStackTrace"),
627       _env(env),
628       _start_depth(start_depth),
629       _max_count(max_count),
630       _frame_buffer(frame_buffer),
631       _count_ptr(count_ptr) {}
632   void do_thread(Thread *target);
633   void do_vthread(Handle target_h);
634 };
635 
636 #ifdef ASSERT
637 // HandshakeClosure to print stack trace in JvmtiVTMSTransitionDisabler error handling.
638 class PrintStackTraceClosure : public HandshakeClosure {
639  public:
640   static void do_thread_impl(Thread *target);
641 
642   PrintStackTraceClosure()
643       : HandshakeClosure("PrintStackTraceClosure") {}
644   void do_thread(Thread *target);
645 };
646 #endif
647 
648 // Forward declaration.
649 struct StackInfoNode;
650 
651 // Get stack trace at safepoint or at direct handshake.
652 class MultipleStackTracesCollector {
653 private:
654   friend class VM_GetThreadListStackTraces;
655   JvmtiEnv *_env;
656   jint _max_frame_count;
657   jvmtiStackInfo *_stack_info;
658   jvmtiError _result;
659   int _frame_count_total;
660   struct StackInfoNode *_head;
661 
662   JvmtiEnvBase *env()                 { return (JvmtiEnvBase *)_env; }
663   jint max_frame_count()              { return _max_frame_count; }
664   struct StackInfoNode *head()        { return _head; }
665   void set_head(StackInfoNode *head)  { _head = head; }
666 
667 public:
668   MultipleStackTracesCollector(JvmtiEnv *env, jint max_frame_count)
669     : _env(env),
670       _max_frame_count(max_frame_count),
671       _stack_info(nullptr),
672       _result(JVMTI_ERROR_NONE),
673       _frame_count_total(0),
674       _head(nullptr) {
675   }
676   void set_result(jvmtiError result)  { _result = result; }
677   void fill_frames(jthread jt, JavaThread *thr, oop thread_oop);
678   void allocate_and_fill_stacks(jint thread_count);
679   jvmtiStackInfo *stack_info()       { return _stack_info; }
680   jvmtiError result()                { return _result; }
681 };
682 
683 
684 // VM operation to get stack trace at safepoint.
685 class VM_GetAllStackTraces : public VM_Operation {
686 private:
687   JavaThread *_calling_thread;
688   jint _final_thread_count;
689   MultipleStackTracesCollector _collector;
690 
691 public:
692   VM_GetAllStackTraces(JvmtiEnv *env, JavaThread *calling_thread,
693                        jint max_frame_count)
694       : _calling_thread(calling_thread),
695         _final_thread_count(0),
696         _collector(env, max_frame_count) {
697   }
698   VMOp_Type type() const          { return VMOp_GetAllStackTraces; }
699   void doit();
700   jint final_thread_count()       { return _final_thread_count; }
701   jvmtiStackInfo *stack_info()    { return _collector.stack_info(); }
702   jvmtiError result()             { return _collector.result(); }
703 };
704 
705 // VM operation to get stack trace at safepoint.
706 class VM_GetThreadListStackTraces : public VM_Operation {
707 private:
708   jint _thread_count;
709   const jthread* _thread_list;
710   MultipleStackTracesCollector _collector;
711 
712   JvmtiEnvBase *env() { return _collector.env(); }
713 
714 public:
715   VM_GetThreadListStackTraces(JvmtiEnv *env, jint thread_count, const jthread* thread_list, jint max_frame_count)
716       : _thread_count(thread_count),
717         _thread_list(thread_list),
718         _collector(env, max_frame_count) {
719   }
720   VMOp_Type type() const { return VMOp_GetThreadListStackTraces; }
721   void doit();
722   jvmtiStackInfo *stack_info()    { return _collector.stack_info(); }
723   jvmtiError result()             { return _collector.result(); }
724 };
725 
726 // HandshakeClosure to get single stack trace.
727 class GetSingleStackTraceClosure : public JvmtiUnitedHandshakeClosure {
728 private:
729   JavaThread *_calling_thread;
730   jthread _jthread;
731   MultipleStackTracesCollector _collector;
732 
733 public:
734   GetSingleStackTraceClosure(JvmtiEnv *env, JavaThread *calling_thread,
735                              jthread thread, jint max_frame_count)
736     : JvmtiUnitedHandshakeClosure("GetSingleStackTrace"),
737       _calling_thread(calling_thread),
738       _jthread(thread),
739       _collector(env, max_frame_count) {
740   }
741   void do_thread(Thread *target);
742   void do_vthread(Handle target_h);
743   void doit();
744   jvmtiStackInfo *stack_info()    { return _collector.stack_info(); }
745   jvmtiError result()             { return _result; }
746 };
747 
748 // HandshakeClosure to count stack frames.
749 class GetFrameCountClosure : public JvmtiUnitedHandshakeClosure {
750 private:
751   JvmtiEnv *_env;
752   jint *_count_ptr;
753 
754 public:
755   GetFrameCountClosure(JvmtiEnv *env, jint *count_ptr)
756     : JvmtiUnitedHandshakeClosure("GetFrameCount"),
757       _env(env),
758       _count_ptr(count_ptr) {}
759   void do_thread(Thread *target);
760   void do_vthread(Handle target_h);
761 };
762 
763 // HandshakeClosure to get frame location.
764 class GetFrameLocationClosure : public JvmtiUnitedHandshakeClosure {
765 private:
766   JvmtiEnv *_env;
767   jint _depth;
768   jmethodID* _method_ptr;
769   jlocation* _location_ptr;
770 
771 public:
772   GetFrameLocationClosure(JvmtiEnv *env, jint depth,
773                           jmethodID* method_ptr, jlocation* location_ptr)
774     : JvmtiUnitedHandshakeClosure("GetFrameLocation"),
775       _env(env),
776       _depth(depth),
777       _method_ptr(method_ptr),
778       _location_ptr(location_ptr) {}
779   void do_thread(Thread *target);
780   void do_vthread(Handle target_h);
781 };
782 
783 // HandshakeClosure to get virtual thread thread at safepoint.
784 class VirtualThreadGetThreadClosure : public HandshakeClosure {
785 private:
786   Handle _vthread_h;
787   jthread* _carrier_thread_ptr;
788   jvmtiError _result;
789 
790 public:
791   VirtualThreadGetThreadClosure(Handle vthread_h, jthread* carrier_thread_ptr)
792     : HandshakeClosure("VirtualThreadGetThread"),
793       _vthread_h(vthread_h),
794       _carrier_thread_ptr(carrier_thread_ptr),
795       _result(JVMTI_ERROR_NONE) {}
796 
797   void do_thread(Thread *target);
798   jvmtiError result() { return _result; }
799 };
800 
801 // ResourceTracker
802 //
803 // ResourceTracker works a little like a ResourceMark. All allocates
804 // using the resource tracker are recorded. If an allocate using the
805 // resource tracker fails the destructor will free any resources
806 // that were allocated using the tracker.
807 // The motive for this class is to avoid messy error recovery code
808 // in situations where multiple allocations are done in sequence. If
809 // the second or subsequent allocation fails it avoids any code to
810 // release memory allocated in the previous calls.
811 //
812 // Usage :-
813 //   ResourceTracker rt(env);
814 //   :
815 //   err = rt.allocate(1024, &ptr);
816 
817 class ResourceTracker : public StackObj {
818  private:
819   JvmtiEnv* _env;
820   GrowableArray<unsigned char*> *_allocations;
821   bool _failed;
822  public:
823   ResourceTracker(JvmtiEnv* env);
824   ~ResourceTracker();
825   jvmtiError allocate(jlong size, unsigned char** mem_ptr);
826   unsigned char* allocate(jlong size);
827   char* strdup(const char* str);
828 };
829 
830 
831 // Jvmti monitor closure to collect off stack monitors.
832 class JvmtiMonitorClosure: public MonitorClosure {
833  private:
834   JavaThread *_calling_thread;
835   GrowableArray<jvmtiMonitorStackDepthInfo*> *_owned_monitors_list;
836   jvmtiError _error;
837   JvmtiEnvBase *_env;
838 
839  public:
840   JvmtiMonitorClosure(JavaThread *calling_thread,
841                       GrowableArray<jvmtiMonitorStackDepthInfo*> *owned_monitors,
842                       JvmtiEnvBase *env) {
843     _calling_thread = calling_thread;
844     _owned_monitors_list = owned_monitors;
845     _error = JVMTI_ERROR_NONE;
846     _env = env;
847   }
848   void do_monitor(ObjectMonitor* mon);
849   jvmtiError error() { return _error;}
850 };
851 
852 
853 // Jvmti module closure to collect all modules loaded to the system.
854 class JvmtiModuleClosure : public StackObj {
855 private:
856   static GrowableArray<OopHandle> *_tbl; // Protected with Module_lock
857 
858   static void do_module(ModuleEntry* entry);
859 public:
860   jvmtiError get_all_modules(JvmtiEnv* env, jint* module_count_ptr, jobject** modules_ptr);
861 };
862 
863 #endif // SHARE_PRIMS_JVMTIENVBASE_HPP