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