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