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