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