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