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