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