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