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