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