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