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