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