1 /* 2 * Copyright (c) 1994, 2014, 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 1.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 * 137 * @param in the new standard input stream. 138 * 139 * @throws SecurityException 140 * if a security manager exists and its 141 * <code>checkPermission</code> method doesn't allow 142 * reassigning of the standard input stream. 143 * 144 * @see SecurityManager#checkPermission 145 * @see java.lang.RuntimePermission 146 * 147 * @since 1.1 148 */ 149 public static void setIn(InputStream in) { 150 checkIO(); 151 setIn0(in); 152 } 153 154 /** 155 * Reassigns the "standard" output stream. 156 * 157 * <p>First, if there is a security manager, its <code>checkPermission</code> 158 * method is called with a <code>RuntimePermission("setIO")</code> permission 159 * to see if it's ok to reassign the "standard" output stream. 160 * 161 * @param out the new standard output stream 162 * 163 * @throws SecurityException 164 * if a security manager exists and its 165 * <code>checkPermission</code> method doesn't allow 166 * reassigning of the standard output stream. 167 * 168 * @see SecurityManager#checkPermission 169 * @see java.lang.RuntimePermission 170 * 171 * @since 1.1 172 */ 173 public static void setOut(PrintStream out) { 174 checkIO(); 175 setOut0(out); 176 } 177 178 /** 179 * Reassigns the "standard" error output stream. 180 * 181 * <p>First, if there is a security manager, its <code>checkPermission</code> 182 * method is called with a <code>RuntimePermission("setIO")</code> permission 183 * to see if it's ok to reassign the "standard" error output stream. 184 * 185 * @param err the new standard error output stream. 186 * 187 * @throws SecurityException 188 * if a security manager exists and its 189 * <code>checkPermission</code> method doesn't allow 190 * reassigning of the standard error output stream. 191 * 192 * @see SecurityManager#checkPermission 193 * @see java.lang.RuntimePermission 194 * 195 * @since 1.1 196 */ 197 public static void setErr(PrintStream err) { 198 checkIO(); 199 setErr0(err); 200 } 201 202 private static volatile Console cons = null; 203 /** 204 * Returns the unique {@link java.io.Console Console} object associated 205 * with the current Java virtual machine, if any. 206 * 207 * @return The system console, if any, otherwise <tt>null</tt>. 208 * 209 * @since 1.6 210 */ 211 public static Console console() { 212 if (cons == null) { 213 synchronized (System.class) { 214 cons = sun.misc.SharedSecrets.getJavaIOAccess().console(); 215 } 216 } 217 return cons; 218 } 219 220 /** 221 * Returns the channel inherited from the entity that created this 222 * Java virtual machine. 223 * 224 * <p> This method returns the channel obtained by invoking the 225 * {@link java.nio.channels.spi.SelectorProvider#inheritedChannel 226 * inheritedChannel} method of the system-wide default 227 * {@link java.nio.channels.spi.SelectorProvider} object. </p> 228 * 229 * <p> In addition to the network-oriented channels described in 230 * {@link java.nio.channels.spi.SelectorProvider#inheritedChannel 231 * inheritedChannel}, this method may return other kinds of 232 * channels in the future. 233 * 234 * @return The inherited channel, if any, otherwise <tt>null</tt>. 235 * 236 * @throws IOException 237 * If an I/O error occurs 238 * 239 * @throws SecurityException 240 * If a security manager is present and it does not 241 * permit access to the channel. 242 * 243 * @since 1.5 244 */ 245 public static Channel inheritedChannel() throws IOException { 246 return SelectorProvider.provider().inheritedChannel(); 247 } 248 249 private static void checkIO() { 250 SecurityManager sm = getSecurityManager(); 251 if (sm != null) { 252 sm.checkPermission(new RuntimePermission("setIO")); 253 } 254 } 255 256 private static native void setIn0(InputStream in); 257 private static native void setOut0(PrintStream out); 258 private static native void setErr0(PrintStream err); 259 260 /** 261 * Sets the System security. 262 * 263 * <p> If there is a security manager already installed, this method first 264 * calls the security manager's <code>checkPermission</code> method 265 * with a <code>RuntimePermission("setSecurityManager")</code> 266 * permission to ensure it's ok to replace the existing 267 * security manager. 268 * This may result in throwing a <code>SecurityException</code>. 269 * 270 * <p> Otherwise, the argument is established as the current 271 * security manager. If the argument is <code>null</code> and no 272 * security manager has been established, then no action is taken and 273 * the method simply returns. 274 * 275 * @param s the security manager. 276 * @exception SecurityException if the security manager has already 277 * been set and its <code>checkPermission</code> method 278 * doesn't allow it to be replaced. 279 * @see #getSecurityManager 280 * @see SecurityManager#checkPermission 281 * @see java.lang.RuntimePermission 282 */ 283 public static 284 void setSecurityManager(final SecurityManager s) { 285 try { 286 s.checkPackageAccess("java.lang"); 287 } catch (Exception e) { 288 // no-op 289 } 290 setSecurityManager0(s); 291 } 292 293 private static synchronized 294 void setSecurityManager0(final SecurityManager s) { 295 SecurityManager sm = getSecurityManager(); 296 if (sm != null) { 297 // ask the currently installed security manager if we 298 // can replace it. 299 sm.checkPermission(new RuntimePermission 300 ("setSecurityManager")); 301 } 302 303 if ((s != null) && (s.getClass().getClassLoader() != null)) { 304 // New security manager class is not on bootstrap classpath. 305 // Cause policy to get initialized before we install the new 306 // security manager, in order to prevent infinite loops when 307 // trying to initialize the policy (which usually involves 308 // accessing some security and/or system properties, which in turn 309 // calls the installed security manager's checkPermission method 310 // which will loop infinitely if there is a non-system class 311 // (in this case: the new security manager class) on the stack). 312 AccessController.doPrivileged(new PrivilegedAction<>() { 313 public Object run() { 314 s.getClass().getProtectionDomain().implies 315 (SecurityConstants.ALL_PERMISSION); 316 return null; 317 } 318 }); 319 } 320 321 security = s; 322 } 323 324 /** 325 * Gets the system security interface. 326 * 327 * @return if a security manager has already been established for the 328 * current application, then that security manager is returned; 329 * otherwise, <code>null</code> is returned. 330 * @see #setSecurityManager 331 */ 332 public static SecurityManager getSecurityManager() { 333 return security; 334 } 335 336 /** 337 * Returns the current time in milliseconds. Note that 338 * while the unit of time of the return value is a millisecond, 339 * the granularity of the value depends on the underlying 340 * operating system and may be larger. For example, many 341 * operating systems measure time in units of tens of 342 * milliseconds. 343 * 344 * <p> See the description of the class <code>Date</code> for 345 * a discussion of slight discrepancies that may arise between 346 * "computer time" and coordinated universal time (UTC). 347 * 348 * @return the difference, measured in milliseconds, between 349 * the current time and midnight, January 1, 1970 UTC. 350 * @see java.util.Date 351 */ 352 public static native long currentTimeMillis(); 353 354 /** 355 * Returns the current value of the running Java Virtual Machine's 356 * high-resolution time source, in nanoseconds. 357 * 358 * <p>This method can only be used to measure elapsed time and is 359 * not related to any other notion of system or wall-clock time. 360 * The value returned represents nanoseconds since some fixed but 361 * arbitrary <i>origin</i> time (perhaps in the future, so values 362 * may be negative). The same origin is used by all invocations of 363 * this method in an instance of a Java virtual machine; other 364 * virtual machine instances are likely to use a different origin. 365 * 366 * <p>This method provides nanosecond precision, but not necessarily 367 * nanosecond resolution (that is, how frequently the value changes) 368 * - no guarantees are made except that the resolution is at least as 369 * good as that of {@link #currentTimeMillis()}. 370 * 371 * <p>Differences in successive calls that span greater than 372 * approximately 292 years (2<sup>63</sup> nanoseconds) will not 373 * correctly compute elapsed time due to numerical overflow. 374 * 375 * <p>The values returned by this method become meaningful only when 376 * the difference between two such values, obtained within the same 377 * instance of a Java virtual machine, is computed. 378 * 379 * <p>For example, to measure how long some code takes to execute: 380 * <pre> {@code 381 * long startTime = System.nanoTime(); 382 * // ... the code being measured ... 383 * long elapsedNanos = System.nanoTime() - startTime;}</pre> 384 * 385 * <p>To compare elapsed time against a timeout, use <pre> {@code 386 * if (System.nanoTime() - startTime >= timeoutNanos) ...}</pre> 387 * instead of <pre> {@code 388 * if (System.nanoTime() >= startTime + timeoutNanos) ...}</pre> 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 1.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>os.name</code></td> 583 * <td>Operating system name</td></tr> 584 * <tr><td><code>os.arch</code></td> 585 * <td>Operating system architecture</td></tr> 586 * <tr><td><code>os.version</code></td> 587 * <td>Operating system version</td></tr> 588 * <tr><td><code>file.separator</code></td> 589 * <td>File separator ("/" on UNIX)</td></tr> 590 * <tr><td><code>path.separator</code></td> 591 * <td>Path separator (":" on UNIX)</td></tr> 592 * <tr><td><code>line.separator</code></td> 593 * <td>Line separator ("\n" on UNIX)</td></tr> 594 * <tr><td><code>user.name</code></td> 595 * <td>User's account name</td></tr> 596 * <tr><td><code>user.home</code></td> 597 * <td>User's home directory</td></tr> 598 * <tr><td><code>user.dir</code></td> 599 * <td>User's current working directory</td></tr> 600 * </table> 601 * <p> 602 * Multiple paths in a system property value are separated by the path 603 * separator character of the platform. 604 * <p> 605 * Note that even if the security manager does not permit the 606 * <code>getProperties</code> operation, it may choose to permit the 607 * {@link #getProperty(String)} operation. 608 * 609 * @return the system properties 610 * @exception SecurityException if a security manager exists and its 611 * <code>checkPropertiesAccess</code> method doesn't allow access 612 * to the system properties. 613 * @see #setProperties 614 * @see java.lang.SecurityException 615 * @see java.lang.SecurityManager#checkPropertiesAccess() 616 * @see java.util.Properties 617 */ 618 public static Properties getProperties() { 619 SecurityManager sm = getSecurityManager(); 620 if (sm != null) { 621 sm.checkPropertiesAccess(); 622 } 623 624 return props; 625 } 626 627 /** 628 * Returns the system-dependent line separator string. It always 629 * returns the same value - the initial value of the {@linkplain 630 * #getProperty(String) system property} {@code line.separator}. 631 * 632 * <p>On UNIX systems, it returns {@code "\n"}; on Microsoft 633 * Windows systems it returns {@code "\r\n"}. 634 * 635 * @return the system-dependent line separator string 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 * 760 * @param key the name of the system property. 761 * @param value the value of the system property. 762 * @return the previous value of the system property, 763 * or <code>null</code> if it did not have one. 764 * 765 * @exception SecurityException if a security manager exists and its 766 * <code>checkPermission</code> method doesn't allow 767 * setting of the specified property. 768 * @exception NullPointerException if <code>key</code> or 769 * <code>value</code> is <code>null</code>. 770 * @exception IllegalArgumentException if <code>key</code> is empty. 771 * @see #getProperty 772 * @see java.lang.System#getProperty(java.lang.String) 773 * @see java.lang.System#getProperty(java.lang.String, java.lang.String) 774 * @see java.util.PropertyPermission 775 * @see SecurityManager#checkPermission 776 * @since 1.2 777 */ 778 public static String setProperty(String key, String value) { 779 checkKey(key); 780 SecurityManager sm = getSecurityManager(); 781 if (sm != null) { 782 sm.checkPermission(new PropertyPermission(key, 783 SecurityConstants.PROPERTY_WRITE_ACTION)); 784 } 785 786 return (String) props.setProperty(key, value); 787 } 788 789 /** 790 * Removes the system property indicated by the specified key. 791 * <p> 792 * First, if a security manager exists, its 793 * <code>SecurityManager.checkPermission</code> method 794 * is called with a <code>PropertyPermission(key, "write")</code> 795 * permission. This may result in a SecurityException being thrown. 796 * If no exception is thrown, the specified property is removed. 797 * 798 * @param key the name of the system property to be removed. 799 * @return the previous string value of the system property, 800 * or <code>null</code> if there was no property with that key. 801 * 802 * @exception SecurityException if a security manager exists and its 803 * <code>checkPropertyAccess</code> method doesn't allow 804 * access to the specified system property. 805 * @exception NullPointerException if <code>key</code> is 806 * <code>null</code>. 807 * @exception IllegalArgumentException if <code>key</code> is empty. 808 * @see #getProperty 809 * @see #setProperty 810 * @see java.util.Properties 811 * @see java.lang.SecurityException 812 * @see java.lang.SecurityManager#checkPropertiesAccess() 813 * @since 1.5 814 */ 815 public static String clearProperty(String key) { 816 checkKey(key); 817 SecurityManager sm = getSecurityManager(); 818 if (sm != null) { 819 sm.checkPermission(new PropertyPermission(key, "write")); 820 } 821 822 return (String) props.remove(key); 823 } 824 825 private static void checkKey(String key) { 826 if (key == null) { 827 throw new NullPointerException("key can't be null"); 828 } 829 if (key.equals("")) { 830 throw new IllegalArgumentException("key can't be empty"); 831 } 832 } 833 834 /** 835 * Gets the value of the specified environment variable. An 836 * environment variable is a system-dependent external named 837 * value. 838 * 839 * <p>If a security manager exists, its 840 * {@link SecurityManager#checkPermission checkPermission} 841 * method is called with a 842 * <code>{@link RuntimePermission}("getenv."+name)</code> 843 * permission. This may result in a {@link SecurityException} 844 * being thrown. If no exception is thrown the value of the 845 * variable <code>name</code> is returned. 846 * 847 * <p><a name="EnvironmentVSSystemProperties"><i>System 848 * properties</i> and <i>environment variables</i></a> are both 849 * conceptually mappings between names and values. Both 850 * mechanisms can be used to pass user-defined information to a 851 * Java process. Environment variables have a more global effect, 852 * because they are visible to all descendants of the process 853 * which defines them, not just the immediate Java subprocess. 854 * They can have subtly different semantics, such as case 855 * insensitivity, on different operating systems. For these 856 * reasons, environment variables are more likely to have 857 * unintended side effects. It is best to use system properties 858 * where possible. Environment variables should be used when a 859 * global effect is desired, or when an external system interface 860 * requires an environment variable (such as <code>PATH</code>). 861 * 862 * <p>On UNIX systems the alphabetic case of <code>name</code> is 863 * typically significant, while on Microsoft Windows systems it is 864 * typically not. For example, the expression 865 * <code>System.getenv("FOO").equals(System.getenv("foo"))</code> 866 * is likely to be true on Microsoft Windows. 867 * 868 * @param name the name of the environment variable 869 * @return the string value of the variable, or <code>null</code> 870 * if the variable is not defined in the system environment 871 * @throws NullPointerException if <code>name</code> is <code>null</code> 872 * @throws SecurityException 873 * if a security manager exists and its 874 * {@link SecurityManager#checkPermission checkPermission} 875 * method doesn't allow access to the environment variable 876 * <code>name</code> 877 * @see #getenv() 878 * @see ProcessBuilder#environment() 879 */ 880 public static String getenv(String name) { 881 SecurityManager sm = getSecurityManager(); 882 if (sm != null) { 883 sm.checkPermission(new RuntimePermission("getenv."+name)); 884 } 885 886 return ProcessEnvironment.getenv(name); 887 } 888 889 890 /** 891 * Returns an unmodifiable string map view of the current system environment. 892 * The environment is a system-dependent mapping from names to 893 * values which is passed from parent to child processes. 894 * 895 * <p>If the system does not support environment variables, an 896 * empty map is returned. 897 * 898 * <p>The returned map will never contain null keys or values. 899 * Attempting to query the presence of a null key or value will 900 * throw a {@link NullPointerException}. Attempting to query 901 * the presence of a key or value which is not of type 902 * {@link String} will throw a {@link ClassCastException}. 903 * 904 * <p>The returned map and its collection views may not obey the 905 * general contract of the {@link Object#equals} and 906 * {@link Object#hashCode} methods. 907 * 908 * <p>The returned map is typically case-sensitive on all platforms. 909 * 910 * <p>If a security manager exists, its 911 * {@link SecurityManager#checkPermission checkPermission} 912 * method is called with a 913 * <code>{@link RuntimePermission}("getenv.*")</code> 914 * permission. This may result in a {@link SecurityException} being 915 * thrown. 916 * 917 * <p>When passing information to a Java subprocess, 918 * <a href=#EnvironmentVSSystemProperties>system properties</a> 919 * are generally preferred over environment variables. 920 * 921 * @return the environment as a map of variable names to values 922 * @throws SecurityException 923 * if a security manager exists and its 924 * {@link SecurityManager#checkPermission checkPermission} 925 * method doesn't allow access to the process environment 926 * @see #getenv(String) 927 * @see ProcessBuilder#environment() 928 * @since 1.5 929 */ 930 public static java.util.Map<String,String> getenv() { 931 SecurityManager sm = getSecurityManager(); 932 if (sm != null) { 933 sm.checkPermission(new RuntimePermission("getenv.*")); 934 } 935 936 return ProcessEnvironment.getenv(); 937 } 938 939 /** 940 * Terminates the currently running Java Virtual Machine. The 941 * argument serves as a status code; by convention, a nonzero status 942 * code indicates abnormal termination. 943 * <p> 944 * This method calls the <code>exit</code> method in class 945 * <code>Runtime</code>. This method never returns normally. 946 * <p> 947 * The call <code>System.exit(n)</code> is effectively equivalent to 948 * the call: 949 * <blockquote><pre> 950 * Runtime.getRuntime().exit(n) 951 * </pre></blockquote> 952 * 953 * @param status exit status. 954 * @throws SecurityException 955 * if a security manager exists and its <code>checkExit</code> 956 * method doesn't allow exit with the specified status. 957 * @see java.lang.Runtime#exit(int) 958 */ 959 public static void exit(int status) { 960 Runtime.getRuntime().exit(status); 961 } 962 963 /** 964 * Runs the garbage collector. 965 * <p> 966 * Calling the <code>gc</code> method suggests that the Java Virtual 967 * Machine expend effort toward recycling unused objects in order to 968 * make the memory they currently occupy available for quick reuse. 969 * When control returns from the method call, the Java Virtual 970 * Machine has made a best effort to reclaim space from all discarded 971 * objects. 972 * <p> 973 * The call <code>System.gc()</code> is effectively equivalent to the 974 * call: 975 * <blockquote><pre> 976 * Runtime.getRuntime().gc() 977 * </pre></blockquote> 978 * 979 * @see java.lang.Runtime#gc() 980 */ 981 public static void gc() { 982 Runtime.getRuntime().gc(); 983 } 984 985 /** 986 * Runs the finalization methods of any objects pending finalization. 987 * <p> 988 * Calling this method suggests that the Java Virtual Machine expend 989 * effort toward running the <code>finalize</code> methods of objects 990 * that have been found to be discarded but whose <code>finalize</code> 991 * methods have not yet been run. When control returns from the 992 * method call, the Java Virtual Machine has made a best effort to 993 * complete all outstanding finalizations. 994 * <p> 995 * The call <code>System.runFinalization()</code> is effectively 996 * equivalent to the call: 997 * <blockquote><pre> 998 * Runtime.getRuntime().runFinalization() 999 * </pre></blockquote> 1000 * 1001 * @see java.lang.Runtime#runFinalization() 1002 */ 1003 public static void runFinalization() { 1004 Runtime.getRuntime().runFinalization(); 1005 } 1006 1007 /** 1008 * Enable or disable finalization on exit; doing so specifies that the 1009 * finalizers of all objects that have finalizers that have not yet been 1010 * automatically invoked are to be run before the Java runtime exits. 1011 * By default, finalization on exit is disabled. 1012 * 1013 * <p>If there is a security manager, 1014 * its <code>checkExit</code> method is first called 1015 * with 0 as its argument to ensure the exit is allowed. 1016 * This could result in a SecurityException. 1017 * 1018 * @deprecated This method is inherently unsafe. It may result in 1019 * finalizers being called on live objects while other threads are 1020 * concurrently manipulating those objects, resulting in erratic 1021 * behavior or deadlock. 1022 * @param value indicating enabling or disabling of finalization 1023 * @throws SecurityException 1024 * if a security manager exists and its <code>checkExit</code> 1025 * method doesn't allow the exit. 1026 * 1027 * @see java.lang.Runtime#exit(int) 1028 * @see java.lang.Runtime#gc() 1029 * @see java.lang.SecurityManager#checkExit(int) 1030 * @since 1.1 1031 */ 1032 @Deprecated 1033 public static void runFinalizersOnExit(boolean value) { 1034 Runtime.runFinalizersOnExit(value); 1035 } 1036 1037 /** 1038 * Loads the native library specified by the filename argument. The filename 1039 * argument must be an absolute path name. 1040 * 1041 * If the filename argument, when stripped of any platform-specific library 1042 * prefix, path, and file extension, indicates a library whose name is, 1043 * for example, L, and a native library called L is statically linked 1044 * with the VM, then the JNI_OnLoad_L function exported by the library 1045 * is invoked rather than attempting to load a dynamic library. 1046 * A filename matching the argument does not have to exist in the 1047 * file system. 1048 * See the JNI Specification for more details. 1049 * 1050 * Otherwise, the filename argument is mapped to a native library image in 1051 * an implementation-dependent manner. 1052 * 1053 * <p> 1054 * The call <code>System.load(name)</code> is effectively equivalent 1055 * to the call: 1056 * <blockquote><pre> 1057 * Runtime.getRuntime().load(name) 1058 * </pre></blockquote> 1059 * 1060 * @param filename the file to load. 1061 * @exception SecurityException if a security manager exists and its 1062 * <code>checkLink</code> method doesn't allow 1063 * loading of the specified dynamic library 1064 * @exception UnsatisfiedLinkError if either the filename is not an 1065 * absolute path name, the native library is not statically 1066 * linked with the VM, or the library cannot be mapped to 1067 * a native library image by the host system. 1068 * @exception NullPointerException if <code>filename</code> is 1069 * <code>null</code> 1070 * @see java.lang.Runtime#load(java.lang.String) 1071 * @see java.lang.SecurityManager#checkLink(java.lang.String) 1072 */ 1073 @CallerSensitive 1074 public static void load(String filename) { 1075 Runtime.getRuntime().load0(Reflection.getCallerClass(), filename); 1076 } 1077 1078 /** 1079 * Loads the native library specified by the <code>libname</code> 1080 * argument. The <code>libname</code> argument must not contain any platform 1081 * specific prefix, file extension or path. If a native library 1082 * called <code>libname</code> is statically linked with the VM, then the 1083 * JNI_OnLoad_<code>libname</code> function exported by the library is invoked. 1084 * See the JNI Specification for more details. 1085 * 1086 * Otherwise, the libname argument is loaded from a system library 1087 * location and mapped to a native library image in an implementation- 1088 * dependent manner. 1089 * <p> 1090 * The call <code>System.loadLibrary(name)</code> is effectively 1091 * equivalent to the call 1092 * <blockquote><pre> 1093 * Runtime.getRuntime().loadLibrary(name) 1094 * </pre></blockquote> 1095 * 1096 * @param libname the name of the library. 1097 * @exception SecurityException if a security manager exists and its 1098 * <code>checkLink</code> method doesn't allow 1099 * loading of the specified dynamic library 1100 * @exception UnsatisfiedLinkError if either the libname argument 1101 * contains a file path, the native library is not statically 1102 * linked with the VM, or the library cannot be mapped to a 1103 * native library image by the host system. 1104 * @exception NullPointerException if <code>libname</code> is 1105 * <code>null</code> 1106 * @see java.lang.Runtime#loadLibrary(java.lang.String) 1107 * @see java.lang.SecurityManager#checkLink(java.lang.String) 1108 */ 1109 @CallerSensitive 1110 public static void loadLibrary(String libname) { 1111 Runtime.getRuntime().loadLibrary0(Reflection.getCallerClass(), libname); 1112 } 1113 1114 /** 1115 * Maps a library name into a platform-specific string representing 1116 * a native library. 1117 * 1118 * @param libname the name of the library. 1119 * @return a platform-dependent native library name. 1120 * @exception NullPointerException if <code>libname</code> is 1121 * <code>null</code> 1122 * @see java.lang.System#loadLibrary(java.lang.String) 1123 * @see java.lang.ClassLoader#findLibrary(java.lang.String) 1124 * @since 1.2 1125 */ 1126 public static native String mapLibraryName(String libname); 1127 1128 /** 1129 * Create PrintStream for stdout/err based on encoding. 1130 */ 1131 private static PrintStream newPrintStream(FileOutputStream fos, String enc) { 1132 if (enc != null) { 1133 try { 1134 return new PrintStream(new BufferedOutputStream(fos, 128), true, enc); 1135 } catch (UnsupportedEncodingException uee) {} 1136 } 1137 return new PrintStream(new BufferedOutputStream(fos, 128), true); 1138 } 1139 1140 1141 /** 1142 * Initialize the system class. Called after thread initialization. 1143 */ 1144 private static void initializeSystemClass() { 1145 1146 // VM might invoke JNU_NewStringPlatform() to set those encoding 1147 // sensitive properties (user.home, user.name, boot.class.path, etc.) 1148 // during "props" initialization, in which it may need access, via 1149 // System.getProperty(), to the related system encoding property that 1150 // have been initialized (put into "props") at early stage of the 1151 // initialization. So make sure the "props" is available at the 1152 // very beginning of the initialization and all system properties to 1153 // be put into it directly. 1154 props = new Properties(); 1155 initProperties(props); // initialized by the VM 1156 1157 // There are certain system configurations that may be controlled by 1158 // VM options such as the maximum amount of direct memory and 1159 // Integer cache size used to support the object identity semantics 1160 // of autoboxing. Typically, the library will obtain these values 1161 // from the properties set by the VM. If the properties are for 1162 // internal implementation use only, these properties should be 1163 // removed from the system properties. 1164 // 1165 // See java.lang.Integer.IntegerCache and the 1166 // sun.misc.VM.saveAndRemoveProperties method for example. 1167 // 1168 // Save a private copy of the system properties object that 1169 // can only be accessed by the internal implementation. Remove 1170 // certain system properties that are not intended for public access. 1171 sun.misc.VM.saveAndRemoveProperties(props); 1172 1173 1174 lineSeparator = props.getProperty("line.separator"); 1175 sun.misc.Version.init(); 1176 1177 FileInputStream fdIn = new FileInputStream(FileDescriptor.in); 1178 FileOutputStream fdOut = new FileOutputStream(FileDescriptor.out); 1179 FileOutputStream fdErr = new FileOutputStream(FileDescriptor.err); 1180 setIn0(new BufferedInputStream(fdIn)); 1181 setOut0(newPrintStream(fdOut, props.getProperty("sun.stdout.encoding"))); 1182 setErr0(newPrintStream(fdErr, props.getProperty("sun.stderr.encoding"))); 1183 1184 // Load the zip library now in order to keep java.util.zip.ZipFile 1185 // from trying to use itself to load this library later. 1186 loadLibrary("zip"); 1187 1188 // Setup Java signal handlers for HUP, TERM, and INT (where available). 1189 Terminator.setup(); 1190 1191 // Initialize any miscellaneous operating system settings that need to be 1192 // set for the class libraries. Currently this is no-op everywhere except 1193 // for Windows where the process-wide error mode is set before the java.io 1194 // classes are used. 1195 sun.misc.VM.initializeOSEnvironment(); 1196 1197 // The main thread is not added to its thread group in the same 1198 // way as other threads; we must do it ourselves here. 1199 Thread current = Thread.currentThread(); 1200 current.getThreadGroup().add(current); 1201 1202 // register shared secrets 1203 setJavaLangAccess(); 1204 1205 // Subsystems that are invoked during initialization can invoke 1206 // sun.misc.VM.isBooted() in order to avoid doing things that should 1207 // wait until the application class loader has been set up. 1208 // IMPORTANT: Ensure that this remains the last initialization action! 1209 sun.misc.VM.booted(); 1210 } 1211 1212 private static void setJavaLangAccess() { 1213 // Allow privileged classes outside of java.lang 1214 sun.misc.SharedSecrets.setJavaLangAccess(new sun.misc.JavaLangAccess(){ 1215 public sun.reflect.ConstantPool getConstantPool(Class<?> klass) { 1216 return klass.getConstantPool(); 1217 } 1218 public boolean casAnnotationType(Class<?> klass, AnnotationType oldType, AnnotationType newType) { 1219 return klass.casAnnotationType(oldType, newType); 1220 } 1221 public AnnotationType getAnnotationType(Class<?> klass) { 1222 return klass.getAnnotationType(); 1223 } 1224 public Map<Class<? extends Annotation>, Annotation> getDeclaredAnnotationMap(Class<?> klass) { 1225 return klass.getDeclaredAnnotationMap(); 1226 } 1227 public byte[] getRawClassAnnotations(Class<?> klass) { 1228 return klass.getRawAnnotations(); 1229 } 1230 public byte[] getRawClassTypeAnnotations(Class<?> klass) { 1231 return klass.getRawTypeAnnotations(); 1232 } 1233 public byte[] getRawExecutableTypeAnnotations(Executable executable) { 1234 return Class.getExecutableTypeAnnotationBytes(executable); 1235 } 1236 public <E extends Enum<E>> 1237 E[] getEnumConstantsShared(Class<E> klass) { 1238 return klass.getEnumConstantsShared(); 1239 } 1240 public void blockedOn(Thread t, Interruptible b) { 1241 t.blockedOn(b); 1242 } 1243 public void registerShutdownHook(int slot, boolean registerShutdownInProgress, Runnable hook) { 1244 Shutdown.add(slot, registerShutdownInProgress, hook); 1245 } 1246 public int getStackTraceDepth(Throwable t) { 1247 return t.getStackTraceDepth(); 1248 } 1249 public StackTraceElement getStackTraceElement(Throwable t, int i) { 1250 return t.getStackTraceElement(i); 1251 } 1252 public String newStringUnsafe(char[] chars) { 1253 return new String(chars, true); 1254 } 1255 public Thread newThreadWithAcc(Runnable target, AccessControlContext acc) { 1256 return new Thread(target, acc); 1257 } 1258 public void invokeFinalize(Object o) throws Throwable { 1259 o.finalize(); 1260 } 1261 public void formatUnsignedLong(long val, int shift, char[] buf, int offset, int len) { 1262 Long.formatUnsignedLong(val, shift, buf, offset, len); 1263 } 1264 public void formatUnsignedInt(int val, int shift, char[] buf, int offset, int len) { 1265 Integer.formatUnsignedInt(val, shift, buf, offset, len); 1266 } 1267 }); 1268 } 1269 }