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