1 /*
   2  * Copyright (c) 2002, 2006, 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.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 package jdk.internal.perf;
  26 
  27 import java.nio.ByteBuffer;
  28 import java.security.Permission;
  29 import java.security.PrivilegedAction;
  30 import java.io.IOException;
  31 import java.io.UnsupportedEncodingException;
  32 import jdk.internal.ref.CleanerFactory;
  33 
  34 /**
  35  * The Perf class provides the ability to attach to an instrumentation
  36  * buffer maintained by a Java virtual machine. The instrumentation
  37  * buffer may be for the Java virtual machine running the methods of
  38  * this class or it may be for another Java virtual machine on the
  39  * same system.
  40  * <p>
  41  * In addition, this class provides methods to create instrumentation
  42  * objects in the instrumentation buffer for the Java virtual machine
  43  * that is running these methods. It also contains methods for acquiring
  44  * the value of a platform specific high resolution clock for time
  45  * stamp and interval measurement purposes.
  46  *
  47  * @author   Brian Doherty
  48  * @since    1.4.2
  49  * @see      #getPerf
  50  * @see      jdk.internal.perf.Perf.GetPerfAction
  51  * @see      java.nio.ByteBuffer
  52  */
  53 public final class Perf {
  54 
  55     private static Perf instance;
  56 
  57     private static final int PERF_MODE_RO = 0;
  58     private static final int PERF_MODE_RW = 1;
  59 
  60     private Perf() { }    // prevent instantiation
  61 
  62     /**
  63      * The GetPerfAction class is a convenience class for acquiring access
  64      * to the singleton Perf instance using the
  65      * <code>AccessController.doPrivileged()</code> method.
  66      * <p>
  67      * An instance of this class can be used as the argument to
  68      * <code>AccessController.doPrivileged(PrivilegedAction)</code>.
  69      * <p> Here is a suggested idiom for use of this class:
  70      *
  71      * <blockquote><pre>{@code
  72      * class MyTrustedClass {
  73      *   private static final Perf perf =
  74      *       AccessController.doPrivileged(new Perf.GetPerfAction<Perf>());
  75      *   ...
  76      * }
  77      * }</pre></blockquote>
  78      * <p>
  79      * In the presence of a security manager, the <code>MyTrustedClass</code>
  80      * class in the above example will need to be granted the
  81      * <em>"sun.misc.Perf.getPerf"</em> <code>RuntimePermission</code>
  82      * permission in order to successfully acquire the singleton Perf instance.
  83      * <p>
  84      * Please note that the <em>"sun.misc.Perf.getPerf"</em> permission
  85      * is not a JDK specified permission.
  86      *
  87      * @see  java.security.AccessController#doPrivileged(PrivilegedAction)
  88      * @see  java.lang.RuntimePermission
  89      */
  90     public static class GetPerfAction implements PrivilegedAction<Perf>
  91     {
  92         /**
  93          * Run the <code>Perf.getPerf()</code> method in a privileged context.
  94          *
  95          * @see #getPerf
  96          */
  97         public Perf run() {
  98             return getPerf();
  99         }
 100     }
 101 
 102     /**
 103      * Return a reference to the singleton Perf instance.
 104      * <p>
 105      * The getPerf() method returns the singleton instance of the Perf
 106      * class. The returned object provides the caller with the capability
 107      * for accessing the instrumentation buffer for this or another local
 108      * Java virtual machine.
 109      * <p>
 110      * If a security manager is installed, its <code>checkPermission</code>
 111      * method is called with a <code>RuntimePermission</code> with a target
 112      * of <em>"sun.misc.Perf.getPerf"</em>. A security exception will result
 113      * if the caller has not been granted this permission.
 114      * <p>
 115      * Access to the returned <code>Perf</code> object should be protected
 116      * by its caller and not passed on to untrusted code. This object can
 117      * be used to attach to the instrumentation buffer provided by this Java
 118      * virtual machine or for those of other Java virtual machines running
 119      * on the same system. The instrumentation buffer may contain senstitive
 120      * information. API's built on top of this interface may want to provide
 121      * finer grained access control to the contents of individual
 122      * instrumentation objects contained within the buffer.
 123      * <p>
 124      * Please note that the <em>"sun.misc.Perf.getPerf"</em> permission
 125      * is not a JDK specified permission.
 126      *
 127      * @return  A reference to the singleton Perf instance.
 128      * @throws SecurityException  if a security manager exists and its
 129      *         <code>checkPermission</code> method doesn't allow access
 130      *         to the <em>"jdk.internal.perf.Perf.getPerf""</em> target.
 131      * @see  java.lang.RuntimePermission
 132      * @see  #attach
 133      */
 134     public static Perf getPerf()
 135     {
 136         SecurityManager security = System.getSecurityManager();
 137         if (security != null) {
 138             Permission perm = new RuntimePermission("jdk.internal.perf.Perf.getPerf");
 139             security.checkPermission(perm);
 140         }
 141 
 142         return instance;
 143     }
 144 
 145     /**
 146      * Attach to the instrumentation buffer for the specified Java virtual
 147      * machine.
 148      * <p>
 149      * This method will attach to the instrumentation buffer for the
 150      * specified virtual machine. It returns a <code>ByteBuffer</code> object
 151      * that is initialized to access the instrumentation buffer for the
 152      * indicated Java virtual machine. The <code>lvmid</code> parameter is
 153      * a integer value that uniquely identifies the target local Java virtual
 154      * machine. It is typically, but not necessarily, the process id of
 155      * the target Java virtual machine.
 156      * <p>
 157      * If the <code>lvmid</code> identifies a Java virtual machine different
 158      * from the one running this method, then the coherency characteristics
 159      * of the buffer are implementation dependent. Implementations that do
 160      * not support named, coherent, shared memory may return a
 161      * <code>ByteBuffer</code> object that contains only a snap shot of the
 162      * data in the instrumentation buffer. Implementations that support named,
 163      * coherent, shared memory, may return a <code>ByteBuffer</code> object
 164      * that will be changing dynamically over time as the target Java virtual
 165      * machine updates its mapping of this buffer.
 166      * <p>
 167      * If the <code>lvmid</code> is 0 or equal to the actual <code>lvmid</code>
 168      * for the Java virtual machine running this method, then the returned
 169      * <code>ByteBuffer</code> object will always be coherent and dynamically
 170      * changing.
 171      * <p>
 172      * The attach mode specifies the access permissions requested for the
 173      * instrumentation buffer of the target virtual machine. The permitted
 174      * access permissions are:
 175      * <ul>
 176      * <li>"r"  - Read only access. This Java virtual machine has only
 177      * read access to the instrumentation buffer for the target Java
 178      * virtual machine.
 179      * <li>"rw"  - Read/Write access. This Java virtual machine has read and
 180      * write access to the instrumentation buffer for the target Java virtual
 181      * machine. This mode is currently not supported and is reserved for
 182      * future enhancements.
 183      * </ul>
 184      *
 185      * @param   lvmid            an integer that uniquely identifies the
 186      *                           target local Java virtual machine.
 187      * @param   mode             a string indicating the attach mode.
 188      * @return  ByteBuffer       a direct allocated byte buffer
 189      * @throws  IllegalArgumentException  The lvmid or mode was invalid.
 190      * @throws  IOException      An I/O error occurred while trying to acquire
 191      *                           the instrumentation buffer.
 192      * @throws  OutOfMemoryError The instrumentation buffer could not be mapped
 193      *                           into the virtual machine's address space.
 194      * @see     java.nio.ByteBuffer
 195      */
 196     public ByteBuffer attach(int lvmid, String mode)
 197            throws IllegalArgumentException, IOException
 198     {
 199         if (mode.compareTo("r") == 0) {
 200             return attachImpl(null, lvmid, PERF_MODE_RO);
 201         }
 202         else if (mode.compareTo("rw") == 0) {
 203             return attachImpl(null, lvmid, PERF_MODE_RW);
 204         }
 205         else {
 206             throw new IllegalArgumentException("unknown mode");
 207         }
 208     }
 209 
 210     /**
 211      * Attach to the instrumentation buffer for the specified Java virtual
 212      * machine owned by the given user.
 213      * <p>
 214      * This method behaves just as the <code>attach(int lvmid, String mode)
 215      * </code> method, except that it only searches for Java virtual machines
 216      * owned by the specified user.
 217      *
 218      * @param   user             A <code>String</code> object containing the
 219      *                           name of the user that owns the target Java
 220      *                           virtual machine.
 221      * @param   lvmid            an integer that uniquely identifies the
 222      *                           target local Java virtual machine.
 223      * @param   mode             a string indicating the attach mode.
 224      * @return  ByteBuffer       a direct allocated byte buffer
 225      * @throws  IllegalArgumentException  The lvmid or mode was invalid.
 226      * @throws  IOException      An I/O error occurred while trying to acquire
 227      *                           the instrumentation buffer.
 228      * @throws  OutOfMemoryError The instrumentation buffer could not be mapped
 229      *                           into the virtual machine's address space.
 230      * @see     java.nio.ByteBuffer
 231      */
 232     public ByteBuffer attach(String user, int lvmid, String mode)
 233            throws IllegalArgumentException, IOException
 234     {
 235         if (mode.compareTo("r") == 0) {
 236             return attachImpl(user, lvmid, PERF_MODE_RO);
 237         }
 238         else if (mode.compareTo("rw") == 0) {
 239             return attachImpl(user, lvmid, PERF_MODE_RW);
 240         }
 241         else {
 242             throw new IllegalArgumentException("unknown mode");
 243         }
 244     }
 245 
 246     /**
 247      * Call the implementation specific attach method.
 248      * <p>
 249      * This method calls into the Java virtual machine to perform the platform
 250      * specific attach method. Buffers returned from this method are
 251      * internally managed as <code>PhantomRefereces</code> to provide for
 252      * guaranteed, secure release of the native resources.
 253      *
 254      * @param   user             A <code>String</code> object containing the
 255      *                           name of the user that owns the target Java
 256      *                           virtual machine.
 257      * @param   lvmid            an integer that uniquely identifies the
 258      *                           target local Java virtual machine.
 259      * @param   mode             a string indicating the attach mode.
 260      * @return  ByteBuffer       a direct allocated byte buffer
 261      * @throws  IllegalArgumentException  The lvmid or mode was invalid.
 262      * @throws  IOException      An I/O error occurred while trying to acquire
 263      *                           the instrumentation buffer.
 264      * @throws  OutOfMemoryError The instrumentation buffer could not be mapped
 265      *                           into the virtual machine's address space.
 266      */
 267     private ByteBuffer attachImpl(String user, int lvmid, int mode)
 268             throws IllegalArgumentException, IOException
 269     {
 270         final ByteBuffer b = attach(user, lvmid, mode);
 271 
 272         if (lvmid == 0) {
 273             // The native instrumentation buffer for this Java virtual
 274             // machine is never unmapped.
 275             return b;
 276         }
 277         else {
 278             // This is an instrumentation buffer for another Java virtual
 279             // machine with native resources that need to be managed. We
 280             // create a duplicate of the native ByteBuffer and manage it
 281             // with a Cleaner. When the duplicate becomes phantom reachable,
 282             // the native resources will be released.
 283 
 284             final ByteBuffer dup = b.duplicate();
 285 
 286             CleanerFactory.cleaner()
 287                           .register(dup, new CleanerAction(instance, b));
 288             return dup;
 289         }
 290     }
 291 
 292     private static class CleanerAction implements Runnable {
 293         private final ByteBuffer bb;
 294         private final Perf perf;
 295         CleanerAction(Perf perf, ByteBuffer bb) {
 296             this.perf = perf;
 297             this.bb = bb;
 298         }
 299         public void run() {
 300             try {
 301                 perf.detach(bb);
 302             } catch (Throwable th) {
 303                 // avoid crashing the reference handler thread,
 304                 // but provide for some diagnosability
 305                 assert false : th.toString();
 306             }
 307         }
 308     }
 309 
 310     /**
 311      * Native method to perform the implementation specific attach mechanism.
 312      * <p>
 313      * The implementation of this method may return distinct or identical
 314      * <code>ByteBuffer</code> objects for two distinct calls requesting
 315      * attachment to the same Java virtual machine.
 316      * <p>
 317      * For the Sun HotSpot JVM, two distinct calls to attach to the same
 318      * target Java virtual machine will result in two distinct ByteBuffer
 319      * objects returned by this method. This may change in a future release.
 320      *
 321      * @param   user             A <code>String</code> object containing the
 322      *                           name of the user that owns the target Java
 323      *                           virtual machine.
 324      * @param   lvmid            an integer that uniquely identifies the
 325      *                           target local Java virtual machine.
 326      * @param   mode             a string indicating the attach mode.
 327      * @return  ByteBuffer       a direct allocated byte buffer
 328      * @throws  IllegalArgumentException  The lvmid or mode was invalid.
 329      * @throws  IOException      An I/O error occurred while trying to acquire
 330      *                           the instrumentation buffer.
 331      * @throws  OutOfMemoryError The instrumentation buffer could not be mapped
 332      *                           into the virtual machine's address space.
 333      */
 334     private native ByteBuffer attach(String user, int lvmid, int mode)
 335                    throws IllegalArgumentException, IOException;
 336 
 337     /**
 338      * Native method to perform the implementation specific detach mechanism.
 339      * <p>
 340      * If this method is passed a <code>ByteBuffer</code> object that is
 341      * not created by the <code>attach</code> method, then the results of
 342      * this method are undefined, with unpredictable and potentially damaging
 343      * effects to the Java virtual machine. To prevent accidental or malicious
 344      * use of this method, all native ByteBuffer created by the <code>
 345      * attach</code> method are managed internally as PhantomReferences
 346      * and resources are freed by the system.
 347      * <p>
 348      * If this method is passed a <code>ByteBuffer</code> object created
 349      * by the <code>attach</code> method with a lvmid for the Java virtual
 350      * machine running this method (lvmid=0, for example), then the detach
 351      * request is silently ignored.
 352      *
 353      * @param bb  A direct allocated byte buffer created by the
 354      *                    <code>attach</code> method.
 355      * @see   java.nio.ByteBuffer
 356      * @see   #attach
 357      */
 358     private native void detach(ByteBuffer bb);
 359 
 360     /**
 361      * Create a <code>long</code> scalar entry in the instrumentation buffer
 362      * with the given variability characteristic, units, and initial value.
 363      * <p>
 364      * Access to the instrument is provided through the returned <code>
 365      * ByteBuffer</code> object. Typically, this object should be wrapped
 366      * with <code>LongBuffer</code> view object.
 367      *
 368      * @param   variability the variability characteristic for this entry.
 369      * @param   units       the units for this entry.
 370      * @param   name        the name of this entry.
 371      * @param   value       the initial value for this entry.
 372      * @return  ByteBuffer  a direct allocated ByteBuffer object that
 373      *                      allows write access to a native memory location
 374      *                      containing a <code>long</code> value.
 375      *
 376      * see sun.misc.perf.Variability
 377      * see sun.misc.perf.Units
 378      * @see java.nio.ByteBuffer
 379      */
 380     public native ByteBuffer createLong(String name, int variability,
 381                                         int units, long value);
 382 
 383     /**
 384      * Create a <code>String</code> entry in the instrumentation buffer with
 385      * the given variability characteristic, units, and initial value.
 386      * <p>
 387      * The maximum length of the <code>String</code> stored in this string
 388      * instrument is given in by <code>maxLength</code> parameter. Updates
 389      * to this instrument with <code>String</code> values with lengths greater
 390      * than <code>maxLength</code> will be truncated to <code>maxLength</code>.
 391      * The truncated value will be terminated by a null character.
 392      * <p>
 393      * The underlying implementation may further limit the length of the
 394      * value, but will continue to preserve the null terminator.
 395      * <p>
 396      * Access to the instrument is provided through the returned <code>
 397      * ByteBuffer</code> object.
 398      *
 399      * @param   variability the variability characteristic for this entry.
 400      * @param   units       the units for this entry.
 401      * @param   name        the name of this entry.
 402      * @param   value       the initial value for this entry.
 403      * @param   maxLength   the maximum string length for this string
 404      *                      instrument.
 405      * @return  ByteBuffer  a direct allocated ByteBuffer that allows
 406      *                      write access to a native memory location
 407      *                      containing a <code>long</code> value.
 408      *
 409      * see sun.misc.perf.Variability
 410      * see sun.misc.perf.Units
 411      * @see java.nio.ByteBuffer
 412      */
 413     public ByteBuffer createString(String name, int variability,
 414                                    int units, String value, int maxLength)
 415     {
 416         byte[] v = getBytes(value);
 417         byte[] v1 = new byte[v.length+1];
 418         System.arraycopy(v, 0, v1, 0, v.length);
 419         v1[v.length] = '\0';
 420         return createByteArray(name, variability, units, v1, Math.max(v1.length, maxLength));
 421     }
 422 
 423     /**
 424      * Create a <code>String</code> entry in the instrumentation buffer with
 425      * the given variability characteristic, units, and initial value.
 426      * <p>
 427      * The maximum length of the <code>String</code> stored in this string
 428      * instrument is implied by the length of the <code>value</code> parameter.
 429      * Subsequent updates to the value of this instrument will be truncated
 430      * to this implied maximum length. The truncated value will be terminated
 431      * by a null character.
 432      * <p>
 433      * The underlying implementation may further limit the length of the
 434      * initial or subsequent value, but will continue to preserve the null
 435      * terminator.
 436      * <p>
 437      * Access to the instrument is provided through the returned <code>
 438      * ByteBuffer</code> object.
 439      *
 440      * @param   variability the variability characteristic for this entry.
 441      * @param   units       the units for this entry.
 442      * @param   name        the name of this entry.
 443      * @param   value       the initial value for this entry.
 444      * @return  ByteBuffer  a direct allocated ByteBuffer that allows
 445      *                      write access to a native memory location
 446      *                      containing a <code>long</code> value.
 447      *
 448      * see sun.misc.perf.Variability
 449      * see sun.misc.perf.Units
 450      * @see java.nio.ByteBuffer
 451      */
 452     public ByteBuffer createString(String name, int variability,
 453                                    int units, String value)
 454     {
 455         byte[] v = getBytes(value);
 456         byte[] v1 = new byte[v.length+1];
 457         System.arraycopy(v, 0, v1, 0, v.length);
 458         v1[v.length] = '\0';
 459         return createByteArray(name, variability, units, v1, v1.length);
 460     }
 461 
 462     /**
 463      * Create a <code>byte</code> vector entry in the instrumentation buffer
 464      * with the given variability characteristic, units, and initial value.
 465      * <p>
 466      * The <code>maxLength</code> parameter limits the size of the byte
 467      * array instrument such that the initial or subsequent updates beyond
 468      * this length are silently ignored. No special handling of truncated
 469      * updates is provided.
 470      * <p>
 471      * The underlying implementation may further limit the length of the
 472      * length of the initial or subsequent value.
 473      * <p>
 474      * Access to the instrument is provided through the returned <code>
 475      * ByteBuffer</code> object.
 476      *
 477      * @param   variability the variability characteristic for this entry.
 478      * @param   units       the units for this entry.
 479      * @param   name        the name of this entry.
 480      * @param   value       the initial value for this entry.
 481      * @param   maxLength   the maximum length of this byte array.
 482      * @return  ByteBuffer  a direct allocated byte buffer that allows
 483      *                      write access to a native memory location
 484      *                      containing a <code>long</code> value.
 485      *
 486      * see sun.misc.perf.Variability
 487      * see sun.misc.perf.Units
 488      * @see java.nio.ByteBuffer
 489      */
 490     public native ByteBuffer createByteArray(String name, int variability,
 491                                              int units, byte[] value,
 492                                              int maxLength);
 493 
 494 
 495     /**
 496      * convert string to an array of UTF-8 bytes
 497      */
 498     private static byte[] getBytes(String s)
 499     {
 500         byte[] bytes = null;
 501 
 502         try {
 503             bytes = s.getBytes("UTF-8");
 504         }
 505         catch (UnsupportedEncodingException e) {
 506             // ignore, UTF-8 encoding is always known
 507         }
 508 
 509         return bytes;
 510     }
 511 
 512     /**
 513      * Return the value of the High Resolution Counter.
 514      *
 515      * The High Resolution Counter returns the number of ticks since
 516      * since the start of the Java virtual machine. The resolution of
 517      * the counter is machine dependent and can be determined from the
 518      * value return by the {@link #highResFrequency} method.
 519      *
 520      * @return  the number of ticks of machine dependent resolution since
 521      *          the start of the Java virtual machine.
 522      *
 523      * @see #highResFrequency
 524      * @see java.lang.System#currentTimeMillis()
 525      */
 526     public native long highResCounter();
 527 
 528     /**
 529      * Returns the frequency of the High Resolution Counter, in ticks per
 530      * second.
 531      *
 532      * This value can be used to convert the value of the High Resolution
 533      * Counter, as returned from a call to the {@link #highResCounter} method,
 534      * into the number of seconds since the start of the Java virtual machine.
 535      *
 536      * @return  the frequency of the High Resolution Counter.
 537      * @see #highResCounter
 538      */
 539     public native long highResFrequency();
 540 
 541     private static native void registerNatives();
 542 
 543     static {
 544         registerNatives();
 545         instance = new Perf();
 546     }
 547 }