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