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