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