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