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