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