1 /* 2 * Copyright (c) 1994, 2023, 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.javac.PreviewFeature; 81 import jdk.internal.logger.LoggerFinderLoader; 82 import jdk.internal.logger.LazyLoggers; 83 import jdk.internal.logger.LocalizedLoggerWrapper; 84 import jdk.internal.misc.VM; 85 import jdk.internal.util.SystemProps; 86 import jdk.internal.vm.Continuation; 87 import jdk.internal.vm.ContinuationScope; 88 import jdk.internal.vm.StackableScope; 89 import jdk.internal.vm.ThreadContainer; 90 import jdk.internal.vm.annotation.ForceInline; 91 import jdk.internal.vm.annotation.IntrinsicCandidate; 92 import jdk.internal.vm.annotation.Stable; 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 os.name}</th> 765 * <td>Operating system name</td></tr> 766 * <tr><th scope="row">{@systemProperty os.arch}</th> 767 * <td>Operating system architecture</td></tr> 768 * <tr><th scope="row">{@systemProperty os.version}</th> 769 * <td>Operating system version</td></tr> 770 * <tr><th scope="row">{@systemProperty file.separator}</th> 771 * <td>File separator ("/" on UNIX)</td></tr> 772 * <tr><th scope="row">{@systemProperty path.separator}</th> 773 * <td>Path separator (":" on UNIX)</td></tr> 774 * <tr><th scope="row">{@systemProperty line.separator}</th> 775 * <td>Line separator ("\n" on UNIX)</td></tr> 776 * <tr><th scope="row">{@systemProperty user.name}</th> 777 * <td>User's account name</td></tr> 778 * <tr><th scope="row">{@systemProperty user.home}</th> 779 * <td>User's home directory</td></tr> 780 * <tr><th scope="row">{@systemProperty user.dir}</th> 781 * <td>User's current working directory</td></tr> 782 * <tr><th scope="row">{@systemProperty native.encoding}</th> 783 * <td>Character encoding name derived from the host environment and/or 784 * the user's settings. Setting this system property has no effect.</td></tr> 785 * <tr><th scope="row">{@systemProperty stdout.encoding}</th> 786 * <td>Character encoding name for {@link System#out System.out}. 787 * The Java runtime can be started with the system property set to {@code UTF-8}, 788 * starting it with the property set to another value leads to undefined behavior. 789 * <tr><th scope="row">{@systemProperty stderr.encoding}</th> 790 * <td>Character encoding name for {@link System#err System.err}. 791 * The Java runtime can be started with the system property set to {@code UTF-8}, 792 * starting it with the property set to another value leads to undefined behavior. 793 * </tbody> 794 * </table> 795 * <p> 796 * The {@code java.specification.maintenance.version} property is 797 * defined if the specification implemented by this runtime at the 798 * time of its construction had undergone a <a 799 * href="https://jcp.org/en/procedures/jcp2#3.6.4">maintenance 800 * release</a>. When defined, its value identifies that 801 * maintenance release. To indicate the first maintenance release 802 * this property will have the value {@code "1"}, to indicate the 803 * second maintenance release this property will have the value 804 * {@code "2"}, and so on. 805 * <p> 806 * Multiple paths in a system property value are separated by the path 807 * separator character of the platform. 808 * <p> 809 * Note that even if the security manager does not permit the 810 * {@code getProperties} operation, it may choose to permit the 811 * {@link #getProperty(String)} operation. 812 * 813 * @apiNote 814 * <strong>Changing a standard system property may have unpredictable results 815 * unless otherwise specified.</strong> 816 * Property values may be cached during initialization or on first use. 817 * Setting a standard property after initialization using {@link #getProperties()}, 818 * {@link #setProperties(Properties)}, {@link #setProperty(String, String)}, or 819 * {@link #clearProperty(String)} may not have the desired effect. 820 * 821 * @implNote 822 * In addition to the standard system properties, the system 823 * properties may include the following keys: 824 * <table class="striped"> 825 * <caption style="display:none">Shows property keys and associated values</caption> 826 * <thead> 827 * <tr><th scope="col">Key</th> 828 * <th scope="col">Description of Associated Value</th></tr> 829 * </thead> 830 * <tbody> 831 * <tr><th scope="row">{@systemProperty jdk.module.path}</th> 832 * <td>The application module path</td></tr> 833 * <tr><th scope="row">{@systemProperty jdk.module.upgrade.path}</th> 834 * <td>The upgrade module path</td></tr> 835 * <tr><th scope="row">{@systemProperty jdk.module.main}</th> 836 * <td>The module name of the initial/main module</td></tr> 837 * <tr><th scope="row">{@systemProperty jdk.module.main.class}</th> 838 * <td>The main class name of the initial module</td></tr> 839 * <tr><th scope="row">{@systemProperty file.encoding}</th> 840 * <td>The name of the default charset, defaults to {@code UTF-8}. 841 * The property may be set on the command line to the value 842 * {@code UTF-8} or {@code COMPAT}. If set on the command line to 843 * the value {@code COMPAT} then the value is replaced with the 844 * value of the {@code native.encoding} property during startup. 845 * Setting the property to a value other than {@code UTF-8} or 846 * {@code COMPAT} leads to unspecified behavior. 847 * </td></tr> 848 * </tbody> 849 * </table> 850 * 851 * @return the system properties 852 * @throws SecurityException if a security manager exists and its 853 * {@code checkPropertiesAccess} method doesn't allow access 854 * to the system properties. 855 * @see #setProperties 856 * @see java.lang.SecurityException 857 * @see java.lang.SecurityManager#checkPropertiesAccess() 858 * @see java.util.Properties 859 */ 860 public static Properties getProperties() { 861 @SuppressWarnings("removal") 862 SecurityManager sm = getSecurityManager(); 863 if (sm != null) { 864 sm.checkPropertiesAccess(); 865 } 866 867 return props; 868 } 869 870 /** 871 * Returns the system-dependent line separator string. It always 872 * returns the same value - the initial value of the {@linkplain 873 * #getProperty(String) system property} {@code line.separator}. 874 * 875 * <p>On UNIX systems, it returns {@code "\n"}; on Microsoft 876 * Windows systems it returns {@code "\r\n"}. 877 * 878 * @return the system-dependent line separator string 879 * @since 1.7 880 */ 881 public static String lineSeparator() { 882 return lineSeparator; 883 } 884 885 private static String lineSeparator; 886 887 /** 888 * Sets the system properties to the {@code Properties} argument. 889 * 890 * First, if there is a security manager, its 891 * {@code checkPropertiesAccess} method is called with no 892 * arguments. This may result in a security exception. 893 * <p> 894 * The argument becomes the current set of system properties for use 895 * by the {@link #getProperty(String)} method. If the argument is 896 * {@code null}, then the current set of system properties is 897 * forgotten. 898 * 899 * @apiNote 900 * <strong>Changing a standard system property may have unpredictable results 901 * unless otherwise specified</strong>. 902 * See {@linkplain #getProperties getProperties} for details. 903 * 904 * @param props the new system properties. 905 * @throws SecurityException if a security manager exists and its 906 * {@code checkPropertiesAccess} method doesn't allow access 907 * to the system properties. 908 * @see #getProperties 909 * @see java.util.Properties 910 * @see java.lang.SecurityException 911 * @see java.lang.SecurityManager#checkPropertiesAccess() 912 */ 913 public static void setProperties(Properties props) { 914 @SuppressWarnings("removal") 915 SecurityManager sm = getSecurityManager(); 916 if (sm != null) { 917 sm.checkPropertiesAccess(); 918 } 919 920 if (props == null) { 921 Map<String, String> tempProps = SystemProps.initProperties(); 922 VersionProps.init(tempProps); 923 props = createProperties(tempProps); 924 } 925 System.props = props; 926 } 927 928 /** 929 * Gets the system property indicated by the specified key. 930 * 931 * First, if there is a security manager, its 932 * {@code checkPropertyAccess} method is called with the key as 933 * its argument. This may result in a SecurityException. 934 * <p> 935 * If there is no current set of system properties, a set of system 936 * properties is first created and initialized in the same manner as 937 * for the {@code getProperties} method. 938 * 939 * @apiNote 940 * <strong>Changing a standard system property may have unpredictable results 941 * unless otherwise specified</strong>. 942 * See {@linkplain #getProperties getProperties} for details. 943 * 944 * @param key the name of the system property. 945 * @return the string value of the system property, 946 * or {@code null} if there is no property with that key. 947 * 948 * @throws SecurityException if a security manager exists and its 949 * {@code checkPropertyAccess} method doesn't allow 950 * access to the specified system property. 951 * @throws NullPointerException if {@code key} is {@code null}. 952 * @throws IllegalArgumentException if {@code key} is empty. 953 * @see #setProperty 954 * @see java.lang.SecurityException 955 * @see java.lang.SecurityManager#checkPropertyAccess(java.lang.String) 956 * @see java.lang.System#getProperties() 957 */ 958 public static String getProperty(String key) { 959 checkKey(key); 960 @SuppressWarnings("removal") 961 SecurityManager sm = getSecurityManager(); 962 if (sm != null) { 963 sm.checkPropertyAccess(key); 964 } 965 966 return props.getProperty(key); 967 } 968 969 /** 970 * Gets the system property indicated by the specified key. 971 * 972 * First, if there is a security manager, its 973 * {@code checkPropertyAccess} method is called with the 974 * {@code key} as its argument. 975 * <p> 976 * If there is no current set of system properties, a set of system 977 * properties is first created and initialized in the same manner as 978 * for the {@code getProperties} method. 979 * 980 * @param key the name of the system property. 981 * @param def a default value. 982 * @return the string value of the system property, 983 * or the default value if there is no property with that key. 984 * 985 * @throws SecurityException if a security manager exists and its 986 * {@code checkPropertyAccess} method doesn't allow 987 * access to the specified system property. 988 * @throws NullPointerException if {@code key} is {@code null}. 989 * @throws IllegalArgumentException if {@code key} is empty. 990 * @see #setProperty 991 * @see java.lang.SecurityManager#checkPropertyAccess(java.lang.String) 992 * @see java.lang.System#getProperties() 993 */ 994 public static String getProperty(String key, String def) { 995 checkKey(key); 996 @SuppressWarnings("removal") 997 SecurityManager sm = getSecurityManager(); 998 if (sm != null) { 999 sm.checkPropertyAccess(key); 1000 } 1001 1002 return props.getProperty(key, def); 1003 } 1004 1005 /** 1006 * Sets the system property indicated by the specified key. 1007 * 1008 * First, if a security manager exists, its 1009 * {@code SecurityManager.checkPermission} method 1010 * is called with a {@code PropertyPermission(key, "write")} 1011 * permission. This may result in a SecurityException being thrown. 1012 * If no exception is thrown, the specified property is set to the given 1013 * value. 1014 * 1015 * @apiNote 1016 * <strong>Changing a standard system property may have unpredictable results 1017 * unless otherwise specified</strong>. 1018 * See {@linkplain #getProperties getProperties} for details. 1019 * 1020 * @param key the name of the system property. 1021 * @param value the value of the system property. 1022 * @return the previous value of the system property, 1023 * or {@code null} if it did not have one. 1024 * 1025 * @throws SecurityException if a security manager exists and its 1026 * {@code checkPermission} method doesn't allow 1027 * setting of the specified property. 1028 * @throws NullPointerException if {@code key} or 1029 * {@code value} is {@code null}. 1030 * @throws IllegalArgumentException if {@code key} is empty. 1031 * @see #getProperty 1032 * @see java.lang.System#getProperty(java.lang.String) 1033 * @see java.lang.System#getProperty(java.lang.String, java.lang.String) 1034 * @see java.util.PropertyPermission 1035 * @see SecurityManager#checkPermission 1036 * @since 1.2 1037 */ 1038 public static String setProperty(String key, String value) { 1039 checkKey(key); 1040 @SuppressWarnings("removal") 1041 SecurityManager sm = getSecurityManager(); 1042 if (sm != null) { 1043 sm.checkPermission(new PropertyPermission(key, 1044 SecurityConstants.PROPERTY_WRITE_ACTION)); 1045 } 1046 1047 return (String) props.setProperty(key, value); 1048 } 1049 1050 /** 1051 * Removes the system property indicated by the specified key. 1052 * 1053 * First, if a security manager exists, its 1054 * {@code SecurityManager.checkPermission} method 1055 * is called with a {@code PropertyPermission(key, "write")} 1056 * permission. This may result in a SecurityException being thrown. 1057 * If no exception is thrown, the specified property is removed. 1058 * 1059 * @apiNote 1060 * <strong>Changing a standard system property may have unpredictable results 1061 * unless otherwise specified</strong>. 1062 * See {@linkplain #getProperties getProperties} method for details. 1063 * 1064 * @param key the name of the system property to be removed. 1065 * @return the previous string value of the system property, 1066 * or {@code null} if there was no property with that key. 1067 * 1068 * @throws SecurityException if a security manager exists and its 1069 * {@code checkPropertyAccess} method doesn't allow 1070 * access to the specified system property. 1071 * @throws NullPointerException if {@code key} is {@code null}. 1072 * @throws IllegalArgumentException if {@code key} is empty. 1073 * @see #getProperty 1074 * @see #setProperty 1075 * @see java.util.Properties 1076 * @see java.lang.SecurityException 1077 * @see java.lang.SecurityManager#checkPropertiesAccess() 1078 * @since 1.5 1079 */ 1080 public static String clearProperty(String key) { 1081 checkKey(key); 1082 @SuppressWarnings("removal") 1083 SecurityManager sm = getSecurityManager(); 1084 if (sm != null) { 1085 sm.checkPermission(new PropertyPermission(key, "write")); 1086 } 1087 1088 return (String) props.remove(key); 1089 } 1090 1091 private static void checkKey(String key) { 1092 if (key == null) { 1093 throw new NullPointerException("key can't be null"); 1094 } 1095 if (key.isEmpty()) { 1096 throw new IllegalArgumentException("key can't be empty"); 1097 } 1098 } 1099 1100 /** 1101 * Gets the value of the specified environment variable. An 1102 * environment variable is a system-dependent external named 1103 * value. 1104 * 1105 * <p>If a security manager exists, its 1106 * {@link SecurityManager#checkPermission checkPermission} 1107 * method is called with a 1108 * {@link RuntimePermission RuntimePermission("getenv."+name)} 1109 * permission. This may result in a {@link SecurityException} 1110 * being thrown. If no exception is thrown the value of the 1111 * variable {@code name} is returned. 1112 * 1113 * <p><a id="EnvironmentVSSystemProperties"><i>System 1114 * properties</i> and <i>environment variables</i></a> are both 1115 * conceptually mappings between names and values. Both 1116 * mechanisms can be used to pass user-defined information to a 1117 * Java process. Environment variables have a more global effect, 1118 * because they are visible to all descendants of the process 1119 * which defines them, not just the immediate Java subprocess. 1120 * They can have subtly different semantics, such as case 1121 * insensitivity, on different operating systems. For these 1122 * reasons, environment variables are more likely to have 1123 * unintended side effects. It is best to use system properties 1124 * where possible. Environment variables should be used when a 1125 * global effect is desired, or when an external system interface 1126 * requires an environment variable (such as {@code PATH}). 1127 * 1128 * <p>On UNIX systems the alphabetic case of {@code name} is 1129 * typically significant, while on Microsoft Windows systems it is 1130 * typically not. For example, the expression 1131 * {@code System.getenv("FOO").equals(System.getenv("foo"))} 1132 * is likely to be true on Microsoft Windows. 1133 * 1134 * @param name the name of the environment variable 1135 * @return the string value of the variable, or {@code null} 1136 * if the variable is not defined in the system environment 1137 * @throws NullPointerException if {@code name} is {@code null} 1138 * @throws SecurityException 1139 * if a security manager exists and its 1140 * {@link SecurityManager#checkPermission checkPermission} 1141 * method doesn't allow access to the environment variable 1142 * {@code name} 1143 * @see #getenv() 1144 * @see ProcessBuilder#environment() 1145 */ 1146 public static String getenv(String name) { 1147 @SuppressWarnings("removal") 1148 SecurityManager sm = getSecurityManager(); 1149 if (sm != null) { 1150 sm.checkPermission(new RuntimePermission("getenv."+name)); 1151 } 1152 1153 return ProcessEnvironment.getenv(name); 1154 } 1155 1156 1157 /** 1158 * Returns an unmodifiable string map view of the current system environment. 1159 * The environment is a system-dependent mapping from names to 1160 * values which is passed from parent to child processes. 1161 * 1162 * <p>If the system does not support environment variables, an 1163 * empty map is returned. 1164 * 1165 * <p>The returned map will never contain null keys or values. 1166 * Attempting to query the presence of a null key or value will 1167 * throw a {@link NullPointerException}. Attempting to query 1168 * the presence of a key or value which is not of type 1169 * {@link String} will throw a {@link ClassCastException}. 1170 * 1171 * <p>The returned map and its collection views may not obey the 1172 * general contract of the {@link Object#equals} and 1173 * {@link Object#hashCode} methods. 1174 * 1175 * <p>The returned map is typically case-sensitive on all platforms. 1176 * 1177 * <p>If a security manager exists, its 1178 * {@link SecurityManager#checkPermission checkPermission} 1179 * method is called with a 1180 * {@link RuntimePermission RuntimePermission("getenv.*")} permission. 1181 * This may result in a {@link SecurityException} being thrown. 1182 * 1183 * <p>When passing information to a Java subprocess, 1184 * <a href=#EnvironmentVSSystemProperties>system properties</a> 1185 * are generally preferred over environment variables. 1186 * 1187 * @return the environment as a map of variable names to values 1188 * @throws SecurityException 1189 * if a security manager exists and its 1190 * {@link SecurityManager#checkPermission checkPermission} 1191 * method doesn't allow access to the process environment 1192 * @see #getenv(String) 1193 * @see ProcessBuilder#environment() 1194 * @since 1.5 1195 */ 1196 public static java.util.Map<String,String> getenv() { 1197 @SuppressWarnings("removal") 1198 SecurityManager sm = getSecurityManager(); 1199 if (sm != null) { 1200 sm.checkPermission(new RuntimePermission("getenv.*")); 1201 } 1202 1203 return ProcessEnvironment.getenv(); 1204 } 1205 1206 /** 1207 * {@code System.Logger} instances log messages that will be 1208 * routed to the underlying logging framework the {@link System.LoggerFinder 1209 * LoggerFinder} uses. 1210 * 1211 * {@code System.Logger} instances are typically obtained from 1212 * the {@link java.lang.System System} class, by calling 1213 * {@link java.lang.System#getLogger(java.lang.String) System.getLogger(loggerName)} 1214 * or {@link java.lang.System#getLogger(java.lang.String, java.util.ResourceBundle) 1215 * System.getLogger(loggerName, bundle)}. 1216 * 1217 * @see java.lang.System#getLogger(java.lang.String) 1218 * @see java.lang.System#getLogger(java.lang.String, java.util.ResourceBundle) 1219 * @see java.lang.System.LoggerFinder 1220 * 1221 * @since 9 1222 */ 1223 public interface Logger { 1224 1225 /** 1226 * System {@linkplain Logger loggers} levels. 1227 * 1228 * A level has a {@linkplain #getName() name} and {@linkplain 1229 * #getSeverity() severity}. 1230 * Level values are {@link #ALL}, {@link #TRACE}, {@link #DEBUG}, 1231 * {@link #INFO}, {@link #WARNING}, {@link #ERROR}, {@link #OFF}, 1232 * by order of increasing severity. 1233 * <br> 1234 * {@link #ALL} and {@link #OFF} 1235 * are simple markers with severities mapped respectively to 1236 * {@link java.lang.Integer#MIN_VALUE Integer.MIN_VALUE} and 1237 * {@link java.lang.Integer#MAX_VALUE Integer.MAX_VALUE}. 1238 * <p> 1239 * <b>Severity values and Mapping to {@code java.util.logging.Level}.</b> 1240 * <p> 1241 * {@linkplain System.Logger.Level System logger levels} are mapped to 1242 * {@linkplain java.logging/java.util.logging.Level java.util.logging levels} 1243 * of corresponding severity. 1244 * <br>The mapping is as follows: 1245 * <br><br> 1246 * <table class="striped"> 1247 * <caption>System.Logger Severity Level Mapping</caption> 1248 * <thead> 1249 * <tr><th scope="col">System.Logger Levels</th> 1250 * <th scope="col">java.util.logging Levels</th> 1251 * </thead> 1252 * <tbody> 1253 * <tr><th scope="row">{@link Logger.Level#ALL ALL}</th> 1254 * <td>{@link java.logging/java.util.logging.Level#ALL ALL}</td> 1255 * <tr><th scope="row">{@link Logger.Level#TRACE TRACE}</th> 1256 * <td>{@link java.logging/java.util.logging.Level#FINER FINER}</td> 1257 * <tr><th scope="row">{@link Logger.Level#DEBUG DEBUG}</th> 1258 * <td>{@link java.logging/java.util.logging.Level#FINE FINE}</td> 1259 * <tr><th scope="row">{@link Logger.Level#INFO INFO}</th> 1260 * <td>{@link java.logging/java.util.logging.Level#INFO INFO}</td> 1261 * <tr><th scope="row">{@link Logger.Level#WARNING WARNING}</th> 1262 * <td>{@link java.logging/java.util.logging.Level#WARNING WARNING}</td> 1263 * <tr><th scope="row">{@link Logger.Level#ERROR ERROR}</th> 1264 * <td>{@link java.logging/java.util.logging.Level#SEVERE SEVERE}</td> 1265 * <tr><th scope="row">{@link Logger.Level#OFF OFF}</th> 1266 * <td>{@link java.logging/java.util.logging.Level#OFF OFF}</td> 1267 * </tbody> 1268 * </table> 1269 * 1270 * @since 9 1271 * 1272 * @see java.lang.System.LoggerFinder 1273 * @see java.lang.System.Logger 1274 */ 1275 @SuppressWarnings("doclint:reference") // cross-module links 1276 public enum Level { 1277 1278 // for convenience, we're reusing java.util.logging.Level int values 1279 // the mapping logic in sun.util.logging.PlatformLogger depends 1280 // on this. 1281 /** 1282 * A marker to indicate that all levels are enabled. 1283 * This level {@linkplain #getSeverity() severity} is 1284 * {@link Integer#MIN_VALUE}. 1285 */ 1286 ALL(Integer.MIN_VALUE), // typically mapped to/from j.u.l.Level.ALL 1287 /** 1288 * {@code TRACE} level: usually used to log diagnostic information. 1289 * This level {@linkplain #getSeverity() severity} is 1290 * {@code 400}. 1291 */ 1292 TRACE(400), // typically mapped to/from j.u.l.Level.FINER 1293 /** 1294 * {@code DEBUG} level: usually used to log debug information traces. 1295 * This level {@linkplain #getSeverity() severity} is 1296 * {@code 500}. 1297 */ 1298 DEBUG(500), // typically mapped to/from j.u.l.Level.FINEST/FINE/CONFIG 1299 /** 1300 * {@code INFO} level: usually used to log information messages. 1301 * This level {@linkplain #getSeverity() severity} is 1302 * {@code 800}. 1303 */ 1304 INFO(800), // typically mapped to/from j.u.l.Level.INFO 1305 /** 1306 * {@code WARNING} level: usually used to log warning messages. 1307 * This level {@linkplain #getSeverity() severity} is 1308 * {@code 900}. 1309 */ 1310 WARNING(900), // typically mapped to/from j.u.l.Level.WARNING 1311 /** 1312 * {@code ERROR} level: usually used to log error messages. 1313 * This level {@linkplain #getSeverity() severity} is 1314 * {@code 1000}. 1315 */ 1316 ERROR(1000), // typically mapped to/from j.u.l.Level.SEVERE 1317 /** 1318 * A marker to indicate that all levels are disabled. 1319 * This level {@linkplain #getSeverity() severity} is 1320 * {@link Integer#MAX_VALUE}. 1321 */ 1322 OFF(Integer.MAX_VALUE); // typically mapped to/from j.u.l.Level.OFF 1323 1324 private final int severity; 1325 1326 private Level(int severity) { 1327 this.severity = severity; 1328 } 1329 1330 /** 1331 * Returns the name of this level. 1332 * @return this level {@linkplain #name()}. 1333 */ 1334 public final String getName() { 1335 return name(); 1336 } 1337 1338 /** 1339 * Returns the severity of this level. 1340 * A higher severity means a more severe condition. 1341 * @return this level severity. 1342 */ 1343 public final int getSeverity() { 1344 return severity; 1345 } 1346 } 1347 1348 /** 1349 * Returns the name of this logger. 1350 * 1351 * @return the logger name. 1352 */ 1353 public String getName(); 1354 1355 /** 1356 * Checks if a message of the given level would be logged by 1357 * this logger. 1358 * 1359 * @param level the log message level. 1360 * @return {@code true} if the given log message level is currently 1361 * being logged. 1362 * 1363 * @throws NullPointerException if {@code level} is {@code null}. 1364 */ 1365 public boolean isLoggable(Level level); 1366 1367 /** 1368 * Logs a message. 1369 * 1370 * @implSpec The default implementation for this method calls 1371 * {@code this.log(level, (ResourceBundle)null, msg, (Object[])null);} 1372 * 1373 * @param level the log message level. 1374 * @param msg the string message (or a key in the message catalog, if 1375 * this logger is a {@link 1376 * LoggerFinder#getLocalizedLogger(java.lang.String, 1377 * java.util.ResourceBundle, java.lang.Module) localized logger}); 1378 * can be {@code null}. 1379 * 1380 * @throws NullPointerException if {@code level} is {@code null}. 1381 */ 1382 public default void log(Level level, String msg) { 1383 log(level, (ResourceBundle) null, msg, (Object[]) null); 1384 } 1385 1386 /** 1387 * Logs a lazily supplied message. 1388 * 1389 * If the logger is currently enabled for the given log message level 1390 * then a message is logged that is the result produced by the 1391 * given supplier function. Otherwise, the supplier is not operated on. 1392 * 1393 * @implSpec When logging is enabled for the given level, the default 1394 * implementation for this method calls 1395 * {@code this.log(level, (ResourceBundle)null, msgSupplier.get(), (Object[])null);} 1396 * 1397 * @param level the log message level. 1398 * @param msgSupplier a supplier function that produces a message. 1399 * 1400 * @throws NullPointerException if {@code level} is {@code null}, 1401 * or {@code msgSupplier} is {@code null}. 1402 */ 1403 public default void log(Level level, Supplier<String> msgSupplier) { 1404 Objects.requireNonNull(msgSupplier); 1405 if (isLoggable(Objects.requireNonNull(level))) { 1406 log(level, (ResourceBundle) null, msgSupplier.get(), (Object[]) null); 1407 } 1408 } 1409 1410 /** 1411 * Logs a message produced from the given object. 1412 * 1413 * If the logger is currently enabled for the given log message level then 1414 * a message is logged that, by default, is the result produced from 1415 * calling toString on the given object. 1416 * Otherwise, the object is not operated on. 1417 * 1418 * @implSpec When logging is enabled for the given level, the default 1419 * implementation for this method calls 1420 * {@code this.log(level, (ResourceBundle)null, obj.toString(), (Object[])null);} 1421 * 1422 * @param level the log message level. 1423 * @param obj the object to log. 1424 * 1425 * @throws NullPointerException if {@code level} is {@code null}, or 1426 * {@code obj} is {@code null}. 1427 */ 1428 public default void log(Level level, Object obj) { 1429 Objects.requireNonNull(obj); 1430 if (isLoggable(Objects.requireNonNull(level))) { 1431 this.log(level, (ResourceBundle) null, obj.toString(), (Object[]) null); 1432 } 1433 } 1434 1435 /** 1436 * Logs a message associated with a given throwable. 1437 * 1438 * @implSpec The default implementation for this method calls 1439 * {@code this.log(level, (ResourceBundle)null, msg, thrown);} 1440 * 1441 * @param level the log message level. 1442 * @param msg the string message (or a key in the message catalog, if 1443 * this logger is a {@link 1444 * LoggerFinder#getLocalizedLogger(java.lang.String, 1445 * java.util.ResourceBundle, java.lang.Module) localized logger}); 1446 * can be {@code null}. 1447 * @param thrown a {@code Throwable} associated with the log message; 1448 * can be {@code null}. 1449 * 1450 * @throws NullPointerException if {@code level} is {@code null}. 1451 */ 1452 public default void log(Level level, String msg, Throwable thrown) { 1453 this.log(level, null, msg, thrown); 1454 } 1455 1456 /** 1457 * Logs a lazily supplied message associated with a given throwable. 1458 * 1459 * If the logger is currently enabled for the given log message level 1460 * then a message is logged that is the result produced by the 1461 * given supplier function. Otherwise, the supplier is not operated on. 1462 * 1463 * @implSpec When logging is enabled for the given level, the default 1464 * implementation for this method calls 1465 * {@code this.log(level, (ResourceBundle)null, msgSupplier.get(), thrown);} 1466 * 1467 * @param level one of the log message level identifiers. 1468 * @param msgSupplier a supplier function that produces a message. 1469 * @param thrown a {@code Throwable} associated with log message; 1470 * can be {@code null}. 1471 * 1472 * @throws NullPointerException if {@code level} is {@code null}, or 1473 * {@code msgSupplier} is {@code null}. 1474 */ 1475 public default void log(Level level, Supplier<String> msgSupplier, 1476 Throwable thrown) { 1477 Objects.requireNonNull(msgSupplier); 1478 if (isLoggable(Objects.requireNonNull(level))) { 1479 this.log(level, null, msgSupplier.get(), thrown); 1480 } 1481 } 1482 1483 /** 1484 * Logs a message with an optional list of parameters. 1485 * 1486 * @implSpec The default implementation for this method calls 1487 * {@code this.log(level, (ResourceBundle)null, format, params);} 1488 * 1489 * @param level one of the log message level identifiers. 1490 * @param format the string message format in {@link 1491 * java.text.MessageFormat} format, (or a key in the message 1492 * catalog, if this logger is a {@link 1493 * LoggerFinder#getLocalizedLogger(java.lang.String, 1494 * java.util.ResourceBundle, java.lang.Module) localized logger}); 1495 * can be {@code null}. 1496 * @param params an optional list of parameters to the message (may be 1497 * none). 1498 * 1499 * @throws NullPointerException if {@code level} is {@code null}. 1500 */ 1501 public default void log(Level level, String format, Object... params) { 1502 this.log(level, null, format, params); 1503 } 1504 1505 /** 1506 * Logs a localized message associated with a given throwable. 1507 * 1508 * If the given resource bundle is non-{@code null}, the {@code msg} 1509 * string is localized using the given resource bundle. 1510 * Otherwise the {@code msg} string is not localized. 1511 * 1512 * @param level the log message level. 1513 * @param bundle a resource bundle to localize {@code msg}; can be 1514 * {@code null}. 1515 * @param msg the string message (or a key in the message catalog, 1516 * if {@code bundle} is not {@code null}); can be {@code null}. 1517 * @param thrown a {@code Throwable} associated with the log message; 1518 * can be {@code null}. 1519 * 1520 * @throws NullPointerException if {@code level} is {@code null}. 1521 */ 1522 public void log(Level level, ResourceBundle bundle, String msg, 1523 Throwable thrown); 1524 1525 /** 1526 * Logs a message with resource bundle and an optional list of 1527 * parameters. 1528 * 1529 * If the given resource bundle is non-{@code null}, the {@code format} 1530 * string is localized using the given resource bundle. 1531 * Otherwise the {@code format} string is not localized. 1532 * 1533 * @param level the log message level. 1534 * @param bundle a resource bundle to localize {@code format}; can be 1535 * {@code null}. 1536 * @param format the string message format in {@link 1537 * java.text.MessageFormat} format, (or a key in the message 1538 * catalog if {@code bundle} is not {@code null}); can be {@code null}. 1539 * @param params an optional list of parameters to the message (may be 1540 * none). 1541 * 1542 * @throws NullPointerException if {@code level} is {@code null}. 1543 */ 1544 public void log(Level level, ResourceBundle bundle, String format, 1545 Object... params); 1546 } 1547 1548 /** 1549 * The {@code LoggerFinder} service is responsible for creating, managing, 1550 * and configuring loggers to the underlying framework it uses. 1551 * 1552 * A logger finder is a concrete implementation of this class that has a 1553 * zero-argument constructor and implements the abstract methods defined 1554 * by this class. 1555 * The loggers returned from a logger finder are capable of routing log 1556 * messages to the logging backend this provider supports. 1557 * A given invocation of the Java Runtime maintains a single 1558 * system-wide LoggerFinder instance that is loaded as follows: 1559 * <ul> 1560 * <li>First it finds any custom {@code LoggerFinder} provider 1561 * using the {@link java.util.ServiceLoader} facility with the 1562 * {@linkplain ClassLoader#getSystemClassLoader() system class 1563 * loader}.</li> 1564 * <li>If no {@code LoggerFinder} provider is found, the system default 1565 * {@code LoggerFinder} implementation will be used.</li> 1566 * </ul> 1567 * <p> 1568 * An application can replace the logging backend 1569 * <i>even when the java.logging module is present</i>, by simply providing 1570 * and declaring an implementation of the {@link LoggerFinder} service. 1571 * <p> 1572 * <b>Default Implementation</b> 1573 * <p> 1574 * The system default {@code LoggerFinder} implementation uses 1575 * {@code java.util.logging} as the backend framework when the 1576 * {@code java.logging} module is present. 1577 * It returns a {@linkplain System.Logger logger} instance 1578 * that will route log messages to a {@link java.logging/java.util.logging.Logger 1579 * java.util.logging.Logger}. Otherwise, if {@code java.logging} is not 1580 * present, the default implementation will return a simple logger 1581 * instance that will route log messages of {@code INFO} level and above to 1582 * the console ({@code System.err}). 1583 * <p> 1584 * <b>Logging Configuration</b> 1585 * <p> 1586 * {@linkplain Logger Logger} instances obtained from the 1587 * {@code LoggerFinder} factory methods are not directly configurable by 1588 * the application. Configuration is the responsibility of the underlying 1589 * logging backend, and usually requires using APIs specific to that backend. 1590 * <p>For the default {@code LoggerFinder} implementation 1591 * using {@code java.util.logging} as its backend, refer to 1592 * {@link java.logging/java.util.logging java.util.logging} for logging configuration. 1593 * For the default {@code LoggerFinder} implementation returning simple loggers 1594 * when the {@code java.logging} module is absent, the configuration 1595 * is implementation dependent. 1596 * <p> 1597 * Usually an application that uses a logging framework will log messages 1598 * through a logger facade defined (or supported) by that framework. 1599 * Applications that wish to use an external framework should log 1600 * through the facade associated with that framework. 1601 * <p> 1602 * A system class that needs to log messages will typically obtain 1603 * a {@link System.Logger} instance to route messages to the logging 1604 * framework selected by the application. 1605 * <p> 1606 * Libraries and classes that only need loggers to produce log messages 1607 * should not attempt to configure loggers by themselves, as that 1608 * would make them dependent from a specific implementation of the 1609 * {@code LoggerFinder} service. 1610 * <p> 1611 * In addition, when a security manager is present, loggers provided to 1612 * system classes should not be directly configurable through the logging 1613 * backend without requiring permissions. 1614 * <br> 1615 * It is the responsibility of the provider of 1616 * the concrete {@code LoggerFinder} implementation to ensure that 1617 * these loggers are not configured by untrusted code without proper 1618 * permission checks, as configuration performed on such loggers usually 1619 * affects all applications in the same Java Runtime. 1620 * <p> 1621 * <b>Message Levels and Mapping to backend levels</b> 1622 * <p> 1623 * A logger finder is responsible for mapping from a {@code 1624 * System.Logger.Level} to a level supported by the logging backend it uses. 1625 * <br>The default LoggerFinder using {@code java.util.logging} as the backend 1626 * maps {@code System.Logger} levels to 1627 * {@linkplain java.logging/java.util.logging.Level java.util.logging} levels 1628 * of corresponding severity - as described in {@link Logger.Level 1629 * Logger.Level}. 1630 * 1631 * @see java.lang.System 1632 * @see java.lang.System.Logger 1633 * 1634 * @since 9 1635 */ 1636 @SuppressWarnings("doclint:reference") // cross-module links 1637 public abstract static class LoggerFinder { 1638 /** 1639 * The {@code RuntimePermission("loggerFinder")} is 1640 * necessary to subclass and instantiate the {@code LoggerFinder} class, 1641 * as well as to obtain loggers from an instance of that class. 1642 */ 1643 static final RuntimePermission LOGGERFINDER_PERMISSION = 1644 new RuntimePermission("loggerFinder"); 1645 1646 /** 1647 * Creates a new instance of {@code LoggerFinder}. 1648 * 1649 * @implNote It is recommended that a {@code LoggerFinder} service 1650 * implementation does not perform any heavy initialization in its 1651 * constructor, in order to avoid possible risks of deadlock or class 1652 * loading cycles during the instantiation of the service provider. 1653 * 1654 * @throws SecurityException if a security manager is present and its 1655 * {@code checkPermission} method doesn't allow the 1656 * {@code RuntimePermission("loggerFinder")}. 1657 */ 1658 protected LoggerFinder() { 1659 this(checkPermission()); 1660 } 1661 1662 private LoggerFinder(Void unused) { 1663 // nothing to do. 1664 } 1665 1666 private static Void checkPermission() { 1667 @SuppressWarnings("removal") 1668 final SecurityManager sm = System.getSecurityManager(); 1669 if (sm != null) { 1670 sm.checkPermission(LOGGERFINDER_PERMISSION); 1671 } 1672 return null; 1673 } 1674 1675 /** 1676 * Returns an instance of {@link Logger Logger} 1677 * for the given {@code module}. 1678 * 1679 * @param name the name of the logger. 1680 * @param module the module for which the logger is being requested. 1681 * 1682 * @return a {@link Logger logger} suitable for use within the given 1683 * module. 1684 * @throws NullPointerException if {@code name} is {@code null} or 1685 * {@code module} is {@code null}. 1686 * @throws SecurityException if a security manager is present and its 1687 * {@code checkPermission} method doesn't allow the 1688 * {@code RuntimePermission("loggerFinder")}. 1689 */ 1690 public abstract Logger getLogger(String name, Module module); 1691 1692 /** 1693 * Returns a localizable instance of {@link Logger Logger} 1694 * for the given {@code module}. 1695 * The returned logger will use the provided resource bundle for 1696 * message localization. 1697 * 1698 * @implSpec By default, this method calls {@link 1699 * #getLogger(java.lang.String, java.lang.Module) 1700 * this.getLogger(name, module)} to obtain a logger, then wraps that 1701 * logger in a {@link Logger} instance where all methods that do not 1702 * take a {@link ResourceBundle} as parameter are redirected to one 1703 * which does - passing the given {@code bundle} for 1704 * localization. So for instance, a call to {@link 1705 * Logger#log(Logger.Level, String) Logger.log(Level.INFO, msg)} 1706 * will end up as a call to {@link 1707 * Logger#log(Logger.Level, ResourceBundle, String, Object...) 1708 * Logger.log(Level.INFO, bundle, msg, (Object[])null)} on the wrapped 1709 * logger instance. 1710 * Note however that by default, string messages returned by {@link 1711 * java.util.function.Supplier Supplier<String>} will not be 1712 * localized, as it is assumed that such strings are messages which are 1713 * already constructed, rather than keys in a resource bundle. 1714 * <p> 1715 * An implementation of {@code LoggerFinder} may override this method, 1716 * for example, when the underlying logging backend provides its own 1717 * mechanism for localizing log messages, then such a 1718 * {@code LoggerFinder} would be free to return a logger 1719 * that makes direct use of the mechanism provided by the backend. 1720 * 1721 * @param name the name of the logger. 1722 * @param bundle a resource bundle; can be {@code null}. 1723 * @param module the module for which the logger is being requested. 1724 * @return an instance of {@link Logger Logger} which will use the 1725 * provided resource bundle for message localization. 1726 * 1727 * @throws NullPointerException if {@code name} is {@code null} or 1728 * {@code module} is {@code null}. 1729 * @throws SecurityException if a security manager is present and its 1730 * {@code checkPermission} method doesn't allow the 1731 * {@code RuntimePermission("loggerFinder")}. 1732 */ 1733 public Logger getLocalizedLogger(String name, ResourceBundle bundle, 1734 Module module) { 1735 return new LocalizedLoggerWrapper<>(getLogger(name, module), bundle); 1736 } 1737 1738 /** 1739 * Returns the {@code LoggerFinder} instance. There is one 1740 * single system-wide {@code LoggerFinder} instance in 1741 * the Java Runtime. See the class specification of how the 1742 * {@link LoggerFinder LoggerFinder} implementation is located and 1743 * loaded. 1744 * 1745 * @return the {@link LoggerFinder LoggerFinder} instance. 1746 * @throws SecurityException if a security manager is present and its 1747 * {@code checkPermission} method doesn't allow the 1748 * {@code RuntimePermission("loggerFinder")}. 1749 */ 1750 public static LoggerFinder getLoggerFinder() { 1751 @SuppressWarnings("removal") 1752 final SecurityManager sm = System.getSecurityManager(); 1753 if (sm != null) { 1754 sm.checkPermission(LOGGERFINDER_PERMISSION); 1755 } 1756 return accessProvider(); 1757 } 1758 1759 1760 private static volatile LoggerFinder service; 1761 @SuppressWarnings("removal") 1762 static LoggerFinder accessProvider() { 1763 // We do not need to synchronize: LoggerFinderLoader will 1764 // always return the same instance, so if we don't have it, 1765 // just fetch it again. 1766 if (service == null) { 1767 PrivilegedAction<LoggerFinder> pa = 1768 () -> LoggerFinderLoader.getLoggerFinder(); 1769 service = AccessController.doPrivileged(pa, null, 1770 LOGGERFINDER_PERMISSION); 1771 } 1772 return service; 1773 } 1774 1775 } 1776 1777 1778 /** 1779 * Returns an instance of {@link Logger Logger} for the caller's 1780 * use. 1781 * 1782 * @implSpec 1783 * Instances returned by this method route messages to loggers 1784 * obtained by calling {@link LoggerFinder#getLogger(java.lang.String, 1785 * java.lang.Module) LoggerFinder.getLogger(name, module)}, where 1786 * {@code module} is the caller's module. 1787 * In cases where {@code System.getLogger} is called from a context where 1788 * there is no caller frame on the stack (e.g when called directly 1789 * from a JNI attached thread), {@code IllegalCallerException} is thrown. 1790 * To obtain a logger in such a context, use an auxiliary class that will 1791 * implicitly be identified as the caller, or use the system {@link 1792 * LoggerFinder#getLoggerFinder() LoggerFinder} to obtain a logger instead. 1793 * Note that doing the latter may eagerly initialize the underlying 1794 * logging system. 1795 * 1796 * @apiNote 1797 * This method may defer calling the {@link 1798 * LoggerFinder#getLogger(java.lang.String, java.lang.Module) 1799 * LoggerFinder.getLogger} method to create an actual logger supplied by 1800 * the logging backend, for instance, to allow loggers to be obtained during 1801 * the system initialization time. 1802 * 1803 * @param name the name of the logger. 1804 * @return an instance of {@link Logger} that can be used by the calling 1805 * class. 1806 * @throws NullPointerException if {@code name} is {@code null}. 1807 * @throws IllegalCallerException if there is no Java caller frame on the 1808 * stack. 1809 * 1810 * @since 9 1811 */ 1812 @CallerSensitive 1813 public static Logger getLogger(String name) { 1814 Objects.requireNonNull(name); 1815 final Class<?> caller = Reflection.getCallerClass(); 1816 if (caller == null) { 1817 throw new IllegalCallerException("no caller frame"); 1818 } 1819 return LazyLoggers.getLogger(name, caller.getModule()); 1820 } 1821 1822 /** 1823 * Returns a localizable instance of {@link Logger 1824 * Logger} for the caller's use. 1825 * The returned logger will use the provided resource bundle for message 1826 * localization. 1827 * 1828 * @implSpec 1829 * The returned logger will perform message localization as specified 1830 * by {@link LoggerFinder#getLocalizedLogger(java.lang.String, 1831 * java.util.ResourceBundle, java.lang.Module) 1832 * LoggerFinder.getLocalizedLogger(name, bundle, module)}, where 1833 * {@code module} is the caller's module. 1834 * In cases where {@code System.getLogger} is called from a context where 1835 * there is no caller frame on the stack (e.g when called directly 1836 * from a JNI attached thread), {@code IllegalCallerException} is thrown. 1837 * To obtain a logger in such a context, use an auxiliary class that 1838 * will implicitly be identified as the caller, or use the system {@link 1839 * LoggerFinder#getLoggerFinder() LoggerFinder} to obtain a logger instead. 1840 * Note that doing the latter may eagerly initialize the underlying 1841 * logging system. 1842 * 1843 * @apiNote 1844 * This method is intended to be used after the system is fully initialized. 1845 * This method may trigger the immediate loading and initialization 1846 * of the {@link LoggerFinder} service, which may cause issues if the 1847 * Java Runtime is not ready to initialize the concrete service 1848 * implementation yet. 1849 * System classes which may be loaded early in the boot sequence and 1850 * need to log localized messages should create a logger using 1851 * {@link #getLogger(java.lang.String)} and then use the log methods that 1852 * take a resource bundle as parameter. 1853 * 1854 * @param name the name of the logger. 1855 * @param bundle a resource bundle. 1856 * @return an instance of {@link Logger} which will use the provided 1857 * resource bundle for message localization. 1858 * @throws NullPointerException if {@code name} is {@code null} or 1859 * {@code bundle} is {@code null}. 1860 * @throws IllegalCallerException if there is no Java caller frame on the 1861 * stack. 1862 * 1863 * @since 9 1864 */ 1865 @SuppressWarnings("removal") 1866 @CallerSensitive 1867 public static Logger getLogger(String name, ResourceBundle bundle) { 1868 final ResourceBundle rb = Objects.requireNonNull(bundle); 1869 Objects.requireNonNull(name); 1870 final Class<?> caller = Reflection.getCallerClass(); 1871 if (caller == null) { 1872 throw new IllegalCallerException("no caller frame"); 1873 } 1874 final SecurityManager sm = System.getSecurityManager(); 1875 // We don't use LazyLoggers if a resource bundle is specified. 1876 // Bootstrap sensitive classes in the JDK do not use resource bundles 1877 // when logging. This could be revisited later, if it needs to. 1878 if (sm != null) { 1879 final PrivilegedAction<Logger> pa = 1880 () -> LoggerFinder.accessProvider() 1881 .getLocalizedLogger(name, rb, caller.getModule()); 1882 return AccessController.doPrivileged(pa, null, 1883 LoggerFinder.LOGGERFINDER_PERMISSION); 1884 } 1885 return LoggerFinder.accessProvider() 1886 .getLocalizedLogger(name, rb, caller.getModule()); 1887 } 1888 1889 /** 1890 * Initiates the {@linkplain Runtime##shutdown shutdown sequence} of the Java Virtual Machine. 1891 * Unless the security manager denies exiting, this method initiates the shutdown sequence 1892 * (if it is not already initiated) and then blocks indefinitely. This method neither returns 1893 * nor throws an exception; that is, it does not complete either normally or abruptly. 1894 * <p> 1895 * The argument serves as a status code. By convention, a nonzero status code 1896 * indicates abnormal termination. 1897 * <p> 1898 * The call {@code System.exit(n)} is effectively equivalent to the call: 1899 * {@snippet : 1900 * Runtime.getRuntime().exit(n) 1901 * } 1902 * 1903 * @implNote 1904 * The initiation of the shutdown sequence is logged by {@link Runtime#exit(int)}. 1905 * 1906 * @param status exit status. 1907 * @throws SecurityException 1908 * if a security manager exists and its {@code checkExit} method 1909 * doesn't allow exit with the specified status. 1910 * @see java.lang.Runtime#exit(int) 1911 */ 1912 public static void exit(int status) { 1913 Runtime.getRuntime().exit(status); 1914 } 1915 1916 /** 1917 * Runs the garbage collector in the Java Virtual Machine. 1918 * <p> 1919 * Calling the {@code gc} method suggests that the Java Virtual Machine 1920 * expend effort toward recycling unused objects in order to 1921 * make the memory they currently occupy available for reuse 1922 * by the Java Virtual Machine. 1923 * When control returns from the method call, the Java Virtual Machine 1924 * has made a best effort to reclaim space from all unused objects. 1925 * There is no guarantee that this effort will recycle any particular 1926 * number of unused objects, reclaim any particular amount of space, or 1927 * complete at any particular time, if at all, before the method returns or ever. 1928 * There is also no guarantee that this effort will determine 1929 * the change of reachability in any particular number of objects, 1930 * or that any particular number of {@link java.lang.ref.Reference Reference} 1931 * objects will be cleared and enqueued. 1932 * 1933 * <p> 1934 * The call {@code System.gc()} is effectively equivalent to the 1935 * call: 1936 * <blockquote><pre> 1937 * Runtime.getRuntime().gc() 1938 * </pre></blockquote> 1939 * 1940 * @see java.lang.Runtime#gc() 1941 */ 1942 public static void gc() { 1943 Runtime.getRuntime().gc(); 1944 } 1945 1946 /** 1947 * Runs the finalization methods of any objects pending finalization. 1948 * 1949 * Calling this method suggests that the Java Virtual Machine expend 1950 * effort toward running the {@code finalize} methods of objects 1951 * that have been found to be discarded but whose {@code finalize} 1952 * methods have not yet been run. When control returns from the 1953 * method call, the Java Virtual Machine has made a best effort to 1954 * complete all outstanding finalizations. 1955 * <p> 1956 * The call {@code System.runFinalization()} is effectively 1957 * equivalent to the call: 1958 * <blockquote><pre> 1959 * Runtime.getRuntime().runFinalization() 1960 * </pre></blockquote> 1961 * 1962 * @deprecated Finalization has been deprecated for removal. See 1963 * {@link java.lang.Object#finalize} for background information and details 1964 * about migration options. 1965 * <p> 1966 * When running in a JVM in which finalization has been disabled or removed, 1967 * no objects will be pending finalization, so this method does nothing. 1968 * 1969 * @see java.lang.Runtime#runFinalization() 1970 * @jls 12.6 Finalization of Class Instances 1971 */ 1972 @Deprecated(since="18", forRemoval=true) 1973 @SuppressWarnings("removal") 1974 public static void runFinalization() { 1975 Runtime.getRuntime().runFinalization(); 1976 } 1977 1978 /** 1979 * Loads the native library specified by the filename argument. The filename 1980 * argument must be an absolute path name. 1981 * 1982 * If the filename argument, when stripped of any platform-specific library 1983 * prefix, path, and file extension, indicates a library whose name is, 1984 * for example, L, and a native library called L is statically linked 1985 * with the VM, then the JNI_OnLoad_L function exported by the library 1986 * is invoked rather than attempting to load a dynamic library. 1987 * A filename matching the argument does not have to exist in the 1988 * file system. 1989 * See the <a href="{@docRoot}/../specs/jni/index.html"> JNI Specification</a> 1990 * for more details. 1991 * 1992 * Otherwise, the filename argument is mapped to a native library image in 1993 * an implementation-dependent manner. 1994 * 1995 * <p> 1996 * The call {@code System.load(name)} is effectively equivalent 1997 * to the call: 1998 * <blockquote><pre> 1999 * Runtime.getRuntime().load(name) 2000 * </pre></blockquote> 2001 * 2002 * @param filename the file to load. 2003 * @throws SecurityException if a security manager exists and its 2004 * {@code checkLink} method doesn't allow 2005 * loading of the specified dynamic library 2006 * @throws UnsatisfiedLinkError if either the filename is not an 2007 * absolute path name, the native library is not statically 2008 * linked with the VM, or the library cannot be mapped to 2009 * a native library image by the host system. 2010 * @throws NullPointerException if {@code filename} is {@code null} 2011 * 2012 * @spec jni/index.html Java Native Interface Specification 2013 * @see java.lang.Runtime#load(java.lang.String) 2014 * @see java.lang.SecurityManager#checkLink(java.lang.String) 2015 */ 2016 @CallerSensitive 2017 public static void load(String filename) { 2018 Runtime.getRuntime().load0(Reflection.getCallerClass(), filename); 2019 } 2020 2021 /** 2022 * Loads the native library specified by the {@code libname} 2023 * argument. The {@code libname} argument must not contain any platform 2024 * specific prefix, file extension or path. If a native library 2025 * called {@code libname} is statically linked with the VM, then the 2026 * JNI_OnLoad_{@code libname} function exported by the library is invoked. 2027 * See the <a href="{@docRoot}/../specs/jni/index.html"> JNI Specification</a> 2028 * for more details. 2029 * 2030 * Otherwise, the libname argument is loaded from a system library 2031 * location and mapped to a native library image in an 2032 * implementation-dependent manner. 2033 * <p> 2034 * The call {@code System.loadLibrary(name)} is effectively 2035 * equivalent to the call 2036 * <blockquote><pre> 2037 * Runtime.getRuntime().loadLibrary(name) 2038 * </pre></blockquote> 2039 * 2040 * @param libname the name of the library. 2041 * @throws SecurityException if a security manager exists and its 2042 * {@code checkLink} method doesn't allow 2043 * loading of the specified dynamic library 2044 * @throws UnsatisfiedLinkError if either the libname argument 2045 * contains a file path, the native library is not statically 2046 * linked with the VM, or the library cannot be mapped to a 2047 * native library image by the host system. 2048 * @throws NullPointerException if {@code libname} is {@code null} 2049 * 2050 * @spec jni/index.html Java Native Interface Specification 2051 * @see java.lang.Runtime#loadLibrary(java.lang.String) 2052 * @see java.lang.SecurityManager#checkLink(java.lang.String) 2053 */ 2054 @CallerSensitive 2055 public static void loadLibrary(String libname) { 2056 Runtime.getRuntime().loadLibrary0(Reflection.getCallerClass(), libname); 2057 } 2058 2059 /** 2060 * Maps a library name into a platform-specific string representing 2061 * a native library. 2062 * 2063 * @param libname the name of the library. 2064 * @return a platform-dependent native library name. 2065 * @throws NullPointerException if {@code libname} is {@code null} 2066 * @see java.lang.System#loadLibrary(java.lang.String) 2067 * @see java.lang.ClassLoader#findLibrary(java.lang.String) 2068 * @since 1.2 2069 */ 2070 public static native String mapLibraryName(String libname); 2071 2072 /** 2073 * Create PrintStream for stdout/err based on encoding. 2074 */ 2075 private static PrintStream newPrintStream(OutputStream out, String enc) { 2076 if (enc != null) { 2077 return new PrintStream(new BufferedOutputStream(out, 128), true, 2078 Charset.forName(enc, UTF_8.INSTANCE)); 2079 } 2080 return new PrintStream(new BufferedOutputStream(out, 128), true); 2081 } 2082 2083 /** 2084 * Logs an exception/error at initialization time to stdout or stderr. 2085 * 2086 * @param printToStderr to print to stderr rather than stdout 2087 * @param printStackTrace to print the stack trace 2088 * @param msg the message to print before the exception, can be {@code null} 2089 * @param e the exception or error 2090 */ 2091 private static void logInitException(boolean printToStderr, 2092 boolean printStackTrace, 2093 String msg, 2094 Throwable e) { 2095 if (VM.initLevel() < 1) { 2096 throw new InternalError("system classes not initialized"); 2097 } 2098 PrintStream log = (printToStderr) ? err : out; 2099 if (msg != null) { 2100 log.println(msg); 2101 } 2102 if (printStackTrace) { 2103 e.printStackTrace(log); 2104 } else { 2105 log.println(e); 2106 for (Throwable suppressed : e.getSuppressed()) { 2107 log.println("Suppressed: " + suppressed); 2108 } 2109 Throwable cause = e.getCause(); 2110 if (cause != null) { 2111 log.println("Caused by: " + cause); 2112 } 2113 } 2114 } 2115 2116 /** 2117 * Create the Properties object from a map - masking out system properties 2118 * that are not intended for public access. 2119 */ 2120 private static Properties createProperties(Map<String, String> initialProps) { 2121 Properties properties = new Properties(initialProps.size()); 2122 for (var entry : initialProps.entrySet()) { 2123 String prop = entry.getKey(); 2124 switch (prop) { 2125 // Do not add private system properties to the Properties 2126 case "sun.nio.MaxDirectMemorySize": 2127 case "sun.nio.PageAlignDirectMemory": 2128 // used by java.lang.Integer.IntegerCache 2129 case "java.lang.Integer.IntegerCache.high": 2130 // used by sun.launcher.LauncherHelper 2131 case "sun.java.launcher.diag": 2132 // used by jdk.internal.loader.ClassLoaders 2133 case "jdk.boot.class.path.append": 2134 break; 2135 default: 2136 properties.put(prop, entry.getValue()); 2137 } 2138 } 2139 return properties; 2140 } 2141 2142 /** 2143 * Initialize the system class. Called after thread initialization. 2144 */ 2145 private static void initPhase1() { 2146 2147 // register the shared secrets - do this first, since SystemProps.initProperties 2148 // might initialize CharsetDecoders that rely on it 2149 setJavaLangAccess(); 2150 2151 // VM might invoke JNU_NewStringPlatform() to set those encoding 2152 // sensitive properties (user.home, user.name, boot.class.path, etc.) 2153 // during "props" initialization. 2154 // The charset is initialized in System.c and does not depend on the Properties. 2155 Map<String, String> tempProps = SystemProps.initProperties(); 2156 VersionProps.init(tempProps); 2157 2158 // There are certain system configurations that may be controlled by 2159 // VM options such as the maximum amount of direct memory and 2160 // Integer cache size used to support the object identity semantics 2161 // of autoboxing. Typically, the library will obtain these values 2162 // from the properties set by the VM. If the properties are for 2163 // internal implementation use only, these properties should be 2164 // masked from the system properties. 2165 // 2166 // Save a private copy of the system properties object that 2167 // can only be accessed by the internal implementation. 2168 VM.saveProperties(tempProps); 2169 props = createProperties(tempProps); 2170 2171 // Check if sun.jnu.encoding is supported. If not, replace it with UTF-8. 2172 var jnuEncoding = props.getProperty("sun.jnu.encoding"); 2173 if (jnuEncoding == null || !Charset.isSupported(jnuEncoding)) { 2174 notSupportedJnuEncoding = jnuEncoding == null ? "null" : jnuEncoding; 2175 props.setProperty("sun.jnu.encoding", "UTF-8"); 2176 } 2177 2178 StaticProperty.javaHome(); // Load StaticProperty to cache the property values 2179 2180 lineSeparator = props.getProperty("line.separator"); 2181 2182 FileInputStream fdIn = new FileInputStream(FileDescriptor.in); 2183 FileOutputStream fdOut = new FileOutputStream(FileDescriptor.out); 2184 FileOutputStream fdErr = new FileOutputStream(FileDescriptor.err); 2185 initialIn = new BufferedInputStream(fdIn); 2186 setIn0(initialIn); 2187 // stdout/err.encoding are set when the VM is associated with the terminal, 2188 // thus they are equivalent to Console.charset(), otherwise the encodings 2189 // of those properties default to native.encoding 2190 setOut0(newPrintStream(fdOut, props.getProperty("stdout.encoding"))); 2191 setErr0(newPrintStream(fdErr, props.getProperty("stderr.encoding"))); 2192 2193 // Setup Java signal handlers for HUP, TERM, and INT (where available). 2194 Terminator.setup(); 2195 2196 // Initialize any miscellaneous operating system settings that need to be 2197 // set for the class libraries. Currently this is no-op everywhere except 2198 // for Windows where the process-wide error mode is set before the java.io 2199 // classes are used. 2200 VM.initializeOSEnvironment(); 2201 2202 // start Finalizer and Reference Handler threads 2203 SharedSecrets.getJavaLangRefAccess().startThreads(); 2204 2205 // system properties, java.lang and other core classes are now initialized 2206 VM.initLevel(1); 2207 } 2208 2209 // @see #initPhase2() 2210 static ModuleLayer bootLayer; 2211 2212 /* 2213 * Invoked by VM. Phase 2 module system initialization. 2214 * Only classes in java.base can be loaded in this phase. 2215 * 2216 * @param printToStderr print exceptions to stderr rather than stdout 2217 * @param printStackTrace print stack trace when exception occurs 2218 * 2219 * @return JNI_OK for success, JNI_ERR for failure 2220 */ 2221 private static int initPhase2(boolean printToStderr, boolean printStackTrace) { 2222 2223 try { 2224 bootLayer = ModuleBootstrap.boot(); 2225 } catch (Exception | Error e) { 2226 logInitException(printToStderr, printStackTrace, 2227 "Error occurred during initialization of boot layer", e); 2228 return -1; // JNI_ERR 2229 } 2230 2231 // module system initialized 2232 VM.initLevel(2); 2233 2234 return 0; // JNI_OK 2235 } 2236 2237 /* 2238 * Invoked by VM. Phase 3 is the final system initialization: 2239 * 1. eagerly initialize bootstrap method factories that might interact 2240 * negatively with custom security managers and custom class loaders 2241 * 2. set security manager 2242 * 3. set system class loader 2243 * 4. set TCCL 2244 * 2245 * This method must be called after the module system initialization. 2246 * The security manager and system class loader may be a custom class from 2247 * the application classpath or modulepath. 2248 */ 2249 @SuppressWarnings("removal") 2250 private static void initPhase3() { 2251 2252 // Initialize the StringConcatFactory eagerly to avoid potential 2253 // bootstrap circularity issues that could be caused by a custom 2254 // SecurityManager 2255 Unsafe.getUnsafe().ensureClassInitialized(StringConcatFactory.class); 2256 2257 // Emit a warning if java.io.tmpdir is set via the command line 2258 // to a directory that doesn't exist 2259 if (SystemProps.isBadIoTmpdir()) { 2260 System.err.println("WARNING: java.io.tmpdir directory does not exist"); 2261 } 2262 2263 String smProp = System.getProperty("java.security.manager"); 2264 boolean needWarning = false; 2265 if (smProp != null) { 2266 switch (smProp) { 2267 case "disallow": 2268 allowSecurityManager = NEVER; 2269 break; 2270 case "allow": 2271 allowSecurityManager = MAYBE; 2272 break; 2273 case "": 2274 case "default": 2275 implSetSecurityManager(new SecurityManager()); 2276 allowSecurityManager = MAYBE; 2277 needWarning = true; 2278 break; 2279 default: 2280 try { 2281 ClassLoader cl = ClassLoader.getBuiltinAppClassLoader(); 2282 Class<?> c = Class.forName(smProp, false, cl); 2283 Constructor<?> ctor = c.getConstructor(); 2284 // Must be a public subclass of SecurityManager with 2285 // a public no-arg constructor 2286 if (!SecurityManager.class.isAssignableFrom(c) || 2287 !Modifier.isPublic(c.getModifiers()) || 2288 !Modifier.isPublic(ctor.getModifiers())) { 2289 throw new Error("Could not create SecurityManager: " 2290 + ctor.toString()); 2291 } 2292 // custom security manager may be in non-exported package 2293 ctor.setAccessible(true); 2294 SecurityManager sm = (SecurityManager) ctor.newInstance(); 2295 implSetSecurityManager(sm); 2296 needWarning = true; 2297 } catch (Exception e) { 2298 throw new InternalError("Could not create SecurityManager", e); 2299 } 2300 allowSecurityManager = MAYBE; 2301 } 2302 } else { 2303 allowSecurityManager = NEVER; 2304 } 2305 2306 if (needWarning) { 2307 System.err.println(""" 2308 WARNING: A command line option has enabled the Security Manager 2309 WARNING: The Security Manager is deprecated and will be removed in a future release"""); 2310 } 2311 2312 // Emit a warning if `sun.jnu.encoding` is not supported. 2313 if (notSupportedJnuEncoding != null) { 2314 System.err.println( 2315 "WARNING: The encoding of the underlying platform's" + 2316 " file system is not supported: " + 2317 notSupportedJnuEncoding); 2318 } 2319 2320 initialErrStream = System.err; 2321 2322 // initializing the system class loader 2323 VM.initLevel(3); 2324 2325 // system class loader initialized 2326 ClassLoader scl = ClassLoader.initSystemClassLoader(); 2327 2328 // set TCCL 2329 Thread.currentThread().setContextClassLoader(scl); 2330 2331 // system is fully initialized 2332 VM.initLevel(4); 2333 } 2334 2335 private static void setJavaLangAccess() { 2336 // Allow privileged classes outside of java.lang 2337 SharedSecrets.setJavaLangAccess(new JavaLangAccess() { 2338 public List<Method> getDeclaredPublicMethods(Class<?> klass, String name, Class<?>... parameterTypes) { 2339 return klass.getDeclaredPublicMethods(name, parameterTypes); 2340 } 2341 public jdk.internal.reflect.ConstantPool getConstantPool(Class<?> klass) { 2342 return klass.getConstantPool(); 2343 } 2344 public boolean casAnnotationType(Class<?> klass, AnnotationType oldType, AnnotationType newType) { 2345 return klass.casAnnotationType(oldType, newType); 2346 } 2347 public AnnotationType getAnnotationType(Class<?> klass) { 2348 return klass.getAnnotationType(); 2349 } 2350 public Map<Class<? extends Annotation>, Annotation> getDeclaredAnnotationMap(Class<?> klass) { 2351 return klass.getDeclaredAnnotationMap(); 2352 } 2353 public byte[] getRawClassAnnotations(Class<?> klass) { 2354 return klass.getRawAnnotations(); 2355 } 2356 public byte[] getRawClassTypeAnnotations(Class<?> klass) { 2357 return klass.getRawTypeAnnotations(); 2358 } 2359 public byte[] getRawExecutableTypeAnnotations(Executable executable) { 2360 return Class.getExecutableTypeAnnotationBytes(executable); 2361 } 2362 public <E extends Enum<E>> 2363 E[] getEnumConstantsShared(Class<E> klass) { 2364 return klass.getEnumConstantsShared(); 2365 } 2366 public void blockedOn(Interruptible b) { 2367 Thread.blockedOn(b); 2368 } 2369 public void registerShutdownHook(int slot, boolean registerShutdownInProgress, Runnable hook) { 2370 Shutdown.add(slot, registerShutdownInProgress, hook); 2371 } 2372 public Thread newThreadWithAcc(Runnable target, @SuppressWarnings("removal") AccessControlContext acc) { 2373 return new Thread(target, acc); 2374 } 2375 @SuppressWarnings("removal") 2376 public void invokeFinalize(Object o) throws Throwable { 2377 o.finalize(); 2378 } 2379 public ConcurrentHashMap<?, ?> createOrGetClassLoaderValueMap(ClassLoader cl) { 2380 return cl.createOrGetClassLoaderValueMap(); 2381 } 2382 public Class<?> defineClass(ClassLoader loader, String name, byte[] b, ProtectionDomain pd, String source) { 2383 return ClassLoader.defineClass1(loader, name, b, 0, b.length, pd, source); 2384 } 2385 public Class<?> defineClass(ClassLoader loader, Class<?> lookup, String name, byte[] b, ProtectionDomain pd, 2386 boolean initialize, int flags, Object classData) { 2387 return ClassLoader.defineClass0(loader, lookup, name, b, 0, b.length, pd, initialize, flags, classData); 2388 } 2389 public Class<?> findBootstrapClassOrNull(String name) { 2390 return ClassLoader.findBootstrapClassOrNull(name); 2391 } 2392 public Package definePackage(ClassLoader cl, String name, Module module) { 2393 return cl.definePackage(name, module); 2394 } 2395 public String fastUUID(long lsb, long msb) { 2396 return Long.fastUUID(lsb, msb); 2397 } 2398 @SuppressWarnings("removal") 2399 public void addNonExportedPackages(ModuleLayer layer) { 2400 SecurityManager.addNonExportedPackages(layer); 2401 } 2402 @SuppressWarnings("removal") 2403 public void invalidatePackageAccessCache() { 2404 SecurityManager.invalidatePackageAccessCache(); 2405 } 2406 public Module defineModule(ClassLoader loader, 2407 ModuleDescriptor descriptor, 2408 URI uri) { 2409 return new Module(null, loader, descriptor, uri); 2410 } 2411 public Module defineUnnamedModule(ClassLoader loader) { 2412 return new Module(loader); 2413 } 2414 public void addReads(Module m1, Module m2) { 2415 m1.implAddReads(m2); 2416 } 2417 public void addReadsAllUnnamed(Module m) { 2418 m.implAddReadsAllUnnamed(); 2419 } 2420 public void addExports(Module m, String pn) { 2421 m.implAddExports(pn); 2422 } 2423 public void addExports(Module m, String pn, Module other) { 2424 m.implAddExports(pn, other); 2425 } 2426 public void addExportsToAllUnnamed(Module m, String pn) { 2427 m.implAddExportsToAllUnnamed(pn); 2428 } 2429 public void addOpens(Module m, String pn, Module other) { 2430 m.implAddOpens(pn, other); 2431 } 2432 public void addOpensToAllUnnamed(Module m, String pn) { 2433 m.implAddOpensToAllUnnamed(pn); 2434 } 2435 public void addOpensToAllUnnamed(Module m, Set<String> concealedPackages, Set<String> exportedPackages) { 2436 m.implAddOpensToAllUnnamed(concealedPackages, exportedPackages); 2437 } 2438 public void addUses(Module m, Class<?> service) { 2439 m.implAddUses(service); 2440 } 2441 public boolean isReflectivelyExported(Module m, String pn, Module other) { 2442 return m.isReflectivelyExported(pn, other); 2443 } 2444 public boolean isReflectivelyOpened(Module m, String pn, Module other) { 2445 return m.isReflectivelyOpened(pn, other); 2446 } 2447 public Module addEnableNativeAccess(Module m) { 2448 return m.implAddEnableNativeAccess(); 2449 } 2450 public void addEnableNativeAccessToAllUnnamed() { 2451 Module.implAddEnableNativeAccessToAllUnnamed(); 2452 } 2453 public void ensureNativeAccess(Module m, Class<?> owner, String methodName) { 2454 m.ensureNativeAccess(owner, methodName); 2455 } 2456 public ServicesCatalog getServicesCatalog(ModuleLayer layer) { 2457 return layer.getServicesCatalog(); 2458 } 2459 public void bindToLoader(ModuleLayer layer, ClassLoader loader) { 2460 layer.bindToLoader(loader); 2461 } 2462 public Stream<ModuleLayer> layers(ModuleLayer layer) { 2463 return layer.layers(); 2464 } 2465 public Stream<ModuleLayer> layers(ClassLoader loader) { 2466 return ModuleLayer.layers(loader); 2467 } 2468 2469 public int countPositives(byte[] bytes, int offset, int length) { 2470 return StringCoding.countPositives(bytes, offset, length); 2471 } 2472 public String newStringNoRepl(byte[] bytes, Charset cs) throws CharacterCodingException { 2473 return String.newStringNoRepl(bytes, cs); 2474 } 2475 public char getUTF16Char(byte[] bytes, int index) { 2476 return StringUTF16.getChar(bytes, index); 2477 } 2478 public byte[] getBytesNoRepl(String s, Charset cs) throws CharacterCodingException { 2479 return String.getBytesNoRepl(s, cs); 2480 } 2481 2482 public String newStringUTF8NoRepl(byte[] bytes, int off, int len) { 2483 return String.newStringUTF8NoRepl(bytes, off, len, true); 2484 } 2485 2486 public byte[] getBytesUTF8NoRepl(String s) { 2487 return String.getBytesUTF8NoRepl(s); 2488 } 2489 2490 public void inflateBytesToChars(byte[] src, int srcOff, char[] dst, int dstOff, int len) { 2491 StringLatin1.inflate(src, srcOff, dst, dstOff, len); 2492 } 2493 2494 public int decodeASCII(byte[] src, int srcOff, char[] dst, int dstOff, int len) { 2495 return String.decodeASCII(src, srcOff, dst, dstOff, len); 2496 } 2497 2498 public int encodeASCII(char[] src, int srcOff, byte[] dst, int dstOff, int len) { 2499 return StringCoding.implEncodeAsciiArray(src, srcOff, dst, dstOff, len); 2500 } 2501 2502 public InputStream initialSystemIn() { 2503 return initialIn; 2504 } 2505 2506 public void setCause(Throwable t, Throwable cause) { 2507 t.setCause(cause); 2508 } 2509 2510 public ProtectionDomain protectionDomain(Class<?> c) { 2511 return c.protectionDomain(); 2512 } 2513 2514 public MethodHandle stringConcatHelper(String name, MethodType methodType) { 2515 return StringConcatHelper.lookupStatic(name, methodType); 2516 } 2517 2518 public long stringConcatInitialCoder() { 2519 return StringConcatHelper.initialCoder(); 2520 } 2521 2522 public long stringConcatMix(long lengthCoder, String constant) { 2523 return StringConcatHelper.mix(lengthCoder, constant); 2524 } 2525 2526 @PreviewFeature(feature=PreviewFeature.Feature.STRING_TEMPLATES) 2527 public long stringConcatCoder(char value) { 2528 return StringConcatHelper.coder(value); 2529 } 2530 2531 @PreviewFeature(feature=PreviewFeature.Feature.STRING_TEMPLATES) 2532 public long stringBuilderConcatMix(long lengthCoder, 2533 StringBuilder sb) { 2534 return sb.mix(lengthCoder); 2535 } 2536 2537 @PreviewFeature(feature=PreviewFeature.Feature.STRING_TEMPLATES) 2538 public long stringBuilderConcatPrepend(long lengthCoder, byte[] buf, 2539 StringBuilder sb) { 2540 return sb.prepend(lengthCoder, buf); 2541 } 2542 2543 public String join(String prefix, String suffix, String delimiter, String[] elements, int size) { 2544 return String.join(prefix, suffix, delimiter, elements, size); 2545 } 2546 2547 public Object classData(Class<?> c) { 2548 return c.getClassData(); 2549 } 2550 2551 @Override 2552 public long findNative(ClassLoader loader, String entry) { 2553 return ClassLoader.findNative(loader, entry); 2554 } 2555 2556 @Override 2557 public void exit(int statusCode) { 2558 Shutdown.exit(statusCode); 2559 } 2560 2561 public Thread[] getAllThreads() { 2562 return Thread.getAllThreads(); 2563 } 2564 2565 public ThreadContainer threadContainer(Thread thread) { 2566 return thread.threadContainer(); 2567 } 2568 2569 public void start(Thread thread, ThreadContainer container) { 2570 thread.start(container); 2571 } 2572 2573 public StackableScope headStackableScope(Thread thread) { 2574 return thread.headStackableScopes(); 2575 } 2576 2577 public void setHeadStackableScope(StackableScope scope) { 2578 Thread.setHeadStackableScope(scope); 2579 } 2580 2581 public Thread currentCarrierThread() { 2582 return Thread.currentCarrierThread(); 2583 } 2584 2585 public <V> V executeOnCarrierThread(Callable<V> task) throws Exception { 2586 if (Thread.currentThread() instanceof VirtualThread vthread) { 2587 return vthread.executeOnCarrierThread(task); 2588 } else { 2589 return task.call(); 2590 } 2591 } 2592 2593 public <T> T getCarrierThreadLocal(CarrierThreadLocal<T> local) { 2594 return ((ThreadLocal<T>)local).getCarrierThreadLocal(); 2595 } 2596 2597 public <T> void setCarrierThreadLocal(CarrierThreadLocal<T> local, T value) { 2598 ((ThreadLocal<T>)local).setCarrierThreadLocal(value); 2599 } 2600 2601 public void removeCarrierThreadLocal(CarrierThreadLocal<?> local) { 2602 ((ThreadLocal<?>)local).removeCarrierThreadLocal(); 2603 } 2604 2605 public boolean isCarrierThreadLocalPresent(CarrierThreadLocal<?> local) { 2606 return ((ThreadLocal<?>)local).isCarrierThreadLocalPresent(); 2607 } 2608 2609 public Object[] scopedValueCache() { 2610 return Thread.scopedValueCache(); 2611 } 2612 2613 public void setScopedValueCache(Object[] cache) { 2614 Thread.setScopedValueCache(cache); 2615 } 2616 2617 public Object scopedValueBindings() { 2618 return Thread.scopedValueBindings(); 2619 } 2620 2621 public Object findScopedValueBindings() { 2622 return Thread.findScopedValueBindings(); 2623 } 2624 2625 public void setScopedValueBindings(Object bindings) { 2626 Thread.setScopedValueBindings(bindings); 2627 } 2628 2629 @ForceInline 2630 public void ensureMaterializedForStackWalk(Object value) { 2631 Thread.ensureMaterializedForStackWalk(value); 2632 } 2633 2634 public Continuation getContinuation(Thread thread) { 2635 return thread.getContinuation(); 2636 } 2637 2638 public void setContinuation(Thread thread, Continuation continuation) { 2639 thread.setContinuation(continuation); 2640 } 2641 2642 public ContinuationScope virtualThreadContinuationScope() { 2643 return VirtualThread.continuationScope(); 2644 } 2645 2646 public void parkVirtualThread() { 2647 Thread thread = Thread.currentThread(); 2648 if (thread instanceof BaseVirtualThread vthread) { 2649 vthread.park(); 2650 } else { 2651 throw new WrongThreadException(); 2652 } 2653 } 2654 2655 public void parkVirtualThread(long nanos) { 2656 Thread thread = Thread.currentThread(); 2657 if (thread instanceof BaseVirtualThread vthread) { 2658 vthread.parkNanos(nanos); 2659 } else { 2660 throw new WrongThreadException(); 2661 } 2662 } 2663 2664 public void unparkVirtualThread(Thread thread) { 2665 if (thread instanceof BaseVirtualThread vthread) { 2666 vthread.unpark(); 2667 } else { 2668 throw new WrongThreadException(); 2669 } 2670 } 2671 2672 public StackWalker newStackWalkerInstance(Set<StackWalker.Option> options, 2673 ContinuationScope contScope, 2674 Continuation continuation) { 2675 return StackWalker.newInstance(options, null, contScope, continuation); 2676 } 2677 2678 public String getLoaderNameID(ClassLoader loader) { 2679 return loader.nameAndId(); 2680 } 2681 }); 2682 } 2683 }