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