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