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