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