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 
  26 package jdk.internal.misc;
  27 
  28 import static java.lang.Thread.State.*;
  29 import java.util.Map;
  30 import java.util.HashMap;
  31 import java.util.Properties;
  32 import java.util.Collections;
  33 
  34 public 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 in the system domain
 128      * in which all permissions are granted.
 129      */
 130     public static boolean isSystemDomainLoader(ClassLoader loader) {
 131         return loader == null;
 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      * It accesses a private copy of the system properties so
 139      * that user's locking of the system properties object will not
 140      * cause the library to deadlock.
 141      *
 142      * Note that the saved system properties do not include
 143      * the ones set by java.lang.VersionProps.init().
 144      *
 145      */
 146     public static String getSavedProperty(String key) {
 147         if (savedProps == null)
 148             throw new IllegalStateException("Not yet initialized");
 149 
 150         return savedProps.get(key);
 151     }
 152 
 153     /**
 154      * Gets an unmodifiable view of the system properties saved at system
 155      * initialization time. This method should only be used
 156      * for the system properties that are not changed during runtime.
 157      *
 158      * Note that the saved system properties do not include
 159      * the ones set by java.lang.VersionProps.init().
 160      */
 161     public static Map<String, String> getSavedProperties() {
 162         if (savedProps == null)
 163             throw new IllegalStateException("Not yet initialized");
 164 
 165         return savedProps;
 166     }
 167 
 168     // TODO: the Property Management needs to be refactored and
 169     // the appropriate prop keys need to be accessible to the
 170     // calling classes to avoid duplication of keys.
 171     private static Map<String, String> savedProps;
 172 
 173     // Save a private copy of the system properties and remove
 174     // the system properties that are not intended for public access.
 175     //
 176     // This method can only be invoked during system initialization.
 177     public static void saveAndRemoveProperties(Properties props) {
 178         if (initLevel() != 0)
 179             throw new IllegalStateException("Wrong init level");
 180 
 181         @SuppressWarnings("unchecked")
 182         Map<String, String> sp = new HashMap<>((Map)props);
 183         // only main thread is running at this time, so savedProps and
 184         // its content will be correctly published to threads started later
 185         savedProps = Collections.unmodifiableMap(sp);
 186 
 187         // Set the maximum amount of direct memory.  This value is controlled
 188         // by the vm option -XX:MaxDirectMemorySize=<size>.
 189         // The maximum amount of allocatable direct buffer memory (in bytes)
 190         // from the system property sun.nio.MaxDirectMemorySize set by the VM.
 191         // The system property will be removed.
 192         String s = (String)props.remove("sun.nio.MaxDirectMemorySize");
 193         if (s != null) {
 194             if (s.equals("-1")) {
 195                 // -XX:MaxDirectMemorySize not given, take default
 196                 directMemory = Runtime.getRuntime().maxMemory();
 197             } else {
 198                 long l = Long.parseLong(s);
 199                 if (l > -1)
 200                     directMemory = l;
 201             }
 202         }
 203 
 204         // Check if direct buffers should be page aligned
 205         s = (String)props.remove("sun.nio.PageAlignDirectMemory");
 206         if ("true".equals(s))
 207             pageAlignDirectMemory = true;
 208 
 209         // Remove other private system properties
 210         // used by java.lang.Integer.IntegerCache
 211         props.remove("java.lang.Integer.IntegerCache.high");
 212 
 213         // used by sun.launcher.LauncherHelper
 214         props.remove("sun.java.launcher.diag");
 215 
 216         // used by jdk.internal.loader.ClassLoaders
 217         props.remove("jdk.boot.class.path.append");
 218     }
 219 
 220     // Initialize any miscellaneous operating system settings that need to be
 221     // set for the class libraries.
 222     //
 223     public static void initializeOSEnvironment() {
 224         if (initLevel() == 0) {
 225             OSEnvironment.initialize();
 226         }
 227     }
 228 
 229     /* Current count of objects pending for finalization */
 230     private static volatile int finalRefCount;
 231 
 232     /* Peak count of objects pending for finalization */
 233     private static volatile int peakFinalRefCount;
 234 
 235     /*
 236      * Gets the number of objects pending for finalization.
 237      *
 238      * @return the number of objects pending for finalization.
 239      */
 240     public static int getFinalRefCount() {
 241         return finalRefCount;
 242     }
 243 
 244     /*
 245      * Gets the peak number of objects pending for finalization.
 246      *
 247      * @return the peak number of objects pending for finalization.
 248      */
 249     public static int getPeakFinalRefCount() {
 250         return peakFinalRefCount;
 251     }
 252 
 253     /*
 254      * Add {@code n} to the objects pending for finalization count.
 255      *
 256      * @param n an integer value to be added to the objects pending
 257      * for finalization count
 258      */
 259     public static void addFinalRefCount(int n) {
 260         // The caller must hold lock to synchronize the update.
 261 
 262         finalRefCount += n;
 263         if (finalRefCount > peakFinalRefCount) {
 264             peakFinalRefCount = finalRefCount;
 265         }
 266     }
 267 
 268     /**
 269      * Returns Thread.State for the given threadStatus
 270      */
 271     public static Thread.State toThreadState(int threadStatus) {
 272         if ((threadStatus & JVMTI_THREAD_STATE_RUNNABLE) != 0) {
 273             return RUNNABLE;
 274         } else if ((threadStatus & JVMTI_THREAD_STATE_BLOCKED_ON_MONITOR_ENTER) != 0) {
 275             return BLOCKED;
 276         } else if ((threadStatus & JVMTI_THREAD_STATE_WAITING_INDEFINITELY) != 0) {
 277             return WAITING;
 278         } else if ((threadStatus & JVMTI_THREAD_STATE_WAITING_WITH_TIMEOUT) != 0) {
 279             return TIMED_WAITING;
 280         } else if ((threadStatus & JVMTI_THREAD_STATE_TERMINATED) != 0) {
 281             return TERMINATED;
 282         } else if ((threadStatus & JVMTI_THREAD_STATE_ALIVE) == 0) {
 283             return NEW;
 284         } else {
 285             return RUNNABLE;
 286         }
 287     }
 288 
 289     /* The threadStatus field is set by the VM at state transition
 290      * in the hotspot implementation. Its value is set according to
 291      * the JVM TI specification GetThreadState function.
 292      */
 293     private static final int JVMTI_THREAD_STATE_ALIVE = 0x0001;
 294     private static final int JVMTI_THREAD_STATE_TERMINATED = 0x0002;
 295     private static final int JVMTI_THREAD_STATE_RUNNABLE = 0x0004;
 296     private static final int JVMTI_THREAD_STATE_BLOCKED_ON_MONITOR_ENTER = 0x0400;
 297     private static final int JVMTI_THREAD_STATE_WAITING_INDEFINITELY = 0x0010;
 298     private static final int JVMTI_THREAD_STATE_WAITING_WITH_TIMEOUT = 0x0020;
 299 
 300     /*
 301      * Returns the first user-defined class loader up the execution stack,
 302      * or the platform class loader if only code from the platform or
 303      * bootstrap class loader is on the stack.
 304      */
 305     public static ClassLoader latestUserDefinedLoader() {
 306         ClassLoader loader = latestUserDefinedLoader0();
 307         return loader != null ? loader : ClassLoader.getPlatformClassLoader();
 308     }
 309 
 310     /*
 311      * Returns the first user-defined class loader up the execution stack,
 312      * or null if only code from the platform or bootstrap class loader is
 313      * on the stack.  VM does not keep a reference of platform loader and so
 314      * it returns null.
 315      *
 316      * This method should be replaced with StackWalker::walk and then we can
 317      * remove the logic in the VM.
 318      */
 319     private static native ClassLoader latestUserDefinedLoader0();
 320 
 321     /**
 322      * Returns {@code true} if we are in a set UID program.
 323      */
 324     public static boolean isSetUID() {
 325         long uid = getuid();
 326         long euid = geteuid();
 327         long gid = getgid();
 328         long egid = getegid();
 329         return uid != euid  || gid != egid;
 330     }
 331 
 332     /**
 333      * Returns the real user ID of the calling process,
 334      * or -1 if the value is not available.
 335      */
 336     public static native long getuid();
 337 
 338     /**
 339      * Returns the effective user ID of the calling process,
 340      * or -1 if the value is not available.
 341      */
 342     public static native long geteuid();
 343 
 344     /**
 345      * Returns the real group ID of the calling process,
 346      * or -1 if the value is not available.
 347      */
 348     public static native long getgid();
 349 
 350     /**
 351      * Returns the effective group ID of the calling process,
 352      * or -1 if the value is not available.
 353      */
 354     public static native long getegid();
 355 
 356     /**
 357      * Get a nanosecond time stamp adjustment in the form of a single long.
 358      *
 359      * This value can be used to create an instant using
 360      * {@link java.time.Instant#ofEpochSecond(long, long)
 361      *  java.time.Instant.ofEpochSecond(offsetInSeconds,
 362      *  getNanoTimeAdjustment(offsetInSeconds))}.
 363      * <p>
 364      * The value returned has the best resolution available to the JVM on
 365      * the current system.
 366      * This is usually down to microseconds - or tenth of microseconds -
 367      * depending on the OS/Hardware and the JVM implementation.
 368      *
 369      * @param offsetInSeconds The offset in seconds from which the nanosecond
 370      *        time stamp should be computed.
 371      *
 372      * @apiNote The offset should be recent enough - so that
 373      *         {@code offsetInSeconds} is within {@code +/- 2^32} seconds of the
 374      *         current UTC time. If the offset is too far off, {@code -1} will be
 375      *         returned. As such, {@code -1} must not be considered as a valid
 376      *         nano time adjustment, but as an exception value indicating
 377      *         that an offset closer to the current time should be used.
 378      *
 379      * @return A nanosecond time stamp adjustment in the form of a single long.
 380      *     If the offset is too far off the current time, this method returns -1.
 381      *     In that case, the caller should call this method again, passing a
 382      *     more accurate offset.
 383      */
 384     public static native long getNanoTimeAdjustment(long offsetInSeconds);
 385 
 386     /**
 387      * Returns the VM arguments for this runtime environment.
 388      *
 389      * @implNote
 390      * The HotSpot JVM processes the input arguments from multiple sources
 391      * in the following order:
 392      * 1. JAVA_TOOL_OPTIONS environment variable
 393      * 2. Options from JNI Invocation API
 394      * 3. _JAVA_OPTIONS environment variable
 395      *
 396      * If VM options file is specified via -XX:VMOptionsFile, the vm options
 397      * file is read and expanded in place of -XX:VMOptionFile option.
 398      */
 399     public static native String[] getRuntimeArguments();
 400 
 401     static {
 402         initialize();
 403     }
 404     private static native void initialize();
 405 }