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