1 /* 2 * Copyright (c) 1994, 2014, 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.*; 28 import java.lang.reflect.Executable; 29 import java.lang.annotation.Annotation; 30 import java.security.AccessControlContext; 31 import java.util.Properties; 32 import java.util.PropertyPermission; 33 import java.util.StringTokenizer; 34 import java.util.Map; 35 import java.security.AccessController; 36 import java.security.PrivilegedAction; 37 import java.security.AllPermission; 38 import java.nio.channels.Channel; 39 import java.nio.channels.spi.SelectorProvider; 40 import sun.nio.ch.Interruptible; 41 import sun.reflect.CallerSensitive; 42 import sun.reflect.Reflection; 43 import sun.security.util.SecurityConstants; 44 import sun.reflect.annotation.AnnotationType; 45 import jdk.internal.HotSpotIntrinsicCandidate; 46 import jdk.internal.misc.JavaLangAccess;; 47 import jdk.internal.misc.SharedSecrets;; 48 49 /** 50 * The <code>System</code> class contains several useful class fields 51 * and methods. It cannot be instantiated. 52 * 53 * <p>Among the facilities provided by the <code>System</code> class 54 * are standard input, standard output, and error output streams; 55 * access to externally defined properties and environment 56 * variables; a means of loading files and libraries; and a utility 57 * method for quickly copying a portion of an array. 58 * 59 * @author unascribed 60 * @since 1.0 61 */ 62 public final class System { 63 64 /* register the natives via the static initializer. 65 * 66 * VM will invoke the initializeSystemClass method to complete 67 * the initialization for this class separated from clinit. 68 * Note that to use properties set by the VM, see the constraints 69 * described in the initializeSystemClass method. 70 */ 71 private static native void registerNatives(); 72 static { 73 registerNatives(); 74 } 75 76 /** Don't let anyone instantiate this class */ 77 private System() { 78 } 79 80 /** 81 * The "standard" input stream. This stream is already 82 * open and ready to supply input data. Typically this stream 83 * corresponds to keyboard input or another input source specified by 84 * the host environment or user. 85 */ 86 public static final InputStream in = null; 87 88 /** 89 * The "standard" output stream. This stream is already 90 * open and ready to accept output data. Typically this stream 91 * corresponds to display output or another output destination 92 * specified by the host environment or user. 93 * <p> 94 * For simple stand-alone Java applications, a typical way to write 95 * a line of output data is: 96 * <blockquote><pre> 97 * System.out.println(data) 98 * </pre></blockquote> 99 * <p> 100 * See the <code>println</code> methods in class <code>PrintStream</code>. 101 * 102 * @see java.io.PrintStream#println() 103 * @see java.io.PrintStream#println(boolean) 104 * @see java.io.PrintStream#println(char) 105 * @see java.io.PrintStream#println(char[]) 106 * @see java.io.PrintStream#println(double) 107 * @see java.io.PrintStream#println(float) 108 * @see java.io.PrintStream#println(int) 109 * @see java.io.PrintStream#println(long) 110 * @see java.io.PrintStream#println(java.lang.Object) 111 * @see java.io.PrintStream#println(java.lang.String) 112 */ 113 public static final PrintStream out = null; 114 115 /** 116 * The "standard" error output stream. This stream is already 117 * open and ready to accept output data. 118 * <p> 119 * Typically this stream corresponds to display output or another 120 * output destination specified by the host environment or user. By 121 * convention, this output stream is used to display error messages 122 * or other information that should come to the immediate attention 123 * of a user even if the principal output stream, the value of the 124 * variable <code>out</code>, has been redirected to a file or other 125 * destination that is typically not continuously monitored. 126 */ 127 public static final PrintStream err = null; 128 129 /* The security manager for the system. 130 */ 131 private static volatile SecurityManager security = null; 132 133 /** 134 * Reassigns the "standard" input stream. 135 * 136 * <p>First, if there is a security manager, its <code>checkPermission</code> 137 * method is called with a <code>RuntimePermission("setIO")</code> permission 138 * to see if it's ok to reassign the "standard" input stream. 139 * 140 * @param in the new standard input stream. 141 * 142 * @throws SecurityException 143 * if a security manager exists and its 144 * <code>checkPermission</code> method doesn't allow 145 * reassigning of the standard input stream. 146 * 147 * @see SecurityManager#checkPermission 148 * @see java.lang.RuntimePermission 149 * 150 * @since 1.1 151 */ 152 public static void setIn(InputStream in) { 153 checkIO(); 154 setIn0(in); 155 } 156 157 /** 158 * Reassigns the "standard" output stream. 159 * 160 * <p>First, if there is a security manager, its <code>checkPermission</code> 161 * method is called with a <code>RuntimePermission("setIO")</code> permission 162 * to see if it's ok to reassign the "standard" output stream. 163 * 164 * @param out the new standard output stream 165 * 166 * @throws SecurityException 167 * if a security manager exists and its 168 * <code>checkPermission</code> method doesn't allow 169 * reassigning of the standard output stream. 170 * 171 * @see SecurityManager#checkPermission 172 * @see java.lang.RuntimePermission 173 * 174 * @since 1.1 175 */ 176 public static void setOut(PrintStream out) { 177 checkIO(); 178 setOut0(out); 179 } 180 181 /** 182 * Reassigns the "standard" error output stream. 183 * 184 * <p>First, if there is a security manager, its <code>checkPermission</code> 185 * method is called with a <code>RuntimePermission("setIO")</code> permission 186 * to see if it's ok to reassign the "standard" error output stream. 187 * 188 * @param err the new standard error output stream. 189 * 190 * @throws SecurityException 191 * if a security manager exists and its 192 * <code>checkPermission</code> method doesn't allow 193 * reassigning of the standard error output stream. 194 * 195 * @see SecurityManager#checkPermission 196 * @see java.lang.RuntimePermission 197 * 198 * @since 1.1 199 */ 200 public static void setErr(PrintStream err) { 201 checkIO(); 202 setErr0(err); 203 } 204 205 private static volatile Console cons = null; 206 /** 207 * Returns the unique {@link java.io.Console Console} object associated 208 * with the current Java virtual machine, if any. 209 * 210 * @return The system console, if any, otherwise {@code null}. 211 * 212 * @since 1.6 213 */ 214 public static Console console() { 215 if (cons == null) { 216 synchronized (System.class) { 217 cons = SharedSecrets.getJavaIOAccess().console(); 218 } 219 } 220 return cons; 221 } 222 223 /** 224 * Returns the channel inherited from the entity that created this 225 * Java virtual machine. 226 * 227 * <p> This method returns the channel obtained by invoking the 228 * {@link java.nio.channels.spi.SelectorProvider#inheritedChannel 229 * inheritedChannel} method of the system-wide default 230 * {@link java.nio.channels.spi.SelectorProvider} object. </p> 231 * 232 * <p> In addition to the network-oriented channels described in 233 * {@link java.nio.channels.spi.SelectorProvider#inheritedChannel 234 * inheritedChannel}, this method may return other kinds of 235 * channels in the future. 236 * 237 * @return The inherited channel, if any, otherwise {@code null}. 238 * 239 * @throws IOException 240 * If an I/O error occurs 241 * 242 * @throws SecurityException 243 * If a security manager is present and it does not 244 * permit access to the channel. 245 * 246 * @since 1.5 247 */ 248 public static Channel inheritedChannel() throws IOException { 249 return SelectorProvider.provider().inheritedChannel(); 250 } 251 252 private static void checkIO() { 253 SecurityManager sm = getSecurityManager(); 254 if (sm != null) { 255 sm.checkPermission(new RuntimePermission("setIO")); 256 } 257 } 258 259 private static native void setIn0(InputStream in); 260 private static native void setOut0(PrintStream out); 261 private static native void setErr0(PrintStream err); 262 263 /** 264 * Sets the System security. 265 * 266 * <p> If there is a security manager already installed, this method first 267 * calls the security manager's <code>checkPermission</code> method 268 * with a <code>RuntimePermission("setSecurityManager")</code> 269 * permission to ensure it's ok to replace the existing 270 * security manager. 271 * This may result in throwing a <code>SecurityException</code>. 272 * 273 * <p> Otherwise, the argument is established as the current 274 * security manager. If the argument is <code>null</code> and no 275 * security manager has been established, then no action is taken and 276 * the method simply returns. 277 * 278 * @param s the security manager. 279 * @exception SecurityException if the security manager has already 280 * been set and its <code>checkPermission</code> method 281 * doesn't allow it to be replaced. 282 * @see #getSecurityManager 283 * @see SecurityManager#checkPermission 284 * @see java.lang.RuntimePermission 285 */ 286 public static 287 void setSecurityManager(final SecurityManager s) { 288 try { 289 s.checkPackageAccess("java.lang"); 290 } catch (Exception e) { 291 // no-op 292 } 293 setSecurityManager0(s); 294 } 295 296 private static synchronized 297 void setSecurityManager0(final SecurityManager s) { 298 SecurityManager sm = getSecurityManager(); 299 if (sm != null) { 300 // ask the currently installed security manager if we 301 // can replace it. 302 sm.checkPermission(new RuntimePermission 303 ("setSecurityManager")); 304 } 305 306 if ((s != null) && (s.getClass().getClassLoader() != null)) { 307 // New security manager class is not on bootstrap classpath. 308 // Cause policy to get initialized before we install the new 309 // security manager, in order to prevent infinite loops when 310 // trying to initialize the policy (which usually involves 311 // accessing some security and/or system properties, which in turn 312 // calls the installed security manager's checkPermission method 313 // which will loop infinitely if there is a non-system class 314 // (in this case: the new security manager class) on the stack). 315 AccessController.doPrivileged(new PrivilegedAction<>() { 316 public Object run() { 317 s.getClass().getProtectionDomain().implies 318 (SecurityConstants.ALL_PERMISSION); 319 return null; 320 } 321 }); 322 } 323 324 security = s; 325 } 326 327 /** 328 * Gets the system security interface. 329 * 330 * @return if a security manager has already been established for the 331 * current application, then that security manager is returned; 332 * otherwise, <code>null</code> is returned. 333 * @see #setSecurityManager 334 */ 335 public static SecurityManager getSecurityManager() { 336 return security; 337 } 338 339 /** 340 * Returns the current time in milliseconds. Note that 341 * while the unit of time of the return value is a millisecond, 342 * the granularity of the value depends on the underlying 343 * operating system and may be larger. For example, many 344 * operating systems measure time in units of tens of 345 * milliseconds. 346 * 347 * <p> See the description of the class <code>Date</code> for 348 * a discussion of slight discrepancies that may arise between 349 * "computer time" and coordinated universal time (UTC). 350 * 351 * @return the difference, measured in milliseconds, between 352 * the current time and midnight, January 1, 1970 UTC. 353 * @see java.util.Date 354 */ 355 @HotSpotIntrinsicCandidate 356 public static native long currentTimeMillis(); 357 358 /** 359 * Returns the current value of the running Java Virtual Machine's 360 * high-resolution time source, in nanoseconds. 361 * 362 * <p>This method can only be used to measure elapsed time and is 363 * not related to any other notion of system or wall-clock time. 364 * The value returned represents nanoseconds since some fixed but 365 * arbitrary <i>origin</i> time (perhaps in the future, so values 366 * may be negative). The same origin is used by all invocations of 367 * this method in an instance of a Java virtual machine; other 368 * virtual machine instances are likely to use a different origin. 369 * 370 * <p>This method provides nanosecond precision, but not necessarily 371 * nanosecond resolution (that is, how frequently the value changes) 372 * - no guarantees are made except that the resolution is at least as 373 * good as that of {@link #currentTimeMillis()}. 374 * 375 * <p>Differences in successive calls that span greater than 376 * approximately 292 years (2<sup>63</sup> nanoseconds) will not 377 * correctly compute elapsed time due to numerical overflow. 378 * 379 * <p>The values returned by this method become meaningful only when 380 * the difference between two such values, obtained within the same 381 * instance of a Java virtual machine, is computed. 382 * 383 * <p>For example, to measure how long some code takes to execute: 384 * <pre> {@code 385 * long startTime = System.nanoTime(); 386 * // ... the code being measured ... 387 * long elapsedNanos = System.nanoTime() - startTime;}</pre> 388 * 389 * <p>To compare elapsed time against a timeout, use <pre> {@code 390 * if (System.nanoTime() - startTime >= timeoutNanos) ...}</pre> 391 * instead of <pre> {@code 392 * if (System.nanoTime() >= startTime + timeoutNanos) ...}</pre> 393 * because of the possibility of numerical overflow. 394 * 395 * @return the current value of the running Java Virtual Machine's 396 * high-resolution time source, in nanoseconds 397 * @since 1.5 398 */ 399 @HotSpotIntrinsicCandidate 400 public static native long nanoTime(); 401 402 /** 403 * Copies an array from the specified source array, beginning at the 404 * specified position, to the specified position of the destination array. 405 * A subsequence of array components are copied from the source 406 * array referenced by <code>src</code> to the destination array 407 * referenced by <code>dest</code>. The number of components copied is 408 * equal to the <code>length</code> argument. The components at 409 * positions <code>srcPos</code> through 410 * <code>srcPos+length-1</code> in the source array are copied into 411 * positions <code>destPos</code> through 412 * <code>destPos+length-1</code>, respectively, of the destination 413 * array. 414 * <p> 415 * If the <code>src</code> and <code>dest</code> arguments refer to the 416 * same array object, then the copying is performed as if the 417 * components at positions <code>srcPos</code> through 418 * <code>srcPos+length-1</code> were first copied to a temporary 419 * array with <code>length</code> components and then the contents of 420 * the temporary array were copied into positions 421 * <code>destPos</code> through <code>destPos+length-1</code> of the 422 * destination array. 423 * <p> 424 * If <code>dest</code> is <code>null</code>, then a 425 * <code>NullPointerException</code> is thrown. 426 * <p> 427 * If <code>src</code> is <code>null</code>, then a 428 * <code>NullPointerException</code> is thrown and the destination 429 * array is not modified. 430 * <p> 431 * Otherwise, if any of the following is true, an 432 * <code>ArrayStoreException</code> is thrown and the destination is 433 * not modified: 434 * <ul> 435 * <li>The <code>src</code> argument refers to an object that is not an 436 * array. 437 * <li>The <code>dest</code> argument refers to an object that is not an 438 * array. 439 * <li>The <code>src</code> argument and <code>dest</code> argument refer 440 * to arrays whose component types are different primitive types. 441 * <li>The <code>src</code> argument refers to an array with a primitive 442 * component type and the <code>dest</code> argument refers to an array 443 * with a reference component type. 444 * <li>The <code>src</code> argument refers to an array with a reference 445 * component type and the <code>dest</code> argument refers to an array 446 * with a primitive component type. 447 * </ul> 448 * <p> 449 * Otherwise, if any of the following is true, an 450 * <code>IndexOutOfBoundsException</code> is 451 * thrown and the destination is not modified: 452 * <ul> 453 * <li>The <code>srcPos</code> argument is negative. 454 * <li>The <code>destPos</code> argument is negative. 455 * <li>The <code>length</code> argument is negative. 456 * <li><code>srcPos+length</code> is greater than 457 * <code>src.length</code>, the length of the source array. 458 * <li><code>destPos+length</code> is greater than 459 * <code>dest.length</code>, the length of the destination array. 460 * </ul> 461 * <p> 462 * Otherwise, if any actual component of the source array from 463 * position <code>srcPos</code> through 464 * <code>srcPos+length-1</code> cannot be converted to the component 465 * type of the destination array by assignment conversion, an 466 * <code>ArrayStoreException</code> is thrown. In this case, let 467 * <b><i>k</i></b> be the smallest nonnegative integer less than 468 * length such that <code>src[srcPos+</code><i>k</i><code>]</code> 469 * cannot be converted to the component type of the destination 470 * array; when the exception is thrown, source array components from 471 * positions <code>srcPos</code> through 472 * <code>srcPos+</code><i>k</i><code>-1</code> 473 * will already have been copied to destination array positions 474 * <code>destPos</code> through 475 * <code>destPos+</code><i>k</I><code>-1</code> and no other 476 * positions of the destination array will have been modified. 477 * (Because of the restrictions already itemized, this 478 * paragraph effectively applies only to the situation where both 479 * arrays have component types that are reference types.) 480 * 481 * @param src the source array. 482 * @param srcPos starting position in the source array. 483 * @param dest the destination array. 484 * @param destPos starting position in the destination data. 485 * @param length the number of array elements to be copied. 486 * @exception IndexOutOfBoundsException if copying would cause 487 * access of data outside array bounds. 488 * @exception ArrayStoreException if an element in the <code>src</code> 489 * array could not be stored into the <code>dest</code> array 490 * because of a type mismatch. 491 * @exception NullPointerException if either <code>src</code> or 492 * <code>dest</code> is <code>null</code>. 493 */ 494 @HotSpotIntrinsicCandidate 495 public static native void arraycopy(Object src, int srcPos, 496 Object dest, int destPos, 497 int length); 498 499 /** 500 * Returns the same hash code for the given object as 501 * would be returned by the default method hashCode(), 502 * whether or not the given object's class overrides 503 * hashCode(). 504 * The hash code for the null reference is zero. 505 * 506 * @param x object for which the hashCode is to be calculated 507 * @return the hashCode 508 * @since 1.1 509 */ 510 @HotSpotIntrinsicCandidate 511 public static native int identityHashCode(Object x); 512 513 /** 514 * System properties. The following properties are guaranteed to be defined: 515 * <dl> 516 * <dt>java.version <dd>Java version number 517 * <dt>java.vendor <dd>Java vendor specific string 518 * <dt>java.vendor.url <dd>Java vendor URL 519 * <dt>java.home <dd>Java installation directory 520 * <dt>java.class.version <dd>Java class version number 521 * <dt>java.class.path <dd>Java classpath 522 * <dt>os.name <dd>Operating System Name 523 * <dt>os.arch <dd>Operating System Architecture 524 * <dt>os.version <dd>Operating System Version 525 * <dt>file.separator <dd>File separator ("/" on Unix) 526 * <dt>path.separator <dd>Path separator (":" on Unix) 527 * <dt>line.separator <dd>Line separator ("\n" on Unix) 528 * <dt>user.name <dd>User account name 529 * <dt>user.home <dd>User home directory 530 * <dt>user.dir <dd>User's current working directory 531 * </dl> 532 */ 533 534 private static Properties props; 535 private static native Properties initProperties(Properties props); 536 537 /** 538 * Determines the current system properties. 539 * <p> 540 * First, if there is a security manager, its 541 * <code>checkPropertiesAccess</code> method is called with no 542 * arguments. This may result in a security exception. 543 * <p> 544 * The current set of system properties for use by the 545 * {@link #getProperty(String)} method is returned as a 546 * <code>Properties</code> object. If there is no current set of 547 * system properties, a set of system properties is first created and 548 * initialized. This set of system properties always includes values 549 * for the following keys: 550 * <table summary="Shows property keys and associated values"> 551 * <tr><th>Key</th> 552 * <th>Description of Associated Value</th></tr> 553 * <tr><td><code>java.version</code></td> 554 * <td>Java Runtime Environment version</td></tr> 555 * <tr><td><code>java.vendor</code></td> 556 * <td>Java Runtime Environment vendor</td></tr> 557 * <tr><td><code>java.vendor.url</code></td> 558 * <td>Java vendor URL</td></tr> 559 * <tr><td><code>java.home</code></td> 560 * <td>Java installation directory</td></tr> 561 * <tr><td><code>java.vm.specification.version</code></td> 562 * <td>Java Virtual Machine specification version</td></tr> 563 * <tr><td><code>java.vm.specification.vendor</code></td> 564 * <td>Java Virtual Machine specification vendor</td></tr> 565 * <tr><td><code>java.vm.specification.name</code></td> 566 * <td>Java Virtual Machine specification name</td></tr> 567 * <tr><td><code>java.vm.version</code></td> 568 * <td>Java Virtual Machine implementation version</td></tr> 569 * <tr><td><code>java.vm.vendor</code></td> 570 * <td>Java Virtual Machine implementation vendor</td></tr> 571 * <tr><td><code>java.vm.name</code></td> 572 * <td>Java Virtual Machine implementation name</td></tr> 573 * <tr><td><code>java.specification.version</code></td> 574 * <td>Java Runtime Environment specification version</td></tr> 575 * <tr><td><code>java.specification.vendor</code></td> 576 * <td>Java Runtime Environment specification vendor</td></tr> 577 * <tr><td><code>java.specification.name</code></td> 578 * <td>Java Runtime Environment specification name</td></tr> 579 * <tr><td><code>java.class.version</code></td> 580 * <td>Java class format version number</td></tr> 581 * <tr><td><code>java.class.path</code></td> 582 * <td>Java class path</td></tr> 583 * <tr><td><code>java.library.path</code></td> 584 * <td>List of paths to search when loading libraries</td></tr> 585 * <tr><td><code>java.io.tmpdir</code></td> 586 * <td>Default temp file path</td></tr> 587 * <tr><td><code>java.compiler</code></td> 588 * <td>Name of JIT compiler to use</td></tr> 589 * <tr><td><code>os.name</code></td> 590 * <td>Operating system name</td></tr> 591 * <tr><td><code>os.arch</code></td> 592 * <td>Operating system architecture</td></tr> 593 * <tr><td><code>os.version</code></td> 594 * <td>Operating system version</td></tr> 595 * <tr><td><code>file.separator</code></td> 596 * <td>File separator ("/" on UNIX)</td></tr> 597 * <tr><td><code>path.separator</code></td> 598 * <td>Path separator (":" on UNIX)</td></tr> 599 * <tr><td><code>line.separator</code></td> 600 * <td>Line separator ("\n" on UNIX)</td></tr> 601 * <tr><td><code>user.name</code></td> 602 * <td>User's account name</td></tr> 603 * <tr><td><code>user.home</code></td> 604 * <td>User's home directory</td></tr> 605 * <tr><td><code>user.dir</code></td> 606 * <td>User's current working directory</td></tr> 607 * </table> 608 * <p> 609 * Multiple paths in a system property value are separated by the path 610 * separator character of the platform. 611 * <p> 612 * Note that even if the security manager does not permit the 613 * <code>getProperties</code> operation, it may choose to permit the 614 * {@link #getProperty(String)} operation. 615 * 616 * @return the system properties 617 * @exception SecurityException if a security manager exists and its 618 * <code>checkPropertiesAccess</code> method doesn't allow access 619 * to the system properties. 620 * @see #setProperties 621 * @see java.lang.SecurityException 622 * @see java.lang.SecurityManager#checkPropertiesAccess() 623 * @see java.util.Properties 624 */ 625 public static Properties getProperties() { 626 SecurityManager sm = getSecurityManager(); 627 if (sm != null) { 628 sm.checkPropertiesAccess(); 629 } 630 631 return props; 632 } 633 634 /** 635 * Returns the system-dependent line separator string. It always 636 * returns the same value - the initial value of the {@linkplain 637 * #getProperty(String) system property} {@code line.separator}. 638 * 639 * <p>On UNIX systems, it returns {@code "\n"}; on Microsoft 640 * Windows systems it returns {@code "\r\n"}. 641 * 642 * @return the system-dependent line separator string 643 * @since 1.7 644 */ 645 public static String lineSeparator() { 646 return lineSeparator; 647 } 648 649 private static String lineSeparator; 650 651 /** 652 * Sets the system properties to the <code>Properties</code> 653 * argument. 654 * <p> 655 * First, if there is a security manager, its 656 * <code>checkPropertiesAccess</code> method is called with no 657 * arguments. This may result in a security exception. 658 * <p> 659 * The argument becomes the current set of system properties for use 660 * by the {@link #getProperty(String)} method. If the argument is 661 * <code>null</code>, then the current set of system properties is 662 * forgotten. 663 * 664 * @param props the new system properties. 665 * @exception SecurityException if a security manager exists and its 666 * <code>checkPropertiesAccess</code> method doesn't allow access 667 * to the system properties. 668 * @see #getProperties 669 * @see java.util.Properties 670 * @see java.lang.SecurityException 671 * @see java.lang.SecurityManager#checkPropertiesAccess() 672 */ 673 public static void setProperties(Properties props) { 674 SecurityManager sm = getSecurityManager(); 675 if (sm != null) { 676 sm.checkPropertiesAccess(); 677 } 678 if (props == null) { 679 props = new Properties(); 680 initProperties(props); 681 } 682 System.props = props; 683 } 684 685 /** 686 * Gets the system property indicated by the specified key. 687 * <p> 688 * First, if there is a security manager, its 689 * <code>checkPropertyAccess</code> method is called with the key as 690 * its argument. This may result in a SecurityException. 691 * <p> 692 * If there is no current set of system properties, a set of system 693 * properties is first created and initialized in the same manner as 694 * for the <code>getProperties</code> method. 695 * 696 * @param key the name of the system property. 697 * @return the string value of the system property, 698 * or <code>null</code> if there is no property with that key. 699 * 700 * @exception SecurityException if a security manager exists and its 701 * <code>checkPropertyAccess</code> method doesn't allow 702 * access to the specified system property. 703 * @exception NullPointerException if <code>key</code> is 704 * <code>null</code>. 705 * @exception IllegalArgumentException if <code>key</code> is empty. 706 * @see #setProperty 707 * @see java.lang.SecurityException 708 * @see java.lang.SecurityManager#checkPropertyAccess(java.lang.String) 709 * @see java.lang.System#getProperties() 710 */ 711 public static String getProperty(String key) { 712 checkKey(key); 713 SecurityManager sm = getSecurityManager(); 714 if (sm != null) { 715 sm.checkPropertyAccess(key); 716 } 717 718 return props.getProperty(key); 719 } 720 721 /** 722 * Gets the system property indicated by the specified key. 723 * <p> 724 * First, if there is a security manager, its 725 * <code>checkPropertyAccess</code> method is called with the 726 * <code>key</code> as its argument. 727 * <p> 728 * If there is no current set of system properties, a set of system 729 * properties is first created and initialized in the same manner as 730 * for the <code>getProperties</code> method. 731 * 732 * @param key the name of the system property. 733 * @param def a default value. 734 * @return the string value of the system property, 735 * or the default value if there is no property with that key. 736 * 737 * @exception SecurityException if a security manager exists and its 738 * <code>checkPropertyAccess</code> method doesn't allow 739 * access to the specified system property. 740 * @exception NullPointerException if <code>key</code> is 741 * <code>null</code>. 742 * @exception IllegalArgumentException if <code>key</code> is empty. 743 * @see #setProperty 744 * @see java.lang.SecurityManager#checkPropertyAccess(java.lang.String) 745 * @see java.lang.System#getProperties() 746 */ 747 public static String getProperty(String key, String def) { 748 checkKey(key); 749 SecurityManager sm = getSecurityManager(); 750 if (sm != null) { 751 sm.checkPropertyAccess(key); 752 } 753 754 return props.getProperty(key, def); 755 } 756 757 /** 758 * Sets the system property indicated by the specified key. 759 * <p> 760 * First, if a security manager exists, its 761 * <code>SecurityManager.checkPermission</code> method 762 * is called with a <code>PropertyPermission(key, "write")</code> 763 * permission. This may result in a SecurityException being thrown. 764 * If no exception is thrown, the specified property is set to the given 765 * value. 766 * 767 * @param key the name of the system property. 768 * @param value the value of the system property. 769 * @return the previous value of the system property, 770 * or <code>null</code> if it did not have one. 771 * 772 * @exception SecurityException if a security manager exists and its 773 * <code>checkPermission</code> method doesn't allow 774 * setting of the specified property. 775 * @exception NullPointerException if <code>key</code> or 776 * <code>value</code> is <code>null</code>. 777 * @exception IllegalArgumentException if <code>key</code> is empty. 778 * @see #getProperty 779 * @see java.lang.System#getProperty(java.lang.String) 780 * @see java.lang.System#getProperty(java.lang.String, java.lang.String) 781 * @see java.util.PropertyPermission 782 * @see SecurityManager#checkPermission 783 * @since 1.2 784 */ 785 public static String setProperty(String key, String value) { 786 checkKey(key); 787 SecurityManager sm = getSecurityManager(); 788 if (sm != null) { 789 sm.checkPermission(new PropertyPermission(key, 790 SecurityConstants.PROPERTY_WRITE_ACTION)); 791 } 792 793 return (String) props.setProperty(key, value); 794 } 795 796 /** 797 * Removes the system property indicated by the specified key. 798 * <p> 799 * First, if a security manager exists, its 800 * <code>SecurityManager.checkPermission</code> method 801 * is called with a <code>PropertyPermission(key, "write")</code> 802 * permission. This may result in a SecurityException being thrown. 803 * If no exception is thrown, the specified property is removed. 804 * 805 * @param key the name of the system property to be removed. 806 * @return the previous string value of the system property, 807 * or <code>null</code> if there was no property with that key. 808 * 809 * @exception SecurityException if a security manager exists and its 810 * <code>checkPropertyAccess</code> method doesn't allow 811 * access to the specified system property. 812 * @exception NullPointerException if <code>key</code> is 813 * <code>null</code>. 814 * @exception IllegalArgumentException if <code>key</code> is empty. 815 * @see #getProperty 816 * @see #setProperty 817 * @see java.util.Properties 818 * @see java.lang.SecurityException 819 * @see java.lang.SecurityManager#checkPropertiesAccess() 820 * @since 1.5 821 */ 822 public static String clearProperty(String key) { 823 checkKey(key); 824 SecurityManager sm = getSecurityManager(); 825 if (sm != null) { 826 sm.checkPermission(new PropertyPermission(key, "write")); 827 } 828 829 return (String) props.remove(key); 830 } 831 832 private static void checkKey(String key) { 833 if (key == null) { 834 throw new NullPointerException("key can't be null"); 835 } 836 if (key.equals("")) { 837 throw new IllegalArgumentException("key can't be empty"); 838 } 839 } 840 841 /** 842 * Gets the value of the specified environment variable. An 843 * environment variable is a system-dependent external named 844 * value. 845 * 846 * <p>If a security manager exists, its 847 * {@link SecurityManager#checkPermission checkPermission} 848 * method is called with a 849 * <code>{@link RuntimePermission}("getenv."+name)</code> 850 * permission. This may result in a {@link SecurityException} 851 * being thrown. If no exception is thrown the value of the 852 * variable <code>name</code> is returned. 853 * 854 * <p><a name="EnvironmentVSSystemProperties"><i>System 855 * properties</i> and <i>environment variables</i></a> are both 856 * conceptually mappings between names and values. Both 857 * mechanisms can be used to pass user-defined information to a 858 * Java process. Environment variables have a more global effect, 859 * because they are visible to all descendants of the process 860 * which defines them, not just the immediate Java subprocess. 861 * They can have subtly different semantics, such as case 862 * insensitivity, on different operating systems. For these 863 * reasons, environment variables are more likely to have 864 * unintended side effects. It is best to use system properties 865 * where possible. Environment variables should be used when a 866 * global effect is desired, or when an external system interface 867 * requires an environment variable (such as <code>PATH</code>). 868 * 869 * <p>On UNIX systems the alphabetic case of <code>name</code> is 870 * typically significant, while on Microsoft Windows systems it is 871 * typically not. For example, the expression 872 * <code>System.getenv("FOO").equals(System.getenv("foo"))</code> 873 * is likely to be true on Microsoft Windows. 874 * 875 * @param name the name of the environment variable 876 * @return the string value of the variable, or <code>null</code> 877 * if the variable is not defined in the system environment 878 * @throws NullPointerException if <code>name</code> is <code>null</code> 879 * @throws SecurityException 880 * if a security manager exists and its 881 * {@link SecurityManager#checkPermission checkPermission} 882 * method doesn't allow access to the environment variable 883 * <code>name</code> 884 * @see #getenv() 885 * @see ProcessBuilder#environment() 886 */ 887 public static String getenv(String name) { 888 SecurityManager sm = getSecurityManager(); 889 if (sm != null) { 890 sm.checkPermission(new RuntimePermission("getenv."+name)); 891 } 892 893 return ProcessEnvironment.getenv(name); 894 } 895 896 897 /** 898 * Returns an unmodifiable string map view of the current system environment. 899 * The environment is a system-dependent mapping from names to 900 * values which is passed from parent to child processes. 901 * 902 * <p>If the system does not support environment variables, an 903 * empty map is returned. 904 * 905 * <p>The returned map will never contain null keys or values. 906 * Attempting to query the presence of a null key or value will 907 * throw a {@link NullPointerException}. Attempting to query 908 * the presence of a key or value which is not of type 909 * {@link String} will throw a {@link ClassCastException}. 910 * 911 * <p>The returned map and its collection views may not obey the 912 * general contract of the {@link Object#equals} and 913 * {@link Object#hashCode} methods. 914 * 915 * <p>The returned map is typically case-sensitive on all platforms. 916 * 917 * <p>If a security manager exists, its 918 * {@link SecurityManager#checkPermission checkPermission} 919 * method is called with a 920 * <code>{@link RuntimePermission}("getenv.*")</code> 921 * permission. This may result in a {@link SecurityException} being 922 * thrown. 923 * 924 * <p>When passing information to a Java subprocess, 925 * <a href=#EnvironmentVSSystemProperties>system properties</a> 926 * are generally preferred over environment variables. 927 * 928 * @return the environment as a map of variable names to values 929 * @throws SecurityException 930 * if a security manager exists and its 931 * {@link SecurityManager#checkPermission checkPermission} 932 * method doesn't allow access to the process environment 933 * @see #getenv(String) 934 * @see ProcessBuilder#environment() 935 * @since 1.5 936 */ 937 public static java.util.Map<String,String> getenv() { 938 SecurityManager sm = getSecurityManager(); 939 if (sm != null) { 940 sm.checkPermission(new RuntimePermission("getenv.*")); 941 } 942 943 return ProcessEnvironment.getenv(); 944 } 945 946 /** 947 * Terminates the currently running Java Virtual Machine. The 948 * argument serves as a status code; by convention, a nonzero status 949 * code indicates abnormal termination. 950 * <p> 951 * This method calls the <code>exit</code> method in class 952 * <code>Runtime</code>. This method never returns normally. 953 * <p> 954 * The call <code>System.exit(n)</code> is effectively equivalent to 955 * the call: 956 * <blockquote><pre> 957 * Runtime.getRuntime().exit(n) 958 * </pre></blockquote> 959 * 960 * @param status exit status. 961 * @throws SecurityException 962 * if a security manager exists and its <code>checkExit</code> 963 * method doesn't allow exit with the specified status. 964 * @see java.lang.Runtime#exit(int) 965 */ 966 public static void exit(int status) { 967 Runtime.getRuntime().exit(status); 968 } 969 970 /** 971 * Runs the garbage collector. 972 * <p> 973 * Calling the <code>gc</code> method suggests that the Java Virtual 974 * Machine expend effort toward recycling unused objects in order to 975 * make the memory they currently occupy available for quick reuse. 976 * When control returns from the method call, the Java Virtual 977 * Machine has made a best effort to reclaim space from all discarded 978 * objects. 979 * <p> 980 * The call <code>System.gc()</code> is effectively equivalent to the 981 * call: 982 * <blockquote><pre> 983 * Runtime.getRuntime().gc() 984 * </pre></blockquote> 985 * 986 * @see java.lang.Runtime#gc() 987 */ 988 public static void gc() { 989 Runtime.getRuntime().gc(); 990 } 991 992 /** 993 * Runs the finalization methods of any objects pending finalization. 994 * <p> 995 * Calling this method suggests that the Java Virtual Machine expend 996 * effort toward running the <code>finalize</code> methods of objects 997 * that have been found to be discarded but whose <code>finalize</code> 998 * methods have not yet been run. When control returns from the 999 * method call, the Java Virtual Machine has made a best effort to 1000 * complete all outstanding finalizations. 1001 * <p> 1002 * The call <code>System.runFinalization()</code> is effectively 1003 * equivalent to the call: 1004 * <blockquote><pre> 1005 * Runtime.getRuntime().runFinalization() 1006 * </pre></blockquote> 1007 * 1008 * @see java.lang.Runtime#runFinalization() 1009 */ 1010 public static void runFinalization() { 1011 Runtime.getRuntime().runFinalization(); 1012 } 1013 1014 /** 1015 * Enable or disable finalization on exit; doing so specifies that the 1016 * finalizers of all objects that have finalizers that have not yet been 1017 * automatically invoked are to be run before the Java runtime exits. 1018 * By default, finalization on exit is disabled. 1019 * 1020 * <p>If there is a security manager, 1021 * its <code>checkExit</code> method is first called 1022 * with 0 as its argument to ensure the exit is allowed. 1023 * This could result in a SecurityException. 1024 * 1025 * @deprecated This method is inherently unsafe. It may result in 1026 * finalizers being called on live objects while other threads are 1027 * concurrently manipulating those objects, resulting in erratic 1028 * behavior or deadlock. 1029 * @param value indicating enabling or disabling of finalization 1030 * @throws SecurityException 1031 * if a security manager exists and its <code>checkExit</code> 1032 * method doesn't allow the exit. 1033 * 1034 * @see java.lang.Runtime#exit(int) 1035 * @see java.lang.Runtime#gc() 1036 * @see java.lang.SecurityManager#checkExit(int) 1037 * @since 1.1 1038 */ 1039 @Deprecated 1040 public static void runFinalizersOnExit(boolean value) { 1041 Runtime.runFinalizersOnExit(value); 1042 } 1043 1044 /** 1045 * Loads the native library specified by the filename argument. The filename 1046 * argument must be an absolute path name. 1047 * 1048 * If the filename argument, when stripped of any platform-specific library 1049 * prefix, path, and file extension, indicates a library whose name is, 1050 * for example, L, and a native library called L is statically linked 1051 * with the VM, then the JNI_OnLoad_L function exported by the library 1052 * is invoked rather than attempting to load a dynamic library. 1053 * A filename matching the argument does not have to exist in the 1054 * file system. 1055 * See the JNI Specification for more details. 1056 * 1057 * Otherwise, the filename argument is mapped to a native library image in 1058 * an implementation-dependent manner. 1059 * 1060 * <p> 1061 * The call <code>System.load(name)</code> is effectively equivalent 1062 * to the call: 1063 * <blockquote><pre> 1064 * Runtime.getRuntime().load(name) 1065 * </pre></blockquote> 1066 * 1067 * @param filename the file to load. 1068 * @exception SecurityException if a security manager exists and its 1069 * <code>checkLink</code> method doesn't allow 1070 * loading of the specified dynamic library 1071 * @exception UnsatisfiedLinkError if either the filename is not an 1072 * absolute path name, the native library is not statically 1073 * linked with the VM, or the library cannot be mapped to 1074 * a native library image by the host system. 1075 * @exception NullPointerException if <code>filename</code> is 1076 * <code>null</code> 1077 * @see java.lang.Runtime#load(java.lang.String) 1078 * @see java.lang.SecurityManager#checkLink(java.lang.String) 1079 */ 1080 @CallerSensitive 1081 public static void load(String filename) { 1082 Runtime.getRuntime().load0(Reflection.getCallerClass(), filename); 1083 } 1084 1085 /** 1086 * Loads the native library specified by the <code>libname</code> 1087 * argument. The <code>libname</code> argument must not contain any platform 1088 * specific prefix, file extension or path. If a native library 1089 * called <code>libname</code> is statically linked with the VM, then the 1090 * JNI_OnLoad_<code>libname</code> function exported by the library is invoked. 1091 * See the JNI Specification for more details. 1092 * 1093 * Otherwise, the libname argument is loaded from a system library 1094 * location and mapped to a native library image in an implementation- 1095 * dependent manner. 1096 * <p> 1097 * The call <code>System.loadLibrary(name)</code> is effectively 1098 * equivalent to the call 1099 * <blockquote><pre> 1100 * Runtime.getRuntime().loadLibrary(name) 1101 * </pre></blockquote> 1102 * 1103 * @param libname the name of the library. 1104 * @exception SecurityException if a security manager exists and its 1105 * <code>checkLink</code> method doesn't allow 1106 * loading of the specified dynamic library 1107 * @exception UnsatisfiedLinkError if either the libname argument 1108 * contains a file path, the native library is not statically 1109 * linked with the VM, or the library cannot be mapped to a 1110 * native library image by the host system. 1111 * @exception NullPointerException if <code>libname</code> is 1112 * <code>null</code> 1113 * @see java.lang.Runtime#loadLibrary(java.lang.String) 1114 * @see java.lang.SecurityManager#checkLink(java.lang.String) 1115 */ 1116 @CallerSensitive 1117 public static void loadLibrary(String libname) { 1118 Runtime.getRuntime().loadLibrary0(Reflection.getCallerClass(), libname); 1119 } 1120 1121 /** 1122 * Maps a library name into a platform-specific string representing 1123 * a native library. 1124 * 1125 * @param libname the name of the library. 1126 * @return a platform-dependent native library name. 1127 * @exception NullPointerException if <code>libname</code> is 1128 * <code>null</code> 1129 * @see java.lang.System#loadLibrary(java.lang.String) 1130 * @see java.lang.ClassLoader#findLibrary(java.lang.String) 1131 * @since 1.2 1132 */ 1133 public static native String mapLibraryName(String libname); 1134 1135 /** 1136 * Create PrintStream for stdout/err based on encoding. 1137 */ 1138 private static PrintStream newPrintStream(FileOutputStream fos, String enc) { 1139 if (enc != null) { 1140 try { 1141 return new PrintStream(new BufferedOutputStream(fos, 128), true, enc); 1142 } catch (UnsupportedEncodingException uee) {} 1143 } 1144 return new PrintStream(new BufferedOutputStream(fos, 128), true); 1145 } 1146 1147 1148 /** 1149 * Initialize the system class. Called after thread initialization. 1150 */ 1151 private static void initializeSystemClass() { 1152 1153 // VM might invoke JNU_NewStringPlatform() to set those encoding 1154 // sensitive properties (user.home, user.name, boot.class.path, etc.) 1155 // during "props" initialization, in which it may need access, via 1156 // System.getProperty(), to the related system encoding property that 1157 // have been initialized (put into "props") at early stage of the 1158 // initialization. So make sure the "props" is available at the 1159 // very beginning of the initialization and all system properties to 1160 // be put into it directly. 1161 props = new Properties(); 1162 initProperties(props); // initialized by the VM 1163 1164 // There are certain system configurations that may be controlled by 1165 // VM options such as the maximum amount of direct memory and 1166 // Integer cache size used to support the object identity semantics 1167 // of autoboxing. Typically, the library will obtain these values 1168 // from the properties set by the VM. If the properties are for 1169 // internal implementation use only, these properties should be 1170 // removed from the system properties. 1171 // 1172 // See java.lang.Integer.IntegerCache and the 1173 // sun.misc.VM.saveAndRemoveProperties method for example. 1174 // 1175 // Save a private copy of the system properties object that 1176 // can only be accessed by the internal implementation. Remove 1177 // certain system properties that are not intended for public access. 1178 sun.misc.VM.saveAndRemoveProperties(props); 1179 1180 1181 lineSeparator = props.getProperty("line.separator"); 1182 sun.misc.Version.init(); 1183 1184 FileInputStream fdIn = new FileInputStream(FileDescriptor.in); 1185 FileOutputStream fdOut = new FileOutputStream(FileDescriptor.out); 1186 FileOutputStream fdErr = new FileOutputStream(FileDescriptor.err); 1187 setIn0(new BufferedInputStream(fdIn)); 1188 setOut0(newPrintStream(fdOut, props.getProperty("sun.stdout.encoding"))); 1189 setErr0(newPrintStream(fdErr, props.getProperty("sun.stderr.encoding"))); 1190 1191 // Load the zip library now in order to keep java.util.zip.ZipFile 1192 // from trying to use itself to load this library later. 1193 loadLibrary("zip"); 1194 1195 // Setup Java signal handlers for HUP, TERM, and INT (where available). 1196 Terminator.setup(); 1197 1198 // Initialize any miscellaneous operating system settings that need to be 1199 // set for the class libraries. Currently this is no-op everywhere except 1200 // for Windows where the process-wide error mode is set before the java.io 1201 // classes are used. 1202 sun.misc.VM.initializeOSEnvironment(); 1203 1204 // The main thread is not added to its thread group in the same 1205 // way as other threads; we must do it ourselves here. 1206 Thread current = Thread.currentThread(); 1207 current.getThreadGroup().add(current); 1208 1209 // register shared secrets 1210 setJavaLangAccess(); 1211 1212 // Subsystems that are invoked during initialization can invoke 1213 // sun.misc.VM.isBooted() in order to avoid doing things that should 1214 // wait until the application class loader has been set up. 1215 // IMPORTANT: Ensure that this remains the last initialization action! 1216 sun.misc.VM.booted(); 1217 } 1218 1219 private static void setJavaLangAccess() { 1220 // Allow privileged classes outside of java.lang 1221 SharedSecrets.setJavaLangAccess(new JavaLangAccess(){ 1222 public sun.reflect.ConstantPool getConstantPool(Class<?> klass) { 1223 return klass.getConstantPool(); 1224 } 1225 public boolean casAnnotationType(Class<?> klass, AnnotationType oldType, AnnotationType newType) { 1226 return klass.casAnnotationType(oldType, newType); 1227 } 1228 public AnnotationType getAnnotationType(Class<?> klass) { 1229 return klass.getAnnotationType(); 1230 } 1231 public Map<Class<? extends Annotation>, Annotation> getDeclaredAnnotationMap(Class<?> klass) { 1232 return klass.getDeclaredAnnotationMap(); 1233 } 1234 public byte[] getRawClassAnnotations(Class<?> klass) { 1235 return klass.getRawAnnotations(); 1236 } 1237 public byte[] getRawClassTypeAnnotations(Class<?> klass) { 1238 return klass.getRawTypeAnnotations(); 1239 } 1240 public byte[] getRawExecutableTypeAnnotations(Executable executable) { 1241 return Class.getExecutableTypeAnnotationBytes(executable); 1242 } 1243 public <E extends Enum<E>> 1244 E[] getEnumConstantsShared(Class<E> klass) { 1245 return klass.getEnumConstantsShared(); 1246 } 1247 public void blockedOn(Thread t, Interruptible b) { 1248 t.blockedOn(b); 1249 } 1250 public void registerShutdownHook(int slot, boolean registerShutdownInProgress, Runnable hook) { 1251 Shutdown.add(slot, registerShutdownInProgress, hook); 1252 } 1253 public int getStackTraceDepth(Throwable t) { 1254 return t.getStackTraceDepth(); 1255 } 1256 public StackTraceElement getStackTraceElement(Throwable t, int i) { 1257 return t.getStackTraceElement(i); 1258 } 1259 public String newStringUnsafe(char[] chars) { 1260 return new String(chars, true); 1261 } 1262 public Thread newThreadWithAcc(Runnable target, AccessControlContext acc) { 1263 return new Thread(target, acc); 1264 } 1265 public void invokeFinalize(Object o) throws Throwable { 1266 o.finalize(); 1267 } 1268 public void formatUnsignedLong(long val, int shift, char[] buf, int offset, int len) { 1269 Long.formatUnsignedLong(val, shift, buf, offset, len); 1270 } 1271 public void formatUnsignedInt(int val, int shift, char[] buf, int offset, int len) { 1272 Integer.formatUnsignedInt(val, shift, buf, offset, len); 1273 } 1274 }); 1275 } 1276 }