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