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