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