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