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