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