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