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