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