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