1 /*
  2  * Copyright (c) 2003, 2021, 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_JVMTITHREADSTATE_HPP
 26 #define SHARE_PRIMS_JVMTITHREADSTATE_HPP
 27 
 28 #include "jvmtifiles/jvmti.h"
 29 #include "memory/allocation.hpp"
 30 #include "oops/oopHandle.hpp"
 31 #include "prims/jvmtiEventController.hpp"
 32 #include "prims/jvmtiExport.hpp"
 33 #include "runtime/thread.hpp"
 34 #include "utilities/growableArray.hpp"
 35 
 36 //
 37 // Forward Declarations
 38 //
 39 
 40 class JvmtiEnvBase;
 41 class JvmtiEnvThreadState;
 42 class JvmtiDynamicCodeEventCollector;
 43 
 44 class JvmtiDeferredEvent;
 45 class JvmtiDeferredEventQueue;
 46 
 47 enum JvmtiClassLoadKind {
 48   jvmti_class_load_kind_load = 100,
 49   jvmti_class_load_kind_retransform,
 50   jvmti_class_load_kind_redefine
 51 };
 52 
 53 ///////////////////////////////////////////////////////////////
 54 //
 55 // class JvmtiEnvThreadStateIterator
 56 //
 57 // The only safe means of iterating through the JvmtiEnvThreadStates
 58 // in a JvmtiThreadState.
 59 // Note that this iteratation includes invalid environments pending
 60 // deallocation -- in fact, some uses depend on this behavior.
 61 //
 62 class JvmtiEnvThreadStateIterator : public StackObj {
 63  private:
 64   JvmtiThreadState* state;
 65  public:
 66   JvmtiEnvThreadStateIterator(JvmtiThreadState* thread_state);
 67   ~JvmtiEnvThreadStateIterator();
 68   JvmtiEnvThreadState* first();
 69   JvmtiEnvThreadState* next(JvmtiEnvThreadState* ets);
 70 };
 71 
 72 ///////////////////////////////////////////////////////////////
 73 //
 74 // class JvmtiVTMTDisabler
 75 //
 76 // Virtual Threads Mount Transition (VTMT) mechanism
 77 //
 78 class JvmtiVTMTDisabler {
 79  private:
 80 #ifdef ASSERT
 81   static volatile unsigned short _suspend_count;
 82 #endif
 83   static volatile unsigned short _VTMT_count;
 84   static volatile unsigned short _VTMT_disable_count; // VTMT is disabled while it is non-zero
 85 
 86   static void disable_VTMT();
 87   static void enable_VTMT();
 88   bool _is_suspender;
 89   bool _self_suspend;
 90 
 91   DEBUG_ONLY(static void print_info();)
 92  public:
 93   JvmtiVTMTDisabler(bool is_suspender = false);
 94   ~JvmtiVTMTDisabler();
 95 
 96   void set_self_suspend();
 97   static void start_VTMT(jthread vthread, int callsite_tag);
 98   static void finish_VTMT(jthread vthread, int callsite_tag);
 99   static int  VTMT_disable_count();
100   static int  VTMT_count();
101 };
102 
103 ///////////////////////////////////////////////////////////////
104 //
105 // class VThreadList
106 //
107 // Used for Virtual Threads Suspend/Resume management
108 //
109 class VThreadList : public GrowableArrayCHeap<OopHandle, mtServiceability> {
110  public:
111   VThreadList() : GrowableArrayCHeap<OopHandle, mtServiceability>(0) {}
112   void append(oop vt);
113   void remove(oop vt);
114   int  find(oop vt) const;
115   bool contains(oop vt) const;
116   void invalidate();
117 };
118 
119 ///////////////////////////////////////////////////////////////
120 //
121 // class JvmtiVTSuspender
122 //
123 // Virtual Threads Suspend/Resume management
124 //
125 class JvmtiVTSuspender : AllStatic {
126  private:
127   // Suspend modes for virtual threads
128   typedef enum VThreadSuspendMode {
129     vthread_suspend_none = 0,
130     vthread_suspend_ind  = 1,
131     vthread_suspend_all  = 2
132   } VThreadSuspendMode;
133 
134   static VThreadSuspendMode _vthread_suspend_mode;
135   static VThreadList* _vthread_suspend_list;
136   static VThreadList* _vthread_resume_list;
137 
138  public:
139   static void register_all_vthreads_suspend();
140   static void register_all_vthreads_resume();
141   static bool register_vthread_suspend(oop vt);
142   static bool register_vthread_resume(oop vt);
143   static bool is_vthread_suspended(oop vt);
144 };
145 
146 ///////////////////////////////////////////////////////////////
147 //
148 // class JvmtiThreadState
149 //
150 // The Jvmti state for each thread (across all JvmtiEnv):
151 // 1. Local table of enabled events.
152 class JvmtiThreadState : public CHeapObj<mtInternal> {
153  private:
154   friend class JvmtiEnv;
155   JavaThread        *_thread;
156   JavaThread        *_thread_saved;
157   OopHandle         _thread_oop_h;
158   // Jvmti Events that cannot be posted in their current context.
159   JvmtiDeferredEventQueue* _jvmti_event_queue;
160   bool              _is_in_VTMT; // saved JavaThread.is_in_VTMT()
161   bool              _is_virtual; // state belongs to a virtual thread
162   bool              _hide_single_stepping;
163   bool              _pending_step_for_popframe;
164   bool              _pending_step_for_earlyret;
165   int               _hide_level;
166 
167  public:
168   enum ExceptionState {
169     ES_CLEARED,
170     ES_DETECTED,
171     ES_CAUGHT
172   };
173 
174  private:
175   ExceptionState _exception_state;
176 
177   // Used to send class being redefined/retransformed and kind of transform
178   // info to the class file load hook event handler.
179   Klass*                _class_being_redefined;
180   JvmtiClassLoadKind    _class_load_kind;
181   GrowableArray<Klass*>* _classes_being_redefined;
182 
183   // This is only valid when is_interp_only_mode() returns true
184   int               _cur_stack_depth;
185   int               _saved_interp_only_mode;
186 
187   JvmtiThreadEventEnable _thread_event_enable;
188 
189   // for support of JvmtiEnvThreadState
190   JvmtiEnvThreadState*   _head_env_thread_state;
191 
192   // doubly-linked linear list of active thread state
193   // needed in order to iterate the list without holding Threads_lock
194   static JvmtiThreadState *_head;
195   JvmtiThreadState *_next;
196   JvmtiThreadState *_prev;
197 
198   // holds the current dynamic code event collector, NULL if no event collector in use
199   JvmtiDynamicCodeEventCollector* _dynamic_code_event_collector;
200   // holds the current vm object alloc event collector, NULL if no event collector in use
201   JvmtiVMObjectAllocEventCollector* _vm_object_alloc_event_collector;
202   // holds the current sampled object alloc event collector, NULL if no event collector in use
203   JvmtiSampledObjectAllocEventCollector* _sampled_object_alloc_event_collector;
204 
205   // Should only be created by factory methods
206   JvmtiThreadState(JavaThread *thread, oop thread_oop);
207 
208   friend class JvmtiEnvThreadStateIterator;
209   inline JvmtiEnvThreadState* head_env_thread_state();
210   inline void set_head_env_thread_state(JvmtiEnvThreadState* ets);
211 
212  public:
213   ~JvmtiThreadState();
214 
215   // is event_type enabled and usable for this thread in any enviroments?
216   bool is_enabled(jvmtiEvent event_type) {
217     return _thread_event_enable.is_enabled(event_type);
218   }
219 
220   JvmtiThreadEventEnable *thread_event_enable() {
221     return &_thread_event_enable;
222   }
223 
224   // Must only be called in situations where the state is for the current thread and
225   // the environment can not go away.  To be safe, the returned JvmtiEnvThreadState
226   // must be used in such a way as there can be no intervening safepoints.
227   inline JvmtiEnvThreadState* env_thread_state(JvmtiEnvBase *env);
228 
229   static void periodic_clean_up();
230 
231   void add_env(JvmtiEnvBase *env);
232 
233   void unbind_from(JavaThread* thread);
234   void bind_to(JavaThread* thread);
235 
236   // Used by the interpreter for fullspeed debugging support
237   bool is_interp_only_mode()                {
238      return _thread == NULL ?  _saved_interp_only_mode != 0 : _thread->is_interp_only_mode();
239   }
240   void enter_interp_only_mode();
241   void leave_interp_only_mode();
242 
243   // access to the linked list of all JVMTI thread states
244   static JvmtiThreadState *first() {
245     assert(Threads::number_of_threads() == 0 || JvmtiThreadState_lock->is_locked(), "sanity check");
246     return _head;
247   }
248 
249   JvmtiThreadState *next()                  {
250     return _next;
251   }
252 
253   // Current stack depth is only valid when is_interp_only_mode() returns true.
254   // These functions should only be called at a safepoint - usually called from same thread.
255   // Returns the number of Java activations on the stack.
256   int cur_stack_depth();
257   void invalidate_cur_stack_depth();
258   void incr_cur_stack_depth();
259   void decr_cur_stack_depth();
260 
261   int count_frames();
262 
263   inline JavaThread *get_thread()      { return _thread;              }
264   inline JavaThread *get_thread_or_saved(); // return _thread_saved if _thread is NULL
265 
266   // Needed for virtual threads as they can migrate to different JavaThread's.
267   // Also used for carrier threads to clear/restore _thread.
268   void set_thread(JavaThread* thread);
269   oop get_thread_oop();
270 
271   // The JavaThread is_in_VTMT() bit saved at unmount to restore at mount.
272   inline bool is_in_VTMT() { return _is_in_VTMT; }
273   inline void set_is_in_VTMT(bool val) { _is_in_VTMT = val; }
274   inline bool is_virtual() { return _is_virtual; } // the _thread is virtual
275 
276   inline bool is_exception_detected()  { return _exception_state == ES_DETECTED;  }
277   inline bool is_exception_caught()    { return _exception_state == ES_CAUGHT;  }
278 
279   inline void set_exception_detected() { _exception_state = ES_DETECTED; }
280   inline void set_exception_caught()   { _exception_state = ES_CAUGHT; }
281 
282   inline void clear_exception_state() { _exception_state = ES_CLEARED; }
283 
284   // We need to save and restore exception state inside JvmtiEventMark
285   inline ExceptionState get_exception_state() { return _exception_state; }
286   inline void restore_exception_state(ExceptionState state) { _exception_state = state; }
287 
288   inline void clear_hide_single_stepping() {
289     if (_hide_level > 0) {
290       _hide_level--;
291     } else {
292       assert(_hide_single_stepping, "hide_single_stepping is out of phase");
293       _hide_single_stepping = false;
294     }
295   }
296   inline bool hide_single_stepping() { return _hide_single_stepping; }
297   inline void set_hide_single_stepping() {
298     if (_hide_single_stepping) {
299       _hide_level++;
300     } else {
301       assert(_hide_level == 0, "hide_level is out of phase");
302       _hide_single_stepping = true;
303     }
304   }
305 
306   // Step pending flag is set when PopFrame is called and it is cleared
307   // when step for the Pop Frame is completed.
308   // This logic is used to distinguish b/w step for pop frame and repeat step.
309   void set_pending_step_for_popframe() { _pending_step_for_popframe = true;  }
310   void clr_pending_step_for_popframe() { _pending_step_for_popframe = false; }
311   bool is_pending_step_for_popframe()  { return _pending_step_for_popframe;  }
312   void process_pending_step_for_popframe();
313 
314   // Step pending flag is set when ForceEarlyReturn is called and it is cleared
315   // when step for the ForceEarlyReturn is completed.
316   // This logic is used to distinguish b/w step for early return and repeat step.
317   void set_pending_step_for_earlyret() { _pending_step_for_earlyret = true;  }
318   void clr_pending_step_for_earlyret() { _pending_step_for_earlyret = false; }
319   bool is_pending_step_for_earlyret()  { return _pending_step_for_earlyret;  }
320   void process_pending_step_for_earlyret();
321 
322   // Setter and getter method is used to send redefined class info
323   // when class file load hook event is posted.
324   // It is set while loading redefined class and cleared before the
325   // class file load hook event is posted.
326   inline void set_class_being_redefined(Klass* k, JvmtiClassLoadKind kind) {
327     _class_being_redefined = k;
328     _class_load_kind = kind;
329   }
330 
331   inline void clear_class_being_redefined() {
332     _class_being_redefined = NULL;
333     _class_load_kind = jvmti_class_load_kind_load;
334   }
335 
336   inline Klass* get_class_being_redefined() {
337     return _class_being_redefined;
338   }
339 
340   inline JvmtiClassLoadKind get_class_load_kind() {
341     return _class_load_kind;
342   }
343 
344   // Get the classes that are currently being redefined by this thread.
345   inline GrowableArray<Klass*>* get_classes_being_redefined() {
346     return _classes_being_redefined;
347   }
348 
349   inline void set_classes_being_redefined(GrowableArray<Klass*>* redef_classes) {
350     _classes_being_redefined = redef_classes;
351   }
352 
353   // RedefineClasses support
354   // The bug 6214132 caused the verification to fail.
355   //
356   // What is done at verification:
357   //   (This seems to only apply to the old verifier.)
358   //   When the verifier makes calls into the VM to ask questions about
359   //   the class being verified, it will pass the jclass to JVM_* functions.
360   //   The jclass is always pointing to the mirror of _the_class.
361   //   ~28 JVM_* functions called by the verifier for the information
362   //   about CP entries and klass structure should check the jvmtiThreadState
363   //   info about equivalent klass versions and use it to replace a Klass*
364   //   of _the_class with a Klass* of _scratch_class. The function
365   //   class_to_verify_considering_redefinition() must be called for it.
366   //
367   //   Note again, that this redirection happens only for the verifier thread.
368   //   Other threads have very small overhead by checking the existence
369   //   of the jvmtiThreadSate and the information about klasses equivalence.
370   //   No JNI functions need to be changed, they don't reference the klass guts.
371   //   The JavaThread pointer is already available in all JVM_* functions
372   //   used by the verifier, so there is no extra performance issue with it.
373 
374  private:
375   Klass* _the_class_for_redefinition_verification;
376   Klass* _scratch_class_for_redefinition_verification;
377 
378  public:
379   inline void set_class_versions_map(Klass* the_class,
380                                      Klass* scratch_class) {
381     _the_class_for_redefinition_verification = the_class;
382     _scratch_class_for_redefinition_verification = scratch_class;
383   }
384 
385   inline void clear_class_versions_map() { set_class_versions_map(NULL, NULL); }
386 
387   static inline
388   Klass* class_to_verify_considering_redefinition(Klass* klass,
389                                                     JavaThread *thread) {
390     JvmtiThreadState *state = thread->jvmti_thread_state();
391     if (state != NULL && state->_the_class_for_redefinition_verification != NULL) {
392       if (state->_the_class_for_redefinition_verification == klass) {
393         klass = state->_scratch_class_for_redefinition_verification;
394       }
395     }
396     return klass;
397   }
398 
399   // Todo: get rid of this!
400  private:
401   bool _debuggable;
402  public:
403   // Should the thread be enumerated by jvmtiInternal::GetAllThreads?
404   bool is_debuggable()                 { return _debuggable; }
405   // If a thread cannot be suspended (has no valid last_java_frame) then it gets marked !debuggable
406   void set_debuggable(bool debuggable) { _debuggable = debuggable; }
407 
408  public:
409 
410   // Thread local event collector setter and getter methods.
411   JvmtiDynamicCodeEventCollector* get_dynamic_code_event_collector() {
412     return _dynamic_code_event_collector;
413   }
414   JvmtiVMObjectAllocEventCollector* get_vm_object_alloc_event_collector() {
415     return _vm_object_alloc_event_collector;
416   }
417   JvmtiSampledObjectAllocEventCollector* get_sampled_object_alloc_event_collector() {
418     return _sampled_object_alloc_event_collector;
419   }
420   void set_dynamic_code_event_collector(JvmtiDynamicCodeEventCollector* collector) {
421     _dynamic_code_event_collector = collector;
422   }
423   void set_vm_object_alloc_event_collector(JvmtiVMObjectAllocEventCollector* collector) {
424     _vm_object_alloc_event_collector = collector;
425   }
426   void set_sampled_object_alloc_event_collector(JvmtiSampledObjectAllocEventCollector* collector) {
427     _sampled_object_alloc_event_collector = collector;
428   }
429 
430 
431   //
432   // Frame routines
433   //
434 
435  public:
436 
437   //  true when the thread was suspended with a pointer to the last Java frame.
438   bool has_last_frame()                     { return _thread->has_last_Java_frame(); }
439 
440   void update_for_pop_top_frame();
441 
442   // already holding JvmtiThreadState_lock - retrieve or create JvmtiThreadState
443   // Can return NULL if JavaThread is exiting.
444   static JvmtiThreadState *state_for_while_locked(JavaThread *thread, oop thread_oop = NULL);
445   // retrieve or create JvmtiThreadState
446   // Can return NULL if JavaThread is exiting.
447   static JvmtiThreadState *state_for(JavaThread *thread, Handle thread_handle = Handle());
448 
449   // JVMTI ForceEarlyReturn support
450 
451   // This is set to earlyret_pending to signal that top Java frame
452   // should be returned immediately
453  public:
454   int           _earlyret_state;
455   TosState      _earlyret_tos;
456   jvalue        _earlyret_value;
457   oop           _earlyret_oop;         // Used to return an oop result into Java code from
458                                        // ForceEarlyReturnObject, GC-preserved
459 
460   // Setting and clearing earlyret_state
461   // earlyret_pending indicates that a ForceEarlyReturn() has been
462   // requested and not yet been completed.
463  public:
464   enum EarlyretState {
465     earlyret_inactive = 0,
466     earlyret_pending  = 1
467   };
468 
469   void set_earlyret_pending(void) { _earlyret_state = earlyret_pending;  }
470   void clr_earlyret_pending(void) { _earlyret_state = earlyret_inactive; }
471   bool is_earlyret_pending(void)  { return (_earlyret_state == earlyret_pending);  }
472 
473   TosState earlyret_tos()                            { return _earlyret_tos; }
474   oop  earlyret_oop() const                          { return _earlyret_oop; }
475   void set_earlyret_oop (oop x)                      { _earlyret_oop = x;    }
476   jvalue earlyret_value()                            { return _earlyret_value; }
477   void set_earlyret_value(jvalue val, TosState tos)  { _earlyret_tos = tos;  _earlyret_value = val;  }
478   void clr_earlyret_value()                          { _earlyret_tos = ilgl; _earlyret_value.j = 0L; }
479 
480   static ByteSize earlyret_state_offset() { return byte_offset_of(JvmtiThreadState, _earlyret_state); }
481   static ByteSize earlyret_tos_offset()   { return byte_offset_of(JvmtiThreadState, _earlyret_tos); }
482   static ByteSize earlyret_oop_offset()   { return byte_offset_of(JvmtiThreadState, _earlyret_oop); }
483   static ByteSize earlyret_value_offset() { return byte_offset_of(JvmtiThreadState, _earlyret_value); }
484 
485   void oops_do(OopClosure* f, CodeBlobClosure* cf) NOT_JVMTI_RETURN; // GC support
486   void nmethods_do(CodeBlobClosure* cf) NOT_JVMTI_RETURN;
487 
488 public:
489   void set_should_post_on_exceptions(bool val);
490 
491   // Thread local event queue, which doesn't require taking the Service_lock.
492   void enqueue_event(JvmtiDeferredEvent* event) NOT_JVMTI_RETURN;
493   void post_events(JvmtiEnv* env);
494   void run_nmethod_entry_barriers();
495 };
496 
497 #endif // SHARE_PRIMS_JVMTITHREADSTATE_HPP