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