1 /*
  2  * Copyright (c) 2003, 2025, 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, refArrayHandle 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, refArrayHandle *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 update for pop top frame.
536 class UpdateForPopTopFrameClosure : public JvmtiUnitedHandshakeClosure {
537 private:
538   JvmtiThreadState* _state;
539 
540 public:
541   UpdateForPopTopFrameClosure(JvmtiThreadState* state)
542     : JvmtiUnitedHandshakeClosure("UpdateForPopTopFrame"),
543      _state(state) {}
544   void doit(Thread *target);
545   void do_thread(Thread *target) {
546     doit(target);
547   }
548   void do_vthread(Handle target_h) {
549     assert(_target_jt != nullptr, "sanity check");
550     // Use jvmti_vthread() instead of vthread() as target could have temporarily changed
551     // identity to carrier thread (see VirtualThread.switchToCarrierThread).
552     assert(_target_jt->jvmti_vthread() == target_h(), "sanity check");
553     doit(_target_jt); // mounted virtual thread
554   }
555 };
556 
557 // HandshakeClosure to set frame pop.
558 class SetOrClearFramePopClosure : public JvmtiUnitedHandshakeClosure {
559 private:
560   JvmtiEnvBase *_env;
561   JvmtiThreadState* _state;
562   bool _set;
563   jint _depth; // used for NotiftyFramePop only
564 
565 public:
566   SetOrClearFramePopClosure(JvmtiEnv *env, JvmtiThreadState* state, bool set, jint depth = 0)
567     : JvmtiUnitedHandshakeClosure("SetOrClearFramePopClosure"),
568       _env((JvmtiEnvBase*)env),
569       _state(state),
570       _set(set),
571       _depth(depth) {}
572   void do_thread(Thread *target);
573   void do_vthread(Handle target_h);
574 };
575 
576 // HandshakeClosure to get monitor information with stack depth.
577 class GetOwnedMonitorInfoClosure : public JvmtiUnitedHandshakeClosure {
578 private:
579   JvmtiEnv *_env;
580   JavaThread* _calling_thread;
581   GrowableArray<jvmtiMonitorStackDepthInfo*> *_owned_monitors_list;
582 
583 public:
584   GetOwnedMonitorInfoClosure(JvmtiEnv* env,
585                              JavaThread* calling_thread,
586                              GrowableArray<jvmtiMonitorStackDepthInfo*>* owned_monitors_list)
587     : JvmtiUnitedHandshakeClosure("GetOwnedMonitorInfo"),
588       _env(env),
589       _calling_thread(calling_thread),
590       _owned_monitors_list(owned_monitors_list) {}
591 
592   void do_thread(Thread *target);
593   void do_vthread(Handle target_h);
594 };
595 
596 // VM operation to get object monitor usage.
597 class VM_GetObjectMonitorUsage : public VM_Operation {
598 private:
599   JvmtiEnv *_env;
600   jobject _object;
601   JavaThread* _calling_thread;
602   jvmtiMonitorUsage* _info_ptr;
603   jvmtiError _result;
604 
605 public:
606   VM_GetObjectMonitorUsage(JvmtiEnv *env, JavaThread* calling_thread, jobject object, jvmtiMonitorUsage* info_ptr) {
607     _env = env;
608     _object = object;
609     _calling_thread = calling_thread;
610     _info_ptr = info_ptr;
611   }
612   VMOp_Type type() const { return VMOp_GetObjectMonitorUsage; }
613   jvmtiError result() { return _result; }
614   void doit() {
615     _result = ((JvmtiEnvBase*) _env)->get_object_monitor_usage(_calling_thread, _object, _info_ptr);
616   }
617 
618 };
619 
620 // HandshakeClosure to get current contended monitor. It is used for both platform and virtual threads.
621 class GetCurrentContendedMonitorClosure : public JvmtiUnitedHandshakeClosure {
622 private:
623   JvmtiEnv *_env;
624   JavaThread *_calling_thread;
625   jobject *_owned_monitor_ptr;
626 
627 public:
628   GetCurrentContendedMonitorClosure(JvmtiEnv *env,
629                                     JavaThread* calling_thread,
630                                     jobject *owned_monitor_ptr)
631     : JvmtiUnitedHandshakeClosure("GetCurrentContendedMonitor"),
632       _env(env),
633       _calling_thread(calling_thread),
634       _owned_monitor_ptr(owned_monitor_ptr) {}
635   void do_thread(Thread *target);
636   void do_vthread(Handle target_h);
637 };
638 
639 // HandshakeClosure to get stack trace.
640 class GetStackTraceClosure : public JvmtiUnitedHandshakeClosure {
641 private:
642   JvmtiEnv *_env;
643   jint _start_depth;
644   jint _max_count;
645   jvmtiFrameInfo *_frame_buffer;
646   jint *_count_ptr;
647 
648 public:
649   GetStackTraceClosure(JvmtiEnv *env, jint start_depth, jint max_count,
650                        jvmtiFrameInfo* frame_buffer, jint* count_ptr)
651     : JvmtiUnitedHandshakeClosure("GetStackTrace"),
652       _env(env),
653       _start_depth(start_depth),
654       _max_count(max_count),
655       _frame_buffer(frame_buffer),
656       _count_ptr(count_ptr) {}
657   void do_thread(Thread *target);
658   void do_vthread(Handle target_h);
659 };
660 
661 #ifdef ASSERT
662 // HandshakeClosure to print stack trace in JvmtiVTMSTransitionDisabler error handling.
663 class PrintStackTraceClosure : public HandshakeClosure {
664  public:
665   static void do_thread_impl(Thread *target);
666 
667   PrintStackTraceClosure()
668       : HandshakeClosure("PrintStackTraceClosure") {}
669   void do_thread(Thread *target);
670 };
671 #endif
672 
673 // Forward declaration.
674 struct StackInfoNode;
675 
676 // Get stack trace at safepoint or at direct handshake.
677 class MultipleStackTracesCollector {
678 private:
679   friend class VM_GetThreadListStackTraces;
680   JvmtiEnv *_env;
681   jint _max_frame_count;
682   jvmtiStackInfo *_stack_info;
683   jvmtiError _result;
684   int _frame_count_total;
685   struct StackInfoNode *_head;
686 
687   JvmtiEnvBase *env()                 { return (JvmtiEnvBase *)_env; }
688   jint max_frame_count()              { return _max_frame_count; }
689   struct StackInfoNode *head()        { return _head; }
690   void set_head(StackInfoNode *head)  { _head = head; }
691 
692 public:
693   MultipleStackTracesCollector(JvmtiEnv *env, jint max_frame_count)
694     : _env(env),
695       _max_frame_count(max_frame_count),
696       _stack_info(nullptr),
697       _result(JVMTI_ERROR_NONE),
698       _frame_count_total(0),
699       _head(nullptr) {
700   }
701   void set_result(jvmtiError result)  { _result = result; }
702   void fill_frames(jthread jt, JavaThread *thr, oop thread_oop);
703   void allocate_and_fill_stacks(jint thread_count);
704   jvmtiStackInfo *stack_info()       { return _stack_info; }
705   jvmtiError result()                { return _result; }
706 };
707 
708 
709 // VM operation to get stack trace at safepoint.
710 class VM_GetAllStackTraces : public VM_Operation {
711 private:
712   JavaThread *_calling_thread;
713   jint _final_thread_count;
714   MultipleStackTracesCollector _collector;
715 
716 public:
717   VM_GetAllStackTraces(JvmtiEnv *env, JavaThread *calling_thread,
718                        jint max_frame_count)
719       : _calling_thread(calling_thread),
720         _final_thread_count(0),
721         _collector(env, max_frame_count) {
722   }
723   VMOp_Type type() const          { return VMOp_GetAllStackTraces; }
724   void doit();
725   jint final_thread_count()       { return _final_thread_count; }
726   jvmtiStackInfo *stack_info()    { return _collector.stack_info(); }
727   jvmtiError result()             { return _collector.result(); }
728 };
729 
730 // VM operation to get stack trace at safepoint.
731 class VM_GetThreadListStackTraces : public VM_Operation {
732 private:
733   jint _thread_count;
734   const jthread* _thread_list;
735   MultipleStackTracesCollector _collector;
736 
737   JvmtiEnvBase *env() { return _collector.env(); }
738 
739 public:
740   VM_GetThreadListStackTraces(JvmtiEnv *env, jint thread_count, const jthread* thread_list, jint max_frame_count)
741       : _thread_count(thread_count),
742         _thread_list(thread_list),
743         _collector(env, max_frame_count) {
744   }
745   VMOp_Type type() const { return VMOp_GetThreadListStackTraces; }
746   void doit();
747   jvmtiStackInfo *stack_info()    { return _collector.stack_info(); }
748   jvmtiError result()             { return _collector.result(); }
749 };
750 
751 // HandshakeClosure to get single stack trace.
752 class GetSingleStackTraceClosure : public JvmtiUnitedHandshakeClosure {
753 private:
754   JavaThread *_calling_thread;
755   jthread _jthread;
756   MultipleStackTracesCollector _collector;
757 
758 public:
759   GetSingleStackTraceClosure(JvmtiEnv *env, JavaThread *calling_thread,
760                              jthread thread, jint max_frame_count)
761     : JvmtiUnitedHandshakeClosure("GetSingleStackTrace"),
762       _calling_thread(calling_thread),
763       _jthread(thread),
764       _collector(env, max_frame_count) {
765   }
766   void do_thread(Thread *target);
767   void do_vthread(Handle target_h);
768   void doit();
769   jvmtiStackInfo *stack_info()    { return _collector.stack_info(); }
770   jvmtiError result()             { return _result; }
771 };
772 
773 // HandshakeClosure to count stack frames.
774 class GetFrameCountClosure : public JvmtiUnitedHandshakeClosure {
775 private:
776   JvmtiEnv *_env;
777   jint *_count_ptr;
778 
779 public:
780   GetFrameCountClosure(JvmtiEnv *env, jint *count_ptr)
781     : JvmtiUnitedHandshakeClosure("GetFrameCount"),
782       _env(env),
783       _count_ptr(count_ptr) {}
784   void do_thread(Thread *target);
785   void do_vthread(Handle target_h);
786 };
787 
788 // HandshakeClosure to get frame location.
789 class GetFrameLocationClosure : public JvmtiUnitedHandshakeClosure {
790 private:
791   JvmtiEnv *_env;
792   jint _depth;
793   jmethodID* _method_ptr;
794   jlocation* _location_ptr;
795 
796 public:
797   GetFrameLocationClosure(JvmtiEnv *env, jint depth,
798                           jmethodID* method_ptr, jlocation* location_ptr)
799     : JvmtiUnitedHandshakeClosure("GetFrameLocation"),
800       _env(env),
801       _depth(depth),
802       _method_ptr(method_ptr),
803       _location_ptr(location_ptr) {}
804   void do_thread(Thread *target);
805   void do_vthread(Handle target_h);
806 };
807 
808 // ResourceTracker
809 //
810 // ResourceTracker works a little like a ResourceMark. All allocates
811 // using the resource tracker are recorded. If an allocate using the
812 // resource tracker fails the destructor will free any resources
813 // that were allocated using the tracker.
814 // The motive for this class is to avoid messy error recovery code
815 // in situations where multiple allocations are done in sequence. If
816 // the second or subsequent allocation fails it avoids any code to
817 // release memory allocated in the previous calls.
818 //
819 // Usage :-
820 //   ResourceTracker rt(env);
821 //   :
822 //   err = rt.allocate(1024, &ptr);
823 
824 class ResourceTracker : public StackObj {
825  private:
826   JvmtiEnv* _env;
827   GrowableArray<unsigned char*> *_allocations;
828   bool _failed;
829  public:
830   ResourceTracker(JvmtiEnv* env);
831   ~ResourceTracker();
832   jvmtiError allocate(jlong size, unsigned char** mem_ptr);
833   unsigned char* allocate(jlong size);
834   char* strdup(const char* str);
835 };
836 
837 
838 // Jvmti monitor closure to collect off stack monitors.
839 class JvmtiMonitorClosure: public MonitorClosure {
840  private:
841   JavaThread *_calling_thread;
842   GrowableArray<jvmtiMonitorStackDepthInfo*> *_owned_monitors_list;
843   jvmtiError _error;
844   JvmtiEnvBase *_env;
845 
846  public:
847   JvmtiMonitorClosure(JavaThread *calling_thread,
848                       GrowableArray<jvmtiMonitorStackDepthInfo*> *owned_monitors,
849                       JvmtiEnvBase *env) {
850     _calling_thread = calling_thread;
851     _owned_monitors_list = owned_monitors;
852     _error = JVMTI_ERROR_NONE;
853     _env = env;
854   }
855   void do_monitor(ObjectMonitor* mon);
856   jvmtiError error() { return _error;}
857 };
858 
859 
860 // Jvmti module closure to collect all modules loaded to the system.
861 class JvmtiModuleClosure : public StackObj {
862 private:
863   static GrowableArray<OopHandle> *_tbl; // Protected with Module_lock
864 
865   static void do_module(ModuleEntry* entry);
866 public:
867   jvmtiError get_all_modules(JvmtiEnv* env, jint* module_count_ptr, jobject** modules_ptr);
868 };
869 
870 #endif // SHARE_PRIMS_JVMTIENVBASE_HPP