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