1/*
2 * Copyright (c) 1996, 2016, 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
26package jdk.internal.misc;
27
28import static java.lang.Thread.State.*;
29import java.util.Map;
30import java.util.HashMap;
31import java.util.Properties;
32import java.util.Collections;
33
34public class VM {
35
36    // the init level when the VM is fully initialized
37    private static final int JAVA_LANG_SYSTEM_INITED     = 1;
38    private static final int MODULE_SYSTEM_INITED        = 2;
39    private static final int SYSTEM_LOADER_INITIALIZING  = 3;
40    private static final int SYSTEM_BOOTED               = 4;
41
42    // 0, 1, 2, ...
43    private static volatile int initLevel;
44    private static final Object lock = new Object();
45
46    /**
47     * Sets the init level.
48     *
49     * @see java.lang.System#initPhase1
50     * @see java.lang.System#initPhase2
51     * @see java.lang.System#initPhase3
52     */
53    public static void initLevel(int value) {
54        synchronized (lock) {
55            if (value <= initLevel || value > SYSTEM_BOOTED)
56                throw new InternalError("Bad level: " + value);
57            initLevel = value;
58            lock.notifyAll();
59        }
60    }
61
62    /**
63     * Returns the current init level.
64     */
65    public static int initLevel() {
66        return initLevel;
67    }
68
69    /**
70     * Waits for the init level to get the given value.
71     *
72     * @see java.lang.ref.Finalizer
73     */
74    public static void awaitInitLevel(int value) throws InterruptedException {
75        synchronized (lock) {
76            while (initLevel < value) {
77                lock.wait();
78            }
79        }
80    }
81
82    /**
83     * Returns {@code true} if the module system has been initialized.
84     * @see java.lang.System#initPhase2
85     */
86    public static boolean isModuleSystemInited() {
87        return VM.initLevel() >= MODULE_SYSTEM_INITED;
88    }
89
90    /**
91     * Returns {@code true} if the VM is fully initialized.
92     */
93    public static boolean isBooted() {
94        return initLevel >= SYSTEM_BOOTED;
95    }
96
97    // A user-settable upper limit on the maximum amount of allocatable direct
98    // buffer memory.  This value may be changed during VM initialization if
99    // "java" is launched with "-XX:MaxDirectMemorySize=<size>".
100    //
101    // The initial value of this field is arbitrary; during JRE initialization
102    // it will be reset to the value specified on the command line, if any,
103    // otherwise to Runtime.getRuntime().maxMemory().
104    //
105    private static long directMemory = 64 * 1024 * 1024;
106
107    // Returns the maximum amount of allocatable direct buffer memory.
108    // The directMemory variable is initialized during system initialization
109    // in the saveAndRemoveProperties method.
110    //
111    public static long maxDirectMemory() {
112        return directMemory;
113    }
114
115    // User-controllable flag that determines if direct buffers should be page
116    // aligned. The "-XX:+PageAlignDirectMemory" option can be used to force
117    // buffers, allocated by ByteBuffer.allocateDirect, to be page aligned.
118    private static boolean pageAlignDirectMemory;
119
120    // Returns {@code true} if the direct buffers should be page aligned. This
121    // variable is initialized by saveAndRemoveProperties.
122    public static boolean isDirectMemoryPageAligned() {
123        return pageAlignDirectMemory;
124    }
125
126    /**
127     * Returns true if the given class loader is the bootstrap class loader
128     * or the platform class loader.
129     */
130    public static boolean isSystemDomainLoader(ClassLoader loader) {
131        return loader == null || loader == ClassLoader.getPlatformClassLoader();
132    }
133
134    /**
135     * Returns the system property of the specified key saved at
136     * system initialization time.  This method should only be used
137     * for the system properties that are not changed during runtime.
138     *
139     * Note that the saved system properties do not include
140     * the ones set by java.lang.VersionProps.init().
141     */
142    public static String getSavedProperty(String key) {
143        if (savedProps == null)
144            throw new IllegalStateException("Not yet initialized");
145
146        return savedProps.get(key);
147    }
148
149    /**
150     * Gets an unmodifiable view of the system properties saved at system
151     * initialization time. This method should only be used
152     * for the system properties that are not changed during runtime.
153     *
154     * Note that the saved system properties do not include
155     * the ones set by java.lang.VersionProps.init().
156     */
157    public static Map<String, String> getSavedProperties() {
158        if (savedProps == null)
159            throw new IllegalStateException("Not yet initialized");
160
161        return savedProps;
162    }
163
164    private static Map<String, String> savedProps;
165
166    // Save a private copy of the system properties and remove
167    // the system properties that are not intended for public access.
168    //
169    // This method can only be invoked during system initialization.
170    public static void saveAndRemoveProperties(Properties props) {
171        if (initLevel() != 0)
172            throw new IllegalStateException("Wrong init level");
173
174        @SuppressWarnings({"rawtypes", "unchecked"})
175        Map<String, String> sp =
176            Map.ofEntries(props.entrySet().toArray(new Map.Entry[0]));
177        // only main thread is running at this time, so savedProps and
178        // its content will be correctly published to threads started later
179        savedProps = sp;
180
181        // Set the maximum amount of direct memory.  This value is controlled
182        // by the vm option -XX:MaxDirectMemorySize=<size>.
183        // The maximum amount of allocatable direct buffer memory (in bytes)
184        // from the system property sun.nio.MaxDirectMemorySize set by the VM.
185        // The system property will be removed.
186        String s = (String)props.remove("sun.nio.MaxDirectMemorySize");
187        if (s != null) {
188            if (s.equals("-1")) {
189                // -XX:MaxDirectMemorySize not given, take default
190                directMemory = Runtime.getRuntime().maxMemory();
191            } else {
192                long l = Long.parseLong(s);
193                if (l > -1)
194                    directMemory = l;
195            }
196        }
197
198        // Check if direct buffers should be page aligned
199        s = (String)props.remove("sun.nio.PageAlignDirectMemory");
200        if ("true".equals(s))
201            pageAlignDirectMemory = true;
202
203        // Remove other private system properties
204        // used by java.lang.Integer.IntegerCache
205        props.remove("java.lang.Integer.IntegerCache.high");
206
207        // used by sun.launcher.LauncherHelper
208        props.remove("sun.java.launcher.diag");
209
210        // used by jdk.internal.loader.ClassLoaders
211        props.remove("jdk.boot.class.path.append");
212    }
213
214    // Initialize any miscellaneous operating system settings that need to be
215    // set for the class libraries.
216    //
217    public static void initializeOSEnvironment() {
218        if (initLevel() == 0) {
219            OSEnvironment.initialize();
220        }
221    }
222
223    /* Current count of objects pending for finalization */
224    private static volatile int finalRefCount;
225
226    /* Peak count of objects pending for finalization */
227    private static volatile int peakFinalRefCount;
228
229    /*
230     * Gets the number of objects pending for finalization.
231     *
232     * @return the number of objects pending for finalization.
233     */
234    public static int getFinalRefCount() {
235        return finalRefCount;
236    }
237
238    /*
239     * Gets the peak number of objects pending for finalization.
240     *
241     * @return the peak number of objects pending for finalization.
242     */
243    public static int getPeakFinalRefCount() {
244        return peakFinalRefCount;
245    }
246
247    /*
248     * Add {@code n} to the objects pending for finalization count.
249     *
250     * @param n an integer value to be added to the objects pending
251     * for finalization count
252     */
253    public static void addFinalRefCount(int n) {
254        // The caller must hold lock to synchronize the update.
255
256        finalRefCount += n;
257        if (finalRefCount > peakFinalRefCount) {
258            peakFinalRefCount = finalRefCount;
259        }
260    }
261
262    /**
263     * Returns Thread.State for the given threadStatus
264     */
265    public static Thread.State toThreadState(int threadStatus) {
266        if ((threadStatus & JVMTI_THREAD_STATE_RUNNABLE) != 0) {
267            return RUNNABLE;
268        } else if ((threadStatus & JVMTI_THREAD_STATE_BLOCKED_ON_MONITOR_ENTER) != 0) {
269            return BLOCKED;
270        } else if ((threadStatus & JVMTI_THREAD_STATE_WAITING_INDEFINITELY) != 0) {
271            return WAITING;
272        } else if ((threadStatus & JVMTI_THREAD_STATE_WAITING_WITH_TIMEOUT) != 0) {
273            return TIMED_WAITING;
274        } else if ((threadStatus & JVMTI_THREAD_STATE_TERMINATED) != 0) {
275            return TERMINATED;
276        } else if ((threadStatus & JVMTI_THREAD_STATE_ALIVE) == 0) {
277            return NEW;
278        } else {
279            return RUNNABLE;
280        }
281    }
282
283    /* The threadStatus field is set by the VM at state transition
284     * in the hotspot implementation. Its value is set according to
285     * the JVM TI specification GetThreadState function.
286     */
287    private static final int JVMTI_THREAD_STATE_ALIVE = 0x0001;
288    private static final int JVMTI_THREAD_STATE_TERMINATED = 0x0002;
289    private static final int JVMTI_THREAD_STATE_RUNNABLE = 0x0004;
290    private static final int JVMTI_THREAD_STATE_BLOCKED_ON_MONITOR_ENTER = 0x0400;
291    private static final int JVMTI_THREAD_STATE_WAITING_INDEFINITELY = 0x0010;
292    private static final int JVMTI_THREAD_STATE_WAITING_WITH_TIMEOUT = 0x0020;
293
294    /*
295     * Returns the first user-defined class loader up the execution stack,
296     * or the platform class loader if only code from the platform or
297     * bootstrap class loader is on the stack.
298     */
299    public static ClassLoader latestUserDefinedLoader() {
300        ClassLoader loader = latestUserDefinedLoader0();
301        return loader != null ? loader : ClassLoader.getPlatformClassLoader();
302    }
303
304    /*
305     * Returns the first user-defined class loader up the execution stack,
306     * or null if only code from the platform or bootstrap class loader is
307     * on the stack.  VM does not keep a reference of platform loader and so
308     * it returns null.
309     *
310     * This method should be replaced with StackWalker::walk and then we can
311     * remove the logic in the VM.
312     */
313    private static native ClassLoader latestUserDefinedLoader0();
314
315    /**
316     * Returns {@code true} if we are in a set UID program.
317     */
318    public static boolean isSetUID() {
319        long uid = getuid();
320        long euid = geteuid();
321        long gid = getgid();
322        long egid = getegid();
323        return uid != euid  || gid != egid;
324    }
325
326    /**
327     * Returns the real user ID of the calling process,
328     * or -1 if the value is not available.
329     */
330    public static native long getuid();
331
332    /**
333     * Returns the effective user ID of the calling process,
334     * or -1 if the value is not available.
335     */
336    public static native long geteuid();
337
338    /**
339     * Returns the real group ID of the calling process,
340     * or -1 if the value is not available.
341     */
342    public static native long getgid();
343
344    /**
345     * Returns the effective group ID of the calling process,
346     * or -1 if the value is not available.
347     */
348    public static native long getegid();
349
350    /**
351     * Get a nanosecond time stamp adjustment in the form of a single long.
352     *
353     * This value can be used to create an instant using
354     * {@link java.time.Instant#ofEpochSecond(long, long)
355     *  java.time.Instant.ofEpochSecond(offsetInSeconds,
356     *  getNanoTimeAdjustment(offsetInSeconds))}.
357     * <p>
358     * The value returned has the best resolution available to the JVM on
359     * the current system.
360     * This is usually down to microseconds - or tenth of microseconds -
361     * depending on the OS/Hardware and the JVM implementation.
362     *
363     * @param offsetInSeconds The offset in seconds from which the nanosecond
364     *        time stamp should be computed.
365     *
366     * @apiNote The offset should be recent enough - so that
367     *         {@code offsetInSeconds} is within {@code +/- 2^32} seconds of the
368     *         current UTC time. If the offset is too far off, {@code -1} will be
369     *         returned. As such, {@code -1} must not be considered as a valid
370     *         nano time adjustment, but as an exception value indicating
371     *         that an offset closer to the current time should be used.
372     *
373     * @return A nanosecond time stamp adjustment in the form of a single long.
374     *     If the offset is too far off the current time, this method returns -1.
375     *     In that case, the caller should call this method again, passing a
376     *     more accurate offset.
377     */
378    public static native long getNanoTimeAdjustment(long offsetInSeconds);
379
380    /**
381     * Returns the VM arguments for this runtime environment.
382     *
383     * @implNote
384     * The HotSpot JVM processes the input arguments from multiple sources
385     * in the following order:
386     * 1. JAVA_TOOL_OPTIONS environment variable
387     * 2. Options from JNI Invocation API
388     * 3. _JAVA_OPTIONS environment variable
389     *
390     * If VM options file is specified via -XX:VMOptionsFile, the vm options
391     * file is read and expanded in place of -XX:VMOptionFile option.
392     */
393    public static native String[] getRuntimeArguments();
394
395    static {
396        initialize();
397    }
398    private static native void initialize();
399}
400