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