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