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