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