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