1 /* 2 * Copyright (c) 1994, 2017, 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 package java.lang; 26 27 import java.io.BufferedInputStream; 28 import java.io.BufferedOutputStream; 29 import java.io.Console; 30 import java.io.FileDescriptor; 31 import java.io.FileInputStream; 32 import java.io.FileOutputStream; 33 import java.io.IOException; 34 import java.io.InputStream; 35 import java.io.PrintStream; 36 import java.io.UnsupportedEncodingException; 37 import java.lang.annotation.Annotation; 38 import java.lang.reflect.Constructor; 39 import java.lang.reflect.Executable; 40 import java.lang.reflect.Layer; 41 import java.lang.reflect.Method; 42 import java.lang.reflect.Modifier; 43 import java.lang.reflect.Module; 44 import java.net.URL; 45 import java.security.AccessControlContext; 46 import java.util.Properties; 47 import java.util.PropertyPermission; 48 import java.util.Map; 49 import java.security.AccessController; 50 import java.security.PrivilegedAction; 51 import java.nio.channels.Channel; 52 import java.nio.channels.spi.SelectorProvider; 53 import java.util.concurrent.ConcurrentHashMap; 54 import java.util.stream.Stream; 55 56 import java.util.Objects; 57 import java.util.ResourceBundle; 58 import java.util.function.Supplier; 59 import sun.nio.ch.Interruptible; 60 import jdk.internal.reflect.CallerSensitive; 61 import jdk.internal.reflect.Reflection; 62 import sun.security.util.SecurityConstants; 63 import sun.reflect.annotation.AnnotationType; 64 import jdk.internal.HotSpotIntrinsicCandidate; 65 import jdk.internal.misc.JavaLangAccess;; 66 import jdk.internal.misc.SharedSecrets;; 67 import jdk.internal.misc.VM; 68 import jdk.internal.logger.LoggerFinderLoader; 69 import jdk.internal.logger.LazyLoggers; 70 import jdk.internal.logger.LocalizedLoggerWrapper; 71 72 import jdk.internal.module.ModuleBootstrap; 73 74 /** 75 * The <code>System</code> class contains several useful class fields 76 * and methods. It cannot be instantiated. 77 * 78 * <p>Among the facilities provided by the <code>System</code> class 79 * are standard input, standard output, and error output streams; 80 * access to externally defined properties and environment 81 * variables; a means of loading files and libraries; and a utility 82 * method for quickly copying a portion of an array. 83 * 84 * @author unascribed 85 * @since 1.0 86 */ 87 public final class System { 88 /* register the natives via the static initializer. 89 * 90 * VM will invoke the initializeSystemClass method to complete 91 * the initialization for this class separated from clinit. 92 * Note that to use properties set by the VM, see the constraints 93 * described in the initializeSystemClass method. 94 */ 95 private static native void registerNatives(); 96 static { 97 registerNatives(); 98 } 99 100 /** Don't let anyone instantiate this class */ 101 private System() { 102 } 103 104 /** 105 * The "standard" input stream. This stream is already 106 * open and ready to supply input data. Typically this stream 107 * corresponds to keyboard input or another input source specified by 108 * the host environment or user. 109 */ 110 public static final InputStream in = null; 111 112 /** 113 * The "standard" output stream. This stream is already 114 * open and ready to accept output data. Typically this stream 115 * corresponds to display output or another output destination 116 * specified by the host environment or user. 117 * <p> 118 * For simple stand-alone Java applications, a typical way to write 119 * a line of output data is: 120 * <blockquote><pre> 121 * System.out.println(data) 122 * </pre></blockquote> 123 * <p> 124 * See the <code>println</code> methods in class <code>PrintStream</code>. 125 * 126 * @see java.io.PrintStream#println() 127 * @see java.io.PrintStream#println(boolean) 128 * @see java.io.PrintStream#println(char) 129 * @see java.io.PrintStream#println(char[]) 130 * @see java.io.PrintStream#println(double) 131 * @see java.io.PrintStream#println(float) 132 * @see java.io.PrintStream#println(int) 133 * @see java.io.PrintStream#println(long) 134 * @see java.io.PrintStream#println(java.lang.Object) 135 * @see java.io.PrintStream#println(java.lang.String) 136 */ 137 public static final PrintStream out = null; 138 139 /** 140 * The "standard" error output stream. This stream is already 141 * open and ready to accept output data. 142 * <p> 143 * Typically this stream corresponds to display output or another 144 * output destination specified by the host environment or user. By 145 * convention, this output stream is used to display error messages 146 * or other information that should come to the immediate attention 147 * of a user even if the principal output stream, the value of the 148 * variable <code>out</code>, has been redirected to a file or other 149 * destination that is typically not continuously monitored. 150 */ 151 public static final PrintStream err = null; 152 153 /* The security manager for the system. 154 */ 155 private static volatile SecurityManager security; 156 157 /** 158 * Reassigns the "standard" input stream. 159 * 160 * <p>First, if there is a security manager, its <code>checkPermission</code> 161 * method is called with a <code>RuntimePermission("setIO")</code> permission 162 * to see if it's ok to reassign the "standard" input stream. 163 * 164 * @param in the new standard input stream. 165 * 166 * @throws SecurityException 167 * if a security manager exists and its 168 * <code>checkPermission</code> method doesn't allow 169 * reassigning of the standard input stream. 170 * 171 * @see SecurityManager#checkPermission 172 * @see java.lang.RuntimePermission 173 * 174 * @since 1.1 175 */ 176 public static void setIn(InputStream in) { 177 checkIO(); 178 setIn0(in); 179 } 180 181 /** 182 * Reassigns the "standard" output stream. 183 * 184 * <p>First, if there is a security manager, its <code>checkPermission</code> 185 * method is called with a <code>RuntimePermission("setIO")</code> permission 186 * to see if it's ok to reassign the "standard" output stream. 187 * 188 * @param out the new standard output stream 189 * 190 * @throws SecurityException 191 * if a security manager exists and its 192 * <code>checkPermission</code> method doesn't allow 193 * reassigning of the standard output stream. 194 * 195 * @see SecurityManager#checkPermission 196 * @see java.lang.RuntimePermission 197 * 198 * @since 1.1 199 */ 200 public static void setOut(PrintStream out) { 201 checkIO(); 202 setOut0(out); 203 } 204 205 /** 206 * Reassigns the "standard" error output stream. 207 * 208 * <p>First, if there is a security manager, its <code>checkPermission</code> 209 * method is called with a <code>RuntimePermission("setIO")</code> permission 210 * to see if it's ok to reassign the "standard" error output stream. 211 * 212 * @param err the new standard error output stream. 213 * 214 * @throws SecurityException 215 * if a security manager exists and its 216 * <code>checkPermission</code> method doesn't allow 217 * reassigning of the standard error output stream. 218 * 219 * @see SecurityManager#checkPermission 220 * @see java.lang.RuntimePermission 221 * 222 * @since 1.1 223 */ 224 public static void setErr(PrintStream err) { 225 checkIO(); 226 setErr0(err); 227 } 228 229 private static volatile Console cons; 230 /** 231 * Returns the unique {@link java.io.Console Console} object associated 232 * with the current Java virtual machine, if any. 233 * 234 * @return The system console, if any, otherwise {@code null}. 235 * 236 * @since 1.6 237 */ 238 public static Console console() { 239 Console c; 240 if ((c = cons) == null) { 241 synchronized (System.class) { 242 if ((c = cons) == null) { 243 cons = c = SharedSecrets.getJavaIOAccess().console(); 244 } 245 } 246 } 247 return c; 248 } 249 250 /** 251 * Returns the channel inherited from the entity that created this 252 * Java virtual machine. 253 * 254 * <p> This method returns the channel obtained by invoking the 255 * {@link java.nio.channels.spi.SelectorProvider#inheritedChannel 256 * inheritedChannel} method of the system-wide default 257 * {@link java.nio.channels.spi.SelectorProvider} object. </p> 258 * 259 * <p> In addition to the network-oriented channels described in 260 * {@link java.nio.channels.spi.SelectorProvider#inheritedChannel 261 * inheritedChannel}, this method may return other kinds of 262 * channels in the future. 263 * 264 * @return The inherited channel, if any, otherwise {@code null}. 265 * 266 * @throws IOException 267 * If an I/O error occurs 268 * 269 * @throws SecurityException 270 * If a security manager is present and it does not 271 * permit access to the channel. 272 * 273 * @since 1.5 274 */ 275 public static Channel inheritedChannel() throws IOException { 276 return SelectorProvider.provider().inheritedChannel(); 277 } 278 279 private static void checkIO() { 280 SecurityManager sm = getSecurityManager(); 281 if (sm != null) { 282 sm.checkPermission(new RuntimePermission("setIO")); 283 } 284 } 285 286 private static native void setIn0(InputStream in); 287 private static native void setOut0(PrintStream out); 288 private static native void setErr0(PrintStream err); 289 290 /** 291 * Sets the System security. 292 * 293 * <p> If there is a security manager already installed, this method first 294 * calls the security manager's <code>checkPermission</code> method 295 * with a <code>RuntimePermission("setSecurityManager")</code> 296 * permission to ensure it's ok to replace the existing 297 * security manager. 298 * This may result in throwing a <code>SecurityException</code>. 299 * 300 * <p> Otherwise, the argument is established as the current 301 * security manager. If the argument is <code>null</code> and no 302 * security manager has been established, then no action is taken and 303 * the method simply returns. 304 * 305 * @param s the security manager. 306 * @exception SecurityException if the security manager has already 307 * been set and its <code>checkPermission</code> method 308 * doesn't allow it to be replaced. 309 * @see #getSecurityManager 310 * @see SecurityManager#checkPermission 311 * @see java.lang.RuntimePermission 312 */ 313 public static void setSecurityManager(final SecurityManager s) { 314 if (s != null) { 315 try { 316 s.checkPackageAccess("java.lang"); 317 } catch (Exception e) { 318 // no-op 319 } 320 } 321 setSecurityManager0(s); 322 } 323 324 private static synchronized 325 void setSecurityManager0(final SecurityManager s) { 326 SecurityManager sm = getSecurityManager(); 327 if (sm != null) { 328 // ask the currently installed security manager if we 329 // can replace it. 330 sm.checkPermission(new RuntimePermission 331 ("setSecurityManager")); 332 } 333 334 if ((s != null) && (s.getClass().getClassLoader() != null)) { 335 // New security manager class is not on bootstrap classpath. 336 // Cause policy to get initialized before we install the new 337 // security manager, in order to prevent infinite loops when 338 // trying to initialize the policy (which usually involves 339 // accessing some security and/or system properties, which in turn 340 // calls the installed security manager's checkPermission method 341 // which will loop infinitely if there is a non-system class 342 // (in this case: the new security manager class) on the stack). 343 AccessController.doPrivileged(new PrivilegedAction<>() { 344 public Object run() { 345 s.getClass().getProtectionDomain().implies 346 (SecurityConstants.ALL_PERMISSION); 347 return null; 348 } 349 }); 350 } 351 352 security = s; 353 } 354 355 /** 356 * Gets the system security interface. 357 * 358 * @return if a security manager has already been established for the 359 * current application, then that security manager is returned; 360 * otherwise, <code>null</code> is returned. 361 * @see #setSecurityManager 362 */ 363 public static SecurityManager getSecurityManager() { 364 return security; 365 } 366 367 /** 368 * Returns the current time in milliseconds. Note that 369 * while the unit of time of the return value is a millisecond, 370 * the granularity of the value depends on the underlying 371 * operating system and may be larger. For example, many 372 * operating systems measure time in units of tens of 373 * milliseconds. 374 * 375 * <p> See the description of the class <code>Date</code> for 376 * a discussion of slight discrepancies that may arise between 377 * "computer time" and coordinated universal time (UTC). 378 * 379 * @return the difference, measured in milliseconds, between 380 * the current time and midnight, January 1, 1970 UTC. 381 * @see java.util.Date 382 */ 383 @HotSpotIntrinsicCandidate 384 public static native long currentTimeMillis(); 385 386 /** 387 * Returns the current value of the running Java Virtual Machine's 388 * high-resolution time source, in nanoseconds. 389 * 390 * <p>This method can only be used to measure elapsed time and is 391 * not related to any other notion of system or wall-clock time. 392 * The value returned represents nanoseconds since some fixed but 393 * arbitrary <i>origin</i> time (perhaps in the future, so values 394 * may be negative). The same origin is used by all invocations of 395 * this method in an instance of a Java virtual machine; other 396 * virtual machine instances are likely to use a different origin. 397 * 398 * <p>This method provides nanosecond precision, but not necessarily 399 * nanosecond resolution (that is, how frequently the value changes) 400 * - no guarantees are made except that the resolution is at least as 401 * good as that of {@link #currentTimeMillis()}. 402 * 403 * <p>Differences in successive calls that span greater than 404 * approximately 292 years (2<sup>63</sup> nanoseconds) will not 405 * correctly compute elapsed time due to numerical overflow. 406 * 407 * <p>The values returned by this method become meaningful only when 408 * the difference between two such values, obtained within the same 409 * instance of a Java virtual machine, is computed. 410 * 411 * <p>For example, to measure how long some code takes to execute: 412 * <pre> {@code 413 * long startTime = System.nanoTime(); 414 * // ... the code being measured ... 415 * long elapsedNanos = System.nanoTime() - startTime;}</pre> 416 * 417 * <p>To compare elapsed time against a timeout, use <pre> {@code 418 * if (System.nanoTime() - startTime >= timeoutNanos) ...}</pre> 419 * instead of <pre> {@code 420 * if (System.nanoTime() >= startTime + timeoutNanos) ...}</pre> 421 * because of the possibility of numerical overflow. 422 * 423 * @return the current value of the running Java Virtual Machine's 424 * high-resolution time source, in nanoseconds 425 * @since 1.5 426 */ 427 @HotSpotIntrinsicCandidate 428 public static native long nanoTime(); 429 430 /** 431 * Copies an array from the specified source array, beginning at the 432 * specified position, to the specified position of the destination array. 433 * A subsequence of array components are copied from the source 434 * array referenced by <code>src</code> to the destination array 435 * referenced by <code>dest</code>. The number of components copied is 436 * equal to the <code>length</code> argument. The components at 437 * positions <code>srcPos</code> through 438 * <code>srcPos+length-1</code> in the source array are copied into 439 * positions <code>destPos</code> through 440 * <code>destPos+length-1</code>, respectively, of the destination 441 * array. 442 * <p> 443 * If the <code>src</code> and <code>dest</code> arguments refer to the 444 * same array object, then the copying is performed as if the 445 * components at positions <code>srcPos</code> through 446 * <code>srcPos+length-1</code> were first copied to a temporary 447 * array with <code>length</code> components and then the contents of 448 * the temporary array were copied into positions 449 * <code>destPos</code> through <code>destPos+length-1</code> of the 450 * destination array. 451 * <p> 452 * If <code>dest</code> is <code>null</code>, then a 453 * <code>NullPointerException</code> is thrown. 454 * <p> 455 * If <code>src</code> is <code>null</code>, then a 456 * <code>NullPointerException</code> is thrown and the destination 457 * array is not modified. 458 * <p> 459 * Otherwise, if any of the following is true, an 460 * <code>ArrayStoreException</code> is thrown and the destination is 461 * not modified: 462 * <ul> 463 * <li>The <code>src</code> argument refers to an object that is not an 464 * array. 465 * <li>The <code>dest</code> argument refers to an object that is not an 466 * array. 467 * <li>The <code>src</code> argument and <code>dest</code> argument refer 468 * to arrays whose component types are different primitive types. 469 * <li>The <code>src</code> argument refers to an array with a primitive 470 * component type and the <code>dest</code> argument refers to an array 471 * with a reference component type. 472 * <li>The <code>src</code> argument refers to an array with a reference 473 * component type and the <code>dest</code> argument refers to an array 474 * with a primitive component type. 475 * </ul> 476 * <p> 477 * Otherwise, if any of the following is true, an 478 * <code>IndexOutOfBoundsException</code> is 479 * thrown and the destination is not modified: 480 * <ul> 481 * <li>The <code>srcPos</code> argument is negative. 482 * <li>The <code>destPos</code> argument is negative. 483 * <li>The <code>length</code> argument is negative. 484 * <li><code>srcPos+length</code> is greater than 485 * <code>src.length</code>, the length of the source array. 486 * <li><code>destPos+length</code> is greater than 487 * <code>dest.length</code>, the length of the destination array. 488 * </ul> 489 * <p> 490 * Otherwise, if any actual component of the source array from 491 * position <code>srcPos</code> through 492 * <code>srcPos+length-1</code> cannot be converted to the component 493 * type of the destination array by assignment conversion, an 494 * <code>ArrayStoreException</code> is thrown. In this case, let 495 * <b><i>k</i></b> be the smallest nonnegative integer less than 496 * length such that <code>src[srcPos+</code><i>k</i><code>]</code> 497 * cannot be converted to the component type of the destination 498 * array; when the exception is thrown, source array components from 499 * positions <code>srcPos</code> through 500 * <code>srcPos+</code><i>k</i><code>-1</code> 501 * will already have been copied to destination array positions 502 * <code>destPos</code> through 503 * <code>destPos+</code><i>k</I><code>-1</code> and no other 504 * positions of the destination array will have been modified. 505 * (Because of the restrictions already itemized, this 506 * paragraph effectively applies only to the situation where both 507 * arrays have component types that are reference types.) 508 * 509 * @param src the source array. 510 * @param srcPos starting position in the source array. 511 * @param dest the destination array. 512 * @param destPos starting position in the destination data. 513 * @param length the number of array elements to be copied. 514 * @exception IndexOutOfBoundsException if copying would cause 515 * access of data outside array bounds. 516 * @exception ArrayStoreException if an element in the <code>src</code> 517 * array could not be stored into the <code>dest</code> array 518 * because of a type mismatch. 519 * @exception NullPointerException if either <code>src</code> or 520 * <code>dest</code> is <code>null</code>. 521 */ 522 @HotSpotIntrinsicCandidate 523 public static native void arraycopy(Object src, int srcPos, 524 Object dest, int destPos, 525 int length); 526 527 /** 528 * Returns the same hash code for the given object as 529 * would be returned by the default method hashCode(), 530 * whether or not the given object's class overrides 531 * hashCode(). 532 * The hash code for the null reference is zero. 533 * 534 * @param x object for which the hashCode is to be calculated 535 * @return the hashCode 536 * @since 1.1 537 */ 538 @HotSpotIntrinsicCandidate 539 public static native int identityHashCode(Object x); 540 541 /** 542 * System properties. The following properties are guaranteed to be defined: 543 * <dl> 544 * <dt>java.version <dd>Java version number 545 * <dt>java.vendor <dd>Java vendor specific string 546 * <dt>java.vendor.url <dd>Java vendor URL 547 * <dt>java.home <dd>Java installation directory 548 * <dt>java.class.version <dd>Java class version number 549 * <dt>java.class.path <dd>Java classpath 550 * <dt>os.name <dd>Operating System Name 551 * <dt>os.arch <dd>Operating System Architecture 552 * <dt>os.version <dd>Operating System Version 553 * <dt>file.separator <dd>File separator ("/" on Unix) 554 * <dt>path.separator <dd>Path separator (":" on Unix) 555 * <dt>line.separator <dd>Line separator ("\n" on Unix) 556 * <dt>user.name <dd>User account name 557 * <dt>user.home <dd>User home directory 558 * <dt>user.dir <dd>User's current working directory 559 * </dl> 560 */ 561 562 private static Properties props; 563 private static native Properties initProperties(Properties props); 564 565 /** 566 * Determines the current system properties. 567 * <p> 568 * First, if there is a security manager, its 569 * <code>checkPropertiesAccess</code> method is called with no 570 * arguments. This may result in a security exception. 571 * <p> 572 * The current set of system properties for use by the 573 * {@link #getProperty(String)} method is returned as a 574 * <code>Properties</code> object. If there is no current set of 575 * system properties, a set of system properties is first created and 576 * initialized. This set of system properties always includes values 577 * for the following keys: 578 * <table summary="Shows property keys and associated values"> 579 * <tr><th>Key</th> 580 * <th>Description of Associated Value</th></tr> 581 * <tr><td><code>java.version</code></td> 582 * <td>Java Runtime Environment version which may be interpreted 583 * as a {@link Runtime.Version}</td></tr> 584 * <tr><td><code>java.vendor</code></td> 585 * <td>Java Runtime Environment vendor</td></tr> 586 * <tr><td><code>java.vendor.url</code></td> 587 * <td>Java vendor URL</td></tr> 588 * <tr><td><code>java.home</code></td> 589 * <td>Java installation directory</td></tr> 590 * <tr><td><code>java.vm.specification.version</code></td> 591 * <td>Java Virtual Machine specification version which may be 592 * interpreted as a {@link Runtime.Version}</td></tr> 593 * <tr><td><code>java.vm.specification.vendor</code></td> 594 * <td>Java Virtual Machine specification vendor</td></tr> 595 * <tr><td><code>java.vm.specification.name</code></td> 596 * <td>Java Virtual Machine specification name</td></tr> 597 * <tr><td><code>java.vm.version</code></td> 598 * <td>Java Virtual Machine implementation version which may be 599 * interpreted as a {@link Runtime.Version}</td></tr> 600 * <tr><td><code>java.vm.vendor</code></td> 601 * <td>Java Virtual Machine implementation vendor</td></tr> 602 * <tr><td><code>java.vm.name</code></td> 603 * <td>Java Virtual Machine implementation name</td></tr> 604 * <tr><td><code>java.specification.version</code></td> 605 * <td>Java Runtime Environment specification version which may be 606 * interpreted as a {@link Runtime.Version}</td></tr> 607 * <tr><td><code>java.specification.vendor</code></td> 608 * <td>Java Runtime Environment specification vendor</td></tr> 609 * <tr><td><code>java.specification.name</code></td> 610 * <td>Java Runtime Environment specification name</td></tr> 611 * <tr><td><code>java.class.version</code></td> 612 * <td>Java class format version number</td></tr> 613 * <tr><td><code>java.class.path</code></td> 614 * <td>Java class path</td></tr> 615 * <tr><td><code>java.library.path</code></td> 616 * <td>List of paths to search when loading libraries</td></tr> 617 * <tr><td><code>java.io.tmpdir</code></td> 618 * <td>Default temp file path</td></tr> 619 * <tr><td><code>java.compiler</code></td> 620 * <td>Name of JIT compiler to use</td></tr> 621 * <tr><td><code>os.name</code></td> 622 * <td>Operating system name</td></tr> 623 * <tr><td><code>os.arch</code></td> 624 * <td>Operating system architecture</td></tr> 625 * <tr><td><code>os.version</code></td> 626 * <td>Operating system version</td></tr> 627 * <tr><td><code>file.separator</code></td> 628 * <td>File separator ("/" on UNIX)</td></tr> 629 * <tr><td><code>path.separator</code></td> 630 * <td>Path separator (":" on UNIX)</td></tr> 631 * <tr><td><code>line.separator</code></td> 632 * <td>Line separator ("\n" on UNIX)</td></tr> 633 * <tr><td><code>user.name</code></td> 634 * <td>User's account name</td></tr> 635 * <tr><td><code>user.home</code></td> 636 * <td>User's home directory</td></tr> 637 * <tr><td><code>user.dir</code></td> 638 * <td>User's current working directory</td></tr> 639 * </table> 640 * <p> 641 * Multiple paths in a system property value are separated by the path 642 * separator character of the platform. 643 * <p> 644 * Note that even if the security manager does not permit the 645 * <code>getProperties</code> operation, it may choose to permit the 646 * {@link #getProperty(String)} operation. 647 * 648 * @implNote In addition to the standard system properties, the system 649 * properties may include the following keys: 650 * <table summary="Shows property keys and associated values"> 651 * <tr><th>Key</th> 652 * <th>Description of Associated Value</th></tr> 653 * <tr><td>{@code jdk.module.path}</td> 654 * <td>The application module path</td></tr> 655 * <tr><td>{@code jdk.module.upgrade.path}</td> 656 * <td>The upgrade module path</td></tr> 657 * <tr><td>{@code jdk.module.main}</td> 658 * <td>The module name of the initial/main module</td></tr> 659 * <tr><td>{@code jdk.module.main.class}</td> 660 * <td>The main class name of the initial module</td></tr> 661 * </table> 662 * 663 * @return the system properties 664 * @exception SecurityException if a security manager exists and its 665 * <code>checkPropertiesAccess</code> method doesn't allow access 666 * to the system properties. 667 * @see #setProperties 668 * @see java.lang.SecurityException 669 * @see java.lang.SecurityManager#checkPropertiesAccess() 670 * @see java.util.Properties 671 */ 672 public static Properties getProperties() { 673 SecurityManager sm = getSecurityManager(); 674 if (sm != null) { 675 sm.checkPropertiesAccess(); 676 } 677 678 return props; 679 } 680 681 /** 682 * Returns the system-dependent line separator string. It always 683 * returns the same value - the initial value of the {@linkplain 684 * #getProperty(String) system property} {@code line.separator}. 685 * 686 * <p>On UNIX systems, it returns {@code "\n"}; on Microsoft 687 * Windows systems it returns {@code "\r\n"}. 688 * 689 * @return the system-dependent line separator string 690 * @since 1.7 691 */ 692 public static String lineSeparator() { 693 return lineSeparator; 694 } 695 696 private static String lineSeparator; 697 698 /** 699 * Sets the system properties to the <code>Properties</code> 700 * argument. 701 * <p> 702 * First, if there is a security manager, its 703 * <code>checkPropertiesAccess</code> method is called with no 704 * arguments. This may result in a security exception. 705 * <p> 706 * The argument becomes the current set of system properties for use 707 * by the {@link #getProperty(String)} method. If the argument is 708 * <code>null</code>, then the current set of system properties is 709 * forgotten. 710 * 711 * @param props the new system properties. 712 * @exception SecurityException if a security manager exists and its 713 * <code>checkPropertiesAccess</code> method doesn't allow access 714 * to the system properties. 715 * @see #getProperties 716 * @see java.util.Properties 717 * @see java.lang.SecurityException 718 * @see java.lang.SecurityManager#checkPropertiesAccess() 719 */ 720 public static void setProperties(Properties props) { 721 SecurityManager sm = getSecurityManager(); 722 if (sm != null) { 723 sm.checkPropertiesAccess(); 724 } 725 if (props == null) { 726 props = new Properties(); 727 initProperties(props); 728 } 729 System.props = props; 730 } 731 732 /** 733 * Gets the system property indicated by the specified key. 734 * <p> 735 * First, if there is a security manager, its 736 * <code>checkPropertyAccess</code> method is called with the key as 737 * its argument. This may result in a SecurityException. 738 * <p> 739 * If there is no current set of system properties, a set of system 740 * properties is first created and initialized in the same manner as 741 * for the <code>getProperties</code> method. 742 * 743 * @param key the name of the system property. 744 * @return the string value of the system property, 745 * or <code>null</code> if there is no property with that key. 746 * 747 * @exception SecurityException if a security manager exists and its 748 * <code>checkPropertyAccess</code> method doesn't allow 749 * access to the specified system property. 750 * @exception NullPointerException if <code>key</code> is 751 * <code>null</code>. 752 * @exception IllegalArgumentException if <code>key</code> is empty. 753 * @see #setProperty 754 * @see java.lang.SecurityException 755 * @see java.lang.SecurityManager#checkPropertyAccess(java.lang.String) 756 * @see java.lang.System#getProperties() 757 */ 758 public static String getProperty(String key) { 759 checkKey(key); 760 SecurityManager sm = getSecurityManager(); 761 if (sm != null) { 762 sm.checkPropertyAccess(key); 763 } 764 765 return props.getProperty(key); 766 } 767 768 /** 769 * Gets the system property indicated by the specified key. 770 * <p> 771 * First, if there is a security manager, its 772 * <code>checkPropertyAccess</code> method is called with the 773 * <code>key</code> as its argument. 774 * <p> 775 * If there is no current set of system properties, a set of system 776 * properties is first created and initialized in the same manner as 777 * for the <code>getProperties</code> method. 778 * 779 * @param key the name of the system property. 780 * @param def a default value. 781 * @return the string value of the system property, 782 * or the default value if there is no property with that key. 783 * 784 * @exception SecurityException if a security manager exists and its 785 * <code>checkPropertyAccess</code> method doesn't allow 786 * access to the specified system property. 787 * @exception NullPointerException if <code>key</code> is 788 * <code>null</code>. 789 * @exception IllegalArgumentException if <code>key</code> is empty. 790 * @see #setProperty 791 * @see java.lang.SecurityManager#checkPropertyAccess(java.lang.String) 792 * @see java.lang.System#getProperties() 793 */ 794 public static String getProperty(String key, String def) { 795 checkKey(key); 796 SecurityManager sm = getSecurityManager(); 797 if (sm != null) { 798 sm.checkPropertyAccess(key); 799 } 800 801 return props.getProperty(key, def); 802 } 803 804 /** 805 * Sets the system property indicated by the specified key. 806 * <p> 807 * First, if a security manager exists, its 808 * <code>SecurityManager.checkPermission</code> method 809 * is called with a <code>PropertyPermission(key, "write")</code> 810 * permission. This may result in a SecurityException being thrown. 811 * If no exception is thrown, the specified property is set to the given 812 * value. 813 * 814 * @param key the name of the system property. 815 * @param value the value of the system property. 816 * @return the previous value of the system property, 817 * or <code>null</code> if it did not have one. 818 * 819 * @exception SecurityException if a security manager exists and its 820 * <code>checkPermission</code> method doesn't allow 821 * setting of the specified property. 822 * @exception NullPointerException if <code>key</code> or 823 * <code>value</code> is <code>null</code>. 824 * @exception IllegalArgumentException if <code>key</code> is empty. 825 * @see #getProperty 826 * @see java.lang.System#getProperty(java.lang.String) 827 * @see java.lang.System#getProperty(java.lang.String, java.lang.String) 828 * @see java.util.PropertyPermission 829 * @see SecurityManager#checkPermission 830 * @since 1.2 831 */ 832 public static String setProperty(String key, String value) { 833 checkKey(key); 834 SecurityManager sm = getSecurityManager(); 835 if (sm != null) { 836 sm.checkPermission(new PropertyPermission(key, 837 SecurityConstants.PROPERTY_WRITE_ACTION)); 838 } 839 840 return (String) props.setProperty(key, value); 841 } 842 843 /** 844 * Removes the system property indicated by the specified key. 845 * <p> 846 * First, if a security manager exists, its 847 * <code>SecurityManager.checkPermission</code> method 848 * is called with a <code>PropertyPermission(key, "write")</code> 849 * permission. This may result in a SecurityException being thrown. 850 * If no exception is thrown, the specified property is removed. 851 * 852 * @param key the name of the system property to be removed. 853 * @return the previous string value of the system property, 854 * or <code>null</code> if there was no property with that key. 855 * 856 * @exception SecurityException if a security manager exists and its 857 * <code>checkPropertyAccess</code> method doesn't allow 858 * access to the specified system property. 859 * @exception NullPointerException if <code>key</code> is 860 * <code>null</code>. 861 * @exception IllegalArgumentException if <code>key</code> is empty. 862 * @see #getProperty 863 * @see #setProperty 864 * @see java.util.Properties 865 * @see java.lang.SecurityException 866 * @see java.lang.SecurityManager#checkPropertiesAccess() 867 * @since 1.5 868 */ 869 public static String clearProperty(String key) { 870 checkKey(key); 871 SecurityManager sm = getSecurityManager(); 872 if (sm != null) { 873 sm.checkPermission(new PropertyPermission(key, "write")); 874 } 875 876 return (String) props.remove(key); 877 } 878 879 private static void checkKey(String key) { 880 if (key == null) { 881 throw new NullPointerException("key can't be null"); 882 } 883 if (key.equals("")) { 884 throw new IllegalArgumentException("key can't be empty"); 885 } 886 } 887 888 /** 889 * Gets the value of the specified environment variable. An 890 * environment variable is a system-dependent external named 891 * value. 892 * 893 * <p>If a security manager exists, its 894 * {@link SecurityManager#checkPermission checkPermission} 895 * method is called with a 896 * <code>{@link RuntimePermission}("getenv."+name)</code> 897 * permission. This may result in a {@link SecurityException} 898 * being thrown. If no exception is thrown the value of the 899 * variable <code>name</code> is returned. 900 * 901 * <p><a name="EnvironmentVSSystemProperties"><i>System 902 * properties</i> and <i>environment variables</i></a> are both 903 * conceptually mappings between names and values. Both 904 * mechanisms can be used to pass user-defined information to a 905 * Java process. Environment variables have a more global effect, 906 * because they are visible to all descendants of the process 907 * which defines them, not just the immediate Java subprocess. 908 * They can have subtly different semantics, such as case 909 * insensitivity, on different operating systems. For these 910 * reasons, environment variables are more likely to have 911 * unintended side effects. It is best to use system properties 912 * where possible. Environment variables should be used when a 913 * global effect is desired, or when an external system interface 914 * requires an environment variable (such as <code>PATH</code>). 915 * 916 * <p>On UNIX systems the alphabetic case of <code>name</code> is 917 * typically significant, while on Microsoft Windows systems it is 918 * typically not. For example, the expression 919 * <code>System.getenv("FOO").equals(System.getenv("foo"))</code> 920 * is likely to be true on Microsoft Windows. 921 * 922 * @param name the name of the environment variable 923 * @return the string value of the variable, or <code>null</code> 924 * if the variable is not defined in the system environment 925 * @throws NullPointerException if <code>name</code> is <code>null</code> 926 * @throws SecurityException 927 * if a security manager exists and its 928 * {@link SecurityManager#checkPermission checkPermission} 929 * method doesn't allow access to the environment variable 930 * <code>name</code> 931 * @see #getenv() 932 * @see ProcessBuilder#environment() 933 */ 934 public static String getenv(String name) { 935 SecurityManager sm = getSecurityManager(); 936 if (sm != null) { 937 sm.checkPermission(new RuntimePermission("getenv."+name)); 938 } 939 940 return ProcessEnvironment.getenv(name); 941 } 942 943 944 /** 945 * Returns an unmodifiable string map view of the current system environment. 946 * The environment is a system-dependent mapping from names to 947 * values which is passed from parent to child processes. 948 * 949 * <p>If the system does not support environment variables, an 950 * empty map is returned. 951 * 952 * <p>The returned map will never contain null keys or values. 953 * Attempting to query the presence of a null key or value will 954 * throw a {@link NullPointerException}. Attempting to query 955 * the presence of a key or value which is not of type 956 * {@link String} will throw a {@link ClassCastException}. 957 * 958 * <p>The returned map and its collection views may not obey the 959 * general contract of the {@link Object#equals} and 960 * {@link Object#hashCode} methods. 961 * 962 * <p>The returned map is typically case-sensitive on all platforms. 963 * 964 * <p>If a security manager exists, its 965 * {@link SecurityManager#checkPermission checkPermission} 966 * method is called with a 967 * <code>{@link RuntimePermission}("getenv.*")</code> 968 * permission. This may result in a {@link SecurityException} being 969 * thrown. 970 * 971 * <p>When passing information to a Java subprocess, 972 * <a href=#EnvironmentVSSystemProperties>system properties</a> 973 * are generally preferred over environment variables. 974 * 975 * @return the environment as a map of variable names to values 976 * @throws SecurityException 977 * if a security manager exists and its 978 * {@link SecurityManager#checkPermission checkPermission} 979 * method doesn't allow access to the process environment 980 * @see #getenv(String) 981 * @see ProcessBuilder#environment() 982 * @since 1.5 983 */ 984 public static java.util.Map<String,String> getenv() { 985 SecurityManager sm = getSecurityManager(); 986 if (sm != null) { 987 sm.checkPermission(new RuntimePermission("getenv.*")); 988 } 989 990 return ProcessEnvironment.getenv(); 991 } 992 993 /** 994 * {@code System.Logger} instances log messages that will be 995 * routed to the underlying logging framework the {@link System.LoggerFinder 996 * LoggerFinder} uses. 997 * <p> 998 * {@code System.Logger} instances are typically obtained from 999 * the {@link java.lang.System System} class, by calling 1000 * {@link java.lang.System#getLogger(java.lang.String) System.getLogger(loggerName)} 1001 * or {@link java.lang.System#getLogger(java.lang.String, java.util.ResourceBundle) 1002 * System.getLogger(loggerName, bundle)}. 1003 * 1004 * @see java.lang.System#getLogger(java.lang.String) 1005 * @see java.lang.System#getLogger(java.lang.String, java.util.ResourceBundle) 1006 * @see java.lang.System.LoggerFinder 1007 * 1008 * @since 9 1009 * 1010 */ 1011 public interface Logger { 1012 1013 /** 1014 * System {@linkplain Logger loggers} levels. 1015 * <p> 1016 * A level has a {@linkplain #getName() name} and {@linkplain 1017 * #getSeverity() severity}. 1018 * Level values are {@link #ALL}, {@link #TRACE}, {@link #DEBUG}, 1019 * {@link #INFO}, {@link #WARNING}, {@link #ERROR}, {@link #OFF}, 1020 * by order of increasing severity. 1021 * <br> 1022 * {@link #ALL} and {@link #OFF} 1023 * are simple markers with severities mapped respectively to 1024 * {@link java.lang.Integer#MIN_VALUE Integer.MIN_VALUE} and 1025 * {@link java.lang.Integer#MAX_VALUE Integer.MAX_VALUE}. 1026 * <p> 1027 * <b>Severity values and Mapping to {@code java.util.logging.Level}.</b> 1028 * <p> 1029 * {@linkplain System.Logger.Level System logger levels} are mapped to 1030 * {@linkplain java.util.logging.Level java.util.logging levels} 1031 * of corresponding severity. 1032 * <br>The mapping is as follows: 1033 * <br><br> 1034 * <table border="1"> 1035 * <caption>System.Logger Severity Level Mapping</caption> 1036 * <tr><td><b>System.Logger Levels</b></td> 1037 * <td>{@link Logger.Level#ALL ALL}</td> 1038 * <td>{@link Logger.Level#TRACE TRACE}</td> 1039 * <td>{@link Logger.Level#DEBUG DEBUG}</td> 1040 * <td>{@link Logger.Level#INFO INFO}</td> 1041 * <td>{@link Logger.Level#WARNING WARNING}</td> 1042 * <td>{@link Logger.Level#ERROR ERROR}</td> 1043 * <td>{@link Logger.Level#OFF OFF}</td> 1044 * </tr> 1045 * <tr><td><b>java.util.logging Levels</b></td> 1046 * <td>{@link java.util.logging.Level#ALL ALL}</td> 1047 * <td>{@link java.util.logging.Level#FINER FINER}</td> 1048 * <td>{@link java.util.logging.Level#FINE FINE}</td> 1049 * <td>{@link java.util.logging.Level#INFO INFO}</td> 1050 * <td>{@link java.util.logging.Level#WARNING WARNING}</td> 1051 * <td>{@link java.util.logging.Level#SEVERE SEVERE}</td> 1052 * <td>{@link java.util.logging.Level#OFF OFF}</td> 1053 * </tr> 1054 * </table> 1055 * 1056 * @since 9 1057 * 1058 * @see java.lang.System.LoggerFinder 1059 * @see java.lang.System.Logger 1060 */ 1061 public enum Level { 1062 1063 // for convenience, we're reusing java.util.logging.Level int values 1064 // the mapping logic in sun.util.logging.PlatformLogger depends 1065 // on this. 1066 /** 1067 * A marker to indicate that all levels are enabled. 1068 * This level {@linkplain #getSeverity() severity} is 1069 * {@link Integer#MIN_VALUE}. 1070 */ 1071 ALL(Integer.MIN_VALUE), // typically mapped to/from j.u.l.Level.ALL 1072 /** 1073 * {@code TRACE} level: usually used to log diagnostic information. 1074 * This level {@linkplain #getSeverity() severity} is 1075 * {@code 400}. 1076 */ 1077 TRACE(400), // typically mapped to/from j.u.l.Level.FINER 1078 /** 1079 * {@code DEBUG} level: usually used to log debug information traces. 1080 * This level {@linkplain #getSeverity() severity} is 1081 * {@code 500}. 1082 */ 1083 DEBUG(500), // typically mapped to/from j.u.l.Level.FINEST/FINE/CONFIG 1084 /** 1085 * {@code INFO} level: usually used to log information messages. 1086 * This level {@linkplain #getSeverity() severity} is 1087 * {@code 800}. 1088 */ 1089 INFO(800), // typically mapped to/from j.u.l.Level.INFO 1090 /** 1091 * {@code WARNING} level: usually used to log warning messages. 1092 * This level {@linkplain #getSeverity() severity} is 1093 * {@code 900}. 1094 */ 1095 WARNING(900), // typically mapped to/from j.u.l.Level.WARNING 1096 /** 1097 * {@code ERROR} level: usually used to log error messages. 1098 * This level {@linkplain #getSeverity() severity} is 1099 * {@code 1000}. 1100 */ 1101 ERROR(1000), // typically mapped to/from j.u.l.Level.SEVERE 1102 /** 1103 * A marker to indicate that all levels are disabled. 1104 * This level {@linkplain #getSeverity() severity} is 1105 * {@link Integer#MAX_VALUE}. 1106 */ 1107 OFF(Integer.MAX_VALUE); // typically mapped to/from j.u.l.Level.OFF 1108 1109 private final int severity; 1110 1111 private Level(int severity) { 1112 this.severity = severity; 1113 } 1114 1115 /** 1116 * Returns the name of this level. 1117 * @return this level {@linkplain #name()}. 1118 */ 1119 public final String getName() { 1120 return name(); 1121 } 1122 1123 /** 1124 * Returns the severity of this level. 1125 * A higher severity means a more severe condition. 1126 * @return this level severity. 1127 */ 1128 public final int getSeverity() { 1129 return severity; 1130 } 1131 } 1132 1133 /** 1134 * Returns the name of this logger. 1135 * 1136 * @return the logger name. 1137 */ 1138 public String getName(); 1139 1140 /** 1141 * Checks if a message of the given level would be logged by 1142 * this logger. 1143 * 1144 * @param level the log message level. 1145 * @return {@code true} if the given log message level is currently 1146 * being logged. 1147 * 1148 * @throws NullPointerException if {@code level} is {@code null}. 1149 */ 1150 public boolean isLoggable(Level level); 1151 1152 /** 1153 * Logs a message. 1154 * 1155 * @implSpec The default implementation for this method calls 1156 * {@code this.log(level, (ResourceBundle)null, msg, (Object[])null);} 1157 * 1158 * @param level the log message level. 1159 * @param msg the string message (or a key in the message catalog, if 1160 * this logger is a {@link 1161 * LoggerFinder#getLocalizedLogger(java.lang.String, 1162 * java.util.ResourceBundle, java.lang.reflect.Module) localized logger}); 1163 * can be {@code null}. 1164 * 1165 * @throws NullPointerException if {@code level} is {@code null}. 1166 */ 1167 public default void log(Level level, String msg) { 1168 log(level, (ResourceBundle) null, msg, (Object[]) null); 1169 } 1170 1171 /** 1172 * Logs a lazily supplied message. 1173 * <p> 1174 * If the logger is currently enabled for the given log message level 1175 * then a message is logged that is the result produced by the 1176 * given supplier function. Otherwise, the supplier is not operated on. 1177 * 1178 * @implSpec When logging is enabled for the given level, the default 1179 * implementation for this method calls 1180 * {@code this.log(level, (ResourceBundle)null, msgSupplier.get(), (Object[])null);} 1181 * 1182 * @param level the log message level. 1183 * @param msgSupplier a supplier function that produces a message. 1184 * 1185 * @throws NullPointerException if {@code level} is {@code null}, 1186 * or {@code msgSupplier} is {@code null}. 1187 */ 1188 public default void log(Level level, Supplier<String> msgSupplier) { 1189 Objects.requireNonNull(msgSupplier); 1190 if (isLoggable(Objects.requireNonNull(level))) { 1191 log(level, (ResourceBundle) null, msgSupplier.get(), (Object[]) null); 1192 } 1193 } 1194 1195 /** 1196 * Logs a message produced from the given object. 1197 * <p> 1198 * If the logger is currently enabled for the given log message level then 1199 * a message is logged that, by default, is the result produced from 1200 * calling toString on the given object. 1201 * Otherwise, the object is not operated on. 1202 * 1203 * @implSpec When logging is enabled for the given level, the default 1204 * implementation for this method calls 1205 * {@code this.log(level, (ResourceBundle)null, obj.toString(), (Object[])null);} 1206 * 1207 * @param level the log message level. 1208 * @param obj the object to log. 1209 * 1210 * @throws NullPointerException if {@code level} is {@code null}, or 1211 * {@code obj} is {@code null}. 1212 */ 1213 public default void log(Level level, Object obj) { 1214 Objects.requireNonNull(obj); 1215 if (isLoggable(Objects.requireNonNull(level))) { 1216 this.log(level, (ResourceBundle) null, obj.toString(), (Object[]) null); 1217 } 1218 } 1219 1220 /** 1221 * Logs a message associated with a given throwable. 1222 * 1223 * @implSpec The default implementation for this method calls 1224 * {@code this.log(level, (ResourceBundle)null, msg, thrown);} 1225 * 1226 * @param level the log message level. 1227 * @param msg the string message (or a key in the message catalog, if 1228 * this logger is a {@link 1229 * LoggerFinder#getLocalizedLogger(java.lang.String, 1230 * java.util.ResourceBundle, java.lang.reflect.Module) localized logger}); 1231 * can be {@code null}. 1232 * @param thrown a {@code Throwable} associated with the log message; 1233 * can be {@code null}. 1234 * 1235 * @throws NullPointerException if {@code level} is {@code null}. 1236 */ 1237 public default void log(Level level, String msg, Throwable thrown) { 1238 this.log(level, null, msg, thrown); 1239 } 1240 1241 /** 1242 * Logs a lazily supplied message associated with a given throwable. 1243 * <p> 1244 * If the logger is currently enabled for the given log message level 1245 * then a message is logged that is the result produced by the 1246 * given supplier function. Otherwise, the supplier is not operated on. 1247 * 1248 * @implSpec When logging is enabled for the given level, the default 1249 * implementation for this method calls 1250 * {@code this.log(level, (ResourceBundle)null, msgSupplier.get(), thrown);} 1251 * 1252 * @param level one of the log message level identifiers. 1253 * @param msgSupplier a supplier function that produces a message. 1254 * @param thrown a {@code Throwable} associated with log message; 1255 * can be {@code null}. 1256 * 1257 * @throws NullPointerException if {@code level} is {@code null}, or 1258 * {@code msgSupplier} is {@code null}. 1259 */ 1260 public default void log(Level level, Supplier<String> msgSupplier, 1261 Throwable thrown) { 1262 Objects.requireNonNull(msgSupplier); 1263 if (isLoggable(Objects.requireNonNull(level))) { 1264 this.log(level, null, msgSupplier.get(), thrown); 1265 } 1266 } 1267 1268 /** 1269 * Logs a message with an optional list of parameters. 1270 * 1271 * @implSpec The default implementation for this method calls 1272 * {@code this.log(level, (ResourceBundle)null, format, params);} 1273 * 1274 * @param level one of the log message level identifiers. 1275 * @param format the string message format in {@link 1276 * java.text.MessageFormat} format, (or a key in the message 1277 * catalog, if this logger is a {@link 1278 * LoggerFinder#getLocalizedLogger(java.lang.String, 1279 * java.util.ResourceBundle, java.lang.reflect.Module) localized logger}); 1280 * can be {@code null}. 1281 * @param params an optional list of parameters to the message (may be 1282 * none). 1283 * 1284 * @throws NullPointerException if {@code level} is {@code null}. 1285 */ 1286 public default void log(Level level, String format, Object... params) { 1287 this.log(level, null, format, params); 1288 } 1289 1290 /** 1291 * Logs a localized message associated with a given throwable. 1292 * <p> 1293 * If the given resource bundle is non-{@code null}, the {@code msg} 1294 * string is localized using the given resource bundle. 1295 * Otherwise the {@code msg} string is not localized. 1296 * 1297 * @param level the log message level. 1298 * @param bundle a resource bundle to localize {@code msg}; can be 1299 * {@code null}. 1300 * @param msg the string message (or a key in the message catalog, 1301 * if {@code bundle} is not {@code null}); can be {@code null}. 1302 * @param thrown a {@code Throwable} associated with the log message; 1303 * can be {@code null}. 1304 * 1305 * @throws NullPointerException if {@code level} is {@code null}. 1306 */ 1307 public void log(Level level, ResourceBundle bundle, String msg, 1308 Throwable thrown); 1309 1310 /** 1311 * Logs a message with resource bundle and an optional list of 1312 * parameters. 1313 * <p> 1314 * If the given resource bundle is non-{@code null}, the {@code format} 1315 * string is localized using the given resource bundle. 1316 * Otherwise the {@code format} string is not localized. 1317 * 1318 * @param level the log message level. 1319 * @param bundle a resource bundle to localize {@code format}; can be 1320 * {@code null}. 1321 * @param format the string message format in {@link 1322 * java.text.MessageFormat} format, (or a key in the message 1323 * catalog if {@code bundle} is not {@code null}); can be {@code null}. 1324 * @param params an optional list of parameters to the message (may be 1325 * none). 1326 * 1327 * @throws NullPointerException if {@code level} is {@code null}. 1328 */ 1329 public void log(Level level, ResourceBundle bundle, String format, 1330 Object... params); 1331 1332 1333 } 1334 1335 /** 1336 * The {@code LoggerFinder} service is responsible for creating, managing, 1337 * and configuring loggers to the underlying framework it uses. 1338 * <p> 1339 * A logger finder is a concrete implementation of this class that has a 1340 * zero-argument constructor and implements the abstract methods defined 1341 * by this class. 1342 * The loggers returned from a logger finder are capable of routing log 1343 * messages to the logging backend this provider supports. 1344 * A given invocation of the Java Runtime maintains a single 1345 * system-wide LoggerFinder instance that is loaded as follows: 1346 * <ul> 1347 * <li>First it finds any custom {@code LoggerFinder} provider 1348 * using the {@link java.util.ServiceLoader} facility with the 1349 * {@linkplain ClassLoader#getSystemClassLoader() system class 1350 * loader}.</li> 1351 * <li>If no {@code LoggerFinder} provider is found, the system default 1352 * {@code LoggerFinder} implementation will be used.</li> 1353 * </ul> 1354 * <p> 1355 * An application can replace the logging backend 1356 * <i>even when the java.logging module is present</i>, by simply providing 1357 * and declaring an implementation of the {@link LoggerFinder} service. 1358 * <p> 1359 * <b>Default Implementation</b> 1360 * <p> 1361 * The system default {@code LoggerFinder} implementation uses 1362 * {@code java.util.logging} as the backend framework when the 1363 * {@code java.logging} module is present. 1364 * It returns a {@linkplain System.Logger logger} instance 1365 * that will route log messages to a {@link java.util.logging.Logger 1366 * java.util.logging.Logger}. Otherwise, if {@code java.logging} is not 1367 * present, the default implementation will return a simple logger 1368 * instance that will route log messages of {@code INFO} level and above to 1369 * the console ({@code System.err}). 1370 * <p> 1371 * <b>Logging Configuration</b> 1372 * <p> 1373 * {@linkplain Logger Logger} instances obtained from the 1374 * {@code LoggerFinder} factory methods are not directly configurable by 1375 * the application. Configuration is the responsibility of the underlying 1376 * logging backend, and usually requires using APIs specific to that backend. 1377 * <p>For the default {@code LoggerFinder} implementation 1378 * using {@code java.util.logging} as its backend, refer to 1379 * {@link java.util.logging java.util.logging} for logging configuration. 1380 * For the default {@code LoggerFinder} implementation returning simple loggers 1381 * when the {@code java.logging} module is absent, the configuration 1382 * is implementation dependent. 1383 * <p> 1384 * Usually an application that uses a logging framework will log messages 1385 * through a logger facade defined (or supported) by that framework. 1386 * Applications that wish to use an external framework should log 1387 * through the facade associated with that framework. 1388 * <p> 1389 * A system class that needs to log messages will typically obtain 1390 * a {@link System.Logger} instance to route messages to the logging 1391 * framework selected by the application. 1392 * <p> 1393 * Libraries and classes that only need loggers to produce log messages 1394 * should not attempt to configure loggers by themselves, as that 1395 * would make them dependent from a specific implementation of the 1396 * {@code LoggerFinder} service. 1397 * <p> 1398 * In addition, when a security manager is present, loggers provided to 1399 * system classes should not be directly configurable through the logging 1400 * backend without requiring permissions. 1401 * <br> 1402 * It is the responsibility of the provider of 1403 * the concrete {@code LoggerFinder} implementation to ensure that 1404 * these loggers are not configured by untrusted code without proper 1405 * permission checks, as configuration performed on such loggers usually 1406 * affects all applications in the same Java Runtime. 1407 * <p> 1408 * <b>Message Levels and Mapping to backend levels</b> 1409 * <p> 1410 * A logger finder is responsible for mapping from a {@code 1411 * System.Logger.Level} to a level supported by the logging backend it uses. 1412 * <br>The default LoggerFinder using {@code java.util.logging} as the backend 1413 * maps {@code System.Logger} levels to 1414 * {@linkplain java.util.logging.Level java.util.logging} levels 1415 * of corresponding severity - as described in {@link Logger.Level 1416 * Logger.Level}. 1417 * 1418 * @see java.lang.System 1419 * @see java.lang.System.Logger 1420 * 1421 * @since 9 1422 */ 1423 public static abstract class LoggerFinder { 1424 /** 1425 * The {@code RuntimePermission("loggerFinder")} is 1426 * necessary to subclass and instantiate the {@code LoggerFinder} class, 1427 * as well as to obtain loggers from an instance of that class. 1428 */ 1429 static final RuntimePermission LOGGERFINDER_PERMISSION = 1430 new RuntimePermission("loggerFinder"); 1431 1432 /** 1433 * Creates a new instance of {@code LoggerFinder}. 1434 * 1435 * @implNote It is recommended that a {@code LoggerFinder} service 1436 * implementation does not perform any heavy initialization in its 1437 * constructor, in order to avoid possible risks of deadlock or class 1438 * loading cycles during the instantiation of the service provider. 1439 * 1440 * @throws SecurityException if a security manager is present and its 1441 * {@code checkPermission} method doesn't allow the 1442 * {@code RuntimePermission("loggerFinder")}. 1443 */ 1444 protected LoggerFinder() { 1445 this(checkPermission()); 1446 } 1447 1448 private LoggerFinder(Void unused) { 1449 // nothing to do. 1450 } 1451 1452 private static Void checkPermission() { 1453 final SecurityManager sm = System.getSecurityManager(); 1454 if (sm != null) { 1455 sm.checkPermission(LOGGERFINDER_PERMISSION); 1456 } 1457 return null; 1458 } 1459 1460 /** 1461 * Returns an instance of {@link Logger Logger} 1462 * for the given {@code module}. 1463 * 1464 * @param name the name of the logger. 1465 * @param module the module for which the logger is being requested. 1466 * 1467 * @return a {@link Logger logger} suitable for use within the given 1468 * module. 1469 * @throws NullPointerException if {@code name} is {@code null} or 1470 * {@code module} is {@code null}. 1471 * @throws SecurityException if a security manager is present and its 1472 * {@code checkPermission} method doesn't allow the 1473 * {@code RuntimePermission("loggerFinder")}. 1474 */ 1475 public abstract Logger getLogger(String name, Module module); 1476 1477 /** 1478 * Returns a localizable instance of {@link Logger Logger} 1479 * for the given {@code module}. 1480 * The returned logger will use the provided resource bundle for 1481 * message localization. 1482 * 1483 * @implSpec By default, this method calls {@link 1484 * #getLogger(java.lang.String, java.lang.reflect.Module) 1485 * this.getLogger(name, module)} to obtain a logger, then wraps that 1486 * logger in a {@link Logger} instance where all methods that do not 1487 * take a {@link ResourceBundle} as parameter are redirected to one 1488 * which does - passing the given {@code bundle} for 1489 * localization. So for instance, a call to {@link 1490 * Logger#log(Level, String) Logger.log(Level.INFO, msg)} 1491 * will end up as a call to {@link 1492 * Logger#log(Level, ResourceBundle, String, Object...) 1493 * Logger.log(Level.INFO, bundle, msg, (Object[])null)} on the wrapped 1494 * logger instance. 1495 * Note however that by default, string messages returned by {@link 1496 * java.util.function.Supplier Supplier<String>} will not be 1497 * localized, as it is assumed that such strings are messages which are 1498 * already constructed, rather than keys in a resource bundle. 1499 * <p> 1500 * An implementation of {@code LoggerFinder} may override this method, 1501 * for example, when the underlying logging backend provides its own 1502 * mechanism for localizing log messages, then such a 1503 * {@code LoggerFinder} would be free to return a logger 1504 * that makes direct use of the mechanism provided by the backend. 1505 * 1506 * @param name the name of the logger. 1507 * @param bundle a resource bundle; can be {@code null}. 1508 * @param module the module for which the logger is being requested. 1509 * @return an instance of {@link Logger Logger} which will use the 1510 * provided resource bundle for message localization. 1511 * 1512 * @throws NullPointerException if {@code name} is {@code null} or 1513 * {@code module} is {@code null}. 1514 * @throws SecurityException if a security manager is present and its 1515 * {@code checkPermission} method doesn't allow the 1516 * {@code RuntimePermission("loggerFinder")}. 1517 */ 1518 public Logger getLocalizedLogger(String name, ResourceBundle bundle, 1519 Module module) { 1520 return new LocalizedLoggerWrapper<>(getLogger(name, module), bundle); 1521 } 1522 1523 /** 1524 * Returns the {@code LoggerFinder} instance. There is one 1525 * single system-wide {@code LoggerFinder} instance in 1526 * the Java Runtime. See the class specification of how the 1527 * {@link LoggerFinder LoggerFinder} implementation is located and 1528 * loaded. 1529 1530 * @return the {@link LoggerFinder LoggerFinder} instance. 1531 * @throws SecurityException if a security manager is present and its 1532 * {@code checkPermission} method doesn't allow the 1533 * {@code RuntimePermission("loggerFinder")}. 1534 */ 1535 public static LoggerFinder getLoggerFinder() { 1536 final SecurityManager sm = System.getSecurityManager(); 1537 if (sm != null) { 1538 sm.checkPermission(LOGGERFINDER_PERMISSION); 1539 } 1540 return accessProvider(); 1541 } 1542 1543 1544 private static volatile LoggerFinder service; 1545 static LoggerFinder accessProvider() { 1546 // We do not need to synchronize: LoggerFinderLoader will 1547 // always return the same instance, so if we don't have it, 1548 // just fetch it again. 1549 if (service == null) { 1550 PrivilegedAction<LoggerFinder> pa = 1551 () -> LoggerFinderLoader.getLoggerFinder(); 1552 service = AccessController.doPrivileged(pa, null, 1553 LOGGERFINDER_PERMISSION); 1554 } 1555 return service; 1556 } 1557 1558 } 1559 1560 1561 /** 1562 * Returns an instance of {@link Logger Logger} for the caller's 1563 * use. 1564 * 1565 * @implSpec 1566 * Instances returned by this method route messages to loggers 1567 * obtained by calling {@link LoggerFinder#getLogger(java.lang.String, 1568 * java.lang.reflect.Module) LoggerFinder.getLogger(name, module)}, where 1569 * {@code module} is the caller's module. 1570 * In cases where {@code System.getLogger} is called from a context where 1571 * there is no caller frame on the stack (e.g when called directly 1572 * from a JNI attached thread), {@code IllegalCallerException} is thrown. 1573 * To obtain a logger in such a context, use an auxiliary class that will 1574 * implicitly be identified as the caller, or use the system {@link 1575 * LoggerFinder#getLoggerFinder() LoggerFinder} to obtain a logger instead. 1576 * Note that doing the latter may eagerly initialize the underlying 1577 * logging system. 1578 * 1579 * @apiNote 1580 * This method may defer calling the {@link 1581 * LoggerFinder#getLogger(java.lang.String, java.lang.reflect.Module) 1582 * LoggerFinder.getLogger} method to create an actual logger supplied by 1583 * the logging backend, for instance, to allow loggers to be obtained during 1584 * the system initialization time. 1585 * 1586 * @param name the name of the logger. 1587 * @return an instance of {@link Logger} that can be used by the calling 1588 * class. 1589 * @throws NullPointerException if {@code name} is {@code null}. 1590 * @throws IllegalCallerException if there is no Java caller frame on the 1591 * stack. 1592 * 1593 * @since 9 1594 */ 1595 @CallerSensitive 1596 public static Logger getLogger(String name) { 1597 Objects.requireNonNull(name); 1598 final Class<?> caller = Reflection.getCallerClass(); 1599 if (caller == null) { 1600 throw new IllegalCallerException("no caller frame"); 1601 } 1602 return LazyLoggers.getLogger(name, caller.getModule()); 1603 } 1604 1605 /** 1606 * Returns a localizable instance of {@link Logger 1607 * Logger} for the caller's use. 1608 * The returned logger will use the provided resource bundle for message 1609 * localization. 1610 * 1611 * @implSpec 1612 * The returned logger will perform message localization as specified 1613 * by {@link LoggerFinder#getLocalizedLogger(java.lang.String, 1614 * java.util.ResourceBundle, java.lang.reflect.Module) 1615 * LoggerFinder.getLocalizedLogger(name, bundle, module)}, where 1616 * {@code module} is the caller's module. 1617 * In cases where {@code System.getLogger} is called from a context where 1618 * there is no caller frame on the stack (e.g when called directly 1619 * from a JNI attached thread), {@code IllegalCallerException} is thrown. 1620 * To obtain a logger in such a context, use an auxiliary class that 1621 * will implicitly be identified as the caller, or use the system {@link 1622 * LoggerFinder#getLoggerFinder() LoggerFinder} to obtain a logger instead. 1623 * Note that doing the latter may eagerly initialize the underlying 1624 * logging system. 1625 * 1626 * @apiNote 1627 * This method is intended to be used after the system is fully initialized. 1628 * This method may trigger the immediate loading and initialization 1629 * of the {@link LoggerFinder} service, which may cause issues if the 1630 * Java Runtime is not ready to initialize the concrete service 1631 * implementation yet. 1632 * System classes which may be loaded early in the boot sequence and 1633 * need to log localized messages should create a logger using 1634 * {@link #getLogger(java.lang.String)} and then use the log methods that 1635 * take a resource bundle as parameter. 1636 * 1637 * @param name the name of the logger. 1638 * @param bundle a resource bundle. 1639 * @return an instance of {@link Logger} which will use the provided 1640 * resource bundle for message localization. 1641 * @throws NullPointerException if {@code name} is {@code null} or 1642 * {@code bundle} is {@code null}. 1643 * @throws IllegalCallerException if there is no Java caller frame on the 1644 * stack. 1645 * 1646 * @since 9 1647 */ 1648 @CallerSensitive 1649 public static Logger getLogger(String name, ResourceBundle bundle) { 1650 final ResourceBundle rb = Objects.requireNonNull(bundle); 1651 Objects.requireNonNull(name); 1652 final Class<?> caller = Reflection.getCallerClass(); 1653 if (caller == null) { 1654 throw new IllegalCallerException("no caller frame"); 1655 } 1656 final SecurityManager sm = System.getSecurityManager(); 1657 // We don't use LazyLoggers if a resource bundle is specified. 1658 // Bootstrap sensitive classes in the JDK do not use resource bundles 1659 // when logging. This could be revisited later, if it needs to. 1660 if (sm != null) { 1661 final PrivilegedAction<Logger> pa = 1662 () -> LoggerFinder.accessProvider() 1663 .getLocalizedLogger(name, rb, caller.getModule()); 1664 return AccessController.doPrivileged(pa, null, 1665 LoggerFinder.LOGGERFINDER_PERMISSION); 1666 } 1667 return LoggerFinder.accessProvider() 1668 .getLocalizedLogger(name, rb, caller.getModule()); 1669 } 1670 1671 /** 1672 * Terminates the currently running Java Virtual Machine. The 1673 * argument serves as a status code; by convention, a nonzero status 1674 * code indicates abnormal termination. 1675 * <p> 1676 * This method calls the <code>exit</code> method in class 1677 * <code>Runtime</code>. This method never returns normally. 1678 * <p> 1679 * The call <code>System.exit(n)</code> is effectively equivalent to 1680 * the call: 1681 * <blockquote><pre> 1682 * Runtime.getRuntime().exit(n) 1683 * </pre></blockquote> 1684 * 1685 * @param status exit status. 1686 * @throws SecurityException 1687 * if a security manager exists and its <code>checkExit</code> 1688 * method doesn't allow exit with the specified status. 1689 * @see java.lang.Runtime#exit(int) 1690 */ 1691 public static void exit(int status) { 1692 Runtime.getRuntime().exit(status); 1693 } 1694 1695 /** 1696 * Runs the garbage collector. 1697 * <p> 1698 * Calling the <code>gc</code> method suggests that the Java Virtual 1699 * Machine expend effort toward recycling unused objects in order to 1700 * make the memory they currently occupy available for quick reuse. 1701 * When control returns from the method call, the Java Virtual 1702 * Machine has made a best effort to reclaim space from all discarded 1703 * objects. 1704 * <p> 1705 * The call <code>System.gc()</code> is effectively equivalent to the 1706 * call: 1707 * <blockquote><pre> 1708 * Runtime.getRuntime().gc() 1709 * </pre></blockquote> 1710 * 1711 * @see java.lang.Runtime#gc() 1712 */ 1713 public static void gc() { 1714 Runtime.getRuntime().gc(); 1715 } 1716 1717 /** 1718 * Runs the finalization methods of any objects pending finalization. 1719 * <p> 1720 * Calling this method suggests that the Java Virtual Machine expend 1721 * effort toward running the <code>finalize</code> methods of objects 1722 * that have been found to be discarded but whose <code>finalize</code> 1723 * methods have not yet been run. When control returns from the 1724 * method call, the Java Virtual Machine has made a best effort to 1725 * complete all outstanding finalizations. 1726 * <p> 1727 * The call <code>System.runFinalization()</code> is effectively 1728 * equivalent to the call: 1729 * <blockquote><pre> 1730 * Runtime.getRuntime().runFinalization() 1731 * </pre></blockquote> 1732 * 1733 * @see java.lang.Runtime#runFinalization() 1734 */ 1735 public static void runFinalization() { 1736 Runtime.getRuntime().runFinalization(); 1737 } 1738 1739 /** 1740 * Enable or disable finalization on exit; doing so specifies that the 1741 * finalizers of all objects that have finalizers that have not yet been 1742 * automatically invoked are to be run before the Java runtime exits. 1743 * By default, finalization on exit is disabled. 1744 * 1745 * <p>If there is a security manager, 1746 * its <code>checkExit</code> method is first called 1747 * with 0 as its argument to ensure the exit is allowed. 1748 * This could result in a SecurityException. 1749 * 1750 * @deprecated This method is inherently unsafe. It may result in 1751 * finalizers being called on live objects while other threads are 1752 * concurrently manipulating those objects, resulting in erratic 1753 * behavior or deadlock. 1754 * This method is subject to removal in a future version of Java SE. 1755 * @param value indicating enabling or disabling of finalization 1756 * @throws SecurityException 1757 * if a security manager exists and its <code>checkExit</code> 1758 * method doesn't allow the exit. 1759 * 1760 * @see java.lang.Runtime#exit(int) 1761 * @see java.lang.Runtime#gc() 1762 * @see java.lang.SecurityManager#checkExit(int) 1763 * @since 1.1 1764 */ 1765 @Deprecated(since="1.2", forRemoval=true) 1766 public static void runFinalizersOnExit(boolean value) { 1767 Runtime.runFinalizersOnExit(value); 1768 } 1769 1770 /** 1771 * Loads the native library specified by the filename argument. The filename 1772 * argument must be an absolute path name. 1773 * 1774 * If the filename argument, when stripped of any platform-specific library 1775 * prefix, path, and file extension, indicates a library whose name is, 1776 * for example, L, and a native library called L is statically linked 1777 * with the VM, then the JNI_OnLoad_L function exported by the library 1778 * is invoked rather than attempting to load a dynamic library. 1779 * A filename matching the argument does not have to exist in the 1780 * file system. 1781 * See the JNI Specification for more details. 1782 * 1783 * Otherwise, the filename argument is mapped to a native library image in 1784 * an implementation-dependent manner. 1785 * 1786 * <p> 1787 * The call <code>System.load(name)</code> is effectively equivalent 1788 * to the call: 1789 * <blockquote><pre> 1790 * Runtime.getRuntime().load(name) 1791 * </pre></blockquote> 1792 * 1793 * @param filename the file to load. 1794 * @exception SecurityException if a security manager exists and its 1795 * <code>checkLink</code> method doesn't allow 1796 * loading of the specified dynamic library 1797 * @exception UnsatisfiedLinkError if either the filename is not an 1798 * absolute path name, the native library is not statically 1799 * linked with the VM, or the library cannot be mapped to 1800 * a native library image by the host system. 1801 * @exception NullPointerException if <code>filename</code> is 1802 * <code>null</code> 1803 * @see java.lang.Runtime#load(java.lang.String) 1804 * @see java.lang.SecurityManager#checkLink(java.lang.String) 1805 */ 1806 @CallerSensitive 1807 public static void load(String filename) { 1808 Runtime.getRuntime().load0(Reflection.getCallerClass(), filename); 1809 } 1810 1811 /** 1812 * Loads the native library specified by the <code>libname</code> 1813 * argument. The <code>libname</code> argument must not contain any platform 1814 * specific prefix, file extension or path. If a native library 1815 * called <code>libname</code> is statically linked with the VM, then the 1816 * JNI_OnLoad_<code>libname</code> function exported by the library is invoked. 1817 * See the JNI Specification for more details. 1818 * 1819 * Otherwise, the libname argument is loaded from a system library 1820 * location and mapped to a native library image in an implementation- 1821 * dependent manner. 1822 * <p> 1823 * The call <code>System.loadLibrary(name)</code> is effectively 1824 * equivalent to the call 1825 * <blockquote><pre> 1826 * Runtime.getRuntime().loadLibrary(name) 1827 * </pre></blockquote> 1828 * 1829 * @param libname the name of the library. 1830 * @exception SecurityException if a security manager exists and its 1831 * <code>checkLink</code> method doesn't allow 1832 * loading of the specified dynamic library 1833 * @exception UnsatisfiedLinkError if either the libname argument 1834 * contains a file path, the native library is not statically 1835 * linked with the VM, or the library cannot be mapped to a 1836 * native library image by the host system. 1837 * @exception NullPointerException if <code>libname</code> is 1838 * <code>null</code> 1839 * @see java.lang.Runtime#loadLibrary(java.lang.String) 1840 * @see java.lang.SecurityManager#checkLink(java.lang.String) 1841 */ 1842 @CallerSensitive 1843 public static void loadLibrary(String libname) { 1844 Runtime.getRuntime().loadLibrary0(Reflection.getCallerClass(), libname); 1845 } 1846 1847 /** 1848 * Maps a library name into a platform-specific string representing 1849 * a native library. 1850 * 1851 * @param libname the name of the library. 1852 * @return a platform-dependent native library name. 1853 * @exception NullPointerException if <code>libname</code> is 1854 * <code>null</code> 1855 * @see java.lang.System#loadLibrary(java.lang.String) 1856 * @see java.lang.ClassLoader#findLibrary(java.lang.String) 1857 * @since 1.2 1858 */ 1859 public static native String mapLibraryName(String libname); 1860 1861 /** 1862 * Create PrintStream for stdout/err based on encoding. 1863 */ 1864 private static PrintStream newPrintStream(FileOutputStream fos, String enc) { 1865 if (enc != null) { 1866 try { 1867 return new PrintStream(new BufferedOutputStream(fos, 128), true, enc); 1868 } catch (UnsupportedEncodingException uee) {} 1869 } 1870 return new PrintStream(new BufferedOutputStream(fos, 128), true); 1871 } 1872 1873 /** 1874 * Initialize the system class. Called after thread initialization. 1875 */ 1876 private static void initPhase1() { 1877 1878 // VM might invoke JNU_NewStringPlatform() to set those encoding 1879 // sensitive properties (user.home, user.name, boot.class.path, etc.) 1880 // during "props" initialization, in which it may need access, via 1881 // System.getProperty(), to the related system encoding property that 1882 // have been initialized (put into "props") at early stage of the 1883 // initialization. So make sure the "props" is available at the 1884 // very beginning of the initialization and all system properties to 1885 // be put into it directly. 1886 props = new Properties(); 1887 initProperties(props); // initialized by the VM 1888 1889 // There are certain system configurations that may be controlled by 1890 // VM options such as the maximum amount of direct memory and 1891 // Integer cache size used to support the object identity semantics 1892 // of autoboxing. Typically, the library will obtain these values 1893 // from the properties set by the VM. If the properties are for 1894 // internal implementation use only, these properties should be 1895 // removed from the system properties. 1896 // 1897 // See java.lang.Integer.IntegerCache and the 1898 // VM.saveAndRemoveProperties method for example. 1899 // 1900 // Save a private copy of the system properties object that 1901 // can only be accessed by the internal implementation. Remove 1902 // certain system properties that are not intended for public access. 1903 VM.saveAndRemoveProperties(props); 1904 1905 lineSeparator = props.getProperty("line.separator"); 1906 VersionProps.init(); 1907 1908 FileInputStream fdIn = new FileInputStream(FileDescriptor.in); 1909 FileOutputStream fdOut = new FileOutputStream(FileDescriptor.out); 1910 FileOutputStream fdErr = new FileOutputStream(FileDescriptor.err); 1911 setIn0(new BufferedInputStream(fdIn)); 1912 setOut0(newPrintStream(fdOut, props.getProperty("sun.stdout.encoding"))); 1913 setErr0(newPrintStream(fdErr, props.getProperty("sun.stderr.encoding"))); 1914 1915 // Load the zip library now in order to keep java.util.zip.ZipFile 1916 // from trying to use itself to load this library later. 1917 loadLibrary("zip"); 1918 1919 // Setup Java signal handlers for HUP, TERM, and INT (where available). 1920 Terminator.setup(); 1921 1922 // Initialize any miscellaneous operating system settings that need to be 1923 // set for the class libraries. Currently this is no-op everywhere except 1924 // for Windows where the process-wide error mode is set before the java.io 1925 // classes are used. 1926 VM.initializeOSEnvironment(); 1927 1928 // The main thread is not added to its thread group in the same 1929 // way as other threads; we must do it ourselves here. 1930 Thread current = Thread.currentThread(); 1931 current.getThreadGroup().add(current); 1932 1933 // register shared secrets 1934 setJavaLangAccess(); 1935 1936 // Subsystems that are invoked during initialization can invoke 1937 // VM.isBooted() in order to avoid doing things that should 1938 // wait until the VM is fully initialized. The initialization level 1939 // is incremented from 0 to 1 here to indicate the first phase of 1940 // initialization has completed. 1941 // IMPORTANT: Ensure that this remains the last initialization action! 1942 VM.initLevel(1); 1943 } 1944 1945 // @see #initPhase2() 1946 private static Layer bootLayer; 1947 1948 /* 1949 * Invoked by VM. Phase 2 module system initialization. 1950 * Only classes in java.base can be loaded in this phase. 1951 */ 1952 private static void initPhase2() { 1953 // initialize the module system 1954 System.bootLayer = ModuleBootstrap.boot(); 1955 1956 // module system initialized 1957 VM.initLevel(2); 1958 } 1959 1960 /* 1961 * Invoked by VM. Phase 3 is the final system initialization: 1962 * 1. set security manager 1963 * 2. set system class loader 1964 * 3. set TCCL 1965 * 1966 * This method must be called after the module system initialization. 1967 * The security manager and system class loader may be custom class from 1968 * the application classpath or modulepath. 1969 */ 1970 private static void initPhase3() { 1971 // set security manager 1972 String cn = System.getProperty("java.security.manager"); 1973 if (cn != null) { 1974 if (cn.isEmpty() || "default".equals(cn)) { 1975 System.setSecurityManager(new SecurityManager()); 1976 } else { 1977 try { 1978 Class<?> c = Class.forName(cn, false, ClassLoader.getBuiltinAppClassLoader()); 1979 Constructor<?> ctor = c.getConstructor(); 1980 // Must be a public subclass of SecurityManager with 1981 // a public no-arg constructor 1982 if (!SecurityManager.class.isAssignableFrom(c) || 1983 !Modifier.isPublic(c.getModifiers()) || 1984 !Modifier.isPublic(ctor.getModifiers())) { 1985 throw new Error("Could not create SecurityManager: " + ctor.toString()); 1986 } 1987 // custom security manager implementation may be in unnamed module 1988 // or a named module but non-exported package 1989 ctor.setAccessible(true); 1990 SecurityManager sm = (SecurityManager) ctor.newInstance(); 1991 System.setSecurityManager(sm); 1992 } catch (Exception e) { 1993 throw new Error("Could not create SecurityManager", e); 1994 } 1995 } 1996 } 1997 1998 // initializing the system class loader 1999 VM.initLevel(3); 2000 2001 // system class loader initialized 2002 ClassLoader scl = ClassLoader.initSystemClassLoader(); 2003 2004 // set TCCL 2005 Thread.currentThread().setContextClassLoader(scl); 2006 2007 // system is fully initialized 2008 VM.initLevel(4); 2009 } 2010 2011 private static void setJavaLangAccess() { 2012 // Allow privileged classes outside of java.lang 2013 SharedSecrets.setJavaLangAccess(new JavaLangAccess() { 2014 public Method getMethodOrNull(Class<?> klass, String name, Class<?>... parameterTypes) { 2015 return klass.getMethodOrNull(name, parameterTypes); 2016 } 2017 public jdk.internal.reflect.ConstantPool getConstantPool(Class<?> klass) { 2018 return klass.getConstantPool(); 2019 } 2020 public boolean casAnnotationType(Class<?> klass, AnnotationType oldType, AnnotationType newType) { 2021 return klass.casAnnotationType(oldType, newType); 2022 } 2023 public AnnotationType getAnnotationType(Class<?> klass) { 2024 return klass.getAnnotationType(); 2025 } 2026 public Map<Class<? extends Annotation>, Annotation> getDeclaredAnnotationMap(Class<?> klass) { 2027 return klass.getDeclaredAnnotationMap(); 2028 } 2029 public byte[] getRawClassAnnotations(Class<?> klass) { 2030 return klass.getRawAnnotations(); 2031 } 2032 public byte[] getRawClassTypeAnnotations(Class<?> klass) { 2033 return klass.getRawTypeAnnotations(); 2034 } 2035 public byte[] getRawExecutableTypeAnnotations(Executable executable) { 2036 return Class.getExecutableTypeAnnotationBytes(executable); 2037 } 2038 public <E extends Enum<E>> 2039 E[] getEnumConstantsShared(Class<E> klass) { 2040 return klass.getEnumConstantsShared(); 2041 } 2042 public void blockedOn(Thread t, Interruptible b) { 2043 t.blockedOn(b); 2044 } 2045 public void registerShutdownHook(int slot, boolean registerShutdownInProgress, Runnable hook) { 2046 Shutdown.add(slot, registerShutdownInProgress, hook); 2047 } 2048 public String newStringUnsafe(char[] chars) { 2049 return new String(chars, true); 2050 } 2051 public Thread newThreadWithAcc(Runnable target, AccessControlContext acc) { 2052 return new Thread(target, acc); 2053 } 2054 public void invokeFinalize(Object o) throws Throwable { 2055 o.finalize(); 2056 } 2057 public Layer getBootLayer() { 2058 return bootLayer; 2059 } 2060 public ConcurrentHashMap<?, ?> createOrGetClassLoaderValueMap(ClassLoader cl) { 2061 return cl.createOrGetClassLoaderValueMap(); 2062 } 2063 public Class<?> findBootstrapClassOrNull(ClassLoader cl, String name) { 2064 return cl.findBootstrapClassOrNull(name); 2065 } 2066 public URL findResource(ClassLoader cl, String mn, String name) throws IOException { 2067 return cl.findResource(mn, name); 2068 } 2069 public Stream<Package> packages(ClassLoader cl) { 2070 return cl.packages(); 2071 } 2072 public Package definePackage(ClassLoader cl, String name, Module module) { 2073 return cl.definePackage(name, module); 2074 } 2075 public String fastUUID(long lsb, long msb) { 2076 return Long.fastUUID(lsb, msb); 2077 } 2078 public void invalidatePackageAccessCache() { 2079 SecurityManager.invalidatePackageAccessCache(); 2080 } 2081 }); 2082 } 2083 }