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