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