1 /*
  2  * Copyright (c) 1996, 2020, 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 
 26 package jdk.internal.misc;
 27 
 28 import static java.lang.Thread.State.*;
 29 
 30 import java.text.NumberFormat;
 31 import java.util.ArrayList;
 32 import java.util.Collections;
 33 import java.util.List;
 34 import java.util.Map;
 35 
 36 import jdk.internal.access.SharedSecrets;
 37 
 38 import sun.nio.ch.FileChannelImpl;
 39 
 40 public class VM {
 41 
 42     // the init level when the VM is fully initialized
 43     private static final int JAVA_LANG_SYSTEM_INITED     = 1;
 44     private static final int MODULE_SYSTEM_INITED        = 2;
 45     private static final int SYSTEM_LOADER_INITIALIZING  = 3;
 46     private static final int SYSTEM_BOOTED               = 4;
 47     private static final int SYSTEM_SHUTDOWN             = 5;
 48 
 49     // 0, 1, 2, ...
 50     private static volatile int initLevel;
 51     private static final Object lock = new Object();
 52 
 53     /**
 54      * Sets the init level.
 55      *
 56      * @see java.lang.System#initPhase1
 57      * @see java.lang.System#initPhase2
 58      * @see java.lang.System#initPhase3
 59      */
 60     public static void initLevel(int value) {
 61         synchronized (lock) {
 62             if (value <= initLevel || value > SYSTEM_SHUTDOWN)
 63                 throw new InternalError("Bad level: " + value);
 64             initLevel = value;
 65             lock.notifyAll();
 66         }
 67     }
 68 
 69     /**
 70      * Returns the current init level.
 71      */
 72     public static int initLevel() {
 73         return initLevel;
 74     }
 75 
 76     /**
 77      * Waits for the init level to get the given value.
 78      *
 79      * @see java.lang.ref.Finalizer
 80      */
 81     public static void awaitInitLevel(int value) throws InterruptedException {
 82         synchronized (lock) {
 83             while (initLevel < value) {
 84                 lock.wait();
 85             }
 86         }
 87     }
 88 
 89     /**
 90      * Returns {@code true} if the module system has been initialized.
 91      * @see java.lang.System#initPhase2
 92      */
 93     public static boolean isModuleSystemInited() {
 94         return VM.initLevel() >= MODULE_SYSTEM_INITED;
 95     }
 96 
 97     /**
 98      * Returns {@code true} if the VM is fully initialized.
 99      */
100     public static boolean isBooted() {
101         return initLevel >= SYSTEM_BOOTED;
102     }
103 
104     /**
105      * Set shutdown state.  Shutdown completes when all registered shutdown
106      * hooks have been run.
107      *
108      * @see java.lang.Shutdown
109      */
110     public static void shutdown() {
111         initLevel(SYSTEM_SHUTDOWN);
112     }
113 
114     /**
115      * Returns {@code true} if the VM has been shutdown
116      */
117     public static boolean isShutdown() {
118         return initLevel == SYSTEM_SHUTDOWN;
119     }
120 
121     // A user-settable upper limit on the maximum amount of allocatable direct
122     // buffer memory.  This value may be changed during VM initialization if
123     // "java" is launched with "-XX:MaxDirectMemorySize=<size>".
124     //
125     // The initial value of this field is arbitrary; during JRE initialization
126     // it will be reset to the value specified on the command line, if any,
127     // otherwise to Runtime.getRuntime().maxMemory().
128     //
129     private static long directMemory = 64 * 1024 * 1024;
130 
131     // Returns the maximum amount of allocatable direct buffer memory.
132     // The directMemory variable is initialized during system initialization
133     // in the saveAndRemoveProperties method.
134     //
135     public static long maxDirectMemory() {
136         return directMemory;
137     }
138 
139     // User-controllable flag that determines if direct buffers should be page
140     // aligned. The "-XX:+PageAlignDirectMemory" option can be used to force
141     // buffers, allocated by ByteBuffer.allocateDirect, to be page aligned.
142     private static boolean pageAlignDirectMemory;
143 
144     // Returns {@code true} if the direct buffers should be page aligned. This
145     // variable is initialized by saveAndRemoveProperties.
146     public static boolean isDirectMemoryPageAligned() {
147         return pageAlignDirectMemory;
148     }
149 
150     private static int classFileMajorVersion;
151     private static int classFileMinorVersion;
152     private static final int PREVIEW_MINOR_VERSION = 65535;
153 
154     /**
155      * Returns the class file version of the current release.
156      * @jvms 4.1 Table 4.1-A. class file format major versions
157      */
158     public static int classFileVersion() {
159         return classFileMajorVersion;
160     }
161 
162     /**
163      * Tests if the given version is a supported {@code class}
164      * file version.
165      *
166      * A {@code class} file depends on the preview features of Java SE {@code N}
167      * if the major version is {@code N} and the minor version is 65535.
168      * This method returns {@code true} if the given version is a supported
169      * {@code class} file version regardless of whether the preview features
170      * are enabled or not.
171      *
172      * @jvms 4.1 Table 4.1-A. class file format major versions
173      */
174     public static boolean isSupportedClassFileVersion(int major, int minor) {
175         if (major < 45 || major > classFileMajorVersion) return false;
176         // for major version is between 45 and 55 inclusive, the minor version may be any value
177         if (major < 56) return true;
178         // otherwise, the minor version must be 0 or 65535
179         return minor == 0 || minor == PREVIEW_MINOR_VERSION;
180     }
181 
182     /**
183      * Tests if the given version is a supported {@code class}
184      * file version for module descriptor.
185      *
186      * major.minor version >= 53.0
187      */
188     public static boolean isSupportedModuleDescriptorVersion(int major, int minor) {
189         if (major < 53 || major > classFileMajorVersion) return false;
190         // for major version is between 45 and 55 inclusive, the minor version may be any value
191         if (major < 56) return true;
192         // otherwise, the minor version must be 0 or 65535
193         // preview features do not apply to module-info.class but JVMS allows it
194         return minor == 0 || minor == PREVIEW_MINOR_VERSION;
195     }
196 
197     /**
198      * Returns true if the given class loader is the bootstrap class loader
199      * or the platform class loader.
200      */
201     public static boolean isSystemDomainLoader(ClassLoader loader) {
202         return loader == null || loader == ClassLoader.getPlatformClassLoader();
203     }
204 
205     /**
206      * Returns the system property of the specified key saved at
207      * system initialization time.  This method should only be used
208      * for the system properties that are not changed during runtime.
209      *
210      * Note that the saved system properties do not include
211      * the ones set by java.lang.VersionProps.init().
212      */
213     public static String getSavedProperty(String key) {
214         if (savedProps == null)
215             throw new IllegalStateException("Not yet initialized");
216 
217         return savedProps.get(key);
218     }
219 
220     /**
221      * Gets an unmodifiable view of the system properties saved at system
222      * initialization time. This method should only be used
223      * for the system properties that are not changed during runtime.
224      *
225      * Note that the saved system properties do not include
226      * the ones set by java.lang.VersionProps.init().
227      */
228     public static Map<String, String> getSavedProperties() {
229         if (savedProps == null)
230             throw new IllegalStateException("Not yet initialized");
231 
232         return Collections.unmodifiableMap(savedProps);
233     }
234 
235     private static Map<String, String> savedProps;
236 
237     // Save a private copy of the system properties and remove
238     // the system properties that are not intended for public access.
239     //
240     // This method can only be invoked during system initialization.
241     public static void saveProperties(Map<String, String> props) {
242         if (initLevel() != 0)
243             throw new IllegalStateException("Wrong init level");
244 
245         // only main thread is running at this time, so savedProps and
246         // its content will be correctly published to threads started later
247         if (savedProps == null) {
248             savedProps = props;
249         }
250 
251         // Set the maximum amount of direct memory.  This value is controlled
252         // by the vm option -XX:MaxDirectMemorySize=<size>.
253         // The maximum amount of allocatable direct buffer memory (in bytes)
254         // from the system property sun.nio.MaxDirectMemorySize set by the VM.
255         // If not set or set to -1, the max memory will be used
256         // The system property will be removed.
257         String s = props.get("sun.nio.MaxDirectMemorySize");
258         if (s == null || s.isEmpty() || s.equals("-1")) {
259             // -XX:MaxDirectMemorySize not given, take default
260             directMemory = Runtime.getRuntime().maxMemory();
261         } else {
262             long l = Long.parseLong(s);
263             if (l > -1)
264                 directMemory = l;
265         }
266 
267         // Check if direct buffers should be page aligned
268         s = props.get("sun.nio.PageAlignDirectMemory");
269         if ("true".equals(s))
270             pageAlignDirectMemory = true;
271 
272         s = props.get("java.class.version");
273         int index = s.indexOf('.');
274         try {
275             classFileMajorVersion = Integer.parseInt(s.substring(0, index));
276             classFileMinorVersion = Integer.parseInt(s.substring(index + 1));
277         } catch (NumberFormatException e) {
278             throw new InternalError(e);
279         }
280     }
281 
282     // Initialize any miscellaneous operating system settings that need to be
283     // set for the class libraries.
284     //
285     public static void initializeOSEnvironment() {
286         if (initLevel() == 0) {
287             OSEnvironment.initialize();
288         }
289     }
290 
291     /* Current count of objects pending for finalization */
292     private static volatile int finalRefCount;
293 
294     /* Peak count of objects pending for finalization */
295     private static volatile int peakFinalRefCount;
296 
297     /*
298      * Gets the number of objects pending for finalization.
299      *
300      * @return the number of objects pending for finalization.
301      */
302     public static int getFinalRefCount() {
303         return finalRefCount;
304     }
305 
306     /*
307      * Gets the peak number of objects pending for finalization.
308      *
309      * @return the peak number of objects pending for finalization.
310      */
311     public static int getPeakFinalRefCount() {
312         return peakFinalRefCount;
313     }
314 
315     /*
316      * Add {@code n} to the objects pending for finalization count.
317      *
318      * @param n an integer value to be added to the objects pending
319      * for finalization count
320      */
321     public static void addFinalRefCount(int n) {
322         // The caller must hold lock to synchronize the update.
323 
324         finalRefCount += n;
325         if (finalRefCount > peakFinalRefCount) {
326             peakFinalRefCount = finalRefCount;
327         }
328     }
329 
330     /**
331      * Returns Thread.State for the given threadStatus
332      */
333     public static Thread.State toThreadState(int threadStatus) {
334         if ((threadStatus & JVMTI_THREAD_STATE_RUNNABLE) != 0) {
335             return RUNNABLE;
336         } else if ((threadStatus & JVMTI_THREAD_STATE_BLOCKED_ON_MONITOR_ENTER) != 0) {
337             return BLOCKED;
338         } else if ((threadStatus & JVMTI_THREAD_STATE_WAITING_INDEFINITELY) != 0) {
339             return WAITING;
340         } else if ((threadStatus & JVMTI_THREAD_STATE_WAITING_WITH_TIMEOUT) != 0) {
341             return TIMED_WAITING;
342         } else if ((threadStatus & JVMTI_THREAD_STATE_TERMINATED) != 0) {
343             return TERMINATED;
344         } else if ((threadStatus & JVMTI_THREAD_STATE_ALIVE) == 0) {
345             return NEW;
346         } else {
347             return RUNNABLE;
348         }
349     }
350 
351     /* The threadStatus field is set by the VM at state transition
352      * in the hotspot implementation. Its value is set according to
353      * the JVM TI specification GetThreadState function.
354      */
355     private static final int JVMTI_THREAD_STATE_ALIVE = 0x0001;
356     private static final int JVMTI_THREAD_STATE_TERMINATED = 0x0002;
357     private static final int JVMTI_THREAD_STATE_RUNNABLE = 0x0004;
358     private static final int JVMTI_THREAD_STATE_BLOCKED_ON_MONITOR_ENTER = 0x0400;
359     private static final int JVMTI_THREAD_STATE_WAITING_INDEFINITELY = 0x0010;
360     private static final int JVMTI_THREAD_STATE_WAITING_WITH_TIMEOUT = 0x0020;
361 
362     /*
363      * Returns the first user-defined class loader up the execution stack,
364      * or the platform class loader if only code from the platform or
365      * bootstrap class loader is on the stack.
366      */
367     public static ClassLoader latestUserDefinedLoader() {
368         ClassLoader loader = latestUserDefinedLoader0();
369         return loader != null ? loader : ClassLoader.getPlatformClassLoader();
370     }
371 
372     /*
373      * Returns the first user-defined class loader up the execution stack,
374      * or null if only code from the platform or bootstrap class loader is
375      * on the stack.  VM does not keep a reference of platform loader and so
376      * it returns null.
377      *
378      * This method should be replaced with StackWalker::walk and then we can
379      * remove the logic in the VM.
380      */
381     private static native ClassLoader latestUserDefinedLoader0();
382 
383     /**
384      * Returns {@code true} if we are in a set UID program.
385      */
386     public static boolean isSetUID() {
387         long uid = getuid();
388         long euid = geteuid();
389         long gid = getgid();
390         long egid = getegid();
391         return uid != euid  || gid != egid;
392     }
393 
394     /**
395      * Returns the real user ID of the calling process,
396      * or -1 if the value is not available.
397      */
398     public static native long getuid();
399 
400     /**
401      * Returns the effective user ID of the calling process,
402      * or -1 if the value is not available.
403      */
404     public static native long geteuid();
405 
406     /**
407      * Returns the real group ID of the calling process,
408      * or -1 if the value is not available.
409      */
410     public static native long getgid();
411 
412     /**
413      * Returns the effective group ID of the calling process,
414      * or -1 if the value is not available.
415      */
416     public static native long getegid();
417 
418     /**
419      * Get a nanosecond time stamp adjustment in the form of a single long.
420      *
421      * This value can be used to create an instant using
422      * {@link java.time.Instant#ofEpochSecond(long, long)
423      *  java.time.Instant.ofEpochSecond(offsetInSeconds,
424      *  getNanoTimeAdjustment(offsetInSeconds))}.
425      * <p>
426      * The value returned has the best resolution available to the JVM on
427      * the current system.
428      * This is usually down to microseconds - or tenth of microseconds -
429      * depending on the OS/Hardware and the JVM implementation.
430      *
431      * @param offsetInSeconds The offset in seconds from which the nanosecond
432      *        time stamp should be computed.
433      *
434      * @apiNote The offset should be recent enough - so that
435      *         {@code offsetInSeconds} is within {@code +/- 2^32} seconds of the
436      *         current UTC time. If the offset is too far off, {@code -1} will be
437      *         returned. As such, {@code -1} must not be considered as a valid
438      *         nano time adjustment, but as an exception value indicating
439      *         that an offset closer to the current time should be used.
440      *
441      * @return A nanosecond time stamp adjustment in the form of a single long.
442      *     If the offset is too far off the current time, this method returns -1.
443      *     In that case, the caller should call this method again, passing a
444      *     more accurate offset.
445      */
446     public static native long getNanoTimeAdjustment(long offsetInSeconds);
447 
448     /**
449      * Returns the VM arguments for this runtime environment.
450      *
451      * @implNote
452      * The HotSpot JVM processes the input arguments from multiple sources
453      * in the following order:
454      * 1. JAVA_TOOL_OPTIONS environment variable
455      * 2. Options from JNI Invocation API
456      * 3. _JAVA_OPTIONS environment variable
457      *
458      * If VM options file is specified via -XX:VMOptionsFile, the vm options
459      * file is read and expanded in place of -XX:VMOptionFile option.
460      */
461     public static native String[] getRuntimeArguments();
462 
463     static {
464         initialize();
465     }
466     private static native void initialize();
467 
468     /**
469      * Provides access to information on buffer usage.
470      */
471     public interface BufferPool {
472         String getName();
473         long getCount();
474         long getTotalCapacity();
475         long getMemoryUsed();
476     }
477 
478     private static class BufferPoolsHolder {
479         static final List<BufferPool> BUFFER_POOLS;
480 
481         static {
482             ArrayList<BufferPool> bufferPools = new ArrayList<>(3);
483             bufferPools.add(SharedSecrets.getJavaNioAccess().getDirectBufferPool());
484             bufferPools.add(FileChannelImpl.getMappedBufferPool());
485             bufferPools.add(FileChannelImpl.getSyncMappedBufferPool());
486 
487             BUFFER_POOLS = Collections.unmodifiableList(bufferPools);
488         }
489     }
490 
491     /**
492      * @return the list of buffer pools.
493      */
494     public static List<BufferPool> getBufferPools() {
495         return BufferPoolsHolder.BUFFER_POOLS;
496     }
497 }