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