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