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