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