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