1 /*
2  * Copyright (c) 1999, 2020, 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_JVMTIIMPL_HPP
26 #define SHARE_PRIMS_JVMTIIMPL_HPP
27 
28 #include "classfile/systemDictionary.hpp"
29 #include "jvmtifiles/jvmti.h"
30 #include "oops/objArrayOop.hpp"
31 #include "prims/jvmtiEnvThreadState.hpp"
32 #include "prims/jvmtiEventController.hpp"
33 #include "prims/jvmtiTrace.hpp"
34 #include "prims/jvmtiUtil.hpp"
35 #include "runtime/escapeBarrier.hpp"
36 #include "runtime/stackValueCollection.hpp"
37 #include "runtime/vmOperations.hpp"
38 #include "utilities/ostream.hpp"
39 
40 //
41 // Forward Declarations
42 //
43 
44 class JvmtiBreakpoint;
45 class JvmtiBreakpoints;
46 
47 
48 ///////////////////////////////////////////////////////////////
49 //
50 // class GrowableCache, GrowableElement
51 // Used by              : JvmtiBreakpointCache
52 // Used by JVMTI methods: none directly.
53 //
54 // GrowableCache is a permanent CHeap growable array of <GrowableElement *>
55 //
56 // In addition, the GrowableCache maintains a NULL terminated cache array of type address
57 // that's created from the element array using the function:
58 //     address GrowableElement::getCacheValue().
59 //
60 // Whenever the GrowableArray changes size, the cache array gets recomputed into a new C_HEAP allocated
61 // block of memory. Additionally, every time the cache changes its position in memory, the
62 //    void (*_listener_fun)(void *this_obj, address* cache)
63 // gets called with the cache's new address. This gives the user of the GrowableCache a callback
64 // to update its pointer to the address cache.
65 //
66 
67 class GrowableElement : public CHeapObj<mtInternal> {
68 public:
~GrowableElement()69   virtual ~GrowableElement() {}
70   virtual address getCacheValue()          =0;
71   virtual bool equals(GrowableElement* e)  =0;
72   virtual GrowableElement *clone()         =0;
73 };
74 
75 class GrowableCache {
76 
77 private:
78   // Object pointer passed into cache & listener functions.
79   void *_this_obj;
80 
81   // Array of elements in the collection
82   GrowableArray<GrowableElement *> *_elements;
83 
84   // Parallel array of cached values
85   address *_cache;
86 
87   // Listener for changes to the _cache field.
88   // Called whenever the _cache field has it's value changed
89   // (but NOT when cached elements are recomputed).
90   void (*_listener_fun)(void *, address*);
91 
92   static bool equals(void *, GrowableElement *);
93 
94   // recache all elements after size change, notify listener
95   void recache();
96 
97 public:
98    GrowableCache();
99    ~GrowableCache();
100 
101   void initialize(void *this_obj, void listener_fun(void *, address*) );
102 
103   // number of elements in the collection
104   int length();
105   // get the value of the index element in the collection
106   GrowableElement* at(int index);
107   // find the index of the element, -1 if it doesn't exist
108   int find(GrowableElement* e);
109   // append a copy of the element to the end of the collection, notify listener
110   void append(GrowableElement* e);
111   // remove the element at index, notify listener
112   void remove (int index);
113   // clear out all elements and release all heap space, notify listener
114   void clear();
115 };
116 
117 
118 ///////////////////////////////////////////////////////////////
119 //
120 // class JvmtiBreakpointCache
121 // Used by              : JvmtiBreakpoints
122 // Used by JVMTI methods: none directly.
123 // Note   : typesafe wrapper for GrowableCache of JvmtiBreakpoint
124 //
125 
126 class JvmtiBreakpointCache : public CHeapObj<mtInternal> {
127 
128 private:
129   GrowableCache _cache;
130 
131 public:
JvmtiBreakpointCache()132   JvmtiBreakpointCache()  {}
~JvmtiBreakpointCache()133   ~JvmtiBreakpointCache() {}
134 
initialize(void * this_obj,void listener_fun (void *,address *))135   void initialize(void *this_obj, void listener_fun(void *, address*) ) {
136     _cache.initialize(this_obj, listener_fun);
137   }
138 
length()139   int length()                          { return _cache.length(); }
at(int index)140   JvmtiBreakpoint& at(int index)        { return (JvmtiBreakpoint&) *(_cache.at(index)); }
find(JvmtiBreakpoint & e)141   int find(JvmtiBreakpoint& e)          { return _cache.find((GrowableElement *) &e); }
append(JvmtiBreakpoint & e)142   void append(JvmtiBreakpoint& e)       { _cache.append((GrowableElement *) &e); }
remove(int index)143   void remove (int index)               { _cache.remove(index); }
144 };
145 
146 
147 ///////////////////////////////////////////////////////////////
148 //
149 // class JvmtiBreakpoint
150 // Used by              : JvmtiBreakpoints
151 // Used by JVMTI methods: SetBreakpoint, ClearBreakpoint, ClearAllBreakpoints
152 // Note: Extends GrowableElement for use in a GrowableCache
153 //
154 // A JvmtiBreakpoint describes a location (class, method, bci) to break at.
155 //
156 
157 typedef void (Method::*method_action)(int _bci);
158 
159 class JvmtiBreakpoint : public GrowableElement {
160 private:
161   Method*               _method;
162   int                   _bci;
163   OopHandle             _class_holder;  // keeps _method memory from being deallocated
164 
165 public:
JvmtiBreakpoint()166   JvmtiBreakpoint() : _method(NULL), _bci(0) {}
167   JvmtiBreakpoint(Method* m_method, jlocation location);
168   virtual ~JvmtiBreakpoint();
169   bool equals(JvmtiBreakpoint& bp);
170   void copy(JvmtiBreakpoint& bp);
171   address getBcp() const;
172   void each_method_version_do(method_action meth_act);
173   void set();
174   void clear();
175   void print_on(outputStream* out) const;
176 
method()177   Method* method() { return _method; }
178 
179   // GrowableElement implementation
getCacheValue()180   address getCacheValue()         { return getBcp(); }
equals(GrowableElement * e)181   bool equals(GrowableElement* e) { return equals((JvmtiBreakpoint&) *e); }
182 
clone()183   GrowableElement *clone()        {
184     JvmtiBreakpoint *bp = new JvmtiBreakpoint();
185     bp->copy(*this);
186     return bp;
187   }
188 };
189 
190 
191 ///////////////////////////////////////////////////////////////
192 //
193 // class JvmtiBreakpoints
194 // Used by              : JvmtiCurrentBreakpoints
195 // Used by JVMTI methods: none directly
196 // Note: A Helper class
197 //
198 // JvmtiBreakpoints is a GrowableCache of JvmtiBreakpoint.
199 // All changes to the GrowableCache occur at a safepoint using VM_ChangeBreakpoints.
200 //
201 // Because _bps is only modified at safepoints, its possible to always use the
202 // cached byte code pointers from _bps without doing any synchronization (see JvmtiCurrentBreakpoints).
203 //
204 // It would be possible to make JvmtiBreakpoints a static class, but I've made it
205 // CHeap allocated to emphasize its similarity to JvmtiFramePops.
206 //
207 
208 class JvmtiBreakpoints : public CHeapObj<mtInternal> {
209 private:
210 
211   JvmtiBreakpointCache _bps;
212 
213   // These should only be used by VM_ChangeBreakpoints
214   // to insure they only occur at safepoints.
215   // Todo: add checks for safepoint
216   friend class VM_ChangeBreakpoints;
217   void set_at_safepoint(JvmtiBreakpoint& bp);
218   void clear_at_safepoint(JvmtiBreakpoint& bp);
219 
220 public:
221   JvmtiBreakpoints(void listener_fun(void *, address *));
222   ~JvmtiBreakpoints();
223 
224   int length();
225   void print();
226 
227   int  set(JvmtiBreakpoint& bp);
228   int  clear(JvmtiBreakpoint& bp);
229   void clearall_in_class_at_safepoint(Klass* klass);
230 };
231 
232 
233 ///////////////////////////////////////////////////////////////
234 //
235 // class JvmtiCurrentBreakpoints
236 //
237 // A static wrapper class for the JvmtiBreakpoints that provides:
238 // 1. a fast inlined function to check if a byte code pointer is a breakpoint (is_breakpoint).
239 // 2. a function for lazily creating the JvmtiBreakpoints class (this is not strictly necessary,
240 //    but I'm copying the code from JvmtiThreadState which needs to lazily initialize
241 //    JvmtiFramePops).
242 // 3. An oops_do entry point for GC'ing the breakpoint array.
243 //
244 
245 class JvmtiCurrentBreakpoints : public AllStatic {
246 
247 private:
248 
249   // Current breakpoints, lazily initialized by get_jvmti_breakpoints();
250   static JvmtiBreakpoints *_jvmti_breakpoints;
251 
252   // NULL terminated cache of byte-code pointers corresponding to current breakpoints.
253   // Updated only at safepoints (with listener_fun) when the cache is moved.
254   // It exists only to make is_breakpoint fast.
255   static address          *_breakpoint_list;
set_breakpoint_list(address * breakpoint_list)256   static inline void set_breakpoint_list(address *breakpoint_list) { _breakpoint_list = breakpoint_list; }
257 
258   // Listener for the GrowableCache in _jvmti_breakpoints, updates _breakpoint_list.
259   static void listener_fun(void *this_obj, address *cache);
260 
261 public:
262   static void initialize();
263   static void destroy();
264 
265   // lazily create _jvmti_breakpoints and _breakpoint_list
266   static JvmtiBreakpoints& get_jvmti_breakpoints();
267 };
268 
269 ///////////////////////////////////////////////////////////////
270 //
271 // class VM_ChangeBreakpoints
272 // Used by              : JvmtiBreakpoints
273 // Used by JVMTI methods: none directly.
274 // Note: A Helper class.
275 //
276 // VM_ChangeBreakpoints implements a VM_Operation for ALL modifications to the JvmtiBreakpoints class.
277 //
278 
279 class VM_ChangeBreakpoints : public VM_Operation {
280 private:
281   JvmtiBreakpoints* _breakpoints;
282   int               _operation;
283   JvmtiBreakpoint*  _bp;
284 
285 public:
286   enum { SET_BREAKPOINT=0, CLEAR_BREAKPOINT=1 };
287 
VM_ChangeBreakpoints(int operation,JvmtiBreakpoint * bp)288   VM_ChangeBreakpoints(int operation, JvmtiBreakpoint *bp) {
289     JvmtiBreakpoints& current_bps = JvmtiCurrentBreakpoints::get_jvmti_breakpoints();
290     _breakpoints = &current_bps;
291     _bp = bp;
292     _operation = operation;
293     assert(bp != NULL, "bp != NULL");
294   }
295 
type() const296   VMOp_Type type() const { return VMOp_ChangeBreakpoints; }
297   void doit();
298 };
299 
300 
301 ///////////////////////////////////////////////////////////////
302 // The get/set local operations must only be done by the VM thread
303 // because the interpreter version needs to access oop maps, which can
304 // only safely be done by the VM thread
305 //
306 // I'm told that in 1.5 oop maps are now protected by a lock and
307 // we could get rid of the VM op
308 // However if the VM op is removed then the target thread must
309 // be suspended AND a lock will be needed to prevent concurrent
310 // setting of locals to the same java thread. This lock is needed
311 // to prevent compiledVFrames from trying to add deferred updates
312 // to the thread simultaneously.
313 //
314 class VM_GetOrSetLocal : public VM_Operation {
315  protected:
316   JavaThread* _thread;
317   JavaThread* _calling_thread;
318   jint        _depth;
319   jint        _index;
320   BasicType   _type;
321   jvalue      _value;
322   javaVFrame* _jvf;
323   bool        _set;
324 
325   EscapeBarrier _eb;
326 
327   // It is possible to get the receiver out of a non-static native wrapper
328   // frame.  Use VM_GetReceiver to do this.
getting_receiver() const329   virtual bool getting_receiver() const { return false; }
330 
331   jvmtiError  _result;
332 
333   vframe* get_vframe();
334   javaVFrame* get_java_vframe();
335   bool check_slot_type_lvt(javaVFrame* vf);
336   bool check_slot_type_no_lvt(javaVFrame* vf);
337 
338 public:
339   // Constructor for non-object getter
340   VM_GetOrSetLocal(JavaThread* thread, jint depth, jint index, BasicType type);
341 
342   // Constructor for object or non-object setter
343   VM_GetOrSetLocal(JavaThread* thread, jint depth, jint index, BasicType type, jvalue value);
344 
345   // Constructor for object getter
346   VM_GetOrSetLocal(JavaThread* thread, JavaThread* calling_thread, jint depth,
347                    int index);
348 
type() const349   VMOp_Type type() const { return VMOp_GetOrSetLocal; }
value()350   jvalue value()         { return _value; }
result()351   jvmtiError result()    { return _result; }
352 
353   bool doit_prologue();
354   void doit();
355   bool allow_nested_vm_operations() const;
name() const356   const char* name() const                       { return "get/set locals"; }
357 
358   // Check that the klass is assignable to a type with the given signature.
359   static bool is_assignable(const char* ty_sign, Klass* klass, Thread* thread);
360 };
361 
362 class VM_GetReceiver : public VM_GetOrSetLocal {
363  protected:
getting_receiver() const364   virtual bool getting_receiver() const { return true; }
365 
366  public:
367   VM_GetReceiver(JavaThread* thread, JavaThread* calling_thread, jint depth);
name() const368   const char* name() const                       { return "get receiver"; }
369 };
370 
371 
372 ///////////////////////////////////////////////////////////////
373 //
374 // class JvmtiSuspendControl
375 //
376 // Convenience routines for suspending and resuming threads.
377 //
378 // All attempts by JVMTI to suspend and resume threads must go through the
379 // JvmtiSuspendControl interface.
380 //
381 // methods return true if successful
382 //
383 class JvmtiSuspendControl : public AllStatic {
384 public:
385   // suspend the thread, taking it to a safepoint
386   static bool suspend(JavaThread *java_thread);
387   // resume the thread
388   static bool resume(JavaThread *java_thread);
389 
390   static void print();
391 };
392 
393 
394 /**
395  * When a thread (such as the compiler thread or VM thread) cannot post a
396  * JVMTI event itself because the event needs to be posted from a Java
397  * thread, then it can defer the event to the Service thread for posting.
398  * The information needed to post the event is encapsulated into this class
399  * and then enqueued onto the JvmtiDeferredEventQueue, where the Service
400  * thread will pick it up and post it.
401  *
402  * This is currently only used for posting compiled-method-load and unload
403  * events, which we don't want posted from the compiler thread.
404  */
405 class JvmtiDeferredEvent {
406   friend class JvmtiDeferredEventQueue;
407  private:
408   typedef enum {
409     TYPE_NONE,
410     TYPE_COMPILED_METHOD_LOAD,
411     TYPE_COMPILED_METHOD_UNLOAD,
412     TYPE_DYNAMIC_CODE_GENERATED,
413     TYPE_CLASS_UNLOAD
414   } Type;
415 
416   Type _type;
417   union {
418     nmethod* compiled_method_load;
419     struct {
420       jmethodID method_id;
421       const void* code_begin;
422     } compiled_method_unload;
423     struct {
424       const char* name;
425       const void* code_begin;
426       const void* code_end;
427     } dynamic_code_generated;
428     struct {
429       const char* name;
430     } class_unload;
431   } _event_data;
432 
JvmtiDeferredEvent(Type t)433   JvmtiDeferredEvent(Type t) : _type(t) {}
434 
435  public:
436 
JvmtiDeferredEvent()437   JvmtiDeferredEvent() : _type(TYPE_NONE) {}
438 
439   // Factory methods
440   static JvmtiDeferredEvent compiled_method_load_event(nmethod* nm)
441     NOT_JVMTI_RETURN_(JvmtiDeferredEvent());
442   static JvmtiDeferredEvent compiled_method_unload_event(
443       jmethodID id, const void* code) NOT_JVMTI_RETURN_(JvmtiDeferredEvent());
444   static JvmtiDeferredEvent dynamic_code_generated_event(
445       const char* name, const void* begin, const void* end)
446           NOT_JVMTI_RETURN_(JvmtiDeferredEvent());
447   static JvmtiDeferredEvent class_unload_event(
448       const char* name) NOT_JVMTI_RETURN_(JvmtiDeferredEvent());
449 
450   // Actually posts the event.
451   void post() NOT_JVMTI_RETURN;
452   void post_compiled_method_load_event(JvmtiEnv* env) NOT_JVMTI_RETURN;
453   void run_nmethod_entry_barriers() NOT_JVMTI_RETURN;
454   // Sweeper support to keep nmethods from being zombied while in the queue.
455   void nmethods_do(CodeBlobClosure* cf) NOT_JVMTI_RETURN;
456   // GC support to keep nmethod from being unloaded while in the queue.
457   void oops_do(OopClosure* f, CodeBlobClosure* cf) NOT_JVMTI_RETURN;
458 };
459 
460 /**
461  * Events enqueued on this queue wake up the Service thread which dequeues
462  * and posts the events.  The Service_lock is required to be held
463  * when operating on the queue.
464  */
465 class JvmtiDeferredEventQueue : public CHeapObj<mtInternal> {
466   friend class JvmtiDeferredEvent;
467  private:
468   class QueueNode : public CHeapObj<mtInternal> {
469    private:
470     JvmtiDeferredEvent _event;
471     QueueNode* _next;
472 
473    public:
QueueNode(const JvmtiDeferredEvent & event)474     QueueNode(const JvmtiDeferredEvent& event)
475       : _event(event), _next(NULL) {}
476 
event()477     JvmtiDeferredEvent& event() { return _event; }
next() const478     QueueNode* next() const { return _next; }
479 
set_next(QueueNode * next)480     void set_next(QueueNode* next) { _next = next; }
481   };
482 
483   QueueNode* _queue_head;
484   QueueNode* _queue_tail;
485 
486  public:
JvmtiDeferredEventQueue()487   JvmtiDeferredEventQueue() : _queue_head(NULL), _queue_tail(NULL) {}
488 
489   bool has_events() NOT_JVMTI_RETURN_(false);
490   JvmtiDeferredEvent dequeue() NOT_JVMTI_RETURN_(JvmtiDeferredEvent());
491 
492   // Post all events in the queue for the current Jvmti environment
493   void post(JvmtiEnv* env) NOT_JVMTI_RETURN;
494   void enqueue(JvmtiDeferredEvent event) NOT_JVMTI_RETURN;
495   void run_nmethod_entry_barriers();
496 
497   // Sweeper support to keep nmethods from being zombied while in the queue.
498   void nmethods_do(CodeBlobClosure* cf) NOT_JVMTI_RETURN;
499   // GC support to keep nmethod from being unloaded while in the queue.
500   void oops_do(OopClosure* f, CodeBlobClosure* cf) NOT_JVMTI_RETURN;
501 };
502 
503 // Utility macro that checks for NULL pointers:
504 #define NULL_CHECK(X, Y) if ((X) == NULL) { return (Y); }
505 
506 #endif // SHARE_PRIMS_JVMTIIMPL_HPP
507