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