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.vendor          <dd>Java vendor specific string
 554      * <dt>java.vendor.url      <dd>Java vendor URL
 555      * <dt>java.home            <dd>Java installation directory
 556      * <dt>java.class.version   <dd>Java class version number
 557      * <dt>java.class.path      <dd>Java classpath
 558      * <dt>os.name              <dd>Operating System Name
 559      * <dt>os.arch              <dd>Operating System Architecture
 560      * <dt>os.version           <dd>Operating System Version
 561      * <dt>file.separator       <dd>File separator ("/" on Unix)
 562      * <dt>path.separator       <dd>Path separator (":" on Unix)
 563      * <dt>line.separator       <dd>Line separator ("\n" on Unix)
 564      * <dt>user.name            <dd>User account name
 565      * <dt>user.home            <dd>User home directory
 566      * <dt>user.dir             <dd>User's current working directory
 567      * </dl>
 568      */
 569 
 570     private static Properties props;
 571     private static native Properties initProperties(Properties props);
 572 
 573     /**
 574      * Determines the current system properties.
 575      * <p>
 576      * First, if there is a security manager, its
 577      * <code>checkPropertiesAccess</code> method is called with no
 578      * arguments. This may result in a security exception.
 579      * <p>
 580      * The current set of system properties for use by the
 581      * {@link #getProperty(String)} method is returned as a
 582      * <code>Properties</code> object. If there is no current set of
 583      * system properties, a set of system properties is first created and
 584      * initialized. This set of system properties always includes values
 585      * for the following keys:
 586      * <table class="striped">
 587      * <caption style="display:none">Shows property keys and associated values</caption>
 588      * <thead>
 589      * <tr><th scope="col">Key</th>
 590      *     <th scope="col">Description of Associated Value</th></tr>
 591      * </thead>
 592      * <tbody>
 593      * <tr><th scope="row"><code>java.version</code></th>
 594      *     <td>Java Runtime Environment version which may be interpreted
 595      *     as a {@link Runtime.Version}</td></tr>
 596      * <tr><th scope="row"><code>java.vendor</code></th>
 597      *     <td>Java Runtime Environment vendor</td></tr>
 598      * <tr><th scope="row"><code>java.vendor.url</code></th>
 599      *     <td>Java vendor URL</td></tr>
 600      * <tr><th scope="row"><code>java.home</code></th>
 601      *     <td>Java installation directory</td></tr>
 602      * <tr><th scope="row"><code>java.vm.specification.version</code></th>
 603      *     <td>Java Virtual Machine specification version which may be
 604      *     interpreted as a {@link Runtime.Version}</td></tr>
 605      * <tr><th scope="row"><code>java.vm.specification.vendor</code></th>
 606      *     <td>Java Virtual Machine specification vendor</td></tr>
 607      * <tr><th scope="row"><code>java.vm.specification.name</code></th>
 608      *     <td>Java Virtual Machine specification name</td></tr>
 609      * <tr><th scope="row"><code>java.vm.version</code></th>
 610      *     <td>Java Virtual Machine implementation version which may be
 611      *     interpreted as a {@link Runtime.Version}</td></tr>
 612      * <tr><th scope="row"><code>java.vm.vendor</code></th>
 613      *     <td>Java Virtual Machine implementation vendor</td></tr>
 614      * <tr><th scope="row"><code>java.vm.name</code></th>
 615      *     <td>Java Virtual Machine implementation name</td></tr>
 616      * <tr><th scope="row"><code>java.specification.version</code></th>
 617      *     <td>Java Runtime Environment specification version which may be
 618      *     interpreted as a {@link Runtime.Version}</td></tr>
 619      * <tr><th scope="row"><code>java.specification.vendor</code></th>
 620      *     <td>Java Runtime Environment specification  vendor</td></tr>
 621      * <tr><th scope="row"><code>java.specification.name</code></th>
 622      *     <td>Java Runtime Environment specification  name</td></tr>
 623      * <tr><th scope="row"><code>java.class.version</code></th>
 624      *     <td>Java class format version number</td></tr>
 625      * <tr><th scope="row"><code>java.class.path</code></th>
 626      *     <td>Java class path</td></tr>
 627      * <tr><th scope="row"><code>java.library.path</code></th>
 628      *     <td>List of paths to search when loading libraries</td></tr>
 629      * <tr><th scope="row"><code>java.io.tmpdir</code></th>
 630      *     <td>Default temp file path</td></tr>
 631      * <tr><th scope="row"><code>java.compiler</code></th>
 632      *     <td>Name of JIT compiler to use</td></tr>
 633      * <tr><th scope="row"><code>os.name</code></th>
 634      *     <td>Operating system name</td></tr>
 635      * <tr><th scope="row"><code>os.arch</code></th>
 636      *     <td>Operating system architecture</td></tr>
 637      * <tr><th scope="row"><code>os.version</code></th>
 638      *     <td>Operating system version</td></tr>
 639      * <tr><th scope="row"><code>file.separator</code></th>
 640      *     <td>File separator ("/" on UNIX)</td></tr>
 641      * <tr><th scope="row"><code>path.separator</code></th>
 642      *     <td>Path separator (":" on UNIX)</td></tr>
 643      * <tr><th scope="row"><code>line.separator</code></th>
 644      *     <td>Line separator ("\n" on UNIX)</td></tr>
 645      * <tr><th scope="row"><code>user.name</code></th>
 646      *     <td>User's account name</td></tr>
 647      * <tr><th scope="row"><code>user.home</code></th>
 648      *     <td>User's home directory</td></tr>
 649      * <tr><th scope="row"><code>user.dir</code></th>
 650      *     <td>User's current working directory</td></tr>
 651      * </tbody>
 652      * </table>
 653      * <p>
 654      * Multiple paths in a system property value are separated by the path
 655      * separator character of the platform.
 656      * <p>
 657      * Note that even if the security manager does not permit the
 658      * <code>getProperties</code> operation, it may choose to permit the
 659      * {@link #getProperty(String)} operation.
 660      *
 661      * @implNote In addition to the standard system properties, the system
 662      * properties may include the following keys:
 663      * <table class="striped">
 664      * <caption style="display:none">Shows property keys and associated values</caption>
 665      * <thead>
 666      * <tr><th scope="col">Key</th>
 667      *     <th scope="col">Description of Associated Value</th></tr>
 668      * </thead>
 669      * <tbody>
 670      * <tr><th scope="row">{@code jdk.module.path}</th>
 671      *     <td>The application module path</td></tr>
 672      * <tr><th scope="row">{@code jdk.module.upgrade.path}</th>
 673      *     <td>The upgrade module path</td></tr>
 674      * <tr><th scope="row">{@code jdk.module.main}</th>
 675      *     <td>The module name of the initial/main module</td></tr>
 676      * <tr><th scope="row">{@code jdk.module.main.class}</th>
 677      *     <td>The main class name of the initial module</td></tr>
 678      * </tbody>
 679      * </table>
 680      *
 681      * @return     the system properties
 682      * @exception  SecurityException  if a security manager exists and its
 683      *             <code>checkPropertiesAccess</code> method doesn't allow access
 684      *              to the system properties.
 685      * @see        #setProperties
 686      * @see        java.lang.SecurityException
 687      * @see        java.lang.SecurityManager#checkPropertiesAccess()
 688      * @see        java.util.Properties
 689      */
 690     public static Properties getProperties() {
 691         SecurityManager sm = getSecurityManager();
 692         if (sm != null) {
 693             sm.checkPropertiesAccess();
 694         }
 695 
 696         return props;
 697     }
 698 
 699     /**
 700      * Returns the system-dependent line separator string.  It always
 701      * returns the same value - the initial value of the {@linkplain
 702      * #getProperty(String) system property} {@code line.separator}.
 703      *
 704      * <p>On UNIX systems, it returns {@code "\n"}; on Microsoft
 705      * Windows systems it returns {@code "\r\n"}.
 706      *
 707      * @return the system-dependent line separator string
 708      * @since 1.7
 709      */
 710     public static String lineSeparator() {
 711         return lineSeparator;
 712     }
 713 
 714     private static String lineSeparator;
 715 
 716     /**
 717      * Sets the system properties to the <code>Properties</code>
 718      * argument.
 719      * <p>
 720      * First, if there is a security manager, its
 721      * <code>checkPropertiesAccess</code> method is called with no
 722      * arguments. This may result in a security exception.
 723      * <p>
 724      * The argument becomes the current set of system properties for use
 725      * by the {@link #getProperty(String)} method. If the argument is
 726      * <code>null</code>, then the current set of system properties is
 727      * forgotten.
 728      *
 729      * @param      props   the new system properties.
 730      * @exception  SecurityException  if a security manager exists and its
 731      *             <code>checkPropertiesAccess</code> method doesn't allow access
 732      *              to the system properties.
 733      * @see        #getProperties
 734      * @see        java.util.Properties
 735      * @see        java.lang.SecurityException
 736      * @see        java.lang.SecurityManager#checkPropertiesAccess()
 737      */
 738     public static void setProperties(Properties props) {
 739         SecurityManager sm = getSecurityManager();
 740         if (sm != null) {
 741             sm.checkPropertiesAccess();
 742         }
 743         if (props == null) {
 744             props = new Properties();
 745             initProperties(props);
 746         }
 747         System.props = props;
 748     }
 749 
 750     /**
 751      * Gets the system property indicated by the specified key.
 752      * <p>
 753      * First, if there is a security manager, its
 754      * <code>checkPropertyAccess</code> method is called with the key as
 755      * its argument. This may result in a SecurityException.
 756      * <p>
 757      * If there is no current set of system properties, a set of system
 758      * properties is first created and initialized in the same manner as
 759      * for the <code>getProperties</code> method.
 760      *
 761      * @param      key   the name of the system property.
 762      * @return     the string value of the system property,
 763      *             or <code>null</code> if there is no property with that key.
 764      *
 765      * @exception  SecurityException  if a security manager exists and its
 766      *             <code>checkPropertyAccess</code> method doesn't allow
 767      *              access to the specified system property.
 768      * @exception  NullPointerException if <code>key</code> is
 769      *             <code>null</code>.
 770      * @exception  IllegalArgumentException if <code>key</code> is empty.
 771      * @see        #setProperty
 772      * @see        java.lang.SecurityException
 773      * @see        java.lang.SecurityManager#checkPropertyAccess(java.lang.String)
 774      * @see        java.lang.System#getProperties()
 775      */
 776     public static String getProperty(String key) {
 777         checkKey(key);
 778         SecurityManager sm = getSecurityManager();
 779         if (sm != null) {
 780             sm.checkPropertyAccess(key);
 781         }
 782 
 783         return props.getProperty(key);
 784     }
 785 
 786     /**
 787      * Gets the system property indicated by the specified key.
 788      * <p>
 789      * First, if there is a security manager, its
 790      * <code>checkPropertyAccess</code> method is called with the
 791      * <code>key</code> as its argument.
 792      * <p>
 793      * If there is no current set of system properties, a set of system
 794      * properties is first created and initialized in the same manner as
 795      * for the <code>getProperties</code> method.
 796      *
 797      * @param      key   the name of the system property.
 798      * @param      def   a default value.
 799      * @return     the string value of the system property,
 800      *             or the default value if there is no property with that key.
 801      *
 802      * @exception  SecurityException  if a security manager exists and its
 803      *             <code>checkPropertyAccess</code> method doesn't allow
 804      *             access to the specified system property.
 805      * @exception  NullPointerException if <code>key</code> is
 806      *             <code>null</code>.
 807      * @exception  IllegalArgumentException if <code>key</code> is empty.
 808      * @see        #setProperty
 809      * @see        java.lang.SecurityManager#checkPropertyAccess(java.lang.String)
 810      * @see        java.lang.System#getProperties()
 811      */
 812     public static String getProperty(String key, String def) {
 813         checkKey(key);
 814         SecurityManager sm = getSecurityManager();
 815         if (sm != null) {
 816             sm.checkPropertyAccess(key);
 817         }
 818 
 819         return props.getProperty(key, def);
 820     }
 821 
 822     /**
 823      * Sets the system property indicated by the specified key.
 824      * <p>
 825      * First, if a security manager exists, its
 826      * <code>SecurityManager.checkPermission</code> method
 827      * is called with a <code>PropertyPermission(key, "write")</code>
 828      * permission. This may result in a SecurityException being thrown.
 829      * If no exception is thrown, the specified property is set to the given
 830      * value.
 831      *
 832      * @param      key   the name of the system property.
 833      * @param      value the value of the system property.
 834      * @return     the previous value of the system property,
 835      *             or <code>null</code> if it did not have one.
 836      *
 837      * @exception  SecurityException  if a security manager exists and its
 838      *             <code>checkPermission</code> method doesn't allow
 839      *             setting of the specified property.
 840      * @exception  NullPointerException if <code>key</code> or
 841      *             <code>value</code> is <code>null</code>.
 842      * @exception  IllegalArgumentException if <code>key</code> is empty.
 843      * @see        #getProperty
 844      * @see        java.lang.System#getProperty(java.lang.String)
 845      * @see        java.lang.System#getProperty(java.lang.String, java.lang.String)
 846      * @see        java.util.PropertyPermission
 847      * @see        SecurityManager#checkPermission
 848      * @since      1.2
 849      */
 850     public static String setProperty(String key, String value) {
 851         checkKey(key);
 852         SecurityManager sm = getSecurityManager();
 853         if (sm != null) {
 854             sm.checkPermission(new PropertyPermission(key,
 855                 SecurityConstants.PROPERTY_WRITE_ACTION));
 856         }
 857 
 858         return (String) props.setProperty(key, value);
 859     }
 860 
 861     /**
 862      * Removes the system property indicated by the specified key.
 863      * <p>
 864      * First, if a security manager exists, its
 865      * <code>SecurityManager.checkPermission</code> method
 866      * is called with a <code>PropertyPermission(key, "write")</code>
 867      * permission. This may result in a SecurityException being thrown.
 868      * If no exception is thrown, the specified property is removed.
 869      *
 870      * @param      key   the name of the system property to be removed.
 871      * @return     the previous string value of the system property,
 872      *             or <code>null</code> if there was no property with that key.
 873      *
 874      * @exception  SecurityException  if a security manager exists and its
 875      *             <code>checkPropertyAccess</code> method doesn't allow
 876      *              access to the specified system property.
 877      * @exception  NullPointerException if <code>key</code> is
 878      *             <code>null</code>.
 879      * @exception  IllegalArgumentException if <code>key</code> is empty.
 880      * @see        #getProperty
 881      * @see        #setProperty
 882      * @see        java.util.Properties
 883      * @see        java.lang.SecurityException
 884      * @see        java.lang.SecurityManager#checkPropertiesAccess()
 885      * @since 1.5
 886      */
 887     public static String clearProperty(String key) {
 888         checkKey(key);
 889         SecurityManager sm = getSecurityManager();
 890         if (sm != null) {
 891             sm.checkPermission(new PropertyPermission(key, "write"));
 892         }
 893 
 894         return (String) props.remove(key);
 895     }
 896 
 897     private static void checkKey(String key) {
 898         if (key == null) {
 899             throw new NullPointerException("key can't be null");
 900         }
 901         if (key.equals("")) {
 902             throw new IllegalArgumentException("key can't be empty");
 903         }
 904     }
 905 
 906     /**
 907      * Gets the value of the specified environment variable. An
 908      * environment variable is a system-dependent external named
 909      * value.
 910      *
 911      * <p>If a security manager exists, its
 912      * {@link SecurityManager#checkPermission checkPermission}
 913      * method is called with a
 914      * <code>{@link RuntimePermission}("getenv."+name)</code>
 915      * permission.  This may result in a {@link SecurityException}
 916      * being thrown.  If no exception is thrown the value of the
 917      * variable <code>name</code> is returned.
 918      *
 919      * <p><a id="EnvironmentVSSystemProperties"><i>System
 920      * properties</i> and <i>environment variables</i></a> are both
 921      * conceptually mappings between names and values.  Both
 922      * mechanisms can be used to pass user-defined information to a
 923      * Java process.  Environment variables have a more global effect,
 924      * because they are visible to all descendants of the process
 925      * which defines them, not just the immediate Java subprocess.
 926      * They can have subtly different semantics, such as case
 927      * insensitivity, on different operating systems.  For these
 928      * reasons, environment variables are more likely to have
 929      * unintended side effects.  It is best to use system properties
 930      * where possible.  Environment variables should be used when a
 931      * global effect is desired, or when an external system interface
 932      * requires an environment variable (such as <code>PATH</code>).
 933      *
 934      * <p>On UNIX systems the alphabetic case of <code>name</code> is
 935      * typically significant, while on Microsoft Windows systems it is
 936      * typically not.  For example, the expression
 937      * <code>System.getenv("FOO").equals(System.getenv("foo"))</code>
 938      * is likely to be true on Microsoft Windows.
 939      *
 940      * @param  name the name of the environment variable
 941      * @return the string value of the variable, or <code>null</code>
 942      *         if the variable is not defined in the system environment
 943      * @throws NullPointerException if <code>name</code> is <code>null</code>
 944      * @throws SecurityException
 945      *         if a security manager exists and its
 946      *         {@link SecurityManager#checkPermission checkPermission}
 947      *         method doesn't allow access to the environment variable
 948      *         <code>name</code>
 949      * @see    #getenv()
 950      * @see    ProcessBuilder#environment()
 951      */
 952     public static String getenv(String name) {
 953         SecurityManager sm = getSecurityManager();
 954         if (sm != null) {
 955             sm.checkPermission(new RuntimePermission("getenv."+name));
 956         }
 957 
 958         return ProcessEnvironment.getenv(name);
 959     }
 960 
 961 
 962     /**
 963      * Returns an unmodifiable string map view of the current system environment.
 964      * The environment is a system-dependent mapping from names to
 965      * values which is passed from parent to child processes.
 966      *
 967      * <p>If the system does not support environment variables, an
 968      * empty map is returned.
 969      *
 970      * <p>The returned map will never contain null keys or values.
 971      * Attempting to query the presence of a null key or value will
 972      * throw a {@link NullPointerException}.  Attempting to query
 973      * the presence of a key or value which is not of type
 974      * {@link String} will throw a {@link ClassCastException}.
 975      *
 976      * <p>The returned map and its collection views may not obey the
 977      * general contract of the {@link Object#equals} and
 978      * {@link Object#hashCode} methods.
 979      *
 980      * <p>The returned map is typically case-sensitive on all platforms.
 981      *
 982      * <p>If a security manager exists, its
 983      * {@link SecurityManager#checkPermission checkPermission}
 984      * method is called with a
 985      * <code>{@link RuntimePermission}("getenv.*")</code>
 986      * permission.  This may result in a {@link SecurityException} being
 987      * thrown.
 988      *
 989      * <p>When passing information to a Java subprocess,
 990      * <a href=#EnvironmentVSSystemProperties>system properties</a>
 991      * are generally preferred over environment variables.
 992      *
 993      * @return the environment as a map of variable names to values
 994      * @throws SecurityException
 995      *         if a security manager exists and its
 996      *         {@link SecurityManager#checkPermission checkPermission}
 997      *         method doesn't allow access to the process environment
 998      * @see    #getenv(String)
 999      * @see    ProcessBuilder#environment()
1000      * @since  1.5
1001      */
1002     public static java.util.Map<String,String> getenv() {
1003         SecurityManager sm = getSecurityManager();
1004         if (sm != null) {
1005             sm.checkPermission(new RuntimePermission("getenv.*"));
1006         }
1007 
1008         return ProcessEnvironment.getenv();
1009     }
1010 
1011     /**
1012      * {@code System.Logger} instances log messages that will be
1013      * routed to the underlying logging framework the {@link System.LoggerFinder
1014      * LoggerFinder} uses.
1015      * <p>
1016      * {@code System.Logger} instances are typically obtained from
1017      * the {@link java.lang.System System} class, by calling
1018      * {@link java.lang.System#getLogger(java.lang.String) System.getLogger(loggerName)}
1019      * or {@link java.lang.System#getLogger(java.lang.String, java.util.ResourceBundle)
1020      * System.getLogger(loggerName, bundle)}.
1021      *
1022      * @see java.lang.System#getLogger(java.lang.String)
1023      * @see java.lang.System#getLogger(java.lang.String, java.util.ResourceBundle)
1024      * @see java.lang.System.LoggerFinder
1025      *
1026      * @since 9
1027      *
1028      */
1029     public interface Logger {
1030 
1031         /**
1032          * System {@linkplain Logger loggers} levels.
1033          * <p>
1034          * A level has a {@linkplain #getName() name} and {@linkplain
1035          * #getSeverity() severity}.
1036          * Level values are {@link #ALL}, {@link #TRACE}, {@link #DEBUG},
1037          * {@link #INFO}, {@link #WARNING}, {@link #ERROR}, {@link #OFF},
1038          * by order of increasing severity.
1039          * <br>
1040          * {@link #ALL} and {@link #OFF}
1041          * are simple markers with severities mapped respectively to
1042          * {@link java.lang.Integer#MIN_VALUE Integer.MIN_VALUE} and
1043          * {@link java.lang.Integer#MAX_VALUE Integer.MAX_VALUE}.
1044          * <p>
1045          * <b>Severity values and Mapping to {@code java.util.logging.Level}.</b>
1046          * <p>
1047          * {@linkplain System.Logger.Level System logger levels} are mapped to
1048          * {@linkplain java.util.logging.Level  java.util.logging levels}
1049          * of corresponding severity.
1050          * <br>The mapping is as follows:
1051          * <br><br>
1052          * <table border="1">
1053          * <caption>System.Logger Severity Level Mapping</caption>
1054          * <tr><td><b>System.Logger Levels</b></td>
1055          * <td>{@link Logger.Level#ALL ALL}</td>
1056          * <td>{@link Logger.Level#TRACE TRACE}</td>
1057          * <td>{@link Logger.Level#DEBUG DEBUG}</td>
1058          * <td>{@link Logger.Level#INFO INFO}</td>
1059          * <td>{@link Logger.Level#WARNING WARNING}</td>
1060          * <td>{@link Logger.Level#ERROR ERROR}</td>
1061          * <td>{@link Logger.Level#OFF OFF}</td>
1062          * </tr>
1063          * <tr><td><b>java.util.logging Levels</b></td>
1064          * <td>{@link java.util.logging.Level#ALL ALL}</td>
1065          * <td>{@link java.util.logging.Level#FINER FINER}</td>
1066          * <td>{@link java.util.logging.Level#FINE FINE}</td>
1067          * <td>{@link java.util.logging.Level#INFO INFO}</td>
1068          * <td>{@link java.util.logging.Level#WARNING WARNING}</td>
1069          * <td>{@link java.util.logging.Level#SEVERE SEVERE}</td>
1070          * <td>{@link java.util.logging.Level#OFF OFF}</td>
1071          * </tr>
1072          * </table>
1073          *
1074          * @since 9
1075          *
1076          * @see java.lang.System.LoggerFinder
1077          * @see java.lang.System.Logger
1078          */
1079         public enum Level {
1080 
1081             // for convenience, we're reusing java.util.logging.Level int values
1082             // the mapping logic in sun.util.logging.PlatformLogger depends
1083             // on this.
1084             /**
1085              * A marker to indicate that all levels are enabled.
1086              * This level {@linkplain #getSeverity() severity} is
1087              * {@link Integer#MIN_VALUE}.
1088              */
1089             ALL(Integer.MIN_VALUE),  // typically mapped to/from j.u.l.Level.ALL
1090             /**
1091              * {@code TRACE} level: usually used to log diagnostic information.
1092              * This level {@linkplain #getSeverity() severity} is
1093              * {@code 400}.
1094              */
1095             TRACE(400),   // typically mapped to/from j.u.l.Level.FINER
1096             /**
1097              * {@code DEBUG} level: usually used to log debug information traces.
1098              * This level {@linkplain #getSeverity() severity} is
1099              * {@code 500}.
1100              */
1101             DEBUG(500),   // typically mapped to/from j.u.l.Level.FINEST/FINE/CONFIG
1102             /**
1103              * {@code INFO} level: usually used to log information messages.
1104              * This level {@linkplain #getSeverity() severity} is
1105              * {@code 800}.
1106              */
1107             INFO(800),    // typically mapped to/from j.u.l.Level.INFO
1108             /**
1109              * {@code WARNING} level: usually used to log warning messages.
1110              * This level {@linkplain #getSeverity() severity} is
1111              * {@code 900}.
1112              */
1113             WARNING(900), // typically mapped to/from j.u.l.Level.WARNING
1114             /**
1115              * {@code ERROR} level: usually used to log error messages.
1116              * This level {@linkplain #getSeverity() severity} is
1117              * {@code 1000}.
1118              */
1119             ERROR(1000),  // typically mapped to/from j.u.l.Level.SEVERE
1120             /**
1121              * A marker to indicate that all levels are disabled.
1122              * This level {@linkplain #getSeverity() severity} is
1123              * {@link Integer#MAX_VALUE}.
1124              */
1125             OFF(Integer.MAX_VALUE);  // typically mapped to/from j.u.l.Level.OFF
1126 
1127             private final int severity;
1128 
1129             private Level(int severity) {
1130                 this.severity = severity;
1131             }
1132 
1133             /**
1134              * Returns the name of this level.
1135              * @return this level {@linkplain #name()}.
1136              */
1137             public final String getName() {
1138                 return name();
1139             }
1140 
1141             /**
1142              * Returns the severity of this level.
1143              * A higher severity means a more severe condition.
1144              * @return this level severity.
1145              */
1146             public final int getSeverity() {
1147                 return severity;
1148             }
1149         }
1150 
1151         /**
1152          * Returns the name of this logger.
1153          *
1154          * @return the logger name.
1155          */
1156         public String getName();
1157 
1158         /**
1159          * Checks if a message of the given level would be logged by
1160          * this logger.
1161          *
1162          * @param level the log message level.
1163          * @return {@code true} if the given log message level is currently
1164          *         being logged.
1165          *
1166          * @throws NullPointerException if {@code level} is {@code null}.
1167          */
1168         public boolean isLoggable(Level level);
1169 
1170         /**
1171          * Logs a message.
1172          *
1173          * @implSpec The default implementation for this method calls
1174          * {@code this.log(level, (ResourceBundle)null, msg, (Object[])null);}
1175          *
1176          * @param level the log message level.
1177          * @param msg the string message (or a key in the message catalog, if
1178          * this logger is a {@link
1179          * LoggerFinder#getLocalizedLogger(java.lang.String,
1180          * java.util.ResourceBundle, java.lang.Module) localized logger});
1181          * can be {@code null}.
1182          *
1183          * @throws NullPointerException if {@code level} is {@code null}.
1184          */
1185         public default void log(Level level, String msg) {
1186             log(level, (ResourceBundle) null, msg, (Object[]) null);
1187         }
1188 
1189         /**
1190          * Logs a lazily supplied message.
1191          * <p>
1192          * If the logger is currently enabled for the given log message level
1193          * then a message is logged that is the result produced by the
1194          * given supplier function.  Otherwise, the supplier is not operated on.
1195          *
1196          * @implSpec When logging is enabled for the given level, the default
1197          * implementation for this method calls
1198          * {@code this.log(level, (ResourceBundle)null, msgSupplier.get(), (Object[])null);}
1199          *
1200          * @param level the log message level.
1201          * @param msgSupplier a supplier function that produces a message.
1202          *
1203          * @throws NullPointerException if {@code level} is {@code null},
1204          *         or {@code msgSupplier} is {@code null}.
1205          */
1206         public default void log(Level level, Supplier<String> msgSupplier) {
1207             Objects.requireNonNull(msgSupplier);
1208             if (isLoggable(Objects.requireNonNull(level))) {
1209                 log(level, (ResourceBundle) null, msgSupplier.get(), (Object[]) null);
1210             }
1211         }
1212 
1213         /**
1214          * Logs a message produced from the given object.
1215          * <p>
1216          * If the logger is currently enabled for the given log message level then
1217          * a message is logged that, by default, is the result produced from
1218          * calling  toString on the given object.
1219          * Otherwise, the object is not operated on.
1220          *
1221          * @implSpec When logging is enabled for the given level, the default
1222          * implementation for this method calls
1223          * {@code this.log(level, (ResourceBundle)null, obj.toString(), (Object[])null);}
1224          *
1225          * @param level the log message level.
1226          * @param obj the object to log.
1227          *
1228          * @throws NullPointerException if {@code level} is {@code null}, or
1229          *         {@code obj} is {@code null}.
1230          */
1231         public default void log(Level level, Object obj) {
1232             Objects.requireNonNull(obj);
1233             if (isLoggable(Objects.requireNonNull(level))) {
1234                 this.log(level, (ResourceBundle) null, obj.toString(), (Object[]) null);
1235             }
1236         }
1237 
1238         /**
1239          * Logs a message associated with a given throwable.
1240          *
1241          * @implSpec The default implementation for this method calls
1242          * {@code this.log(level, (ResourceBundle)null, msg, thrown);}
1243          *
1244          * @param level the log message level.
1245          * @param msg the string message (or a key in the message catalog, if
1246          * this logger is a {@link
1247          * LoggerFinder#getLocalizedLogger(java.lang.String,
1248          * java.util.ResourceBundle, java.lang.Module) localized logger});
1249          * can be {@code null}.
1250          * @param thrown a {@code Throwable} associated with the log message;
1251          *        can be {@code null}.
1252          *
1253          * @throws NullPointerException if {@code level} is {@code null}.
1254          */
1255         public default void log(Level level, String msg, Throwable thrown) {
1256             this.log(level, null, msg, thrown);
1257         }
1258 
1259         /**
1260          * Logs a lazily supplied message associated with a given throwable.
1261          * <p>
1262          * If the logger is currently enabled for the given log message level
1263          * then a message is logged that is the result produced by the
1264          * given supplier function.  Otherwise, the supplier is not operated on.
1265          *
1266          * @implSpec When logging is enabled for the given level, the default
1267          * implementation for this method calls
1268          * {@code this.log(level, (ResourceBundle)null, msgSupplier.get(), thrown);}
1269          *
1270          * @param level one of the log message level identifiers.
1271          * @param msgSupplier a supplier function that produces a message.
1272          * @param thrown a {@code Throwable} associated with log message;
1273          *               can be {@code null}.
1274          *
1275          * @throws NullPointerException if {@code level} is {@code null}, or
1276          *                               {@code msgSupplier} is {@code null}.
1277          */
1278         public default void log(Level level, Supplier<String> msgSupplier,
1279                 Throwable thrown) {
1280             Objects.requireNonNull(msgSupplier);
1281             if (isLoggable(Objects.requireNonNull(level))) {
1282                 this.log(level, null, msgSupplier.get(), thrown);
1283             }
1284         }
1285 
1286         /**
1287          * Logs a message with an optional list of parameters.
1288          *
1289          * @implSpec The default implementation for this method calls
1290          * {@code this.log(level, (ResourceBundle)null, format, params);}
1291          *
1292          * @param level one of the log message level identifiers.
1293          * @param format the string message format in {@link
1294          * java.text.MessageFormat} format, (or a key in the message
1295          * catalog, if this logger is a {@link
1296          * LoggerFinder#getLocalizedLogger(java.lang.String,
1297          * java.util.ResourceBundle, java.lang.Module) localized logger});
1298          * can be {@code null}.
1299          * @param params an optional list of parameters to the message (may be
1300          * none).
1301          *
1302          * @throws NullPointerException if {@code level} is {@code null}.
1303          */
1304         public default void log(Level level, String format, Object... params) {
1305             this.log(level, null, format, params);
1306         }
1307 
1308         /**
1309          * Logs a localized message associated with a given throwable.
1310          * <p>
1311          * If the given resource bundle is non-{@code null},  the {@code msg}
1312          * string is localized using the given resource bundle.
1313          * Otherwise the {@code msg} string is not localized.
1314          *
1315          * @param level the log message level.
1316          * @param bundle a resource bundle to localize {@code msg}; can be
1317          * {@code null}.
1318          * @param msg the string message (or a key in the message catalog,
1319          *            if {@code bundle} is not {@code null}); can be {@code null}.
1320          * @param thrown a {@code Throwable} associated with the log message;
1321          *        can be {@code null}.
1322          *
1323          * @throws NullPointerException if {@code level} is {@code null}.
1324          */
1325         public void log(Level level, ResourceBundle bundle, String msg,
1326                 Throwable thrown);
1327 
1328         /**
1329          * Logs a message with resource bundle and an optional list of
1330          * parameters.
1331          * <p>
1332          * If the given resource bundle is non-{@code null},  the {@code format}
1333          * string is localized using the given resource bundle.
1334          * Otherwise the {@code format} string is not localized.
1335          *
1336          * @param level the log message level.
1337          * @param bundle a resource bundle to localize {@code format}; can be
1338          * {@code null}.
1339          * @param format the string message format in {@link
1340          * java.text.MessageFormat} format, (or a key in the message
1341          * catalog if {@code bundle} is not {@code null}); can be {@code null}.
1342          * @param params an optional list of parameters to the message (may be
1343          * none).
1344          *
1345          * @throws NullPointerException if {@code level} is {@code null}.
1346          */
1347         public void log(Level level, ResourceBundle bundle, String format,
1348                 Object... params);
1349 
1350 
1351     }
1352 
1353     /**
1354      * The {@code LoggerFinder} service is responsible for creating, managing,
1355      * and configuring loggers to the underlying framework it uses.
1356      * <p>
1357      * A logger finder is a concrete implementation of this class that has a
1358      * zero-argument constructor and implements the abstract methods defined
1359      * by this class.
1360      * The loggers returned from a logger finder are capable of routing log
1361      * messages to the logging backend this provider supports.
1362      * A given invocation of the Java Runtime maintains a single
1363      * system-wide LoggerFinder instance that is loaded as follows:
1364      * <ul>
1365      *    <li>First it finds any custom {@code LoggerFinder} provider
1366      *        using the {@link java.util.ServiceLoader} facility with the
1367      *        {@linkplain ClassLoader#getSystemClassLoader() system class
1368      *        loader}.</li>
1369      *    <li>If no {@code LoggerFinder} provider is found, the system default
1370      *        {@code LoggerFinder} implementation will be used.</li>
1371      * </ul>
1372      * <p>
1373      * An application can replace the logging backend
1374      * <i>even when the java.logging module is present</i>, by simply providing
1375      * and declaring an implementation of the {@link LoggerFinder} service.
1376      * <p>
1377      * <b>Default Implementation</b>
1378      * <p>
1379      * The system default {@code LoggerFinder} implementation uses
1380      * {@code java.util.logging} as the backend framework when the
1381      * {@code java.logging} module is present.
1382      * It returns a {@linkplain System.Logger logger} instance
1383      * that will route log messages to a {@link java.util.logging.Logger
1384      * java.util.logging.Logger}. Otherwise, if {@code java.logging} is not
1385      * present, the default implementation will return a simple logger
1386      * instance that will route log messages of {@code INFO} level and above to
1387      * the console ({@code System.err}).
1388      * <p>
1389      * <b>Logging Configuration</b>
1390      * <p>
1391      * {@linkplain Logger Logger} instances obtained from the
1392      * {@code LoggerFinder} factory methods are not directly configurable by
1393      * the application. Configuration is the responsibility of the underlying
1394      * logging backend, and usually requires using APIs specific to that backend.
1395      * <p>For the default {@code LoggerFinder} implementation
1396      * using {@code java.util.logging} as its backend, refer to
1397      * {@link java.util.logging java.util.logging} for logging configuration.
1398      * For the default {@code LoggerFinder} implementation returning simple loggers
1399      * when the {@code java.logging} module is absent, the configuration
1400      * is implementation dependent.
1401      * <p>
1402      * Usually an application that uses a logging framework will log messages
1403      * through a logger facade defined (or supported) by that framework.
1404      * Applications that wish to use an external framework should log
1405      * through the facade associated with that framework.
1406      * <p>
1407      * A system class that needs to log messages will typically obtain
1408      * a {@link System.Logger} instance to route messages to the logging
1409      * framework selected by the application.
1410      * <p>
1411      * Libraries and classes that only need loggers to produce log messages
1412      * should not attempt to configure loggers by themselves, as that
1413      * would make them dependent from a specific implementation of the
1414      * {@code LoggerFinder} service.
1415      * <p>
1416      * In addition, when a security manager is present, loggers provided to
1417      * system classes should not be directly configurable through the logging
1418      * backend without requiring permissions.
1419      * <br>
1420      * It is the responsibility of the provider of
1421      * the concrete {@code LoggerFinder} implementation to ensure that
1422      * these loggers are not configured by untrusted code without proper
1423      * permission checks, as configuration performed on such loggers usually
1424      * affects all applications in the same Java Runtime.
1425      * <p>
1426      * <b>Message Levels and Mapping to backend levels</b>
1427      * <p>
1428      * A logger finder is responsible for mapping from a {@code
1429      * System.Logger.Level} to a level supported by the logging backend it uses.
1430      * <br>The default LoggerFinder using {@code java.util.logging} as the backend
1431      * maps {@code System.Logger} levels to
1432      * {@linkplain java.util.logging.Level java.util.logging} levels
1433      * of corresponding severity - as described in {@link Logger.Level
1434      * Logger.Level}.
1435      *
1436      * @see java.lang.System
1437      * @see java.lang.System.Logger
1438      *
1439      * @since 9
1440      */
1441     public static abstract class LoggerFinder {
1442         /**
1443          * The {@code RuntimePermission("loggerFinder")} is
1444          * necessary to subclass and instantiate the {@code LoggerFinder} class,
1445          * as well as to obtain loggers from an instance of that class.
1446          */
1447         static final RuntimePermission LOGGERFINDER_PERMISSION =
1448                 new RuntimePermission("loggerFinder");
1449 
1450         /**
1451          * Creates a new instance of {@code LoggerFinder}.
1452          *
1453          * @implNote It is recommended that a {@code LoggerFinder} service
1454          *   implementation does not perform any heavy initialization in its
1455          *   constructor, in order to avoid possible risks of deadlock or class
1456          *   loading cycles during the instantiation of the service provider.
1457          *
1458          * @throws SecurityException if a security manager is present and its
1459          *         {@code checkPermission} method doesn't allow the
1460          *         {@code RuntimePermission("loggerFinder")}.
1461          */
1462         protected LoggerFinder() {
1463             this(checkPermission());
1464         }
1465 
1466         private LoggerFinder(Void unused) {
1467             // nothing to do.
1468         }
1469 
1470         private static Void checkPermission() {
1471             final SecurityManager sm = System.getSecurityManager();
1472             if (sm != null) {
1473                 sm.checkPermission(LOGGERFINDER_PERMISSION);
1474             }
1475             return null;
1476         }
1477 
1478         /**
1479          * Returns an instance of {@link Logger Logger}
1480          * for the given {@code module}.
1481          *
1482          * @param name the name of the logger.
1483          * @param module the module for which the logger is being requested.
1484          *
1485          * @return a {@link Logger logger} suitable for use within the given
1486          *         module.
1487          * @throws NullPointerException if {@code name} is {@code null} or
1488          *        {@code module} is {@code null}.
1489          * @throws SecurityException if a security manager is present and its
1490          *         {@code checkPermission} method doesn't allow the
1491          *         {@code RuntimePermission("loggerFinder")}.
1492          */
1493         public abstract Logger getLogger(String name, Module module);
1494 
1495         /**
1496          * Returns a localizable instance of {@link Logger Logger}
1497          * for the given {@code module}.
1498          * The returned logger will use the provided resource bundle for
1499          * message localization.
1500          *
1501          * @implSpec By default, this method calls {@link
1502          * #getLogger(java.lang.String, java.lang.Module)
1503          * this.getLogger(name, module)} to obtain a logger, then wraps that
1504          * logger in a {@link Logger} instance where all methods that do not
1505          * take a {@link ResourceBundle} as parameter are redirected to one
1506          * which does - passing the given {@code bundle} for
1507          * localization. So for instance, a call to {@link
1508          * Logger#log(Level, String) Logger.log(Level.INFO, msg)}
1509          * will end up as a call to {@link
1510          * Logger#log(Level, ResourceBundle, String, Object...)
1511          * Logger.log(Level.INFO, bundle, msg, (Object[])null)} on the wrapped
1512          * logger instance.
1513          * Note however that by default, string messages returned by {@link
1514          * java.util.function.Supplier Supplier&lt;String&gt;} will not be
1515          * localized, as it is assumed that such strings are messages which are
1516          * already constructed, rather than keys in a resource bundle.
1517          * <p>
1518          * An implementation of {@code LoggerFinder} may override this method,
1519          * for example, when the underlying logging backend provides its own
1520          * mechanism for localizing log messages, then such a
1521          * {@code LoggerFinder} would be free to return a logger
1522          * that makes direct use of the mechanism provided by the backend.
1523          *
1524          * @param name    the name of the logger.
1525          * @param bundle  a resource bundle; can be {@code null}.
1526          * @param module  the module for which the logger is being requested.
1527          * @return an instance of {@link Logger Logger}  which will use the
1528          * provided resource bundle for message localization.
1529          *
1530          * @throws NullPointerException if {@code name} is {@code null} or
1531          *         {@code module} is {@code null}.
1532          * @throws SecurityException if a security manager is present and its
1533          *         {@code checkPermission} method doesn't allow the
1534          *         {@code RuntimePermission("loggerFinder")}.
1535          */
1536         public Logger getLocalizedLogger(String name, ResourceBundle bundle,
1537                                          Module module) {
1538             return new LocalizedLoggerWrapper<>(getLogger(name, module), bundle);
1539         }
1540 
1541         /**
1542          * Returns the {@code LoggerFinder} instance. There is one
1543          * single system-wide {@code LoggerFinder} instance in
1544          * the Java Runtime.  See the class specification of how the
1545          * {@link LoggerFinder LoggerFinder} implementation is located and
1546          * loaded.
1547 
1548          * @return the {@link LoggerFinder LoggerFinder} instance.
1549          * @throws SecurityException if a security manager is present and its
1550          *         {@code checkPermission} method doesn't allow the
1551          *         {@code RuntimePermission("loggerFinder")}.
1552          */
1553         public static LoggerFinder getLoggerFinder() {
1554             final SecurityManager sm = System.getSecurityManager();
1555             if (sm != null) {
1556                 sm.checkPermission(LOGGERFINDER_PERMISSION);
1557             }
1558             return accessProvider();
1559         }
1560 
1561 
1562         private static volatile LoggerFinder service;
1563         static LoggerFinder accessProvider() {
1564             // We do not need to synchronize: LoggerFinderLoader will
1565             // always return the same instance, so if we don't have it,
1566             // just fetch it again.
1567             if (service == null) {
1568                 PrivilegedAction<LoggerFinder> pa =
1569                         () -> LoggerFinderLoader.getLoggerFinder();
1570                 service = AccessController.doPrivileged(pa, null,
1571                         LOGGERFINDER_PERMISSION);
1572             }
1573             return service;
1574         }
1575 
1576     }
1577 
1578 
1579     /**
1580      * Returns an instance of {@link Logger Logger} for the caller's
1581      * use.
1582      *
1583      * @implSpec
1584      * Instances returned by this method route messages to loggers
1585      * obtained by calling {@link LoggerFinder#getLogger(java.lang.String,
1586      * java.lang.Module) LoggerFinder.getLogger(name, module)}, where
1587      * {@code module} is the caller's module.
1588      * In cases where {@code System.getLogger} is called from a context where
1589      * there is no caller frame on the stack (e.g when called directly
1590      * from a JNI attached thread), {@code IllegalCallerException} is thrown.
1591      * To obtain a logger in such a context, use an auxiliary class that will
1592      * implicitly be identified as the caller, or use the system {@link
1593      * LoggerFinder#getLoggerFinder() LoggerFinder} to obtain a logger instead.
1594      * Note that doing the latter may eagerly initialize the underlying
1595      * logging system.
1596      *
1597      * @apiNote
1598      * This method may defer calling the {@link
1599      * LoggerFinder#getLogger(java.lang.String, java.lang.Module)
1600      * LoggerFinder.getLogger} method to create an actual logger supplied by
1601      * the logging backend, for instance, to allow loggers to be obtained during
1602      * the system initialization time.
1603      *
1604      * @param name the name of the logger.
1605      * @return an instance of {@link Logger} that can be used by the calling
1606      *         class.
1607      * @throws NullPointerException if {@code name} is {@code null}.
1608      * @throws IllegalCallerException if there is no Java caller frame on the
1609      *         stack.
1610      *
1611      * @since 9
1612      */
1613     @CallerSensitive
1614     public static Logger getLogger(String name) {
1615         Objects.requireNonNull(name);
1616         final Class<?> caller = Reflection.getCallerClass();
1617         if (caller == null) {
1618             throw new IllegalCallerException("no caller frame");
1619         }
1620         return LazyLoggers.getLogger(name, caller.getModule());
1621     }
1622 
1623     /**
1624      * Returns a localizable instance of {@link Logger
1625      * Logger} for the caller's use.
1626      * The returned logger will use the provided resource bundle for message
1627      * localization.
1628      *
1629      * @implSpec
1630      * The returned logger will perform message localization as specified
1631      * by {@link LoggerFinder#getLocalizedLogger(java.lang.String,
1632      * java.util.ResourceBundle, java.lang.Module)
1633      * LoggerFinder.getLocalizedLogger(name, bundle, module)}, where
1634      * {@code module} is the caller's module.
1635      * In cases where {@code System.getLogger} is called from a context where
1636      * there is no caller frame on the stack (e.g when called directly
1637      * from a JNI attached thread), {@code IllegalCallerException} is thrown.
1638      * To obtain a logger in such a context, use an auxiliary class that
1639      * will implicitly be identified as the caller, or use the system {@link
1640      * LoggerFinder#getLoggerFinder() LoggerFinder} to obtain a logger instead.
1641      * Note that doing the latter may eagerly initialize the underlying
1642      * logging system.
1643      *
1644      * @apiNote
1645      * This method is intended to be used after the system is fully initialized.
1646      * This method may trigger the immediate loading and initialization
1647      * of the {@link LoggerFinder} service, which may cause issues if the
1648      * Java Runtime is not ready to initialize the concrete service
1649      * implementation yet.
1650      * System classes which may be loaded early in the boot sequence and
1651      * need to log localized messages should create a logger using
1652      * {@link #getLogger(java.lang.String)} and then use the log methods that
1653      * take a resource bundle as parameter.
1654      *
1655      * @param name    the name of the logger.
1656      * @param bundle  a resource bundle.
1657      * @return an instance of {@link Logger} which will use the provided
1658      * resource bundle for message localization.
1659      * @throws NullPointerException if {@code name} is {@code null} or
1660      *         {@code bundle} is {@code null}.
1661      * @throws IllegalCallerException if there is no Java caller frame on the
1662      *         stack.
1663      *
1664      * @since 9
1665      */
1666     @CallerSensitive
1667     public static Logger getLogger(String name, ResourceBundle bundle) {
1668         final ResourceBundle rb = Objects.requireNonNull(bundle);
1669         Objects.requireNonNull(name);
1670         final Class<?> caller = Reflection.getCallerClass();
1671         if (caller == null) {
1672             throw new IllegalCallerException("no caller frame");
1673         }
1674         final SecurityManager sm = System.getSecurityManager();
1675         // We don't use LazyLoggers if a resource bundle is specified.
1676         // Bootstrap sensitive classes in the JDK do not use resource bundles
1677         // when logging. This could be revisited later, if it needs to.
1678         if (sm != null) {
1679             final PrivilegedAction<Logger> pa =
1680                     () -> LoggerFinder.accessProvider()
1681                             .getLocalizedLogger(name, rb, caller.getModule());
1682             return AccessController.doPrivileged(pa, null,
1683                                          LoggerFinder.LOGGERFINDER_PERMISSION);
1684         }
1685         return LoggerFinder.accessProvider()
1686                 .getLocalizedLogger(name, rb, caller.getModule());
1687     }
1688 
1689     /**
1690      * Terminates the currently running Java Virtual Machine. The
1691      * argument serves as a status code; by convention, a nonzero status
1692      * code indicates abnormal termination.
1693      * <p>
1694      * This method calls the <code>exit</code> method in class
1695      * <code>Runtime</code>. This method never returns normally.
1696      * <p>
1697      * The call <code>System.exit(n)</code> is effectively equivalent to
1698      * the call:
1699      * <blockquote><pre>
1700      * Runtime.getRuntime().exit(n)
1701      * </pre></blockquote>
1702      *
1703      * @param      status   exit status.
1704      * @throws  SecurityException
1705      *        if a security manager exists and its <code>checkExit</code>
1706      *        method doesn't allow exit with the specified status.
1707      * @see        java.lang.Runtime#exit(int)
1708      */
1709     public static void exit(int status) {
1710         Runtime.getRuntime().exit(status);
1711     }
1712 
1713     /**
1714      * Runs the garbage collector.
1715      * <p>
1716      * Calling the <code>gc</code> method suggests that the Java Virtual
1717      * Machine expend effort toward recycling unused objects in order to
1718      * make the memory they currently occupy available for quick reuse.
1719      * When control returns from the method call, the Java Virtual
1720      * Machine has made a best effort to reclaim space from all discarded
1721      * objects.
1722      * <p>
1723      * The call <code>System.gc()</code> is effectively equivalent to the
1724      * call:
1725      * <blockquote><pre>
1726      * Runtime.getRuntime().gc()
1727      * </pre></blockquote>
1728      *
1729      * @see     java.lang.Runtime#gc()
1730      */
1731     public static void gc() {
1732         Runtime.getRuntime().gc();
1733     }
1734 
1735     /**
1736      * Runs the finalization methods of any objects pending finalization.
1737      * <p>
1738      * Calling this method suggests that the Java Virtual Machine expend
1739      * effort toward running the <code>finalize</code> methods of objects
1740      * that have been found to be discarded but whose <code>finalize</code>
1741      * methods have not yet been run. When control returns from the
1742      * method call, the Java Virtual Machine has made a best effort to
1743      * complete all outstanding finalizations.
1744      * <p>
1745      * The call <code>System.runFinalization()</code> is effectively
1746      * equivalent to the call:
1747      * <blockquote><pre>
1748      * Runtime.getRuntime().runFinalization()
1749      * </pre></blockquote>
1750      *
1751      * @see     java.lang.Runtime#runFinalization()
1752      */
1753     public static void runFinalization() {
1754         Runtime.getRuntime().runFinalization();
1755     }
1756 
1757     /**
1758      * Enable or disable finalization on exit; doing so specifies that the
1759      * finalizers of all objects that have finalizers that have not yet been
1760      * automatically invoked are to be run before the Java runtime exits.
1761      * By default, finalization on exit is disabled.
1762      *
1763      * <p>If there is a security manager,
1764      * its <code>checkExit</code> method is first called
1765      * with 0 as its argument to ensure the exit is allowed.
1766      * This could result in a SecurityException.
1767      *
1768      * @deprecated  This method is inherently unsafe.  It may result in
1769      *      finalizers being called on live objects while other threads are
1770      *      concurrently manipulating those objects, resulting in erratic
1771      *      behavior or deadlock.
1772      *      This method is subject to removal in a future version of Java SE.
1773      * @param value indicating enabling or disabling of finalization
1774      * @throws  SecurityException
1775      *        if a security manager exists and its <code>checkExit</code>
1776      *        method doesn't allow the exit.
1777      *
1778      * @see     java.lang.Runtime#exit(int)
1779      * @see     java.lang.Runtime#gc()
1780      * @see     java.lang.SecurityManager#checkExit(int)
1781      * @since   1.1
1782      */
1783     @Deprecated(since="1.2", forRemoval=true)
1784     @SuppressWarnings("removal")
1785     public static void runFinalizersOnExit(boolean value) {
1786         Runtime.runFinalizersOnExit(value);
1787     }
1788 
1789     /**
1790      * Loads the native library specified by the filename argument.  The filename
1791      * argument must be an absolute path name.
1792      *
1793      * If the filename argument, when stripped of any platform-specific library
1794      * prefix, path, and file extension, indicates a library whose name is,
1795      * for example, L, and a native library called L is statically linked
1796      * with the VM, then the JNI_OnLoad_L function exported by the library
1797      * is invoked rather than attempting to load a dynamic library.
1798      * A filename matching the argument does not have to exist in the
1799      * file system.
1800      * See the JNI Specification for more details.
1801      *
1802      * Otherwise, the filename argument is mapped to a native library image in
1803      * an implementation-dependent manner.
1804      *
1805      * <p>
1806      * The call <code>System.load(name)</code> is effectively equivalent
1807      * to the call:
1808      * <blockquote><pre>
1809      * Runtime.getRuntime().load(name)
1810      * </pre></blockquote>
1811      *
1812      * @param      filename   the file to load.
1813      * @exception  SecurityException  if a security manager exists and its
1814      *             <code>checkLink</code> method doesn't allow
1815      *             loading of the specified dynamic library
1816      * @exception  UnsatisfiedLinkError  if either the filename is not an
1817      *             absolute path name, the native library is not statically
1818      *             linked with the VM, or the library cannot be mapped to
1819      *             a native library image by the host system.
1820      * @exception  NullPointerException if <code>filename</code> is
1821      *             <code>null</code>
1822      * @see        java.lang.Runtime#load(java.lang.String)
1823      * @see        java.lang.SecurityManager#checkLink(java.lang.String)
1824      */
1825     @CallerSensitive
1826     public static void load(String filename) {
1827         Runtime.getRuntime().load0(Reflection.getCallerClass(), filename);
1828     }
1829 
1830     /**
1831      * Loads the native library specified by the <code>libname</code>
1832      * argument.  The <code>libname</code> argument must not contain any platform
1833      * specific prefix, file extension or path. If a native library
1834      * called <code>libname</code> is statically linked with the VM, then the
1835      * JNI_OnLoad_<code>libname</code> function exported by the library is invoked.
1836      * See the JNI Specification for more details.
1837      *
1838      * Otherwise, the libname argument is loaded from a system library
1839      * location and mapped to a native library image in an implementation-
1840      * dependent manner.
1841      * <p>
1842      * The call <code>System.loadLibrary(name)</code> is effectively
1843      * equivalent to the call
1844      * <blockquote><pre>
1845      * Runtime.getRuntime().loadLibrary(name)
1846      * </pre></blockquote>
1847      *
1848      * @param      libname   the name of the library.
1849      * @exception  SecurityException  if a security manager exists and its
1850      *             <code>checkLink</code> method doesn't allow
1851      *             loading of the specified dynamic library
1852      * @exception  UnsatisfiedLinkError if either the libname argument
1853      *             contains a file path, the native library is not statically
1854      *             linked with the VM,  or the library cannot be mapped to a
1855      *             native library image by the host system.
1856      * @exception  NullPointerException if <code>libname</code> is
1857      *             <code>null</code>
1858      * @see        java.lang.Runtime#loadLibrary(java.lang.String)
1859      * @see        java.lang.SecurityManager#checkLink(java.lang.String)
1860      */
1861     @CallerSensitive
1862     public static void loadLibrary(String libname) {
1863         Runtime.getRuntime().loadLibrary0(Reflection.getCallerClass(), libname);
1864     }
1865 
1866     /**
1867      * Maps a library name into a platform-specific string representing
1868      * a native library.
1869      *
1870      * @param      libname the name of the library.
1871      * @return     a platform-dependent native library name.
1872      * @exception  NullPointerException if <code>libname</code> is
1873      *             <code>null</code>
1874      * @see        java.lang.System#loadLibrary(java.lang.String)
1875      * @see        java.lang.ClassLoader#findLibrary(java.lang.String)
1876      * @since      1.2
1877      */
1878     public static native String mapLibraryName(String libname);
1879 
1880     /**
1881      * Create PrintStream for stdout/err based on encoding.
1882      */
1883     private static PrintStream newPrintStream(FileOutputStream fos, String enc) {
1884        if (enc != null) {
1885             try {
1886                 return new PrintStream(new BufferedOutputStream(fos, 128), true, enc);
1887             } catch (UnsupportedEncodingException uee) {}
1888         }
1889         return new PrintStream(new BufferedOutputStream(fos, 128), true);
1890     }
1891 
1892     /**
1893      * Logs an exception/error at initialization time to stdout or stderr.
1894      *
1895      * @param printToStderr to print to stderr rather than stdout
1896      * @param printStackTrace to print the stack trace
1897      * @param msg the message to print before the exception, can be {@code null}
1898      * @param e the exception or error
1899      */
1900     private static void logInitException(boolean printToStderr,
1901                                          boolean printStackTrace,
1902                                          String msg,
1903                                          Throwable e) {
1904         if (VM.initLevel() < 1) {
1905             throw new InternalError("system classes not initialized");
1906         }
1907         PrintStream log = (printToStderr) ? err : out;
1908         if (msg != null) {
1909             log.println(msg);
1910         }
1911         if (printStackTrace) {
1912             e.printStackTrace(log);
1913         } else {
1914             log.println(e);
1915             for (Throwable suppressed : e.getSuppressed()) {
1916                 log.println("Suppressed: " + suppressed);
1917             }
1918             Throwable cause = e.getCause();
1919             if (cause != null) {
1920                 log.println("Caused by: " + cause);
1921             }
1922         }
1923     }
1924 
1925     /**
1926      * Initialize the system class.  Called after thread initialization.
1927      */
1928     private static void initPhase1() {
1929 
1930         // VM might invoke JNU_NewStringPlatform() to set those encoding
1931         // sensitive properties (user.home, user.name, boot.class.path, etc.)
1932         // during "props" initialization, in which it may need access, via
1933         // System.getProperty(), to the related system encoding property that
1934         // have been initialized (put into "props") at early stage of the
1935         // initialization. So make sure the "props" is available at the
1936         // very beginning of the initialization and all system properties to
1937         // be put into it directly.
1938         props = new Properties();
1939         initProperties(props);  // initialized by the VM
1940 
1941         // There are certain system configurations that may be controlled by
1942         // VM options such as the maximum amount of direct memory and
1943         // Integer cache size used to support the object identity semantics
1944         // of autoboxing.  Typically, the library will obtain these values
1945         // from the properties set by the VM.  If the properties are for
1946         // internal implementation use only, these properties should be
1947         // removed from the system properties.
1948         //
1949         // See java.lang.Integer.IntegerCache and the
1950         // VM.saveAndRemoveProperties method for example.
1951         //
1952         // Save a private copy of the system properties object that
1953         // can only be accessed by the internal implementation.  Remove
1954         // certain system properties that are not intended for public access.
1955         VM.saveAndRemoveProperties(props);
1956 
1957         lineSeparator = props.getProperty("line.separator");
1958         VersionProps.init();
1959 
1960         FileInputStream fdIn = new FileInputStream(FileDescriptor.in);
1961         FileOutputStream fdOut = new FileOutputStream(FileDescriptor.out);
1962         FileOutputStream fdErr = new FileOutputStream(FileDescriptor.err);
1963         setIn0(new BufferedInputStream(fdIn));
1964         setOut0(newPrintStream(fdOut, props.getProperty("sun.stdout.encoding")));
1965         setErr0(newPrintStream(fdErr, props.getProperty("sun.stderr.encoding")));
1966 
1967         // Setup Java signal handlers for HUP, TERM, and INT (where available).
1968         Terminator.setup();
1969 
1970         // Initialize any miscellaneous operating system settings that need to be
1971         // set for the class libraries. Currently this is no-op everywhere except
1972         // for Windows where the process-wide error mode is set before the java.io
1973         // classes are used.
1974         VM.initializeOSEnvironment();
1975 
1976         // The main thread is not added to its thread group in the same
1977         // way as other threads; we must do it ourselves here.
1978         Thread current = Thread.currentThread();
1979         current.getThreadGroup().add(current);
1980 
1981         // register shared secrets
1982         setJavaLangAccess();
1983 
1984         // Subsystems that are invoked during initialization can invoke
1985         // VM.isBooted() in order to avoid doing things that should
1986         // wait until the VM is fully initialized. The initialization level
1987         // is incremented from 0 to 1 here to indicate the first phase of
1988         // initialization has completed.
1989         // IMPORTANT: Ensure that this remains the last initialization action!
1990         VM.initLevel(1);
1991     }
1992 
1993     // @see #initPhase2()
1994     static ModuleLayer bootLayer;
1995 
1996     /*
1997      * Invoked by VM.  Phase 2 module system initialization.
1998      * Only classes in java.base can be loaded in this phase.
1999      *
2000      * @param printToStderr print exceptions to stderr rather than stdout
2001      * @param printStackTrace print stack trace when exception occurs
2002      *
2003      * @return JNI_OK for success, JNI_ERR for failure
2004      */
2005     private static int initPhase2(boolean printToStderr, boolean printStackTrace) {
2006         try {
2007             bootLayer = ModuleBootstrap.boot();
2008         } catch (Exception | Error e) {
2009             logInitException(printToStderr, printStackTrace,
2010                              "Error occurred during initialization of boot layer", e);
2011             return -1; // JNI_ERR
2012         }
2013 
2014         // module system initialized
2015         VM.initLevel(2);
2016 
2017         return 0; // JNI_OK
2018     }
2019 
2020     /*
2021      * Invoked by VM.  Phase 3 is the final system initialization:
2022      * 1. set security manager
2023      * 2. set system class loader
2024      * 3. set TCCL
2025      *
2026      * This method must be called after the module system initialization.
2027      * The security manager and system class loader may be custom class from
2028      * the application classpath or modulepath.
2029      */
2030     private static void initPhase3() {
2031         // set security manager
2032         String cn = System.getProperty("java.security.manager");
2033         if (cn != null) {
2034             if (cn.isEmpty() || "default".equals(cn)) {
2035                 System.setSecurityManager(new SecurityManager());
2036             } else {
2037                 try {
2038                     Class<?> c = Class.forName(cn, false, ClassLoader.getBuiltinAppClassLoader());
2039                     Constructor<?> ctor = c.getConstructor();
2040                     // Must be a public subclass of SecurityManager with
2041                     // a public no-arg constructor
2042                     if (!SecurityManager.class.isAssignableFrom(c) ||
2043                             !Modifier.isPublic(c.getModifiers()) ||
2044                             !Modifier.isPublic(ctor.getModifiers())) {
2045                         throw new Error("Could not create SecurityManager: " + ctor.toString());
2046                     }
2047                     // custom security manager implementation may be in unnamed module
2048                     // or a named module but non-exported package
2049                     ctor.setAccessible(true);
2050                     SecurityManager sm = (SecurityManager) ctor.newInstance();
2051                     System.setSecurityManager(sm);
2052                 } catch (Exception e) {
2053                     throw new Error("Could not create SecurityManager", e);
2054                 }
2055             }
2056         }
2057 
2058         // initializing the system class loader
2059         VM.initLevel(3);
2060 
2061         // system class loader initialized
2062         ClassLoader scl = ClassLoader.initSystemClassLoader();
2063 
2064         // set TCCL
2065         Thread.currentThread().setContextClassLoader(scl);
2066 
2067         // system is fully initialized
2068         VM.initLevel(4);
2069     }
2070 
2071     private static void setJavaLangAccess() {
2072         // Allow privileged classes outside of java.lang
2073         SharedSecrets.setJavaLangAccess(new JavaLangAccess() {
2074             public List<Method> getDeclaredPublicMethods(Class<?> klass, String name, Class<?>... parameterTypes) {
2075                 return klass.getDeclaredPublicMethods(name, parameterTypes);
2076             }
2077             public jdk.internal.reflect.ConstantPool getConstantPool(Class<?> klass) {
2078                 return klass.getConstantPool();
2079             }
2080             public boolean casAnnotationType(Class<?> klass, AnnotationType oldType, AnnotationType newType) {
2081                 return klass.casAnnotationType(oldType, newType);
2082             }
2083             public AnnotationType getAnnotationType(Class<?> klass) {
2084                 return klass.getAnnotationType();
2085             }
2086             public Map<Class<? extends Annotation>, Annotation> getDeclaredAnnotationMap(Class<?> klass) {
2087                 return klass.getDeclaredAnnotationMap();
2088             }
2089             public byte[] getRawClassAnnotations(Class<?> klass) {
2090                 return klass.getRawAnnotations();
2091             }
2092             public byte[] getRawClassTypeAnnotations(Class<?> klass) {
2093                 return klass.getRawTypeAnnotations();
2094             }
2095             public byte[] getRawExecutableTypeAnnotations(Executable executable) {
2096                 return Class.getExecutableTypeAnnotationBytes(executable);
2097             }
2098             public <E extends Enum<E>>
2099             E[] getEnumConstantsShared(Class<E> klass) {
2100                 return klass.getEnumConstantsShared();
2101             }
2102             public void blockedOn(Thread t, Interruptible b) {
2103                 t.blockedOn(b);
2104             }
2105             public void registerShutdownHook(int slot, boolean registerShutdownInProgress, Runnable hook) {
2106                 Shutdown.add(slot, registerShutdownInProgress, hook);
2107             }
2108             public String newStringUnsafe(char[] chars) {
2109                 return new String(chars, true);
2110             }
2111             public Thread newThreadWithAcc(Runnable target, AccessControlContext acc) {
2112                 return new Thread(target, acc);
2113             }
2114             @SuppressWarnings("deprecation")
2115             public void invokeFinalize(Object o) throws Throwable {
2116                 o.finalize();
2117             }
2118             public ConcurrentHashMap<?, ?> createOrGetClassLoaderValueMap(ClassLoader cl) {
2119                 return cl.createOrGetClassLoaderValueMap();
2120             }
2121             public Class<?> defineClass(ClassLoader loader, String name, byte[] b, ProtectionDomain pd, String source) {
2122                 return ClassLoader.defineClass1(loader, name, b, 0, b.length, pd, source);
2123             }
2124             public Class<?> findBootstrapClassOrNull(ClassLoader cl, String name) {
2125                 return cl.findBootstrapClassOrNull(name);
2126             }
2127             public Package definePackage(ClassLoader cl, String name, Module module) {
2128                 return cl.definePackage(name, module);
2129             }
2130             public String fastUUID(long lsb, long msb) {
2131                 return Long.fastUUID(lsb, msb);
2132             }
2133             public void addNonExportedPackages(ModuleLayer layer) {
2134                 SecurityManager.addNonExportedPackages(layer);
2135             }
2136             public void invalidatePackageAccessCache() {
2137                 SecurityManager.invalidatePackageAccessCache();
2138             }
2139             public Module defineModule(ClassLoader loader,
2140                                        ModuleDescriptor descriptor,
2141                                        URI uri) {
2142                 return new Module(null, loader, descriptor, uri);
2143             }
2144             public Module defineUnnamedModule(ClassLoader loader) {
2145                 return new Module(loader);
2146             }
2147             public void addReads(Module m1, Module m2) {
2148                 m1.implAddReads(m2);
2149             }
2150             public void addReadsAllUnnamed(Module m) {
2151                 m.implAddReadsAllUnnamed();
2152             }
2153             public void addExports(Module m, String pn, Module other) {
2154                 m.implAddExports(pn, other);
2155             }
2156             public void addExportsToAllUnnamed(Module m, String pn) {
2157                 m.implAddExportsToAllUnnamed(pn);
2158             }
2159             public void addOpens(Module m, String pn, Module other) {
2160                 m.implAddOpens(pn, other);
2161             }
2162             public void addOpensToAllUnnamed(Module m, String pn) {
2163                 m.implAddOpensToAllUnnamed(pn);
2164             }
2165             public void addOpensToAllUnnamed(Module m, Iterator<String> packages) {
2166                 m.implAddOpensToAllUnnamed(packages);
2167             }
2168             public void addUses(Module m, Class<?> service) {
2169                 m.implAddUses(service);
2170             }
2171             public boolean isReflectivelyExported(Module m, String pn, Module other) {
2172                 return m.isReflectivelyExported(pn, other);
2173             }
2174             public boolean isReflectivelyOpened(Module m, String pn, Module other) {
2175                 return m.isReflectivelyOpened(pn, other);
2176             }
2177             public ServicesCatalog getServicesCatalog(ModuleLayer layer) {
2178                 return layer.getServicesCatalog();
2179             }
2180             public Stream<ModuleLayer> layers(ModuleLayer layer) {
2181                 return layer.layers();
2182             }
2183             public Stream<ModuleLayer> layers(ClassLoader loader) {
2184                 return ModuleLayer.layers(loader);
2185             }
2186         });
2187     }
2188 }