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