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