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 jdk.internal.reflect.CallerSensitive; 60 import jdk.internal.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.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, 1158 * java.util.ResourceBundle, java.lang.reflect.Module) localized logger}); 1159 * can be {@code null}. 1160 * 1161 * @throws NullPointerException if {@code level} is {@code null}. 1162 */ 1163 public default void log(Level level, String msg) { 1164 log(level, (ResourceBundle) null, msg, (Object[]) null); 1165 } 1166 1167 /** 1168 * Logs a lazily supplied message. 1169 * <p> 1170 * If the logger is currently enabled for the given log message level 1171 * then a message is logged that is the result produced by the 1172 * given supplier function. Otherwise, the supplier is not operated on. 1173 * 1174 * @implSpec When logging is enabled for the given level, the default 1175 * implementation for this method calls 1176 * {@code this.log(level, (ResourceBundle)null, msgSupplier.get(), (Object[])null);} 1177 * 1178 * @param level the log message level. 1179 * @param msgSupplier a supplier function that produces a message. 1180 * 1181 * @throws NullPointerException if {@code level} is {@code null}, 1182 * or {@code msgSupplier} is {@code null}. 1183 */ 1184 public default void log(Level level, Supplier<String> msgSupplier) { 1185 Objects.requireNonNull(msgSupplier); 1186 if (isLoggable(Objects.requireNonNull(level))) { 1187 log(level, (ResourceBundle) null, msgSupplier.get(), (Object[]) null); 1188 } 1189 } 1190 1191 /** 1192 * Logs a message produced from the given object. 1193 * <p> 1194 * If the logger is currently enabled for the given log message level then 1195 * a message is logged that, by default, is the result produced from 1196 * calling toString on the given object. 1197 * Otherwise, the object is not operated on. 1198 * 1199 * @implSpec When logging is enabled for the given level, the default 1200 * implementation for this method calls 1201 * {@code this.log(level, (ResourceBundle)null, obj.toString(), (Object[])null);} 1202 * 1203 * @param level the log message level. 1204 * @param obj the object to log. 1205 * 1206 * @throws NullPointerException if {@code level} is {@code null}, or 1207 * {@code obj} is {@code null}. 1208 */ 1209 public default void log(Level level, Object obj) { 1210 Objects.requireNonNull(obj); 1211 if (isLoggable(Objects.requireNonNull(level))) { 1212 this.log(level, (ResourceBundle) null, obj.toString(), (Object[]) null); 1213 } 1214 } 1215 1216 /** 1217 * Logs a message associated with a given throwable. 1218 * 1219 * @implSpec The default implementation for this method calls 1220 * {@code this.log(level, (ResourceBundle)null, msg, thrown);} 1221 * 1222 * @param level the log message level. 1223 * @param msg the string message (or a key in the message catalog, if 1224 * this logger is a {@link 1225 * LoggerFinder#getLocalizedLogger(java.lang.String, 1226 * java.util.ResourceBundle, java.lang.reflect.Module) localized logger}); 1227 * can be {@code null}. 1228 * @param thrown a {@code Throwable} associated with the log message; 1229 * can be {@code null}. 1230 * 1231 * @throws NullPointerException if {@code level} is {@code null}. 1232 */ 1233 public default void log(Level level, String msg, Throwable thrown) { 1234 this.log(level, null, msg, thrown); 1235 } 1236 1237 /** 1238 * Logs a lazily supplied message associated with a given throwable. 1239 * <p> 1240 * If the logger is currently enabled for the given log message level 1241 * then a message is logged that is the result produced by the 1242 * given supplier function. Otherwise, the supplier is not operated on. 1243 * 1244 * @implSpec When logging is enabled for the given level, the default 1245 * implementation for this method calls 1246 * {@code this.log(level, (ResourceBundle)null, msgSupplier.get(), thrown);} 1247 * 1248 * @param level one of the log message level identifiers. 1249 * @param msgSupplier a supplier function that produces a message. 1250 * @param thrown a {@code Throwable} associated with log message; 1251 * can be {@code null}. 1252 * 1253 * @throws NullPointerException if {@code level} is {@code null}, or 1254 * {@code msgSupplier} is {@code null}. 1255 */ 1256 public default void log(Level level, Supplier<String> msgSupplier, 1257 Throwable thrown) { 1258 Objects.requireNonNull(msgSupplier); 1259 if (isLoggable(Objects.requireNonNull(level))) { 1260 this.log(level, null, msgSupplier.get(), thrown); 1261 } 1262 } 1263 1264 /** 1265 * Logs a message with an optional list of parameters. 1266 * 1267 * @implSpec The default implementation for this method calls 1268 * {@code this.log(level, (ResourceBundle)null, format, params);} 1269 * 1270 * @param level one of the log message level identifiers. 1271 * @param format the string message format in {@link 1272 * java.text.MessageFormat} format, (or a key in the message 1273 * catalog, if this logger is a {@link 1274 * LoggerFinder#getLocalizedLogger(java.lang.String, 1275 * java.util.ResourceBundle, java.lang.reflect.Module) localized logger}); 1276 * can be {@code null}. 1277 * @param params an optional list of parameters to the message (may be 1278 * none). 1279 * 1280 * @throws NullPointerException if {@code level} is {@code null}. 1281 */ 1282 public default void log(Level level, String format, Object... params) { 1283 this.log(level, null, format, params); 1284 } 1285 1286 /** 1287 * Logs a localized message associated with a given throwable. 1288 * <p> 1289 * If the given resource bundle is non-{@code null}, the {@code msg} 1290 * string is localized using the given resource bundle. 1291 * Otherwise the {@code msg} string is not localized. 1292 * 1293 * @param level the log message level. 1294 * @param bundle a resource bundle to localize {@code msg}; can be 1295 * {@code null}. 1296 * @param msg the string message (or a key in the message catalog, 1297 * if {@code bundle} is not {@code null}); can be {@code null}. 1298 * @param thrown a {@code Throwable} associated with the log message; 1299 * can be {@code null}. 1300 * 1301 * @throws NullPointerException if {@code level} is {@code null}. 1302 */ 1303 public void log(Level level, ResourceBundle bundle, String msg, 1304 Throwable thrown); 1305 1306 /** 1307 * Logs a message with resource bundle and an optional list of 1308 * parameters. 1309 * <p> 1310 * If the given resource bundle is non-{@code null}, the {@code format} 1311 * string is localized using the given resource bundle. 1312 * Otherwise the {@code format} string is not localized. 1313 * 1314 * @param level the log message level. 1315 * @param bundle a resource bundle to localize {@code format}; can be 1316 * {@code null}. 1317 * @param format the string message format in {@link 1318 * java.text.MessageFormat} format, (or a key in the message 1319 * catalog if {@code bundle} is not {@code null}); can be {@code null}. 1320 * @param params an optional list of parameters to the message (may be 1321 * none). 1322 * 1323 * @throws NullPointerException if {@code level} is {@code null}. 1324 */ 1325 public void log(Level level, ResourceBundle bundle, String format, 1326 Object... params); 1327 1328 1329 } 1330 1331 /** 1332 * The {@code LoggerFinder} service is responsible for creating, managing, 1333 * and configuring loggers to the underlying framework it uses. 1334 * <p> 1335 * A logger finder is a concrete implementation of this class that has a 1336 * zero-argument constructor and implements the abstract methods defined 1337 * by this class. 1338 * The loggers returned from a logger finder are capable of routing log 1339 * messages to the logging backend this provider supports. 1340 * A given invocation of the Java Runtime maintains a single 1341 * system-wide LoggerFinder instance that is loaded as follows: 1342 * <ul> 1343 * <li>First it finds any custom {@code LoggerFinder} provider 1344 * using the {@link java.util.ServiceLoader} facility with the 1345 * {@linkplain ClassLoader#getSystemClassLoader() system class 1346 * loader}.</li> 1347 * <li>If no {@code LoggerFinder} provider is found, the system default 1348 * {@code LoggerFinder} implementation will be used.</li> 1349 * </ul> 1350 * <p> 1351 * An application can replace the logging backend 1352 * <i>even when the java.logging module is present</i>, by simply providing 1353 * and declaring an implementation of the {@link LoggerFinder} service. 1354 * <p> 1355 * <b>Default Implementation</b> 1356 * <p> 1357 * The system default {@code LoggerFinder} implementation uses 1358 * {@code java.util.logging} as the backend framework when the 1359 * {@code java.logging} module is present. 1360 * It returns a {@linkplain System.Logger logger} instance 1361 * that will route log messages to a {@link java.util.logging.Logger 1362 * java.util.logging.Logger}. Otherwise, if {@code java.logging} is not 1363 * present, the default implementation will return a simple logger 1364 * instance that will route log messages of {@code INFO} level and above to 1365 * the console ({@code System.err}). 1366 * <p> 1367 * <b>Logging Configuration</b> 1368 * <p> 1369 * {@linkplain Logger Logger} instances obtained from the 1370 * {@code LoggerFinder} factory methods are not directly configurable by 1371 * the application. Configuration is the responsibility of the underlying 1372 * logging backend, and usually requires using APIs specific to that backend. 1373 * <p>For the default {@code LoggerFinder} implementation 1374 * using {@code java.util.logging} as its backend, refer to 1375 * {@link java.util.logging java.util.logging} for logging configuration. 1376 * For the default {@code LoggerFinder} implementation returning simple loggers 1377 * when the {@code java.logging} module is absent, the configuration 1378 * is implementation dependent. 1379 * <p> 1380 * Usually an application that uses a logging framework will log messages 1381 * through a logger facade defined (or supported) by that framework. 1382 * Applications that wish to use an external framework should log 1383 * through the facade associated with that framework. 1384 * <p> 1385 * A system class that needs to log messages will typically obtain 1386 * a {@link System.Logger} instance to route messages to the logging 1387 * framework selected by the application. 1388 * <p> 1389 * Libraries and classes that only need loggers to produce log messages 1390 * should not attempt to configure loggers by themselves, as that 1391 * would make them dependent from a specific implementation of the 1392 * {@code LoggerFinder} service. 1393 * <p> 1394 * In addition, when a security manager is present, loggers provided to 1395 * system classes should not be directly configurable through the logging 1396 * backend without requiring permissions. 1397 * <br> 1398 * It is the responsibility of the provider of 1399 * the concrete {@code LoggerFinder} implementation to ensure that 1400 * these loggers are not configured by untrusted code without proper 1401 * permission checks, as configuration performed on such loggers usually 1402 * affects all applications in the same Java Runtime. 1403 * <p> 1404 * <b>Message Levels and Mapping to backend levels</b> 1405 * <p> 1406 * A logger finder is responsible for mapping from a {@code 1407 * System.Logger.Level} to a level supported by the logging backend it uses. 1408 * <br>The default LoggerFinder using {@code java.util.logging} as the backend 1409 * maps {@code System.Logger} levels to 1410 * {@linkplain java.util.logging.Level java.util.logging} levels 1411 * of corresponding severity - as described in {@link Logger.Level 1412 * Logger.Level}. 1413 * 1414 * @see java.lang.System 1415 * @see java.lang.System.Logger 1416 * 1417 * @since 9 1418 */ 1419 public static abstract class LoggerFinder { 1420 /** 1421 * The {@code RuntimePermission("loggerFinder")} is 1422 * necessary to subclass and instantiate the {@code LoggerFinder} class, 1423 * as well as to obtain loggers from an instance of that class. 1424 */ 1425 static final RuntimePermission LOGGERFINDER_PERMISSION = 1426 new RuntimePermission("loggerFinder"); 1427 1428 /** 1429 * Creates a new instance of {@code LoggerFinder}. 1430 * 1431 * @implNote It is recommended that a {@code LoggerFinder} service 1432 * implementation does not perform any heavy initialization in its 1433 * constructor, in order to avoid possible risks of deadlock or class 1434 * loading cycles during the instantiation of the service provider. 1435 * 1436 * @throws SecurityException if a security manager is present and its 1437 * {@code checkPermission} method doesn't allow the 1438 * {@code RuntimePermission("loggerFinder")}. 1439 */ 1440 protected LoggerFinder() { 1441 this(checkPermission()); 1442 } 1443 1444 private LoggerFinder(Void unused) { 1445 // nothing to do. 1446 } 1447 1448 private static Void checkPermission() { 1449 final SecurityManager sm = System.getSecurityManager(); 1450 if (sm != null) { 1451 sm.checkPermission(LOGGERFINDER_PERMISSION); 1452 } 1453 return null; 1454 } 1455 1456 /** 1457 * Returns an instance of {@link Logger Logger} 1458 * for the given {@code module}. 1459 * 1460 * @param name the name of the logger. 1461 * @param module the module for which the logger is being requested. 1462 * 1463 * @return a {@link Logger logger} suitable for use within the given 1464 * module. 1465 * @throws NullPointerException if {@code name} is {@code null} or 1466 * {@code module} is {@code null}. 1467 * @throws SecurityException if a security manager is present and its 1468 * {@code checkPermission} method doesn't allow the 1469 * {@code RuntimePermission("loggerFinder")}. 1470 */ 1471 public abstract Logger getLogger(String name, Module module); 1472 1473 /** 1474 * Returns a localizable instance of {@link Logger Logger} 1475 * for the given {@code module}. 1476 * The returned logger will use the provided resource bundle for 1477 * message localization. 1478 * 1479 * @implSpec By default, this method calls {@link 1480 * #getLogger(java.lang.String, java.lang.reflect.Module) 1481 * this.getLogger(name, module)} to obtain a logger, then wraps that 1482 * logger in a {@link Logger} instance where all methods that do not 1483 * take a {@link ResourceBundle} as parameter are redirected to one 1484 * which does - passing the given {@code bundle} for 1485 * localization. So for instance, a call to {@link 1486 * Logger#log(Level, String) Logger.log(Level.INFO, msg)} 1487 * will end up as a call to {@link 1488 * Logger#log(Level, ResourceBundle, String, Object...) 1489 * Logger.log(Level.INFO, bundle, msg, (Object[])null)} on the wrapped 1490 * logger instance. 1491 * Note however that by default, string messages returned by {@link 1492 * java.util.function.Supplier Supplier<String>} will not be 1493 * localized, as it is assumed that such strings are messages which are 1494 * already constructed, rather than keys in a resource bundle. 1495 * <p> 1496 * An implementation of {@code LoggerFinder} may override this method, 1497 * for example, when the underlying logging backend provides its own 1498 * mechanism for localizing log messages, then such a 1499 * {@code LoggerFinder} would be free to return a logger 1500 * that makes direct use of the mechanism provided by the backend. 1501 * 1502 * @param name the name of the logger. 1503 * @param bundle a resource bundle; can be {@code null}. 1504 * @param module the module for which the logger is being requested. 1505 * @return an instance of {@link Logger Logger} which will use the 1506 * provided resource bundle for message localization. 1507 * 1508 * @throws NullPointerException if {@code name} is {@code null} or 1509 * {@code module} is {@code null}. 1510 * @throws SecurityException if a security manager is present and its 1511 * {@code checkPermission} method doesn't allow the 1512 * {@code RuntimePermission("loggerFinder")}. 1513 */ 1514 public Logger getLocalizedLogger(String name, ResourceBundle bundle, 1515 Module module) { 1516 return new LocalizedLoggerWrapper<>(getLogger(name, module), bundle); 1517 } 1518 1519 /** 1520 * Returns the {@code LoggerFinder} instance. There is one 1521 * single system-wide {@code LoggerFinder} instance in 1522 * the Java Runtime. See the class specification of how the 1523 * {@link LoggerFinder LoggerFinder} implementation is located and 1524 * loaded. 1525 1526 * @return the {@link LoggerFinder LoggerFinder} instance. 1527 * @throws SecurityException if a security manager is present and its 1528 * {@code checkPermission} method doesn't allow the 1529 * {@code RuntimePermission("loggerFinder")}. 1530 */ 1531 public static LoggerFinder getLoggerFinder() { 1532 final SecurityManager sm = System.getSecurityManager(); 1533 if (sm != null) { 1534 sm.checkPermission(LOGGERFINDER_PERMISSION); 1535 } 1536 return accessProvider(); 1537 } 1538 1539 1540 private static volatile LoggerFinder service; 1541 static LoggerFinder accessProvider() { 1542 // We do not need to synchronize: LoggerFinderLoader will 1543 // always return the same instance, so if we don't have it, 1544 // just fetch it again. 1545 if (service == null) { 1546 PrivilegedAction<LoggerFinder> pa = 1547 () -> LoggerFinderLoader.getLoggerFinder(); 1548 service = AccessController.doPrivileged(pa, null, 1549 LOGGERFINDER_PERMISSION); 1550 } 1551 return service; 1552 } 1553 1554 } 1555 1556 1557 /** 1558 * Returns an instance of {@link Logger Logger} for the caller's 1559 * use. 1560 * 1561 * @implSpec 1562 * Instances returned by this method route messages to loggers 1563 * obtained by calling {@link LoggerFinder#getLogger(java.lang.String, 1564 * java.lang.reflect.Module) LoggerFinder.getLogger(name, module)}, where 1565 * {@code module} is the caller's module. 1566 * 1567 * @apiNote 1568 * This method may defer calling the {@link 1569 * LoggerFinder#getLogger(java.lang.String, java.lang.reflect.Module) 1570 * LoggerFinder.getLogger} method to create an actual logger supplied by 1571 * the logging backend, for instance, to allow loggers to be obtained during 1572 * the system initialization time. 1573 * 1574 * @param name the name of the logger. 1575 * @return an instance of {@link Logger} that can be used by the calling 1576 * class. 1577 * @throws NullPointerException if {@code name} is {@code null}. 1578 * 1579 * @since 9 1580 */ 1581 @CallerSensitive 1582 public static Logger getLogger(String name) { 1583 Objects.requireNonNull(name); 1584 final Class<?> caller = Reflection.getCallerClass(); 1585 return LazyLoggers.getLogger(name, caller.getModule()); 1586 } 1587 1588 /** 1589 * Returns a localizable instance of {@link Logger 1590 * Logger} for the caller's use. 1591 * The returned logger will use the provided resource bundle for message 1592 * localization. 1593 * 1594 * @implSpec 1595 * The returned logger will perform message localization as specified 1596 * by {@link LoggerFinder#getLocalizedLogger(java.lang.String, 1597 * java.util.ResourceBundle, java.lang.reflect.Module) 1598 * LoggerFinder.getLocalizedLogger(name, bundle, module}, where 1599 * {@code module} is the caller's module. 1600 * 1601 * @apiNote 1602 * This method is intended to be used after the system is fully initialized. 1603 * This method may trigger the immediate loading and initialization 1604 * of the {@link LoggerFinder} service, which may cause issues if the 1605 * Java Runtime is not ready to initialize the concrete service 1606 * implementation yet. 1607 * System classes which may be loaded early in the boot sequence and 1608 * need to log localized messages should create a logger using 1609 * {@link #getLogger(java.lang.String)} and then use the log methods that 1610 * take a resource bundle as parameter. 1611 * 1612 * @param name the name of the logger. 1613 * @param bundle a resource bundle. 1614 * @return an instance of {@link Logger} which will use the provided 1615 * resource bundle for message localization. 1616 * @throws NullPointerException if {@code name} is {@code null} or 1617 * {@code bundle} is {@code null}. 1618 * 1619 * @since 9 1620 */ 1621 @CallerSensitive 1622 public static Logger getLogger(String name, ResourceBundle bundle) { 1623 final ResourceBundle rb = Objects.requireNonNull(bundle); 1624 Objects.requireNonNull(name); 1625 final Class<?> caller = Reflection.getCallerClass(); 1626 final SecurityManager sm = System.getSecurityManager(); 1627 // We don't use LazyLoggers if a resource bundle is specified. 1628 // Bootstrap sensitive classes in the JDK do not use resource bundles 1629 // when logging. This could be revisited later, if it needs to. 1630 if (sm != null) { 1631 final PrivilegedAction<Logger> pa = 1632 () -> LoggerFinder.accessProvider() 1633 .getLocalizedLogger(name, rb, caller.getModule()); 1634 return AccessController.doPrivileged(pa, null, 1635 LoggerFinder.LOGGERFINDER_PERMISSION); 1636 } 1637 return LoggerFinder.accessProvider() 1638 .getLocalizedLogger(name, rb, caller.getModule()); 1639 } 1640 1641 /** 1642 * Terminates the currently running Java Virtual Machine. The 1643 * argument serves as a status code; by convention, a nonzero status 1644 * code indicates abnormal termination. 1645 * <p> 1646 * This method calls the <code>exit</code> method in class 1647 * <code>Runtime</code>. This method never returns normally. 1648 * <p> 1649 * The call <code>System.exit(n)</code> is effectively equivalent to 1650 * the call: 1651 * <blockquote><pre> 1652 * Runtime.getRuntime().exit(n) 1653 * </pre></blockquote> 1654 * 1655 * @param status exit status. 1656 * @throws SecurityException 1657 * if a security manager exists and its <code>checkExit</code> 1658 * method doesn't allow exit with the specified status. 1659 * @see java.lang.Runtime#exit(int) 1660 */ 1661 public static void exit(int status) { 1662 Runtime.getRuntime().exit(status); 1663 } 1664 1665 /** 1666 * Runs the garbage collector. 1667 * <p> 1668 * Calling the <code>gc</code> method suggests that the Java Virtual 1669 * Machine expend effort toward recycling unused objects in order to 1670 * make the memory they currently occupy available for quick reuse. 1671 * When control returns from the method call, the Java Virtual 1672 * Machine has made a best effort to reclaim space from all discarded 1673 * objects. 1674 * <p> 1675 * The call <code>System.gc()</code> is effectively equivalent to the 1676 * call: 1677 * <blockquote><pre> 1678 * Runtime.getRuntime().gc() 1679 * </pre></blockquote> 1680 * 1681 * @see java.lang.Runtime#gc() 1682 */ 1683 public static void gc() { 1684 Runtime.getRuntime().gc(); 1685 } 1686 1687 /** 1688 * Runs the finalization methods of any objects pending finalization. 1689 * <p> 1690 * Calling this method suggests that the Java Virtual Machine expend 1691 * effort toward running the <code>finalize</code> methods of objects 1692 * that have been found to be discarded but whose <code>finalize</code> 1693 * methods have not yet been run. When control returns from the 1694 * method call, the Java Virtual Machine has made a best effort to 1695 * complete all outstanding finalizations. 1696 * <p> 1697 * The call <code>System.runFinalization()</code> is effectively 1698 * equivalent to the call: 1699 * <blockquote><pre> 1700 * Runtime.getRuntime().runFinalization() 1701 * </pre></blockquote> 1702 * 1703 * @see java.lang.Runtime#runFinalization() 1704 */ 1705 public static void runFinalization() { 1706 Runtime.getRuntime().runFinalization(); 1707 } 1708 1709 /** 1710 * Enable or disable finalization on exit; doing so specifies that the 1711 * finalizers of all objects that have finalizers that have not yet been 1712 * automatically invoked are to be run before the Java runtime exits. 1713 * By default, finalization on exit is disabled. 1714 * 1715 * <p>If there is a security manager, 1716 * its <code>checkExit</code> method is first called 1717 * with 0 as its argument to ensure the exit is allowed. 1718 * This could result in a SecurityException. 1719 * 1720 * @deprecated This method is inherently unsafe. It may result in 1721 * finalizers being called on live objects while other threads are 1722 * concurrently manipulating those objects, resulting in erratic 1723 * behavior or deadlock. 1724 * This method is subject to removal in a future version of Java SE. 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(since="1.2", forRemoval=true) 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 // module system initialized 1927 VM.initLevel(2); 1928 } 1929 1930 /* 1931 * Invoked by VM. Phase 3 is the final system initialization: 1932 * 1. set security manager 1933 * 2. set system class loader 1934 * 3. set TCCL 1935 * 1936 * This method must be called after the module system initialization. 1937 * The security manager and system class loader may be custom class from 1938 * the application classpath or modulepath. 1939 */ 1940 private static void initPhase3() { 1941 // set security manager 1942 String cn = System.getProperty("java.security.manager"); 1943 if (cn != null) { 1944 if (cn.isEmpty() || "default".equals(cn)) { 1945 System.setSecurityManager(new SecurityManager()); 1946 } else { 1947 try { 1948 Class<?> c = Class.forName(cn, false, ClassLoader.getBuiltinAppClassLoader()); 1949 Constructor<?> ctor = c.getConstructor(); 1950 // Must be a public subclass of SecurityManager with 1951 // a public no-arg constructor 1952 if (!SecurityManager.class.isAssignableFrom(c) || 1953 !Modifier.isPublic(c.getModifiers()) || 1954 !Modifier.isPublic(ctor.getModifiers())) { 1955 throw new Error("Could not create SecurityManager: " + ctor.toString()); 1956 } 1957 // custom security manager implementation may be in unnamed module 1958 // or a named module but non-exported package 1959 ctor.setAccessible(true); 1960 SecurityManager sm = (SecurityManager) ctor.newInstance(); 1961 System.setSecurityManager(sm); 1962 } catch (Exception e) { 1963 throw new Error("Could not create SecurityManager", e); 1964 } 1965 } 1966 } 1967 1968 // initializing the system class loader 1969 VM.initLevel(3); 1970 1971 // system class loader initialized 1972 ClassLoader scl = ClassLoader.initSystemClassLoader(); 1973 1974 // set TCCL 1975 Thread.currentThread().setContextClassLoader(scl); 1976 1977 // system is fully initialized 1978 VM.initLevel(4); 1979 } 1980 1981 private static void setJavaLangAccess() { 1982 // Allow privileged classes outside of java.lang 1983 SharedSecrets.setJavaLangAccess(new JavaLangAccess(){ 1984 public jdk.internal.reflect.ConstantPool getConstantPool(Class<?> klass) { 1985 return klass.getConstantPool(); 1986 } 1987 public boolean casAnnotationType(Class<?> klass, AnnotationType oldType, AnnotationType newType) { 1988 return klass.casAnnotationType(oldType, newType); 1989 } 1990 public AnnotationType getAnnotationType(Class<?> klass) { 1991 return klass.getAnnotationType(); 1992 } 1993 public Map<Class<? extends Annotation>, Annotation> getDeclaredAnnotationMap(Class<?> klass) { 1994 return klass.getDeclaredAnnotationMap(); 1995 } 1996 public byte[] getRawClassAnnotations(Class<?> klass) { 1997 return klass.getRawAnnotations(); 1998 } 1999 public byte[] getRawClassTypeAnnotations(Class<?> klass) { 2000 return klass.getRawTypeAnnotations(); 2001 } 2002 public byte[] getRawExecutableTypeAnnotations(Executable executable) { 2003 return Class.getExecutableTypeAnnotationBytes(executable); 2004 } 2005 public <E extends Enum<E>> 2006 E[] getEnumConstantsShared(Class<E> klass) { 2007 return klass.getEnumConstantsShared(); 2008 } 2009 public void blockedOn(Thread t, Interruptible b) { 2010 t.blockedOn(b); 2011 } 2012 public void registerShutdownHook(int slot, boolean registerShutdownInProgress, Runnable hook) { 2013 Shutdown.add(slot, registerShutdownInProgress, hook); 2014 } 2015 public String newStringUnsafe(char[] chars) { 2016 return new String(chars, true); 2017 } 2018 public Thread newThreadWithAcc(Runnable target, AccessControlContext acc) { 2019 return new Thread(target, acc); 2020 } 2021 public void invokeFinalize(Object o) throws Throwable { 2022 o.finalize(); 2023 } 2024 public Layer getBootLayer() { 2025 return bootLayer; 2026 } 2027 public ServicesCatalog getServicesCatalog(ClassLoader cl) { 2028 return cl.getServicesCatalog(); 2029 } 2030 public ServicesCatalog createOrGetServicesCatalog(ClassLoader cl) { 2031 return cl.createOrGetServicesCatalog(); 2032 } 2033 public ConcurrentHashMap<?, ?> createOrGetClassLoaderValueMap(ClassLoader cl) { 2034 return cl.createOrGetClassLoaderValueMap(); 2035 } 2036 public Class<?> findBootstrapClassOrNull(ClassLoader cl, String name) { 2037 return cl.findBootstrapClassOrNull(name); 2038 } 2039 public URL findResource(ClassLoader cl, String mn, String name) throws IOException { 2040 return cl.findResource(mn, name); 2041 } 2042 public Stream<Package> packages(ClassLoader cl) { 2043 return cl.packages(); 2044 } 2045 public Package definePackage(ClassLoader cl, String name, Module module) { 2046 return cl.definePackage(name, module); 2047 } 2048 public String fastUUID(long lsb, long msb) { 2049 return Long.fastUUID(lsb, msb); 2050 } 2051 }); 2052 } 2053 }