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