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