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