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