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