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