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.module.ModuleDescriptor; 39 import java.lang.reflect.Constructor; 40 import java.lang.reflect.Executable; 41 import java.lang.reflect.Method; 42 import java.lang.reflect.Modifier; 43 import java.net.URI; 44 import java.security.AccessControlContext; 45 import java.security.ProtectionDomain; 46 import java.security.AccessController; 47 import java.security.PrivilegedAction; 48 import java.nio.channels.Channel; 49 import java.nio.channels.spi.SelectorProvider; 50 import java.util.Map; 51 import java.util.Objects; 52 import java.util.Properties; 53 import java.util.PropertyPermission; 54 import java.util.ResourceBundle; 55 import java.util.function.Supplier; 56 import java.util.concurrent.ConcurrentHashMap; 57 import java.util.stream.Stream; 58 59 import jdk.internal.module.ModuleBootstrap; 60 import jdk.internal.module.ServicesCatalog; 61 import jdk.internal.reflect.CallerSensitive; 62 import jdk.internal.reflect.Reflection; 63 import jdk.internal.HotSpotIntrinsicCandidate; 64 import jdk.internal.misc.JavaLangAccess;; 65 import jdk.internal.misc.SharedSecrets;; 66 import jdk.internal.misc.VM; 67 import jdk.internal.logger.LoggerFinderLoader; 68 import jdk.internal.logger.LazyLoggers; 69 import jdk.internal.logger.LocalizedLoggerWrapper; 70 import sun.reflect.annotation.AnnotationType; 71 import sun.nio.ch.Interruptible; 72 import sun.security.util.SecurityConstants; 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 class="striped"> 579 * <caption style="display:none">Shows property keys and associated values</caption> 580 * <thead> 581 * <tr><th>Key</th> 582 * <th>Description of Associated Value</th></tr> 583 * </thead> 584 * <tbody> 585 * <tr><td><code>java.version</code></td> 586 * <td>Java Runtime Environment version which may be interpreted 587 * as a {@link Runtime.Version}</td></tr> 588 * <tr><td><code>java.vendor</code></td> 589 * <td>Java Runtime Environment vendor</td></tr> 590 * <tr><td><code>java.vendor.url</code></td> 591 * <td>Java vendor URL</td></tr> 592 * <tr><td><code>java.home</code></td> 593 * <td>Java installation directory</td></tr> 594 * <tr><td><code>java.vm.specification.version</code></td> 595 * <td>Java Virtual Machine specification version which may be 596 * interpreted as a {@link Runtime.Version}</td></tr> 597 * <tr><td><code>java.vm.specification.vendor</code></td> 598 * <td>Java Virtual Machine specification vendor</td></tr> 599 * <tr><td><code>java.vm.specification.name</code></td> 600 * <td>Java Virtual Machine specification name</td></tr> 601 * <tr><td><code>java.vm.version</code></td> 602 * <td>Java Virtual Machine implementation version which may be 603 * interpreted as a {@link Runtime.Version}</td></tr> 604 * <tr><td><code>java.vm.vendor</code></td> 605 * <td>Java Virtual Machine implementation vendor</td></tr> 606 * <tr><td><code>java.vm.name</code></td> 607 * <td>Java Virtual Machine implementation name</td></tr> 608 * <tr><td><code>java.specification.version</code></td> 609 * <td>Java Runtime Environment specification version which may be 610 * interpreted as a {@link Runtime.Version}</td></tr> 611 * <tr><td><code>java.specification.vendor</code></td> 612 * <td>Java Runtime Environment specification vendor</td></tr> 613 * <tr><td><code>java.specification.name</code></td> 614 * <td>Java Runtime Environment specification name</td></tr> 615 * <tr><td><code>java.class.version</code></td> 616 * <td>Java class format version number</td></tr> 617 * <tr><td><code>java.class.path</code></td> 618 * <td>Java class path</td></tr> 619 * <tr><td><code>java.library.path</code></td> 620 * <td>List of paths to search when loading libraries</td></tr> 621 * <tr><td><code>java.io.tmpdir</code></td> 622 * <td>Default temp file path</td></tr> 623 * <tr><td><code>java.compiler</code></td> 624 * <td>Name of JIT compiler to use</td></tr> 625 * <tr><td><code>os.name</code></td> 626 * <td>Operating system name</td></tr> 627 * <tr><td><code>os.arch</code></td> 628 * <td>Operating system architecture</td></tr> 629 * <tr><td><code>os.version</code></td> 630 * <td>Operating system version</td></tr> 631 * <tr><td><code>file.separator</code></td> 632 * <td>File separator ("/" on UNIX)</td></tr> 633 * <tr><td><code>path.separator</code></td> 634 * <td>Path separator (":" on UNIX)</td></tr> 635 * <tr><td><code>line.separator</code></td> 636 * <td>Line separator ("\n" on UNIX)</td></tr> 637 * <tr><td><code>user.name</code></td> 638 * <td>User's account name</td></tr> 639 * <tr><td><code>user.home</code></td> 640 * <td>User's home directory</td></tr> 641 * <tr><td><code>user.dir</code></td> 642 * <td>User's current working directory</td></tr> 643 * </tbody> 644 * </table> 645 * <p> 646 * Multiple paths in a system property value are separated by the path 647 * separator character of the platform. 648 * <p> 649 * Note that even if the security manager does not permit the 650 * <code>getProperties</code> operation, it may choose to permit the 651 * {@link #getProperty(String)} operation. 652 * 653 * @implNote In addition to the standard system properties, the system 654 * properties may include the following keys: 655 * <table class="striped"> 656 * <caption style="display:none">Shows property keys and associated values</caption> 657 * <thead> 658 * <tr><th>Key</th> 659 * <th>Description of Associated Value</th></tr> 660 * </thead> 661 * <tbody> 662 * <tr><td>{@code jdk.module.path}</td> 663 * <td>The application module path</td></tr> 664 * <tr><td>{@code jdk.module.upgrade.path}</td> 665 * <td>The upgrade module path</td></tr> 666 * <tr><td>{@code jdk.module.main}</td> 667 * <td>The module name of the initial/main module</td></tr> 668 * <tr><td>{@code jdk.module.main.class}</td> 669 * <td>The main class name of the initial module</td></tr> 670 * </tbody> 671 * </table> 672 * 673 * @return the system properties 674 * @exception SecurityException if a security manager exists and its 675 * <code>checkPropertiesAccess</code> method doesn't allow access 676 * to the system properties. 677 * @see #setProperties 678 * @see java.lang.SecurityException 679 * @see java.lang.SecurityManager#checkPropertiesAccess() 680 * @see java.util.Properties 681 */ 682 public static Properties getProperties() { 683 SecurityManager sm = getSecurityManager(); 684 if (sm != null) { 685 sm.checkPropertiesAccess(); 686 } 687 688 return props; 689 } 690 691 /** 692 * Returns the system-dependent line separator string. It always 693 * returns the same value - the initial value of the {@linkplain 694 * #getProperty(String) system property} {@code line.separator}. 695 * 696 * <p>On UNIX systems, it returns {@code "\n"}; on Microsoft 697 * Windows systems it returns {@code "\r\n"}. 698 * 699 * @return the system-dependent line separator string 700 * @since 1.7 701 */ 702 public static String lineSeparator() { 703 return lineSeparator; 704 } 705 706 private static String lineSeparator; 707 708 /** 709 * Sets the system properties to the <code>Properties</code> 710 * argument. 711 * <p> 712 * First, if there is a security manager, its 713 * <code>checkPropertiesAccess</code> method is called with no 714 * arguments. This may result in a security exception. 715 * <p> 716 * The argument becomes the current set of system properties for use 717 * by the {@link #getProperty(String)} method. If the argument is 718 * <code>null</code>, then the current set of system properties is 719 * forgotten. 720 * 721 * @param props the new system properties. 722 * @exception SecurityException if a security manager exists and its 723 * <code>checkPropertiesAccess</code> method doesn't allow access 724 * to the system properties. 725 * @see #getProperties 726 * @see java.util.Properties 727 * @see java.lang.SecurityException 728 * @see java.lang.SecurityManager#checkPropertiesAccess() 729 */ 730 public static void setProperties(Properties props) { 731 SecurityManager sm = getSecurityManager(); 732 if (sm != null) { 733 sm.checkPropertiesAccess(); 734 } 735 if (props == null) { 736 props = new Properties(); 737 initProperties(props); 738 } 739 System.props = props; 740 } 741 742 /** 743 * Gets the system property indicated by the specified key. 744 * <p> 745 * First, if there is a security manager, its 746 * <code>checkPropertyAccess</code> method is called with the key as 747 * its argument. This may result in a SecurityException. 748 * <p> 749 * If there is no current set of system properties, a set of system 750 * properties is first created and initialized in the same manner as 751 * for the <code>getProperties</code> method. 752 * 753 * @param key the name of the system property. 754 * @return the string value of the system property, 755 * or <code>null</code> if there is no property with that key. 756 * 757 * @exception SecurityException if a security manager exists and its 758 * <code>checkPropertyAccess</code> method doesn't allow 759 * access to the specified system property. 760 * @exception NullPointerException if <code>key</code> is 761 * <code>null</code>. 762 * @exception IllegalArgumentException if <code>key</code> is empty. 763 * @see #setProperty 764 * @see java.lang.SecurityException 765 * @see java.lang.SecurityManager#checkPropertyAccess(java.lang.String) 766 * @see java.lang.System#getProperties() 767 */ 768 public static String getProperty(String key) { 769 checkKey(key); 770 SecurityManager sm = getSecurityManager(); 771 if (sm != null) { 772 sm.checkPropertyAccess(key); 773 } 774 775 return props.getProperty(key); 776 } 777 778 /** 779 * Gets the system property indicated by the specified key. 780 * <p> 781 * First, if there is a security manager, its 782 * <code>checkPropertyAccess</code> method is called with the 783 * <code>key</code> as its argument. 784 * <p> 785 * If there is no current set of system properties, a set of system 786 * properties is first created and initialized in the same manner as 787 * for the <code>getProperties</code> method. 788 * 789 * @param key the name of the system property. 790 * @param def a default value. 791 * @return the string value of the system property, 792 * or the default value if there is no property with that key. 793 * 794 * @exception SecurityException if a security manager exists and its 795 * <code>checkPropertyAccess</code> method doesn't allow 796 * access to the specified system property. 797 * @exception NullPointerException if <code>key</code> is 798 * <code>null</code>. 799 * @exception IllegalArgumentException if <code>key</code> is empty. 800 * @see #setProperty 801 * @see java.lang.SecurityManager#checkPropertyAccess(java.lang.String) 802 * @see java.lang.System#getProperties() 803 */ 804 public static String getProperty(String key, String def) { 805 checkKey(key); 806 SecurityManager sm = getSecurityManager(); 807 if (sm != null) { 808 sm.checkPropertyAccess(key); 809 } 810 811 return props.getProperty(key, def); 812 } 813 814 /** 815 * Sets the system property indicated by the specified key. 816 * <p> 817 * First, if a security manager exists, its 818 * <code>SecurityManager.checkPermission</code> method 819 * is called with a <code>PropertyPermission(key, "write")</code> 820 * permission. This may result in a SecurityException being thrown. 821 * If no exception is thrown, the specified property is set to the given 822 * value. 823 * 824 * @param key the name of the system property. 825 * @param value the value of the system property. 826 * @return the previous value of the system property, 827 * or <code>null</code> if it did not have one. 828 * 829 * @exception SecurityException if a security manager exists and its 830 * <code>checkPermission</code> method doesn't allow 831 * setting of the specified property. 832 * @exception NullPointerException if <code>key</code> or 833 * <code>value</code> is <code>null</code>. 834 * @exception IllegalArgumentException if <code>key</code> is empty. 835 * @see #getProperty 836 * @see java.lang.System#getProperty(java.lang.String) 837 * @see java.lang.System#getProperty(java.lang.String, java.lang.String) 838 * @see java.util.PropertyPermission 839 * @see SecurityManager#checkPermission 840 * @since 1.2 841 */ 842 public static String setProperty(String key, String value) { 843 checkKey(key); 844 SecurityManager sm = getSecurityManager(); 845 if (sm != null) { 846 sm.checkPermission(new PropertyPermission(key, 847 SecurityConstants.PROPERTY_WRITE_ACTION)); 848 } 849 850 return (String) props.setProperty(key, value); 851 } 852 853 /** 854 * Removes the system property indicated by the specified key. 855 * <p> 856 * First, if a security manager exists, its 857 * <code>SecurityManager.checkPermission</code> method 858 * is called with a <code>PropertyPermission(key, "write")</code> 859 * permission. This may result in a SecurityException being thrown. 860 * If no exception is thrown, the specified property is removed. 861 * 862 * @param key the name of the system property to be removed. 863 * @return the previous string value of the system property, 864 * or <code>null</code> if there was no property with that key. 865 * 866 * @exception SecurityException if a security manager exists and its 867 * <code>checkPropertyAccess</code> method doesn't allow 868 * access to the specified system property. 869 * @exception NullPointerException if <code>key</code> is 870 * <code>null</code>. 871 * @exception IllegalArgumentException if <code>key</code> is empty. 872 * @see #getProperty 873 * @see #setProperty 874 * @see java.util.Properties 875 * @see java.lang.SecurityException 876 * @see java.lang.SecurityManager#checkPropertiesAccess() 877 * @since 1.5 878 */ 879 public static String clearProperty(String key) { 880 checkKey(key); 881 SecurityManager sm = getSecurityManager(); 882 if (sm != null) { 883 sm.checkPermission(new PropertyPermission(key, "write")); 884 } 885 886 return (String) props.remove(key); 887 } 888 889 private static void checkKey(String key) { 890 if (key == null) { 891 throw new NullPointerException("key can't be null"); 892 } 893 if (key.equals("")) { 894 throw new IllegalArgumentException("key can't be empty"); 895 } 896 } 897 898 /** 899 * Gets the value of the specified environment variable. An 900 * environment variable is a system-dependent external named 901 * value. 902 * 903 * <p>If a security manager exists, its 904 * {@link SecurityManager#checkPermission checkPermission} 905 * method is called with a 906 * <code>{@link RuntimePermission}("getenv."+name)</code> 907 * permission. This may result in a {@link SecurityException} 908 * being thrown. If no exception is thrown the value of the 909 * variable <code>name</code> is returned. 910 * 911 * <p><a id="EnvironmentVSSystemProperties"><i>System 912 * properties</i> and <i>environment variables</i></a> are both 913 * conceptually mappings between names and values. Both 914 * mechanisms can be used to pass user-defined information to a 915 * Java process. Environment variables have a more global effect, 916 * because they are visible to all descendants of the process 917 * which defines them, not just the immediate Java subprocess. 918 * They can have subtly different semantics, such as case 919 * insensitivity, on different operating systems. For these 920 * reasons, environment variables are more likely to have 921 * unintended side effects. It is best to use system properties 922 * where possible. Environment variables should be used when a 923 * global effect is desired, or when an external system interface 924 * requires an environment variable (such as <code>PATH</code>). 925 * 926 * <p>On UNIX systems the alphabetic case of <code>name</code> is 927 * typically significant, while on Microsoft Windows systems it is 928 * typically not. For example, the expression 929 * <code>System.getenv("FOO").equals(System.getenv("foo"))</code> 930 * is likely to be true on Microsoft Windows. 931 * 932 * @param name the name of the environment variable 933 * @return the string value of the variable, or <code>null</code> 934 * if the variable is not defined in the system environment 935 * @throws NullPointerException if <code>name</code> is <code>null</code> 936 * @throws SecurityException 937 * if a security manager exists and its 938 * {@link SecurityManager#checkPermission checkPermission} 939 * method doesn't allow access to the environment variable 940 * <code>name</code> 941 * @see #getenv() 942 * @see ProcessBuilder#environment() 943 */ 944 public static String getenv(String name) { 945 SecurityManager sm = getSecurityManager(); 946 if (sm != null) { 947 sm.checkPermission(new RuntimePermission("getenv."+name)); 948 } 949 950 return ProcessEnvironment.getenv(name); 951 } 952 953 954 /** 955 * Returns an unmodifiable string map view of the current system environment. 956 * The environment is a system-dependent mapping from names to 957 * values which is passed from parent to child processes. 958 * 959 * <p>If the system does not support environment variables, an 960 * empty map is returned. 961 * 962 * <p>The returned map will never contain null keys or values. 963 * Attempting to query the presence of a null key or value will 964 * throw a {@link NullPointerException}. Attempting to query 965 * the presence of a key or value which is not of type 966 * {@link String} will throw a {@link ClassCastException}. 967 * 968 * <p>The returned map and its collection views may not obey the 969 * general contract of the {@link Object#equals} and 970 * {@link Object#hashCode} methods. 971 * 972 * <p>The returned map is typically case-sensitive on all platforms. 973 * 974 * <p>If a security manager exists, its 975 * {@link SecurityManager#checkPermission checkPermission} 976 * method is called with a 977 * <code>{@link RuntimePermission}("getenv.*")</code> 978 * permission. This may result in a {@link SecurityException} being 979 * thrown. 980 * 981 * <p>When passing information to a Java subprocess, 982 * <a href=#EnvironmentVSSystemProperties>system properties</a> 983 * are generally preferred over environment variables. 984 * 985 * @return the environment as a map of variable names to values 986 * @throws SecurityException 987 * if a security manager exists and its 988 * {@link SecurityManager#checkPermission checkPermission} 989 * method doesn't allow access to the process environment 990 * @see #getenv(String) 991 * @see ProcessBuilder#environment() 992 * @since 1.5 993 */ 994 public static java.util.Map<String,String> getenv() { 995 SecurityManager sm = getSecurityManager(); 996 if (sm != null) { 997 sm.checkPermission(new RuntimePermission("getenv.*")); 998 } 999 1000 return ProcessEnvironment.getenv(); 1001 } 1002 1003 /** 1004 * {@code System.Logger} instances log messages that will be 1005 * routed to the underlying logging framework the {@link System.LoggerFinder 1006 * LoggerFinder} uses. 1007 * <p> 1008 * {@code System.Logger} instances are typically obtained from 1009 * the {@link java.lang.System System} class, by calling 1010 * {@link java.lang.System#getLogger(java.lang.String) System.getLogger(loggerName)} 1011 * or {@link java.lang.System#getLogger(java.lang.String, java.util.ResourceBundle) 1012 * System.getLogger(loggerName, bundle)}. 1013 * 1014 * @see java.lang.System#getLogger(java.lang.String) 1015 * @see java.lang.System#getLogger(java.lang.String, java.util.ResourceBundle) 1016 * @see java.lang.System.LoggerFinder 1017 * 1018 * @since 9 1019 * 1020 */ 1021 public interface Logger { 1022 1023 /** 1024 * System {@linkplain Logger loggers} levels. 1025 * <p> 1026 * A level has a {@linkplain #getName() name} and {@linkplain 1027 * #getSeverity() severity}. 1028 * Level values are {@link #ALL}, {@link #TRACE}, {@link #DEBUG}, 1029 * {@link #INFO}, {@link #WARNING}, {@link #ERROR}, {@link #OFF}, 1030 * by order of increasing severity. 1031 * <br> 1032 * {@link #ALL} and {@link #OFF} 1033 * are simple markers with severities mapped respectively to 1034 * {@link java.lang.Integer#MIN_VALUE Integer.MIN_VALUE} and 1035 * {@link java.lang.Integer#MAX_VALUE Integer.MAX_VALUE}. 1036 * <p> 1037 * <b>Severity values and Mapping to {@code java.util.logging.Level}.</b> 1038 * <p> 1039 * {@linkplain System.Logger.Level System logger levels} are mapped to 1040 * {@linkplain java.util.logging.Level java.util.logging levels} 1041 * of corresponding severity. 1042 * <br>The mapping is as follows: 1043 * <br><br> 1044 * <table border="1"> 1045 * <caption>System.Logger Severity Level Mapping</caption> 1046 * <tr><td><b>System.Logger Levels</b></td> 1047 * <td>{@link Logger.Level#ALL ALL}</td> 1048 * <td>{@link Logger.Level#TRACE TRACE}</td> 1049 * <td>{@link Logger.Level#DEBUG DEBUG}</td> 1050 * <td>{@link Logger.Level#INFO INFO}</td> 1051 * <td>{@link Logger.Level#WARNING WARNING}</td> 1052 * <td>{@link Logger.Level#ERROR ERROR}</td> 1053 * <td>{@link Logger.Level#OFF OFF}</td> 1054 * </tr> 1055 * <tr><td><b>java.util.logging Levels</b></td> 1056 * <td>{@link java.util.logging.Level#ALL ALL}</td> 1057 * <td>{@link java.util.logging.Level#FINER FINER}</td> 1058 * <td>{@link java.util.logging.Level#FINE FINE}</td> 1059 * <td>{@link java.util.logging.Level#INFO INFO}</td> 1060 * <td>{@link java.util.logging.Level#WARNING WARNING}</td> 1061 * <td>{@link java.util.logging.Level#SEVERE SEVERE}</td> 1062 * <td>{@link java.util.logging.Level#OFF OFF}</td> 1063 * </tr> 1064 * </table> 1065 * 1066 * @since 9 1067 * 1068 * @see java.lang.System.LoggerFinder 1069 * @see java.lang.System.Logger 1070 */ 1071 public enum Level { 1072 1073 // for convenience, we're reusing java.util.logging.Level int values 1074 // the mapping logic in sun.util.logging.PlatformLogger depends 1075 // on this. 1076 /** 1077 * A marker to indicate that all levels are enabled. 1078 * This level {@linkplain #getSeverity() severity} is 1079 * {@link Integer#MIN_VALUE}. 1080 */ 1081 ALL(Integer.MIN_VALUE), // typically mapped to/from j.u.l.Level.ALL 1082 /** 1083 * {@code TRACE} level: usually used to log diagnostic information. 1084 * This level {@linkplain #getSeverity() severity} is 1085 * {@code 400}. 1086 */ 1087 TRACE(400), // typically mapped to/from j.u.l.Level.FINER 1088 /** 1089 * {@code DEBUG} level: usually used to log debug information traces. 1090 * This level {@linkplain #getSeverity() severity} is 1091 * {@code 500}. 1092 */ 1093 DEBUG(500), // typically mapped to/from j.u.l.Level.FINEST/FINE/CONFIG 1094 /** 1095 * {@code INFO} level: usually used to log information messages. 1096 * This level {@linkplain #getSeverity() severity} is 1097 * {@code 800}. 1098 */ 1099 INFO(800), // typically mapped to/from j.u.l.Level.INFO 1100 /** 1101 * {@code WARNING} level: usually used to log warning messages. 1102 * This level {@linkplain #getSeverity() severity} is 1103 * {@code 900}. 1104 */ 1105 WARNING(900), // typically mapped to/from j.u.l.Level.WARNING 1106 /** 1107 * {@code ERROR} level: usually used to log error messages. 1108 * This level {@linkplain #getSeverity() severity} is 1109 * {@code 1000}. 1110 */ 1111 ERROR(1000), // typically mapped to/from j.u.l.Level.SEVERE 1112 /** 1113 * A marker to indicate that all levels are disabled. 1114 * This level {@linkplain #getSeverity() severity} is 1115 * {@link Integer#MAX_VALUE}. 1116 */ 1117 OFF(Integer.MAX_VALUE); // typically mapped to/from j.u.l.Level.OFF 1118 1119 private final int severity; 1120 1121 private Level(int severity) { 1122 this.severity = severity; 1123 } 1124 1125 /** 1126 * Returns the name of this level. 1127 * @return this level {@linkplain #name()}. 1128 */ 1129 public final String getName() { 1130 return name(); 1131 } 1132 1133 /** 1134 * Returns the severity of this level. 1135 * A higher severity means a more severe condition. 1136 * @return this level severity. 1137 */ 1138 public final int getSeverity() { 1139 return severity; 1140 } 1141 } 1142 1143 /** 1144 * Returns the name of this logger. 1145 * 1146 * @return the logger name. 1147 */ 1148 public String getName(); 1149 1150 /** 1151 * Checks if a message of the given level would be logged by 1152 * this logger. 1153 * 1154 * @param level the log message level. 1155 * @return {@code true} if the given log message level is currently 1156 * being logged. 1157 * 1158 * @throws NullPointerException if {@code level} is {@code null}. 1159 */ 1160 public boolean isLoggable(Level level); 1161 1162 /** 1163 * Logs a message. 1164 * 1165 * @implSpec The default implementation for this method calls 1166 * {@code this.log(level, (ResourceBundle)null, msg, (Object[])null);} 1167 * 1168 * @param level the log message level. 1169 * @param msg the string message (or a key in the message catalog, if 1170 * this logger is a {@link 1171 * LoggerFinder#getLocalizedLogger(java.lang.String, 1172 * java.util.ResourceBundle, java.lang.Module) localized logger}); 1173 * can be {@code null}. 1174 * 1175 * @throws NullPointerException if {@code level} is {@code null}. 1176 */ 1177 public default void log(Level level, String msg) { 1178 log(level, (ResourceBundle) null, msg, (Object[]) null); 1179 } 1180 1181 /** 1182 * Logs a lazily supplied message. 1183 * <p> 1184 * If the logger is currently enabled for the given log message level 1185 * then a message is logged that is the result produced by the 1186 * given supplier function. Otherwise, the supplier is not operated on. 1187 * 1188 * @implSpec When logging is enabled for the given level, the default 1189 * implementation for this method calls 1190 * {@code this.log(level, (ResourceBundle)null, msgSupplier.get(), (Object[])null);} 1191 * 1192 * @param level the log message level. 1193 * @param msgSupplier a supplier function that produces a message. 1194 * 1195 * @throws NullPointerException if {@code level} is {@code null}, 1196 * or {@code msgSupplier} is {@code null}. 1197 */ 1198 public default void log(Level level, Supplier<String> msgSupplier) { 1199 Objects.requireNonNull(msgSupplier); 1200 if (isLoggable(Objects.requireNonNull(level))) { 1201 log(level, (ResourceBundle) null, msgSupplier.get(), (Object[]) null); 1202 } 1203 } 1204 1205 /** 1206 * Logs a message produced from the given object. 1207 * <p> 1208 * If the logger is currently enabled for the given log message level then 1209 * a message is logged that, by default, is the result produced from 1210 * calling toString on the given object. 1211 * Otherwise, the object is not operated on. 1212 * 1213 * @implSpec When logging is enabled for the given level, the default 1214 * implementation for this method calls 1215 * {@code this.log(level, (ResourceBundle)null, obj.toString(), (Object[])null);} 1216 * 1217 * @param level the log message level. 1218 * @param obj the object to log. 1219 * 1220 * @throws NullPointerException if {@code level} is {@code null}, or 1221 * {@code obj} is {@code null}. 1222 */ 1223 public default void log(Level level, Object obj) { 1224 Objects.requireNonNull(obj); 1225 if (isLoggable(Objects.requireNonNull(level))) { 1226 this.log(level, (ResourceBundle) null, obj.toString(), (Object[]) null); 1227 } 1228 } 1229 1230 /** 1231 * Logs a message associated with a given throwable. 1232 * 1233 * @implSpec The default implementation for this method calls 1234 * {@code this.log(level, (ResourceBundle)null, msg, thrown);} 1235 * 1236 * @param level the log message level. 1237 * @param msg the string message (or a key in the message catalog, if 1238 * this logger is a {@link 1239 * LoggerFinder#getLocalizedLogger(java.lang.String, 1240 * java.util.ResourceBundle, java.lang.Module) localized logger}); 1241 * can be {@code null}. 1242 * @param thrown a {@code Throwable} associated with the log message; 1243 * can be {@code null}. 1244 * 1245 * @throws NullPointerException if {@code level} is {@code null}. 1246 */ 1247 public default void log(Level level, String msg, Throwable thrown) { 1248 this.log(level, null, msg, thrown); 1249 } 1250 1251 /** 1252 * Logs a lazily supplied message associated with a given throwable. 1253 * <p> 1254 * If the logger is currently enabled for the given log message level 1255 * then a message is logged that is the result produced by the 1256 * given supplier function. Otherwise, the supplier is not operated on. 1257 * 1258 * @implSpec When logging is enabled for the given level, the default 1259 * implementation for this method calls 1260 * {@code this.log(level, (ResourceBundle)null, msgSupplier.get(), thrown);} 1261 * 1262 * @param level one of the log message level identifiers. 1263 * @param msgSupplier a supplier function that produces a message. 1264 * @param thrown a {@code Throwable} associated with log message; 1265 * can be {@code null}. 1266 * 1267 * @throws NullPointerException if {@code level} is {@code null}, or 1268 * {@code msgSupplier} is {@code null}. 1269 */ 1270 public default void log(Level level, Supplier<String> msgSupplier, 1271 Throwable thrown) { 1272 Objects.requireNonNull(msgSupplier); 1273 if (isLoggable(Objects.requireNonNull(level))) { 1274 this.log(level, null, msgSupplier.get(), thrown); 1275 } 1276 } 1277 1278 /** 1279 * Logs a message with an optional list of parameters. 1280 * 1281 * @implSpec The default implementation for this method calls 1282 * {@code this.log(level, (ResourceBundle)null, format, params);} 1283 * 1284 * @param level one of the log message level identifiers. 1285 * @param format the string message format in {@link 1286 * java.text.MessageFormat} format, (or a key in the message 1287 * catalog, if this logger is a {@link 1288 * LoggerFinder#getLocalizedLogger(java.lang.String, 1289 * java.util.ResourceBundle, java.lang.Module) localized logger}); 1290 * can be {@code null}. 1291 * @param params an optional list of parameters to the message (may be 1292 * none). 1293 * 1294 * @throws NullPointerException if {@code level} is {@code null}. 1295 */ 1296 public default void log(Level level, String format, Object... params) { 1297 this.log(level, null, format, params); 1298 } 1299 1300 /** 1301 * Logs a localized message associated with a given throwable. 1302 * <p> 1303 * If the given resource bundle is non-{@code null}, the {@code msg} 1304 * string is localized using the given resource bundle. 1305 * Otherwise the {@code msg} string is not localized. 1306 * 1307 * @param level the log message level. 1308 * @param bundle a resource bundle to localize {@code msg}; can be 1309 * {@code null}. 1310 * @param msg the string message (or a key in the message catalog, 1311 * if {@code bundle} is not {@code null}); can be {@code null}. 1312 * @param thrown a {@code Throwable} associated with the log message; 1313 * can be {@code null}. 1314 * 1315 * @throws NullPointerException if {@code level} is {@code null}. 1316 */ 1317 public void log(Level level, ResourceBundle bundle, String msg, 1318 Throwable thrown); 1319 1320 /** 1321 * Logs a message with resource bundle and an optional list of 1322 * parameters. 1323 * <p> 1324 * If the given resource bundle is non-{@code null}, the {@code format} 1325 * string is localized using the given resource bundle. 1326 * Otherwise the {@code format} string is not localized. 1327 * 1328 * @param level the log message level. 1329 * @param bundle a resource bundle to localize {@code format}; can be 1330 * {@code null}. 1331 * @param format the string message format in {@link 1332 * java.text.MessageFormat} format, (or a key in the message 1333 * catalog if {@code bundle} is not {@code null}); can be {@code null}. 1334 * @param params an optional list of parameters to the message (may be 1335 * none). 1336 * 1337 * @throws NullPointerException if {@code level} is {@code null}. 1338 */ 1339 public void log(Level level, ResourceBundle bundle, String format, 1340 Object... params); 1341 1342 1343 } 1344 1345 /** 1346 * The {@code LoggerFinder} service is responsible for creating, managing, 1347 * and configuring loggers to the underlying framework it uses. 1348 * <p> 1349 * A logger finder is a concrete implementation of this class that has a 1350 * zero-argument constructor and implements the abstract methods defined 1351 * by this class. 1352 * The loggers returned from a logger finder are capable of routing log 1353 * messages to the logging backend this provider supports. 1354 * A given invocation of the Java Runtime maintains a single 1355 * system-wide LoggerFinder instance that is loaded as follows: 1356 * <ul> 1357 * <li>First it finds any custom {@code LoggerFinder} provider 1358 * using the {@link java.util.ServiceLoader} facility with the 1359 * {@linkplain ClassLoader#getSystemClassLoader() system class 1360 * loader}.</li> 1361 * <li>If no {@code LoggerFinder} provider is found, the system default 1362 * {@code LoggerFinder} implementation will be used.</li> 1363 * </ul> 1364 * <p> 1365 * An application can replace the logging backend 1366 * <i>even when the java.logging module is present</i>, by simply providing 1367 * and declaring an implementation of the {@link LoggerFinder} service. 1368 * <p> 1369 * <b>Default Implementation</b> 1370 * <p> 1371 * The system default {@code LoggerFinder} implementation uses 1372 * {@code java.util.logging} as the backend framework when the 1373 * {@code java.logging} module is present. 1374 * It returns a {@linkplain System.Logger logger} instance 1375 * that will route log messages to a {@link java.util.logging.Logger 1376 * java.util.logging.Logger}. Otherwise, if {@code java.logging} is not 1377 * present, the default implementation will return a simple logger 1378 * instance that will route log messages of {@code INFO} level and above to 1379 * the console ({@code System.err}). 1380 * <p> 1381 * <b>Logging Configuration</b> 1382 * <p> 1383 * {@linkplain Logger Logger} instances obtained from the 1384 * {@code LoggerFinder} factory methods are not directly configurable by 1385 * the application. Configuration is the responsibility of the underlying 1386 * logging backend, and usually requires using APIs specific to that backend. 1387 * <p>For the default {@code LoggerFinder} implementation 1388 * using {@code java.util.logging} as its backend, refer to 1389 * {@link java.util.logging java.util.logging} for logging configuration. 1390 * For the default {@code LoggerFinder} implementation returning simple loggers 1391 * when the {@code java.logging} module is absent, the configuration 1392 * is implementation dependent. 1393 * <p> 1394 * Usually an application that uses a logging framework will log messages 1395 * through a logger facade defined (or supported) by that framework. 1396 * Applications that wish to use an external framework should log 1397 * through the facade associated with that framework. 1398 * <p> 1399 * A system class that needs to log messages will typically obtain 1400 * a {@link System.Logger} instance to route messages to the logging 1401 * framework selected by the application. 1402 * <p> 1403 * Libraries and classes that only need loggers to produce log messages 1404 * should not attempt to configure loggers by themselves, as that 1405 * would make them dependent from a specific implementation of the 1406 * {@code LoggerFinder} service. 1407 * <p> 1408 * In addition, when a security manager is present, loggers provided to 1409 * system classes should not be directly configurable through the logging 1410 * backend without requiring permissions. 1411 * <br> 1412 * It is the responsibility of the provider of 1413 * the concrete {@code LoggerFinder} implementation to ensure that 1414 * these loggers are not configured by untrusted code without proper 1415 * permission checks, as configuration performed on such loggers usually 1416 * affects all applications in the same Java Runtime. 1417 * <p> 1418 * <b>Message Levels and Mapping to backend levels</b> 1419 * <p> 1420 * A logger finder is responsible for mapping from a {@code 1421 * System.Logger.Level} to a level supported by the logging backend it uses. 1422 * <br>The default LoggerFinder using {@code java.util.logging} as the backend 1423 * maps {@code System.Logger} levels to 1424 * {@linkplain java.util.logging.Level java.util.logging} levels 1425 * of corresponding severity - as described in {@link Logger.Level 1426 * Logger.Level}. 1427 * 1428 * @see java.lang.System 1429 * @see java.lang.System.Logger 1430 * 1431 * @since 9 1432 */ 1433 public static abstract class LoggerFinder { 1434 /** 1435 * The {@code RuntimePermission("loggerFinder")} is 1436 * necessary to subclass and instantiate the {@code LoggerFinder} class, 1437 * as well as to obtain loggers from an instance of that class. 1438 */ 1439 static final RuntimePermission LOGGERFINDER_PERMISSION = 1440 new RuntimePermission("loggerFinder"); 1441 1442 /** 1443 * Creates a new instance of {@code LoggerFinder}. 1444 * 1445 * @implNote It is recommended that a {@code LoggerFinder} service 1446 * implementation does not perform any heavy initialization in its 1447 * constructor, in order to avoid possible risks of deadlock or class 1448 * loading cycles during the instantiation of the service provider. 1449 * 1450 * @throws SecurityException if a security manager is present and its 1451 * {@code checkPermission} method doesn't allow the 1452 * {@code RuntimePermission("loggerFinder")}. 1453 */ 1454 protected LoggerFinder() { 1455 this(checkPermission()); 1456 } 1457 1458 private LoggerFinder(Void unused) { 1459 // nothing to do. 1460 } 1461 1462 private static Void checkPermission() { 1463 final SecurityManager sm = System.getSecurityManager(); 1464 if (sm != null) { 1465 sm.checkPermission(LOGGERFINDER_PERMISSION); 1466 } 1467 return null; 1468 } 1469 1470 /** 1471 * Returns an instance of {@link Logger Logger} 1472 * for the given {@code module}. 1473 * 1474 * @param name the name of the logger. 1475 * @param module the module for which the logger is being requested. 1476 * 1477 * @return a {@link Logger logger} suitable for use within the given 1478 * module. 1479 * @throws NullPointerException if {@code name} is {@code null} or 1480 * {@code module} is {@code null}. 1481 * @throws SecurityException if a security manager is present and its 1482 * {@code checkPermission} method doesn't allow the 1483 * {@code RuntimePermission("loggerFinder")}. 1484 */ 1485 public abstract Logger getLogger(String name, Module module); 1486 1487 /** 1488 * Returns a localizable instance of {@link Logger Logger} 1489 * for the given {@code module}. 1490 * The returned logger will use the provided resource bundle for 1491 * message localization. 1492 * 1493 * @implSpec By default, this method calls {@link 1494 * #getLogger(java.lang.String, java.lang.Module) 1495 * this.getLogger(name, module)} to obtain a logger, then wraps that 1496 * logger in a {@link Logger} instance where all methods that do not 1497 * take a {@link ResourceBundle} as parameter are redirected to one 1498 * which does - passing the given {@code bundle} for 1499 * localization. So for instance, a call to {@link 1500 * Logger#log(Level, String) Logger.log(Level.INFO, msg)} 1501 * will end up as a call to {@link 1502 * Logger#log(Level, ResourceBundle, String, Object...) 1503 * Logger.log(Level.INFO, bundle, msg, (Object[])null)} on the wrapped 1504 * logger instance. 1505 * Note however that by default, string messages returned by {@link 1506 * java.util.function.Supplier Supplier<String>} will not be 1507 * localized, as it is assumed that such strings are messages which are 1508 * already constructed, rather than keys in a resource bundle. 1509 * <p> 1510 * An implementation of {@code LoggerFinder} may override this method, 1511 * for example, when the underlying logging backend provides its own 1512 * mechanism for localizing log messages, then such a 1513 * {@code LoggerFinder} would be free to return a logger 1514 * that makes direct use of the mechanism provided by the backend. 1515 * 1516 * @param name the name of the logger. 1517 * @param bundle a resource bundle; can be {@code null}. 1518 * @param module the module for which the logger is being requested. 1519 * @return an instance of {@link Logger Logger} which will use the 1520 * provided resource bundle for message localization. 1521 * 1522 * @throws NullPointerException if {@code name} is {@code null} or 1523 * {@code module} is {@code null}. 1524 * @throws SecurityException if a security manager is present and its 1525 * {@code checkPermission} method doesn't allow the 1526 * {@code RuntimePermission("loggerFinder")}. 1527 */ 1528 public Logger getLocalizedLogger(String name, ResourceBundle bundle, 1529 Module module) { 1530 return new LocalizedLoggerWrapper<>(getLogger(name, module), bundle); 1531 } 1532 1533 /** 1534 * Returns the {@code LoggerFinder} instance. There is one 1535 * single system-wide {@code LoggerFinder} instance in 1536 * the Java Runtime. See the class specification of how the 1537 * {@link LoggerFinder LoggerFinder} implementation is located and 1538 * loaded. 1539 1540 * @return the {@link LoggerFinder LoggerFinder} instance. 1541 * @throws SecurityException if a security manager is present and its 1542 * {@code checkPermission} method doesn't allow the 1543 * {@code RuntimePermission("loggerFinder")}. 1544 */ 1545 public static LoggerFinder getLoggerFinder() { 1546 final SecurityManager sm = System.getSecurityManager(); 1547 if (sm != null) { 1548 sm.checkPermission(LOGGERFINDER_PERMISSION); 1549 } 1550 return accessProvider(); 1551 } 1552 1553 1554 private static volatile LoggerFinder service; 1555 static LoggerFinder accessProvider() { 1556 // We do not need to synchronize: LoggerFinderLoader will 1557 // always return the same instance, so if we don't have it, 1558 // just fetch it again. 1559 if (service == null) { 1560 PrivilegedAction<LoggerFinder> pa = 1561 () -> LoggerFinderLoader.getLoggerFinder(); 1562 service = AccessController.doPrivileged(pa, null, 1563 LOGGERFINDER_PERMISSION); 1564 } 1565 return service; 1566 } 1567 1568 } 1569 1570 1571 /** 1572 * Returns an instance of {@link Logger Logger} for the caller's 1573 * use. 1574 * 1575 * @implSpec 1576 * Instances returned by this method route messages to loggers 1577 * obtained by calling {@link LoggerFinder#getLogger(java.lang.String, 1578 * java.lang.Module) LoggerFinder.getLogger(name, module)}, where 1579 * {@code module} is the caller's module. 1580 * In cases where {@code System.getLogger} is called from a context where 1581 * there is no caller frame on the stack (e.g when called directly 1582 * from a JNI attached thread), {@code IllegalCallerException} is thrown. 1583 * To obtain a logger in such a context, use an auxiliary class that will 1584 * implicitly be identified as the caller, or use the system {@link 1585 * LoggerFinder#getLoggerFinder() LoggerFinder} to obtain a logger instead. 1586 * Note that doing the latter may eagerly initialize the underlying 1587 * logging system. 1588 * 1589 * @apiNote 1590 * This method may defer calling the {@link 1591 * LoggerFinder#getLogger(java.lang.String, java.lang.Module) 1592 * LoggerFinder.getLogger} method to create an actual logger supplied by 1593 * the logging backend, for instance, to allow loggers to be obtained during 1594 * the system initialization time. 1595 * 1596 * @param name the name of the logger. 1597 * @return an instance of {@link Logger} that can be used by the calling 1598 * class. 1599 * @throws NullPointerException if {@code name} is {@code null}. 1600 * @throws IllegalCallerException if there is no Java caller frame on the 1601 * stack. 1602 * 1603 * @since 9 1604 */ 1605 @CallerSensitive 1606 public static Logger getLogger(String name) { 1607 Objects.requireNonNull(name); 1608 final Class<?> caller = Reflection.getCallerClass(); 1609 if (caller == null) { 1610 throw new IllegalCallerException("no caller frame"); 1611 } 1612 return LazyLoggers.getLogger(name, caller.getModule()); 1613 } 1614 1615 /** 1616 * Returns a localizable instance of {@link Logger 1617 * Logger} for the caller's use. 1618 * The returned logger will use the provided resource bundle for message 1619 * localization. 1620 * 1621 * @implSpec 1622 * The returned logger will perform message localization as specified 1623 * by {@link LoggerFinder#getLocalizedLogger(java.lang.String, 1624 * java.util.ResourceBundle, java.lang.Module) 1625 * LoggerFinder.getLocalizedLogger(name, bundle, module)}, where 1626 * {@code module} is the caller's module. 1627 * In cases where {@code System.getLogger} is called from a context where 1628 * there is no caller frame on the stack (e.g when called directly 1629 * from a JNI attached thread), {@code IllegalCallerException} is thrown. 1630 * To obtain a logger in such a context, use an auxiliary class that 1631 * will implicitly be identified as the caller, or use the system {@link 1632 * LoggerFinder#getLoggerFinder() LoggerFinder} to obtain a logger instead. 1633 * Note that doing the latter may eagerly initialize the underlying 1634 * logging system. 1635 * 1636 * @apiNote 1637 * This method is intended to be used after the system is fully initialized. 1638 * This method may trigger the immediate loading and initialization 1639 * of the {@link LoggerFinder} service, which may cause issues if the 1640 * Java Runtime is not ready to initialize the concrete service 1641 * implementation yet. 1642 * System classes which may be loaded early in the boot sequence and 1643 * need to log localized messages should create a logger using 1644 * {@link #getLogger(java.lang.String)} and then use the log methods that 1645 * take a resource bundle as parameter. 1646 * 1647 * @param name the name of the logger. 1648 * @param bundle a resource bundle. 1649 * @return an instance of {@link Logger} which will use the provided 1650 * resource bundle for message localization. 1651 * @throws NullPointerException if {@code name} is {@code null} or 1652 * {@code bundle} is {@code null}. 1653 * @throws IllegalCallerException if there is no Java caller frame on the 1654 * stack. 1655 * 1656 * @since 9 1657 */ 1658 @CallerSensitive 1659 public static Logger getLogger(String name, ResourceBundle bundle) { 1660 final ResourceBundle rb = Objects.requireNonNull(bundle); 1661 Objects.requireNonNull(name); 1662 final Class<?> caller = Reflection.getCallerClass(); 1663 if (caller == null) { 1664 throw new IllegalCallerException("no caller frame"); 1665 } 1666 final SecurityManager sm = System.getSecurityManager(); 1667 // We don't use LazyLoggers if a resource bundle is specified. 1668 // Bootstrap sensitive classes in the JDK do not use resource bundles 1669 // when logging. This could be revisited later, if it needs to. 1670 if (sm != null) { 1671 final PrivilegedAction<Logger> pa = 1672 () -> LoggerFinder.accessProvider() 1673 .getLocalizedLogger(name, rb, caller.getModule()); 1674 return AccessController.doPrivileged(pa, null, 1675 LoggerFinder.LOGGERFINDER_PERMISSION); 1676 } 1677 return LoggerFinder.accessProvider() 1678 .getLocalizedLogger(name, rb, caller.getModule()); 1679 } 1680 1681 /** 1682 * Terminates the currently running Java Virtual Machine. The 1683 * argument serves as a status code; by convention, a nonzero status 1684 * code indicates abnormal termination. 1685 * <p> 1686 * This method calls the <code>exit</code> method in class 1687 * <code>Runtime</code>. This method never returns normally. 1688 * <p> 1689 * The call <code>System.exit(n)</code> is effectively equivalent to 1690 * the call: 1691 * <blockquote><pre> 1692 * Runtime.getRuntime().exit(n) 1693 * </pre></blockquote> 1694 * 1695 * @param status exit status. 1696 * @throws SecurityException 1697 * if a security manager exists and its <code>checkExit</code> 1698 * method doesn't allow exit with the specified status. 1699 * @see java.lang.Runtime#exit(int) 1700 */ 1701 public static void exit(int status) { 1702 Runtime.getRuntime().exit(status); 1703 } 1704 1705 /** 1706 * Runs the garbage collector. 1707 * <p> 1708 * Calling the <code>gc</code> method suggests that the Java Virtual 1709 * Machine expend effort toward recycling unused objects in order to 1710 * make the memory they currently occupy available for quick reuse. 1711 * When control returns from the method call, the Java Virtual 1712 * Machine has made a best effort to reclaim space from all discarded 1713 * objects. 1714 * <p> 1715 * The call <code>System.gc()</code> is effectively equivalent to the 1716 * call: 1717 * <blockquote><pre> 1718 * Runtime.getRuntime().gc() 1719 * </pre></blockquote> 1720 * 1721 * @see java.lang.Runtime#gc() 1722 */ 1723 public static void gc() { 1724 Runtime.getRuntime().gc(); 1725 } 1726 1727 /** 1728 * Runs the finalization methods of any objects pending finalization. 1729 * <p> 1730 * Calling this method suggests that the Java Virtual Machine expend 1731 * effort toward running the <code>finalize</code> methods of objects 1732 * that have been found to be discarded but whose <code>finalize</code> 1733 * methods have not yet been run. When control returns from the 1734 * method call, the Java Virtual Machine has made a best effort to 1735 * complete all outstanding finalizations. 1736 * <p> 1737 * The call <code>System.runFinalization()</code> is effectively 1738 * equivalent to the call: 1739 * <blockquote><pre> 1740 * Runtime.getRuntime().runFinalization() 1741 * </pre></blockquote> 1742 * 1743 * @see java.lang.Runtime#runFinalization() 1744 */ 1745 public static void runFinalization() { 1746 Runtime.getRuntime().runFinalization(); 1747 } 1748 1749 /** 1750 * Enable or disable finalization on exit; doing so specifies that the 1751 * finalizers of all objects that have finalizers that have not yet been 1752 * automatically invoked are to be run before the Java runtime exits. 1753 * By default, finalization on exit is disabled. 1754 * 1755 * <p>If there is a security manager, 1756 * its <code>checkExit</code> method is first called 1757 * with 0 as its argument to ensure the exit is allowed. 1758 * This could result in a SecurityException. 1759 * 1760 * @deprecated This method is inherently unsafe. It may result in 1761 * finalizers being called on live objects while other threads are 1762 * concurrently manipulating those objects, resulting in erratic 1763 * behavior or deadlock. 1764 * This method is subject to removal in a future version of Java SE. 1765 * @param value indicating enabling or disabling of finalization 1766 * @throws SecurityException 1767 * if a security manager exists and its <code>checkExit</code> 1768 * method doesn't allow the exit. 1769 * 1770 * @see java.lang.Runtime#exit(int) 1771 * @see java.lang.Runtime#gc() 1772 * @see java.lang.SecurityManager#checkExit(int) 1773 * @since 1.1 1774 */ 1775 @Deprecated(since="1.2", forRemoval=true) 1776 @SuppressWarnings("removal") 1777 public static void runFinalizersOnExit(boolean value) { 1778 Runtime.runFinalizersOnExit(value); 1779 } 1780 1781 /** 1782 * Loads the native library specified by the filename argument. The filename 1783 * argument must be an absolute path name. 1784 * 1785 * If the filename argument, when stripped of any platform-specific library 1786 * prefix, path, and file extension, indicates a library whose name is, 1787 * for example, L, and a native library called L is statically linked 1788 * with the VM, then the JNI_OnLoad_L function exported by the library 1789 * is invoked rather than attempting to load a dynamic library. 1790 * A filename matching the argument does not have to exist in the 1791 * file system. 1792 * See the JNI Specification for more details. 1793 * 1794 * Otherwise, the filename argument is mapped to a native library image in 1795 * an implementation-dependent manner. 1796 * 1797 * <p> 1798 * The call <code>System.load(name)</code> is effectively equivalent 1799 * to the call: 1800 * <blockquote><pre> 1801 * Runtime.getRuntime().load(name) 1802 * </pre></blockquote> 1803 * 1804 * @param filename the file to load. 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 filename is not an 1809 * absolute path name, the native library is not statically 1810 * linked with the VM, or the library cannot be mapped to 1811 * a native library image by the host system. 1812 * @exception NullPointerException if <code>filename</code> is 1813 * <code>null</code> 1814 * @see java.lang.Runtime#load(java.lang.String) 1815 * @see java.lang.SecurityManager#checkLink(java.lang.String) 1816 */ 1817 @CallerSensitive 1818 public static void load(String filename) { 1819 Runtime.getRuntime().load0(Reflection.getCallerClass(), filename); 1820 } 1821 1822 /** 1823 * Loads the native library specified by the <code>libname</code> 1824 * argument. The <code>libname</code> argument must not contain any platform 1825 * specific prefix, file extension or path. If a native library 1826 * called <code>libname</code> is statically linked with the VM, then the 1827 * JNI_OnLoad_<code>libname</code> function exported by the library is invoked. 1828 * See the JNI Specification for more details. 1829 * 1830 * Otherwise, the libname argument is loaded from a system library 1831 * location and mapped to a native library image in an implementation- 1832 * dependent manner. 1833 * <p> 1834 * The call <code>System.loadLibrary(name)</code> is effectively 1835 * equivalent to the call 1836 * <blockquote><pre> 1837 * Runtime.getRuntime().loadLibrary(name) 1838 * </pre></blockquote> 1839 * 1840 * @param libname the name of the library. 1841 * @exception SecurityException if a security manager exists and its 1842 * <code>checkLink</code> method doesn't allow 1843 * loading of the specified dynamic library 1844 * @exception UnsatisfiedLinkError if either the libname argument 1845 * contains a file path, the native library is not statically 1846 * linked with the VM, or the library cannot be mapped to a 1847 * native library image by the host system. 1848 * @exception NullPointerException if <code>libname</code> is 1849 * <code>null</code> 1850 * @see java.lang.Runtime#loadLibrary(java.lang.String) 1851 * @see java.lang.SecurityManager#checkLink(java.lang.String) 1852 */ 1853 @CallerSensitive 1854 public static void loadLibrary(String libname) { 1855 Runtime.getRuntime().loadLibrary0(Reflection.getCallerClass(), libname); 1856 } 1857 1858 /** 1859 * Maps a library name into a platform-specific string representing 1860 * a native library. 1861 * 1862 * @param libname the name of the library. 1863 * @return a platform-dependent native library name. 1864 * @exception NullPointerException if <code>libname</code> is 1865 * <code>null</code> 1866 * @see java.lang.System#loadLibrary(java.lang.String) 1867 * @see java.lang.ClassLoader#findLibrary(java.lang.String) 1868 * @since 1.2 1869 */ 1870 public static native String mapLibraryName(String libname); 1871 1872 /** 1873 * Create PrintStream for stdout/err based on encoding. 1874 */ 1875 private static PrintStream newPrintStream(FileOutputStream fos, String enc) { 1876 if (enc != null) { 1877 try { 1878 return new PrintStream(new BufferedOutputStream(fos, 128), true, enc); 1879 } catch (UnsupportedEncodingException uee) {} 1880 } 1881 return new PrintStream(new BufferedOutputStream(fos, 128), true); 1882 } 1883 1884 /** 1885 * Logs an exception/error at initialization time to stdout or stderr. 1886 * 1887 * @param printToStderr to print to stderr rather than stdout 1888 * @param printStackTrace to print the stack trace 1889 * @param msg the message to print before the exception, can be {@code null} 1890 * @param e the exception or error 1891 */ 1892 private static void logInitException(boolean printToStderr, 1893 boolean printStackTrace, 1894 String msg, 1895 Throwable e) { 1896 if (VM.initLevel() < 1) { 1897 throw new InternalError("system classes not initialized"); 1898 } 1899 PrintStream log = (printToStderr) ? err : out; 1900 if (msg != null) { 1901 log.println(msg); 1902 } 1903 if (printStackTrace) { 1904 e.printStackTrace(log); 1905 } else { 1906 log.println(e); 1907 for (Throwable suppressed : e.getSuppressed()) { 1908 log.println("Suppressed: " + suppressed); 1909 } 1910 Throwable cause = e.getCause(); 1911 if (cause != null) { 1912 log.println("Caused by: " + cause); 1913 } 1914 } 1915 } 1916 1917 /** 1918 * Initialize the system class. Called after thread initialization. 1919 */ 1920 private static void initPhase1() { 1921 1922 // VM might invoke JNU_NewStringPlatform() to set those encoding 1923 // sensitive properties (user.home, user.name, boot.class.path, etc.) 1924 // during "props" initialization, in which it may need access, via 1925 // System.getProperty(), to the related system encoding property that 1926 // have been initialized (put into "props") at early stage of the 1927 // initialization. So make sure the "props" is available at the 1928 // very beginning of the initialization and all system properties to 1929 // be put into it directly. 1930 props = new Properties(); 1931 initProperties(props); // initialized by the VM 1932 1933 // There are certain system configurations that may be controlled by 1934 // VM options such as the maximum amount of direct memory and 1935 // Integer cache size used to support the object identity semantics 1936 // of autoboxing. Typically, the library will obtain these values 1937 // from the properties set by the VM. If the properties are for 1938 // internal implementation use only, these properties should be 1939 // removed from the system properties. 1940 // 1941 // See java.lang.Integer.IntegerCache and the 1942 // VM.saveAndRemoveProperties method for example. 1943 // 1944 // Save a private copy of the system properties object that 1945 // can only be accessed by the internal implementation. Remove 1946 // certain system properties that are not intended for public access. 1947 VM.saveAndRemoveProperties(props); 1948 1949 lineSeparator = props.getProperty("line.separator"); 1950 VersionProps.init(); 1951 1952 FileInputStream fdIn = new FileInputStream(FileDescriptor.in); 1953 FileOutputStream fdOut = new FileOutputStream(FileDescriptor.out); 1954 FileOutputStream fdErr = new FileOutputStream(FileDescriptor.err); 1955 setIn0(new BufferedInputStream(fdIn)); 1956 setOut0(newPrintStream(fdOut, props.getProperty("sun.stdout.encoding"))); 1957 setErr0(newPrintStream(fdErr, props.getProperty("sun.stderr.encoding"))); 1958 1959 // Load the zip library now in order to keep java.util.zip.ZipFile 1960 // from trying to use itself to load this library later. 1961 loadLibrary("zip"); 1962 1963 // Setup Java signal handlers for HUP, TERM, and INT (where available). 1964 Terminator.setup(); 1965 1966 // Initialize any miscellaneous operating system settings that need to be 1967 // set for the class libraries. Currently this is no-op everywhere except 1968 // for Windows where the process-wide error mode is set before the java.io 1969 // classes are used. 1970 VM.initializeOSEnvironment(); 1971 1972 // The main thread is not added to its thread group in the same 1973 // way as other threads; we must do it ourselves here. 1974 Thread current = Thread.currentThread(); 1975 current.getThreadGroup().add(current); 1976 1977 // register shared secrets 1978 setJavaLangAccess(); 1979 1980 // Subsystems that are invoked during initialization can invoke 1981 // VM.isBooted() in order to avoid doing things that should 1982 // wait until the VM is fully initialized. The initialization level 1983 // is incremented from 0 to 1 here to indicate the first phase of 1984 // initialization has completed. 1985 // IMPORTANT: Ensure that this remains the last initialization action! 1986 VM.initLevel(1); 1987 } 1988 1989 // @see #initPhase2() 1990 static ModuleLayer bootLayer; 1991 1992 /* 1993 * Invoked by VM. Phase 2 module system initialization. 1994 * Only classes in java.base can be loaded in this phase. 1995 * 1996 * @param printToStderr print exceptions to stderr rather than stdout 1997 * @param printStackTrace print stack trace when exception occurs 1998 * 1999 * @return JNI_OK for success, JNI_ERR for failure 2000 */ 2001 private static int initPhase2(boolean printToStderr, boolean printStackTrace) { 2002 try { 2003 bootLayer = ModuleBootstrap.boot(); 2004 } catch (Exception | Error e) { 2005 logInitException(printToStderr, printStackTrace, 2006 "Error occurred during initialization of boot layer", e); 2007 return -1; // JNI_ERR 2008 } 2009 2010 // module system initialized 2011 VM.initLevel(2); 2012 2013 return 0; // JNI_OK 2014 } 2015 2016 /* 2017 * Invoked by VM. Phase 3 is the final system initialization: 2018 * 1. set security manager 2019 * 2. set system class loader 2020 * 3. set TCCL 2021 * 2022 * This method must be called after the module system initialization. 2023 * The security manager and system class loader may be custom class from 2024 * the application classpath or modulepath. 2025 */ 2026 private static void initPhase3() { 2027 // set security manager 2028 String cn = System.getProperty("java.security.manager"); 2029 if (cn != null) { 2030 if (cn.isEmpty() || "default".equals(cn)) { 2031 System.setSecurityManager(new SecurityManager()); 2032 } else { 2033 try { 2034 Class<?> c = Class.forName(cn, false, ClassLoader.getBuiltinAppClassLoader()); 2035 Constructor<?> ctor = c.getConstructor(); 2036 // Must be a public subclass of SecurityManager with 2037 // a public no-arg constructor 2038 if (!SecurityManager.class.isAssignableFrom(c) || 2039 !Modifier.isPublic(c.getModifiers()) || 2040 !Modifier.isPublic(ctor.getModifiers())) { 2041 throw new Error("Could not create SecurityManager: " + ctor.toString()); 2042 } 2043 // custom security manager implementation may be in unnamed module 2044 // or a named module but non-exported package 2045 ctor.setAccessible(true); 2046 SecurityManager sm = (SecurityManager) ctor.newInstance(); 2047 System.setSecurityManager(sm); 2048 } catch (Exception e) { 2049 throw new Error("Could not create SecurityManager", e); 2050 } 2051 } 2052 } 2053 2054 // initializing the system class loader 2055 VM.initLevel(3); 2056 2057 // system class loader initialized 2058 ClassLoader scl = ClassLoader.initSystemClassLoader(); 2059 2060 // set TCCL 2061 Thread.currentThread().setContextClassLoader(scl); 2062 2063 // system is fully initialized 2064 VM.initLevel(4); 2065 } 2066 2067 private static void setJavaLangAccess() { 2068 // Allow privileged classes outside of java.lang 2069 SharedSecrets.setJavaLangAccess(new JavaLangAccess() { 2070 public Method getMethodOrNull(Class<?> klass, String name, Class<?>... parameterTypes) { 2071 return klass.getMethodOrNull(name, parameterTypes); 2072 } 2073 public jdk.internal.reflect.ConstantPool getConstantPool(Class<?> klass) { 2074 return klass.getConstantPool(); 2075 } 2076 public boolean casAnnotationType(Class<?> klass, AnnotationType oldType, AnnotationType newType) { 2077 return klass.casAnnotationType(oldType, newType); 2078 } 2079 public AnnotationType getAnnotationType(Class<?> klass) { 2080 return klass.getAnnotationType(); 2081 } 2082 public Map<Class<? extends Annotation>, Annotation> getDeclaredAnnotationMap(Class<?> klass) { 2083 return klass.getDeclaredAnnotationMap(); 2084 } 2085 public byte[] getRawClassAnnotations(Class<?> klass) { 2086 return klass.getRawAnnotations(); 2087 } 2088 public byte[] getRawClassTypeAnnotations(Class<?> klass) { 2089 return klass.getRawTypeAnnotations(); 2090 } 2091 public byte[] getRawExecutableTypeAnnotations(Executable executable) { 2092 return Class.getExecutableTypeAnnotationBytes(executable); 2093 } 2094 public <E extends Enum<E>> 2095 E[] getEnumConstantsShared(Class<E> klass) { 2096 return klass.getEnumConstantsShared(); 2097 } 2098 public void blockedOn(Thread t, Interruptible b) { 2099 t.blockedOn(b); 2100 } 2101 public void registerShutdownHook(int slot, boolean registerShutdownInProgress, Runnable hook) { 2102 Shutdown.add(slot, registerShutdownInProgress, hook); 2103 } 2104 public String newStringUnsafe(char[] chars) { 2105 return new String(chars, true); 2106 } 2107 public Thread newThreadWithAcc(Runnable target, AccessControlContext acc) { 2108 return new Thread(target, acc); 2109 } 2110 @SuppressWarnings("deprecation") 2111 public void invokeFinalize(Object o) throws Throwable { 2112 o.finalize(); 2113 } 2114 public ConcurrentHashMap<?, ?> createOrGetClassLoaderValueMap(ClassLoader cl) { 2115 return cl.createOrGetClassLoaderValueMap(); 2116 } 2117 public Class<?> defineClass(ClassLoader loader, String name, byte[] b, ProtectionDomain pd, String source) { 2118 return ClassLoader.defineClass1(loader, name, b, 0, b.length, pd, source); 2119 } 2120 public Class<?> findBootstrapClassOrNull(ClassLoader cl, String name) { 2121 return cl.findBootstrapClassOrNull(name); 2122 } 2123 public Stream<Package> packages(ClassLoader cl) { 2124 return cl.packages(); 2125 } 2126 public Package definePackage(ClassLoader cl, String name, Module module) { 2127 return cl.definePackage(name, module); 2128 } 2129 public String fastUUID(long lsb, long msb) { 2130 return Long.fastUUID(lsb, msb); 2131 } 2132 public void addNonExportedPackages(ModuleLayer layer) { 2133 SecurityManager.addNonExportedPackages(layer); 2134 } 2135 public void invalidatePackageAccessCache() { 2136 SecurityManager.invalidatePackageAccessCache(); 2137 } 2138 public Module defineModule(ClassLoader loader, 2139 ModuleDescriptor descriptor, 2140 URI uri) { 2141 return new Module(null, loader, descriptor, uri); 2142 } 2143 public Module defineUnnamedModule(ClassLoader loader) { 2144 return new Module(loader); 2145 } 2146 public void addReads(Module m1, Module m2) { 2147 m1.implAddReads(m2); 2148 } 2149 public void addReadsAllUnnamed(Module m) { 2150 m.implAddReadsAllUnnamed(); 2151 } 2152 public void addExports(Module m, String pn, Module other) { 2153 m.implAddExports(pn, other); 2154 } 2155 public void addExportsToAllUnnamed(Module m, String pn) { 2156 m.implAddExportsToAllUnnamed(pn); 2157 } 2158 public void addOpens(Module m, String pn, Module other) { 2159 m.implAddOpens(pn, other); 2160 } 2161 public void addOpensToAllUnnamed(Module m, String pn) { 2162 m.implAddOpensToAllUnnamed(pn); 2163 } 2164 public void addUses(Module m, Class<?> service) { 2165 m.implAddUses(service); 2166 } 2167 public ServicesCatalog getServicesCatalog(ModuleLayer layer) { 2168 return layer.getServicesCatalog(); 2169 } 2170 public Stream<ModuleLayer> layers(ModuleLayer layer) { 2171 return layer.layers(); 2172 } 2173 public Stream<ModuleLayer> layers(ClassLoader loader) { 2174 return ModuleLayer.layers(loader); 2175 } 2176 }); 2177 } 2178 }