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