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