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