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