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