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