1 /* 2 * Copyright (C) 2014 The Android Open Source Project 3 * Copyright (c) 1994, 2013, Oracle and/or its affiliates. All rights reserved. 4 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 5 * 6 * This code is free software; you can redistribute it and/or modify it 7 * under the terms of the GNU General Public License version 2 only, as 8 * published by the Free Software Foundation. Oracle designates this 9 * particular file as subject to the "Classpath" exception as provided 10 * by Oracle in the LICENSE file that accompanied this code. 11 * 12 * This code is distributed in the hope that it will be useful, but WITHOUT 13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 14 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 15 * version 2 for more details (a copy is included in the LICENSE file that 16 * accompanied this code). 17 * 18 * You should have received a copy of the GNU General Public License version 19 * 2 along with this work; if not, write to the Free Software Foundation, 20 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 21 * 22 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 23 * or visit www.oracle.com if you need additional information or have any 24 * questions. 25 */ 26 package java.lang; 27 28 import dalvik.annotation.optimization.CriticalNative; 29 import dalvik.annotation.optimization.FastNative; 30 import android.system.ErrnoException; 31 import android.system.StructUtsname; 32 import dalvik.system.VMRuntime; 33 import java.io.*; 34 import java.nio.channels.Channel; 35 import java.nio.channels.spi.SelectorProvider; 36 import java.util.Locale; 37 import java.util.Properties; 38 import java.util.PropertyPermission; 39 import libcore.icu.ICU; 40 import libcore.io.Libcore; 41 42 import sun.reflect.CallerSensitive; 43 import sun.reflect.Reflection; 44 import sun.security.util.SecurityConstants; 45 /** 46 * The <code>System</code> class contains several useful class fields 47 * and methods. It cannot be instantiated. 48 * 49 * <p>Among the facilities provided by the <code>System</code> class 50 * are standard input, standard output, and error output streams; 51 * access to externally defined properties and environment 52 * variables; a means of loading files and libraries; and a utility 53 * method for quickly copying a portion of an array. 54 * 55 * @author unascribed 56 * @since JDK1.0 57 */ 58 public final class System { 59 /** Don't let anyone instantiate this class */ System()60 private System() { 61 } 62 63 /** 64 * The "standard" input stream. This stream is already 65 * open and ready to supply input data. Typically this stream 66 * corresponds to keyboard input or another input source specified by 67 * the host environment or user. 68 */ 69 public final static InputStream in; 70 71 /** 72 * The "standard" output stream. This stream is already 73 * open and ready to accept output data. Typically this stream 74 * corresponds to display output or another output destination 75 * specified by the host environment or user. 76 * <p> 77 * For simple stand-alone Java applications, a typical way to write 78 * a line of output data is: 79 * <blockquote><pre> 80 * System.out.println(data) 81 * </pre></blockquote> 82 * <p> 83 * See the <code>println</code> methods in class <code>PrintStream</code>. 84 * 85 * @see java.io.PrintStream#println() 86 * @see java.io.PrintStream#println(boolean) 87 * @see java.io.PrintStream#println(char) 88 * @see java.io.PrintStream#println(char[]) 89 * @see java.io.PrintStream#println(double) 90 * @see java.io.PrintStream#println(float) 91 * @see java.io.PrintStream#println(int) 92 * @see java.io.PrintStream#println(long) 93 * @see java.io.PrintStream#println(java.lang.Object) 94 * @see java.io.PrintStream#println(java.lang.String) 95 */ 96 public final static PrintStream out; 97 98 /** 99 * The "standard" error output stream. This stream is already 100 * open and ready to accept output data. 101 * <p> 102 * Typically this stream corresponds to display output or another 103 * output destination specified by the host environment or user. By 104 * convention, this output stream is used to display error messages 105 * or other information that should come to the immediate attention 106 * of a user even if the principal output stream, the value of the 107 * variable <code>out</code>, has been redirected to a file or other 108 * destination that is typically not continuously monitored. 109 */ 110 public final static PrintStream err; 111 112 /** 113 * Dedicated lock for GC / Finalization logic. 114 */ 115 private static final Object LOCK = new Object(); 116 117 /** 118 * Whether or not we need to do a GC before running the finalizers. 119 */ 120 private static boolean runGC; 121 122 /** 123 * If we just ran finalization, we might want to do a GC to free the finalized objects. 124 * This lets us do gc/runFinlization/gc sequences but prevents back to back System.gc(). 125 */ 126 private static boolean justRanFinalization; 127 128 /** 129 * Reassigns the "standard" input stream. 130 * 131 * <p>First, if there is a security manager, its <code>checkPermission</code> 132 * method is called with a <code>RuntimePermission("setIO")</code> permission 133 * to see if it's ok to reassign the "standard" input stream. 134 * <p> 135 * 136 * @param in the new standard input stream. 137 * 138 * @throws SecurityException 139 * if a security manager exists and its 140 * <code>checkPermission</code> method doesn't allow 141 * reassigning of the standard input stream. 142 * 143 * @see SecurityManager#checkPermission 144 * @see java.lang.RuntimePermission 145 * 146 * @since JDK1.1 147 */ setIn(InputStream in)148 public static void setIn(InputStream in) { 149 setIn0(in); 150 } 151 152 /** 153 * Reassigns the "standard" output stream. 154 * 155 * <p>First, if there is a security manager, its <code>checkPermission</code> 156 * method is called with a <code>RuntimePermission("setIO")</code> permission 157 * to see if it's ok to reassign the "standard" output stream. 158 * 159 * @param out the new standard output stream 160 * 161 * @throws SecurityException 162 * if a security manager exists and its 163 * <code>checkPermission</code> method doesn't allow 164 * reassigning of the standard output stream. 165 * 166 * @see SecurityManager#checkPermission 167 * @see java.lang.RuntimePermission 168 * 169 * @since JDK1.1 170 */ setOut(PrintStream out)171 public static void setOut(PrintStream out) { 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 */ setErr(PrintStream err)194 public static void setErr(PrintStream err) { 195 setErr0(err); 196 } 197 198 private static volatile Console cons = null; 199 /** 200 * Returns the unique {@link java.io.Console Console} object associated 201 * with the current Java virtual machine, if any. 202 * 203 * @return The system console, if any, otherwise <tt>null</tt>. 204 * 205 * @since 1.6 206 */ console()207 public static Console console() { 208 // Android-changed: Added proper double checked locking for cons access 209 if (cons == null) { 210 synchronized (System.class) { 211 if (cons == null) { 212 cons = Console.console(); 213 } 214 } 215 } 216 return cons; 217 } 218 219 /** 220 * Returns the channel inherited from the entity that created this 221 * Java virtual machine. 222 * 223 * <p> This method returns the channel obtained by invoking the 224 * {@link java.nio.channels.spi.SelectorProvider#inheritedChannel 225 * inheritedChannel} method of the system-wide default 226 * {@link java.nio.channels.spi.SelectorProvider} object. </p> 227 * 228 * <p> In addition to the network-oriented channels described in 229 * {@link java.nio.channels.spi.SelectorProvider#inheritedChannel 230 * inheritedChannel}, this method may return other kinds of 231 * channels in the future. 232 * 233 * @return The inherited channel, if any, otherwise <tt>null</tt>. 234 * 235 * @throws IOException 236 * If an I/O error occurs 237 * 238 * @throws SecurityException 239 * If a security manager is present and it does not 240 * permit access to the channel. 241 * 242 * @since 1.5 243 */ inheritedChannel()244 public static Channel inheritedChannel() throws IOException { 245 return SelectorProvider.provider().inheritedChannel(); 246 } 247 setIn0(InputStream in)248 private static native void setIn0(InputStream in); setOut0(PrintStream out)249 private static native void setOut0(PrintStream out); setErr0(PrintStream err)250 private static native void setErr0(PrintStream err); 251 252 /** 253 * Throws {@code SecurityException} (except in case {@code sm == null}). 254 * 255 * <p>Security managers do <i>not</i> provide a secure environment for 256 * executing untrusted code and are unsupported on Android. Untrusted code 257 * cannot be safely isolated within a single VM on Android, so this method 258 * <i>always</i> throws a {@code SecurityException} when passed a non-null SecurityManager 259 * 260 * @param s a security manager 261 * @throws SecurityException always, unless {@code sm == null} 262 */ 263 public static setSecurityManager(final SecurityManager s)264 void setSecurityManager(final SecurityManager s) { 265 if (s != null) { 266 throw new SecurityException(); 267 } 268 } 269 270 /** 271 * Always returns {@code null} in Android 272 * 273 * @return {@code null} in Android 274 */ getSecurityManager()275 public static SecurityManager getSecurityManager() { 276 // No-op on android. 277 return null; 278 } 279 280 /** 281 * Returns the current time in milliseconds. Note that 282 * while the unit of time of the return value is a millisecond, 283 * the granularity of the value depends on the underlying 284 * operating system and may be larger. For example, many 285 * operating systems measure time in units of tens of 286 * milliseconds. 287 * 288 * <p> See the description of the class <code>Date</code> for 289 * a discussion of slight discrepancies that may arise between 290 * "computer time" and coordinated universal time (UTC). 291 * 292 * @return the difference, measured in milliseconds, between 293 * the current time and midnight, January 1, 1970 UTC. 294 * @see java.util.Date 295 */ 296 @CriticalNative currentTimeMillis()297 public static native long currentTimeMillis(); 298 299 /** 300 * Returns the current value of the running Java Virtual Machine's 301 * high-resolution time source, in nanoseconds. 302 * 303 * <p>This method can only be used to measure elapsed time and is 304 * not related to any other notion of system or wall-clock time. 305 * The value returned represents nanoseconds since some fixed but 306 * arbitrary <i>origin</i> time (perhaps in the future, so values 307 * may be negative). The same origin is used by all invocations of 308 * this method in an instance of a Java virtual machine; other 309 * virtual machine instances are likely to use a different origin. 310 * 311 * <p>This method provides nanosecond precision, but not necessarily 312 * nanosecond resolution (that is, how frequently the value changes) 313 * - no guarantees are made except that the resolution is at least as 314 * good as that of {@link #currentTimeMillis()}. 315 * 316 * <p>Differences in successive calls that span greater than 317 * approximately 292 years (2<sup>63</sup> nanoseconds) will not 318 * correctly compute elapsed time due to numerical overflow. 319 * 320 * <p>The values returned by this method become meaningful only when 321 * the difference between two such values, obtained within the same 322 * instance of a Java virtual machine, is computed. 323 * 324 * <p> For example, to measure how long some code takes to execute: 325 * <pre> {@code 326 * long startTime = System.nanoTime(); 327 * // ... the code being measured ... 328 * long estimatedTime = System.nanoTime() - startTime;}</pre> 329 * 330 * <p>To compare two nanoTime values 331 * <pre> {@code 332 * long t0 = System.nanoTime(); 333 * ... 334 * long t1 = System.nanoTime();}</pre> 335 * 336 * one should use {@code t1 - t0 < 0}, not {@code t1 < t0}, 337 * because of the possibility of numerical overflow. 338 * 339 * @return the current value of the running Java Virtual Machine's 340 * high-resolution time source, in nanoseconds 341 * @since 1.5 342 */ 343 @CriticalNative nanoTime()344 public static native long nanoTime(); 345 346 /** 347 * Copies an array from the specified source array, beginning at the 348 * specified position, to the specified position of the destination array. 349 * A subsequence of array components are copied from the source 350 * array referenced by <code>src</code> to the destination array 351 * referenced by <code>dest</code>. The number of components copied is 352 * equal to the <code>length</code> argument. The components at 353 * positions <code>srcPos</code> through 354 * <code>srcPos+length-1</code> in the source array are copied into 355 * positions <code>destPos</code> through 356 * <code>destPos+length-1</code>, respectively, of the destination 357 * array. 358 * <p> 359 * If the <code>src</code> and <code>dest</code> arguments refer to the 360 * same array object, then the copying is performed as if the 361 * components at positions <code>srcPos</code> through 362 * <code>srcPos+length-1</code> were first copied to a temporary 363 * array with <code>length</code> components and then the contents of 364 * the temporary array were copied into positions 365 * <code>destPos</code> through <code>destPos+length-1</code> of the 366 * destination array. 367 * <p> 368 * If <code>dest</code> is <code>null</code>, then a 369 * <code>NullPointerException</code> is thrown. 370 * <p> 371 * If <code>src</code> is <code>null</code>, then a 372 * <code>NullPointerException</code> is thrown and the destination 373 * array is not modified. 374 * <p> 375 * Otherwise, if any of the following is true, an 376 * <code>ArrayStoreException</code> is thrown and the destination is 377 * not modified: 378 * <ul> 379 * <li>The <code>src</code> argument refers to an object that is not an 380 * array. 381 * <li>The <code>dest</code> argument refers to an object that is not an 382 * array. 383 * <li>The <code>src</code> argument and <code>dest</code> argument refer 384 * to arrays whose component types are different primitive types. 385 * <li>The <code>src</code> argument refers to an array with a primitive 386 * component type and the <code>dest</code> argument refers to an array 387 * with a reference component type. 388 * <li>The <code>src</code> argument refers to an array with a reference 389 * component type and the <code>dest</code> argument refers to an array 390 * with a primitive component type. 391 * </ul> 392 * <p> 393 * Otherwise, if any of the following is true, an 394 * <code>IndexOutOfBoundsException</code> is 395 * thrown and the destination is not modified: 396 * <ul> 397 * <li>The <code>srcPos</code> argument is negative. 398 * <li>The <code>destPos</code> argument is negative. 399 * <li>The <code>length</code> argument is negative. 400 * <li><code>srcPos+length</code> is greater than 401 * <code>src.length</code>, the length of the source array. 402 * <li><code>destPos+length</code> is greater than 403 * <code>dest.length</code>, the length of the destination array. 404 * </ul> 405 * <p> 406 * Otherwise, if any actual component of the source array from 407 * position <code>srcPos</code> through 408 * <code>srcPos+length-1</code> cannot be converted to the component 409 * type of the destination array by assignment conversion, an 410 * <code>ArrayStoreException</code> is thrown. In this case, let 411 * <b><i>k</i></b> be the smallest nonnegative integer less than 412 * length such that <code>src[srcPos+</code><i>k</i><code>]</code> 413 * cannot be converted to the component type of the destination 414 * array; when the exception is thrown, source array components from 415 * positions <code>srcPos</code> through 416 * <code>srcPos+</code><i>k</i><code>-1</code> 417 * will already have been copied to destination array positions 418 * <code>destPos</code> through 419 * <code>destPos+</code><i>k</I><code>-1</code> and no other 420 * positions of the destination array will have been modified. 421 * (Because of the restrictions already itemized, this 422 * paragraph effectively applies only to the situation where both 423 * arrays have component types that are reference types.) 424 * 425 * @param src the source array. 426 * @param srcPos starting position in the source array. 427 * @param dest the destination array. 428 * @param destPos starting position in the destination data. 429 * @param length the number of array elements to be copied. 430 * @exception IndexOutOfBoundsException if copying would cause 431 * access of data outside array bounds. 432 * @exception ArrayStoreException if an element in the <code>src</code> 433 * array could not be stored into the <code>dest</code> array 434 * because of a type mismatch. 435 * @exception NullPointerException if either <code>src</code> or 436 * <code>dest</code> is <code>null</code>. 437 */ 438 @FastNative arraycopy(Object src, int srcPos, Object dest, int destPos, int length)439 public static native void arraycopy(Object src, int srcPos, 440 Object dest, int destPos, 441 int length); 442 443 444 // BEGIN Android-changed 445 /** 446 * The char array length threshold below which to use a Java 447 * (non-native) version of arraycopy() instead of the native 448 * version. See b/7103825. 449 */ 450 private static final int ARRAYCOPY_SHORT_CHAR_ARRAY_THRESHOLD = 32; 451 452 /** 453 * The char[] specialized version of arraycopy(). 454 * Note: This method is required for runtime ART compiler optimizations. 455 * Do not remove or change the signature. 456 */ 457 @SuppressWarnings("unused") arraycopy(char[] src, int srcPos, char[] dst, int dstPos, int length)458 private static void arraycopy(char[] src, int srcPos, char[] dst, int dstPos, int length) { 459 if (src == null) { 460 throw new NullPointerException("src == null"); 461 } 462 if (dst == null) { 463 throw new NullPointerException("dst == null"); 464 } 465 if (srcPos < 0 || dstPos < 0 || length < 0 || 466 srcPos > src.length - length || dstPos > dst.length - length) { 467 throw new ArrayIndexOutOfBoundsException( 468 "src.length=" + src.length + " srcPos=" + srcPos + 469 " dst.length=" + dst.length + " dstPos=" + dstPos + " length=" + length); 470 } 471 if (length <= ARRAYCOPY_SHORT_CHAR_ARRAY_THRESHOLD) { 472 // Copy char by char for shorter arrays. 473 if (src == dst && srcPos < dstPos && dstPos < srcPos + length) { 474 // Copy backward (to avoid overwriting elements before 475 // they are copied in case of an overlap on the same 476 // array.) 477 for (int i = length - 1; i >= 0; --i) { 478 dst[dstPos + i] = src[srcPos + i]; 479 } 480 } else { 481 // Copy forward. 482 for (int i = 0; i < length; ++i) { 483 dst[dstPos + i] = src[srcPos + i]; 484 } 485 } 486 } else { 487 // Call the native version for longer arrays. 488 arraycopyCharUnchecked(src, srcPos, dst, dstPos, length); 489 } 490 } 491 492 /** 493 * The char[] specialized, unchecked, native version of 494 * arraycopy(). This assumes error checking has been done. 495 */ 496 @FastNative arraycopyCharUnchecked(char[] src, int srcPos, char[] dst, int dstPos, int length)497 private static native void arraycopyCharUnchecked(char[] src, int srcPos, 498 char[] dst, int dstPos, int length); 499 500 /** 501 * The byte array length threshold below which to use a Java 502 * (non-native) version of arraycopy() instead of the native 503 * version. See b/7103825. 504 */ 505 private static final int ARRAYCOPY_SHORT_BYTE_ARRAY_THRESHOLD = 32; 506 507 /** 508 * The byte[] specialized version of arraycopy(). 509 * Note: This method is required for runtime ART compiler optimizations. 510 * Do not remove or change the signature. 511 */ 512 @SuppressWarnings("unused") arraycopy(byte[] src, int srcPos, byte[] dst, int dstPos, int length)513 private static void arraycopy(byte[] src, int srcPos, byte[] dst, int dstPos, int length) { 514 if (src == null) { 515 throw new NullPointerException("src == null"); 516 } 517 if (dst == null) { 518 throw new NullPointerException("dst == null"); 519 } 520 if (srcPos < 0 || dstPos < 0 || length < 0 || 521 srcPos > src.length - length || dstPos > dst.length - length) { 522 throw new ArrayIndexOutOfBoundsException( 523 "src.length=" + src.length + " srcPos=" + srcPos + 524 " dst.length=" + dst.length + " dstPos=" + dstPos + " length=" + length); 525 } 526 if (length <= ARRAYCOPY_SHORT_BYTE_ARRAY_THRESHOLD) { 527 // Copy byte by byte for shorter arrays. 528 if (src == dst && srcPos < dstPos && dstPos < srcPos + length) { 529 // Copy backward (to avoid overwriting elements before 530 // they are copied in case of an overlap on the same 531 // array.) 532 for (int i = length - 1; i >= 0; --i) { 533 dst[dstPos + i] = src[srcPos + i]; 534 } 535 } else { 536 // Copy forward. 537 for (int i = 0; i < length; ++i) { 538 dst[dstPos + i] = src[srcPos + i]; 539 } 540 } 541 } else { 542 // Call the native version for longer arrays. 543 arraycopyByteUnchecked(src, srcPos, dst, dstPos, length); 544 } 545 } 546 547 /** 548 * The byte[] specialized, unchecked, native version of 549 * arraycopy(). This assumes error checking has been done. 550 */ 551 @FastNative arraycopyByteUnchecked(byte[] src, int srcPos, byte[] dst, int dstPos, int length)552 private static native void arraycopyByteUnchecked(byte[] src, int srcPos, 553 byte[] dst, int dstPos, int length); 554 555 /** 556 * The short array length threshold below which to use a Java 557 * (non-native) version of arraycopy() instead of the native 558 * version. See b/7103825. 559 */ 560 private static final int ARRAYCOPY_SHORT_SHORT_ARRAY_THRESHOLD = 32; 561 562 /** 563 * The short[] specialized version of arraycopy(). 564 * Note: This method is required for runtime ART compiler optimizations. 565 * Do not remove or change the signature. 566 */ 567 @SuppressWarnings("unused") arraycopy(short[] src, int srcPos, short[] dst, int dstPos, int length)568 private static void arraycopy(short[] src, int srcPos, short[] dst, int dstPos, int length) { 569 if (src == null) { 570 throw new NullPointerException("src == null"); 571 } 572 if (dst == null) { 573 throw new NullPointerException("dst == null"); 574 } 575 if (srcPos < 0 || dstPos < 0 || length < 0 || 576 srcPos > src.length - length || dstPos > dst.length - length) { 577 throw new ArrayIndexOutOfBoundsException( 578 "src.length=" + src.length + " srcPos=" + srcPos + 579 " dst.length=" + dst.length + " dstPos=" + dstPos + " length=" + length); 580 } 581 if (length <= ARRAYCOPY_SHORT_SHORT_ARRAY_THRESHOLD) { 582 // Copy short by short for shorter arrays. 583 if (src == dst && srcPos < dstPos && dstPos < srcPos + length) { 584 // Copy backward (to avoid overwriting elements before 585 // they are copied in case of an overlap on the same 586 // array.) 587 for (int i = length - 1; i >= 0; --i) { 588 dst[dstPos + i] = src[srcPos + i]; 589 } 590 } else { 591 // Copy forward. 592 for (int i = 0; i < length; ++i) { 593 dst[dstPos + i] = src[srcPos + i]; 594 } 595 } 596 } else { 597 // Call the native version for longer arrays. 598 arraycopyShortUnchecked(src, srcPos, dst, dstPos, length); 599 } 600 } 601 602 /** 603 * The short[] specialized, unchecked, native version of 604 * arraycopy(). This assumes error checking has been done. 605 */ 606 @FastNative arraycopyShortUnchecked(short[] src, int srcPos, short[] dst, int dstPos, int length)607 private static native void arraycopyShortUnchecked(short[] src, int srcPos, 608 short[] dst, int dstPos, int length); 609 610 /** 611 * The short array length threshold below which to use a Java 612 * (non-native) version of arraycopy() instead of the native 613 * version. See b/7103825. 614 */ 615 private static final int ARRAYCOPY_SHORT_INT_ARRAY_THRESHOLD = 32; 616 617 /** 618 * The int[] specialized version of arraycopy(). 619 * Note: This method is required for runtime ART compiler optimizations. 620 * Do not remove or change the signature. 621 */ 622 @SuppressWarnings("unused") arraycopy(int[] src, int srcPos, int[] dst, int dstPos, int length)623 private static void arraycopy(int[] src, int srcPos, int[] dst, int dstPos, int length) { 624 if (src == null) { 625 throw new NullPointerException("src == null"); 626 } 627 if (dst == null) { 628 throw new NullPointerException("dst == null"); 629 } 630 if (srcPos < 0 || dstPos < 0 || length < 0 || 631 srcPos > src.length - length || dstPos > dst.length - length) { 632 throw new ArrayIndexOutOfBoundsException( 633 "src.length=" + src.length + " srcPos=" + srcPos + 634 " dst.length=" + dst.length + " dstPos=" + dstPos + " length=" + length); 635 } 636 if (length <= ARRAYCOPY_SHORT_INT_ARRAY_THRESHOLD) { 637 // Copy int by int for shorter arrays. 638 if (src == dst && srcPos < dstPos && dstPos < srcPos + length) { 639 // Copy backward (to avoid overwriting elements before 640 // they are copied in case of an overlap on the same 641 // array.) 642 for (int i = length - 1; i >= 0; --i) { 643 dst[dstPos + i] = src[srcPos + i]; 644 } 645 } else { 646 // Copy forward. 647 for (int i = 0; i < length; ++i) { 648 dst[dstPos + i] = src[srcPos + i]; 649 } 650 } 651 } else { 652 // Call the native version for longer arrays. 653 arraycopyIntUnchecked(src, srcPos, dst, dstPos, length); 654 } 655 } 656 657 /** 658 * The int[] specialized, unchecked, native version of 659 * arraycopy(). This assumes error checking has been done. 660 */ 661 @FastNative arraycopyIntUnchecked(int[] src, int srcPos, int[] dst, int dstPos, int length)662 private static native void arraycopyIntUnchecked(int[] src, int srcPos, 663 int[] dst, int dstPos, int length); 664 665 /** 666 * The short array length threshold below which to use a Java 667 * (non-native) version of arraycopy() instead of the native 668 * version. See b/7103825. 669 */ 670 private static final int ARRAYCOPY_SHORT_LONG_ARRAY_THRESHOLD = 32; 671 672 /** 673 * The long[] specialized version of arraycopy(). 674 * Note: This method is required for runtime ART compiler optimizations. 675 * Do not remove or change the signature. 676 */ 677 @SuppressWarnings("unused") arraycopy(long[] src, int srcPos, long[] dst, int dstPos, int length)678 private static void arraycopy(long[] src, int srcPos, long[] dst, int dstPos, int length) { 679 if (src == null) { 680 throw new NullPointerException("src == null"); 681 } 682 if (dst == null) { 683 throw new NullPointerException("dst == null"); 684 } 685 if (srcPos < 0 || dstPos < 0 || length < 0 || 686 srcPos > src.length - length || dstPos > dst.length - length) { 687 throw new ArrayIndexOutOfBoundsException( 688 "src.length=" + src.length + " srcPos=" + srcPos + 689 " dst.length=" + dst.length + " dstPos=" + dstPos + " length=" + length); 690 } 691 if (length <= ARRAYCOPY_SHORT_LONG_ARRAY_THRESHOLD) { 692 // Copy long by long for shorter arrays. 693 if (src == dst && srcPos < dstPos && dstPos < srcPos + length) { 694 // Copy backward (to avoid overwriting elements before 695 // they are copied in case of an overlap on the same 696 // array.) 697 for (int i = length - 1; i >= 0; --i) { 698 dst[dstPos + i] = src[srcPos + i]; 699 } 700 } else { 701 // Copy forward. 702 for (int i = 0; i < length; ++i) { 703 dst[dstPos + i] = src[srcPos + i]; 704 } 705 } 706 } else { 707 // Call the native version for longer arrays. 708 arraycopyLongUnchecked(src, srcPos, dst, dstPos, length); 709 } 710 } 711 712 /** 713 * The long[] specialized, unchecked, native version of 714 * arraycopy(). This assumes error checking has been done. 715 */ 716 @FastNative arraycopyLongUnchecked(long[] src, int srcPos, long[] dst, int dstPos, int length)717 private static native void arraycopyLongUnchecked(long[] src, int srcPos, 718 long[] dst, int dstPos, int length); 719 720 /** 721 * The short array length threshold below which to use a Java 722 * (non-native) version of arraycopy() instead of the native 723 * version. See b/7103825. 724 */ 725 private static final int ARRAYCOPY_SHORT_FLOAT_ARRAY_THRESHOLD = 32; 726 727 /** 728 * The float[] specialized version of arraycopy(). 729 * Note: This method is required for runtime ART compiler optimizations. 730 * Do not remove or change the signature. 731 */ 732 @SuppressWarnings("unused") arraycopy(float[] src, int srcPos, float[] dst, int dstPos, int length)733 private static void arraycopy(float[] src, int srcPos, float[] dst, int dstPos, int length) { 734 if (src == null) { 735 throw new NullPointerException("src == null"); 736 } 737 if (dst == null) { 738 throw new NullPointerException("dst == null"); 739 } 740 if (srcPos < 0 || dstPos < 0 || length < 0 || 741 srcPos > src.length - length || dstPos > dst.length - length) { 742 throw new ArrayIndexOutOfBoundsException( 743 "src.length=" + src.length + " srcPos=" + srcPos + 744 " dst.length=" + dst.length + " dstPos=" + dstPos + " length=" + length); 745 } 746 if (length <= ARRAYCOPY_SHORT_FLOAT_ARRAY_THRESHOLD) { 747 // Copy float by float for shorter arrays. 748 if (src == dst && srcPos < dstPos && dstPos < srcPos + length) { 749 // Copy backward (to avoid overwriting elements before 750 // they are copied in case of an overlap on the same 751 // array.) 752 for (int i = length - 1; i >= 0; --i) { 753 dst[dstPos + i] = src[srcPos + i]; 754 } 755 } else { 756 // Copy forward. 757 for (int i = 0; i < length; ++i) { 758 dst[dstPos + i] = src[srcPos + i]; 759 } 760 } 761 } else { 762 // Call the native version for floater arrays. 763 arraycopyFloatUnchecked(src, srcPos, dst, dstPos, length); 764 } 765 } 766 767 /** 768 * The float[] specialized, unchecked, native version of 769 * arraycopy(). This assumes error checking has been done. 770 */ 771 @FastNative arraycopyFloatUnchecked(float[] src, int srcPos, float[] dst, int dstPos, int length)772 private static native void arraycopyFloatUnchecked(float[] src, int srcPos, 773 float[] dst, int dstPos, int length); 774 775 /** 776 * The short array length threshold below which to use a Java 777 * (non-native) version of arraycopy() instead of the native 778 * version. See b/7103825. 779 */ 780 private static final int ARRAYCOPY_SHORT_DOUBLE_ARRAY_THRESHOLD = 32; 781 782 /** 783 * The double[] specialized version of arraycopy(). 784 * Note: This method is required for runtime ART compiler optimizations. 785 * Do not remove or change the signature. 786 */ 787 @SuppressWarnings("unused") arraycopy(double[] src, int srcPos, double[] dst, int dstPos, int length)788 private static void arraycopy(double[] src, int srcPos, double[] dst, int dstPos, int length) { 789 if (src == null) { 790 throw new NullPointerException("src == null"); 791 } 792 if (dst == null) { 793 throw new NullPointerException("dst == null"); 794 } 795 if (srcPos < 0 || dstPos < 0 || length < 0 || 796 srcPos > src.length - length || dstPos > dst.length - length) { 797 throw new ArrayIndexOutOfBoundsException( 798 "src.length=" + src.length + " srcPos=" + srcPos + 799 " dst.length=" + dst.length + " dstPos=" + dstPos + " length=" + length); 800 } 801 if (length <= ARRAYCOPY_SHORT_DOUBLE_ARRAY_THRESHOLD) { 802 // Copy double by double for shorter arrays. 803 if (src == dst && srcPos < dstPos && dstPos < srcPos + length) { 804 // Copy backward (to avoid overwriting elements before 805 // they are copied in case of an overlap on the same 806 // array.) 807 for (int i = length - 1; i >= 0; --i) { 808 dst[dstPos + i] = src[srcPos + i]; 809 } 810 } else { 811 // Copy forward. 812 for (int i = 0; i < length; ++i) { 813 dst[dstPos + i] = src[srcPos + i]; 814 } 815 } 816 } else { 817 // Call the native version for floater arrays. 818 arraycopyDoubleUnchecked(src, srcPos, dst, dstPos, length); 819 } 820 } 821 822 /** 823 * The double[] specialized, unchecked, native version of 824 * arraycopy(). This assumes error checking has been done. 825 */ 826 @FastNative arraycopyDoubleUnchecked(double[] src, int srcPos, double[] dst, int dstPos, int length)827 private static native void arraycopyDoubleUnchecked(double[] src, int srcPos, 828 double[] dst, int dstPos, int length); 829 830 /** 831 * The short array length threshold below which to use a Java 832 * (non-native) version of arraycopy() instead of the native 833 * version. See b/7103825. 834 */ 835 private static final int ARRAYCOPY_SHORT_BOOLEAN_ARRAY_THRESHOLD = 32; 836 837 /** 838 * The boolean[] specialized version of arraycopy(). 839 * Note: This method is required for runtime ART compiler optimizations. 840 * Do not remove or change the signature. 841 */ 842 @SuppressWarnings("unused") arraycopy(boolean[] src, int srcPos, boolean[] dst, int dstPos, int length)843 private static void arraycopy(boolean[] src, int srcPos, boolean[] dst, int dstPos, int length) { 844 if (src == null) { 845 throw new NullPointerException("src == null"); 846 } 847 if (dst == null) { 848 throw new NullPointerException("dst == null"); 849 } 850 if (srcPos < 0 || dstPos < 0 || length < 0 || 851 srcPos > src.length - length || dstPos > dst.length - length) { 852 throw new ArrayIndexOutOfBoundsException( 853 "src.length=" + src.length + " srcPos=" + srcPos + 854 " dst.length=" + dst.length + " dstPos=" + dstPos + " length=" + length); 855 } 856 if (length <= ARRAYCOPY_SHORT_BOOLEAN_ARRAY_THRESHOLD) { 857 // Copy boolean by boolean for shorter arrays. 858 if (src == dst && srcPos < dstPos && dstPos < srcPos + length) { 859 // Copy backward (to avoid overwriting elements before 860 // they are copied in case of an overlap on the same 861 // array.) 862 for (int i = length - 1; i >= 0; --i) { 863 dst[dstPos + i] = src[srcPos + i]; 864 } 865 } else { 866 // Copy forward. 867 for (int i = 0; i < length; ++i) { 868 dst[dstPos + i] = src[srcPos + i]; 869 } 870 } 871 } else { 872 // Call the native version for floater arrays. 873 arraycopyBooleanUnchecked(src, srcPos, dst, dstPos, length); 874 } 875 } 876 877 /** 878 * The boolean[] specialized, unchecked, native version of 879 * arraycopy(). This assumes error checking has been done. 880 */ 881 @FastNative arraycopyBooleanUnchecked(boolean[] src, int srcPos, boolean[] dst, int dstPos, int length)882 private static native void arraycopyBooleanUnchecked(boolean[] src, int srcPos, 883 boolean[] dst, int dstPos, int length); 884 // END Android-changed 885 886 /** 887 * Returns the same hash code for the given object as 888 * would be returned by the default method hashCode(), 889 * whether or not the given object's class overrides 890 * hashCode(). 891 * The hash code for the null reference is zero. 892 * 893 * @param x object for which the hashCode is to be calculated 894 * @return the hashCode 895 * @since JDK1.1 896 */ identityHashCode(Object x)897 public static int identityHashCode(Object x) { 898 if (x == null) { 899 return 0; 900 } 901 return Object.identityHashCode(x); 902 } 903 904 /** 905 * System properties. The following properties are guaranteed to be defined: 906 * <dl> 907 * <dt>java.version <dd>Java version number 908 * <dt>java.vendor <dd>Java vendor specific string 909 * <dt>java.vendor.url <dd>Java vendor URL 910 * <dt>java.home <dd>Java installation directory 911 * <dt>java.class.version <dd>Java class version number 912 * <dt>java.class.path <dd>Java classpath 913 * <dt>os.name <dd>Operating System Name 914 * <dt>os.arch <dd>Operating System Architecture 915 * <dt>os.version <dd>Operating System Version 916 * <dt>file.separator <dd>File separator ("/" on Unix) 917 * <dt>path.separator <dd>Path separator (":" on Unix) 918 * <dt>line.separator <dd>Line separator ("\n" on Unix) 919 * <dt>user.name <dd>User account name 920 * <dt>user.home <dd>User home directory 921 * <dt>user.dir <dd>User's current working directory 922 * </dl> 923 */ 924 925 private static Properties props; 926 private static Properties unchangeableProps; 927 specialProperties()928 private static native String[] specialProperties(); 929 930 static final class PropertiesWithNonOverrideableDefaults extends Properties { PropertiesWithNonOverrideableDefaults(Properties defaults)931 PropertiesWithNonOverrideableDefaults(Properties defaults) { 932 super(defaults); 933 } 934 935 @Override put(Object key, Object value)936 public Object put(Object key, Object value) { 937 if (defaults.containsKey(key)) { 938 logE("Ignoring attempt to set property \"" + key + 939 "\" to value \"" + value + "\"."); 940 return defaults.get(key); 941 } 942 943 return super.put(key, value); 944 } 945 946 @Override remove(Object key)947 public Object remove(Object key) { 948 if (defaults.containsKey(key)) { 949 logE("Ignoring attempt to remove property \"" + key + "\"."); 950 return null; 951 } 952 953 return super.remove(key); 954 } 955 } 956 parsePropertyAssignments(Properties p, String[] assignments)957 private static void parsePropertyAssignments(Properties p, String[] assignments) { 958 for (String assignment : assignments) { 959 int split = assignment.indexOf('='); 960 String key = assignment.substring(0, split); 961 String value = assignment.substring(split + 1); 962 p.put(key, value); 963 } 964 } 965 initUnchangeableSystemProperties()966 private static Properties initUnchangeableSystemProperties() { 967 VMRuntime runtime = VMRuntime.getRuntime(); 968 Properties p = new Properties(); 969 970 // Set non-static properties. 971 p.put("java.boot.class.path", runtime.bootClassPath()); 972 p.put("java.class.path", runtime.classPath()); 973 974 // TODO: does this make any sense? Should we just leave java.home unset? 975 String javaHome = getenv("JAVA_HOME"); 976 if (javaHome == null) { 977 javaHome = "/system"; 978 } 979 p.put("java.home", javaHome); 980 981 p.put("java.vm.version", runtime.vmVersion()); 982 983 String userName; 984 try { 985 userName = Libcore.os.getpwuid(Libcore.os.getuid()).pw_name; 986 } catch (ErrnoException exception) { 987 userName = "unknown"; 988 } 989 p.put("user.name", userName); 990 991 StructUtsname info = Libcore.os.uname(); 992 p.put("os.arch", info.machine); 993 // os.name was previously hardcoded to "Linux", but was reverted due to support 994 // for Fuchsia. b/121268567 shows initialization regressions. 995 p.put("os.name", info.sysname); 996 p.put("os.version", info.release); 997 998 // Android-added: Undocumented properties that exist only on Android. 999 p.put("android.icu.library.version", ICU.getIcuVersion()); 1000 p.put("android.icu.unicode.version", ICU.getUnicodeVersion()); 1001 p.put("android.icu.cldr.version", ICU.getCldrVersion()); 1002 1003 parsePropertyAssignments(p, specialProperties()); 1004 1005 // Override built-in properties with settings from the command line. 1006 // Note: it is not possible to override hardcoded values. 1007 parsePropertyAssignments(p, runtime.properties()); 1008 1009 1010 // Set static hardcoded properties. 1011 // These come last, as they must be guaranteed to agree with what a backend compiler 1012 // may assume when compiling the boot image on Android. 1013 for (String[] pair : AndroidHardcodedSystemProperties.STATIC_PROPERTIES) { 1014 if (p.containsKey(pair[0])) { 1015 logE("Ignoring command line argument: -D" + pair[0]); 1016 } 1017 if (pair[1] == null) { 1018 p.remove(pair[0]); 1019 } else { 1020 p.put(pair[0], pair[1]); 1021 } 1022 } 1023 1024 return p; 1025 } 1026 initProperties()1027 private static Properties initProperties() { 1028 Properties p = new PropertiesWithNonOverrideableDefaults(unchangeableProps); 1029 setDefaultChangeableProperties(p); 1030 return p; 1031 } 1032 setDefaultChangeableProperties(Properties p)1033 private static Properties setDefaultChangeableProperties(Properties p) { 1034 // On Android, each app gets its own temporary directory. 1035 // (See android.app.ActivityThread.) This is just a fallback default, 1036 // useful only on the host. 1037 // We check first if the property has not been set already: note that it 1038 // can only be set from the command line through the '-Djava.io.tmpdir=' option. 1039 if (!unchangeableProps.containsKey("java.io.tmpdir")) { 1040 p.put("java.io.tmpdir", "/tmp"); 1041 } 1042 1043 // Android has always had an empty "user.home" (see docs for getProperty). 1044 // This is not useful for normal android apps which need to use android specific 1045 // APIs such as {@code Context.getFilesDir} and {@code Context.getCacheDir} but 1046 // we make it changeable for backward compatibility, so that they can change it 1047 // to a writeable location if required. 1048 // We check first if the property has not been set already: note that it 1049 // can only be set from the command line through the '-Duser.home=' option. 1050 if (!unchangeableProps.containsKey("user.home")) { 1051 p.put("user.home", ""); 1052 } 1053 1054 return p; 1055 } 1056 1057 /** 1058 * Inits an unchangeable system property with the given value. 1059 * 1060 * This is called from native code when the environment needs to change under native 1061 * bridge emulation. 1062 * 1063 * @hide also visible for tests. 1064 */ setUnchangeableSystemProperty(String key, String value)1065 public static void setUnchangeableSystemProperty(String key, String value) { 1066 checkKey(key); 1067 unchangeableProps.put(key, value); 1068 } 1069 addLegacyLocaleSystemProperties()1070 private static void addLegacyLocaleSystemProperties() { 1071 final String locale = getProperty("user.locale", ""); 1072 if (!locale.isEmpty()) { 1073 Locale l = Locale.forLanguageTag(locale); 1074 setUnchangeableSystemProperty("user.language", l.getLanguage()); 1075 setUnchangeableSystemProperty("user.region", l.getCountry()); 1076 setUnchangeableSystemProperty("user.variant", l.getVariant()); 1077 } else { 1078 // If "user.locale" isn't set we fall back to our old defaults of 1079 // language="en" and region="US" (if unset) and don't attempt to set it. 1080 // The Locale class will fall back to using user.language and 1081 // user.region if unset. 1082 final String language = getProperty("user.language", ""); 1083 final String region = getProperty("user.region", ""); 1084 1085 if (language.isEmpty()) { 1086 setUnchangeableSystemProperty("user.language", "en"); 1087 } 1088 1089 if (region.isEmpty()) { 1090 setUnchangeableSystemProperty("user.region", "US"); 1091 } 1092 } 1093 } 1094 1095 /** 1096 * Determines the current system properties. 1097 * 1098 * 1099 * <p>The following properties are always provided by the Dalvik VM:</p> 1100 * <p><table BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> 1101 * <tr BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> 1102 * <td><b>Name</b></td> <td><b>Meaning</b></td> <td><b>Example</b></td></tr> 1103 * <tr><td>file.separator</td> <td>{@link java.io.File#separator}</td> <td>{@code /}</td></tr> 1104 * 1105 * <tr><td>java.class.path</td> <td>System class path</td> <td>{@code .}</td></tr> 1106 * <tr><td>java.class.version</td> <td>(Not useful on Android)</td> <td>{@code 50.0}</td></tr> 1107 * <tr><td>java.compiler</td> <td>(Not useful on Android)</td> <td>Empty</td></tr> 1108 * <tr><td>java.ext.dirs</td> <td>(Not useful on Android)</td> <td>Empty</td></tr> 1109 * <tr><td>java.home</td> <td>Location of the VM on the file system</td> <td>{@code /system}</td></tr> 1110 * <tr><td>java.io.tmpdir</td> <td>See {@link java.io.File#createTempFile}</td> <td>{@code /sdcard}</td></tr> 1111 * <tr><td>java.library.path</td> <td>Search path for JNI libraries</td> <td>{@code /vendor/lib:/system/lib}</td></tr> 1112 * <tr><td>java.vendor</td> <td>Human-readable VM vendor</td> <td>{@code The Android Project}</td></tr> 1113 * <tr><td>java.vendor.url</td> <td>URL for VM vendor's web site</td> <td>{@code http://www.android.com/}</td></tr> 1114 * <tr><td>java.version</td> <td>(Not useful on Android)</td> <td>{@code 0}</td></tr> 1115 * 1116 * <tr><td>java.specification.version</td> <td>VM libraries version</td> <td>{@code 0.9}</td></tr> 1117 * <tr><td>java.specification.vendor</td> <td>VM libraries vendor</td> <td>{@code The Android Project}</td></tr> 1118 * <tr><td>java.specification.name</td> <td>VM libraries name</td> <td>{@code Dalvik Core Library}</td></tr> 1119 * <tr><td>java.vm.version</td> <td>VM implementation version</td> <td>{@code 1.2.0}</td></tr> 1120 * <tr><td>java.vm.vendor</td> <td>VM implementation vendor</td> <td>{@code The Android Project}</td></tr> 1121 * <tr><td>java.vm.name</td> <td>VM implementation name</td> <td>{@code Dalvik}</td></tr> 1122 * <tr><td>java.vm.specification.version</td> <td>VM specification version</td> <td>{@code 0.9}</td></tr> 1123 * <tr><td>java.vm.specification.vendor</td> <td>VM specification vendor</td> <td>{@code The Android Project}</td></tr> 1124 * <tr><td>java.vm.specification.name</td> <td>VM specification name</td> <td>{@code Dalvik Virtual Machine Specification}</td></tr> 1125 * 1126 * <tr><td>line.separator</td> <td>The system line separator</td> <td>{@code \n}</td></tr> 1127 * 1128 * <tr><td>os.arch</td> <td>OS architecture</td> <td>{@code armv7l}</td></tr> 1129 * <tr><td>os.name</td> <td>OS (kernel) name</td> <td>{@code Linux}</td></tr> 1130 * <tr><td>os.version</td> <td>OS (kernel) version</td> <td>{@code 2.6.32.9-g103d848}</td></tr> 1131 * 1132 * <tr><td>path.separator</td> <td>See {@link java.io.File#pathSeparator}</td> <td>{@code :}</td></tr> 1133 * 1134 * <tr><td>user.dir</td> <td>Base of non-absolute paths</td> <td>{@code /}</td></tr> 1135 * <tr><td>user.home</td> <td>(Not useful on Android)</td> <td>Empty</td></tr> 1136 * <tr><td>user.name</td> <td>(Not useful on Android)</td> <td>Empty</td></tr> 1137 * 1138 * </table> 1139 * <p> 1140 * Multiple paths in a system property value are separated by the path 1141 * separator character of the platform. 1142 * <p> 1143 * Note that even if the security manager does not permit the 1144 * <code>getProperties</code> operation, it may choose to permit the 1145 * {@link #getProperty(String)} operation. 1146 * 1147 * @return the system properties 1148 * @exception SecurityException if a security manager exists and its 1149 * <code>checkPropertiesAccess</code> method doesn't allow access 1150 * to the system properties. 1151 * @see #setProperties 1152 * @see java.lang.SecurityException 1153 * @see java.lang.SecurityManager#checkPropertiesAccess() 1154 * @see java.util.Properties 1155 */ getProperties()1156 public static Properties getProperties() { 1157 SecurityManager sm = getSecurityManager(); 1158 if (sm != null) { 1159 sm.checkPropertiesAccess(); 1160 } 1161 1162 return props; 1163 } 1164 1165 /** 1166 * Returns the system-dependent line separator string. It always 1167 * returns the same value - the initial value of the {@linkplain 1168 * #getProperty(String) system property} {@code line.separator}. 1169 * 1170 * <p>On UNIX systems, it returns {@code "\n"}; on Microsoft 1171 * Windows systems it returns {@code "\r\n"}. 1172 * 1173 * @return the system-dependent line separator string 1174 * @since 1.7 1175 */ lineSeparator()1176 public static String lineSeparator() { 1177 return lineSeparator; 1178 } 1179 1180 private static String lineSeparator; 1181 1182 1183 // Comment replaced with android one. 1184 /** 1185 * Attempts to set all system properties. Copies all properties from 1186 * {@code p} and discards system properties that are read only and cannot 1187 * be modified. See {@link #getProperty} for a list of such properties. 1188 */ setProperties(Properties props)1189 public static void setProperties(Properties props) { 1190 Properties baseProperties = new PropertiesWithNonOverrideableDefaults(unchangeableProps); 1191 if (props != null) { 1192 baseProperties.putAll(props); 1193 } else { 1194 setDefaultChangeableProperties(baseProperties); 1195 } 1196 1197 System.props = baseProperties; 1198 } 1199 1200 /** 1201 * Gets the system property indicated by the specified key. 1202 * <p> 1203 * First, if there is a security manager, its 1204 * <code>checkPropertyAccess</code> method is called with the key as 1205 * its argument. This may result in a SecurityException. 1206 * <p> 1207 * If there is no current set of system properties, a set of system 1208 * properties is first created and initialized in the same manner as 1209 * for the <code>getProperties</code> method. 1210 * 1211 * @param key the name of the system property. 1212 * @return the string value of the system property, 1213 * or <code>null</code> if there is no property with that key. 1214 * 1215 * @exception SecurityException if a security manager exists and its 1216 * <code>checkPropertyAccess</code> method doesn't allow 1217 * access to the specified system property. 1218 * @exception NullPointerException if <code>key</code> is 1219 * <code>null</code>. 1220 * @exception IllegalArgumentException if <code>key</code> is empty. 1221 * @see #setProperty 1222 * @see java.lang.SecurityException 1223 * @see java.lang.SecurityManager#checkPropertyAccess(java.lang.String) 1224 * @see java.lang.System#getProperties() 1225 */ getProperty(String key)1226 public static String getProperty(String key) { 1227 checkKey(key); 1228 SecurityManager sm = getSecurityManager(); 1229 if (sm != null) { 1230 sm.checkPropertyAccess(key); 1231 } 1232 1233 return props.getProperty(key); 1234 } 1235 1236 /** 1237 * Gets the system property indicated by the specified key. 1238 * <p> 1239 * First, if there is a security manager, its 1240 * <code>checkPropertyAccess</code> method is called with the 1241 * <code>key</code> as its argument. 1242 * <p> 1243 * If there is no current set of system properties, a set of system 1244 * properties is first created and initialized in the same manner as 1245 * for the <code>getProperties</code> method. 1246 * 1247 * @param key the name of the system property. 1248 * @param def a default value. 1249 * @return the string value of the system property, 1250 * or the default value if there is no property with that key. 1251 * 1252 * @exception SecurityException if a security manager exists and its 1253 * <code>checkPropertyAccess</code> method doesn't allow 1254 * access to the specified system property. 1255 * @exception NullPointerException if <code>key</code> is 1256 * <code>null</code>. 1257 * @exception IllegalArgumentException if <code>key</code> is empty. 1258 * @see #setProperty 1259 * @see java.lang.SecurityManager#checkPropertyAccess(java.lang.String) 1260 * @see java.lang.System#getProperties() 1261 */ getProperty(String key, String def)1262 public static String getProperty(String key, String def) { 1263 checkKey(key); 1264 SecurityManager sm = getSecurityManager(); 1265 if (sm != null) { 1266 sm.checkPropertyAccess(key); 1267 } 1268 1269 return props.getProperty(key, def); 1270 } 1271 1272 /** 1273 * Sets the system property indicated by the specified key. 1274 * <p> 1275 * First, if a security manager exists, its 1276 * <code>SecurityManager.checkPermission</code> method 1277 * is called with a <code>PropertyPermission(key, "write")</code> 1278 * permission. This may result in a SecurityException being thrown. 1279 * If no exception is thrown, the specified property is set to the given 1280 * value. 1281 * <p> 1282 * 1283 * @param key the name of the system property. 1284 * @param value the value of the system property. 1285 * @return the previous value of the system property, 1286 * or <code>null</code> if it did not have one. 1287 * 1288 * @exception SecurityException if a security manager exists and its 1289 * <code>checkPermission</code> method doesn't allow 1290 * setting of the specified property. 1291 * @exception NullPointerException if <code>key</code> or 1292 * <code>value</code> is <code>null</code>. 1293 * @exception IllegalArgumentException if <code>key</code> is empty. 1294 * @see #getProperty 1295 * @see java.lang.System#getProperty(java.lang.String) 1296 * @see java.lang.System#getProperty(java.lang.String, java.lang.String) 1297 * @see java.util.PropertyPermission 1298 * @see SecurityManager#checkPermission 1299 * @since 1.2 1300 */ setProperty(String key, String value)1301 public static String setProperty(String key, String value) { 1302 checkKey(key); 1303 SecurityManager sm = getSecurityManager(); 1304 if (sm != null) { 1305 sm.checkPermission(new PropertyPermission(key, 1306 SecurityConstants.PROPERTY_WRITE_ACTION)); 1307 } 1308 1309 return (String) props.setProperty(key, value); 1310 } 1311 1312 /** 1313 * Removes the system property indicated by the specified key. 1314 * <p> 1315 * First, if a security manager exists, its 1316 * <code>SecurityManager.checkPermission</code> method 1317 * is called with a <code>PropertyPermission(key, "write")</code> 1318 * permission. This may result in a SecurityException being thrown. 1319 * If no exception is thrown, the specified property is removed. 1320 * <p> 1321 * 1322 * @param key the name of the system property to be removed. 1323 * @return the previous string value of the system property, 1324 * or <code>null</code> if there was no property with that key. 1325 * 1326 * @exception SecurityException if a security manager exists and its 1327 * <code>checkPropertyAccess</code> method doesn't allow 1328 * access to the specified system property. 1329 * @exception NullPointerException if <code>key</code> is 1330 * <code>null</code>. 1331 * @exception IllegalArgumentException if <code>key</code> is empty. 1332 * @see #getProperty 1333 * @see #setProperty 1334 * @see java.util.Properties 1335 * @see java.lang.SecurityException 1336 * @see java.lang.SecurityManager#checkPropertiesAccess() 1337 * @since 1.5 1338 */ clearProperty(String key)1339 public static String clearProperty(String key) { 1340 checkKey(key); 1341 SecurityManager sm = getSecurityManager(); 1342 if (sm != null) { 1343 sm.checkPermission(new PropertyPermission(key, "write")); 1344 } 1345 1346 return (String) props.remove(key); 1347 } 1348 checkKey(String key)1349 private static void checkKey(String key) { 1350 if (key == null) { 1351 throw new NullPointerException("key can't be null"); 1352 } 1353 if (key.equals("")) { 1354 throw new IllegalArgumentException("key can't be empty"); 1355 } 1356 } 1357 1358 /** 1359 * Gets the value of the specified environment variable. An 1360 * environment variable is a system-dependent external named 1361 * value. 1362 * 1363 * <p>If a security manager exists, its 1364 * {@link SecurityManager#checkPermission checkPermission} 1365 * method is called with a 1366 * <code>{@link RuntimePermission}("getenv."+name)</code> 1367 * permission. This may result in a {@link SecurityException} 1368 * being thrown. If no exception is thrown the value of the 1369 * variable <code>name</code> is returned. 1370 * 1371 * <p><a name="EnvironmentVSSystemProperties"><i>System 1372 * properties</i> and <i>environment variables</i></a> are both 1373 * conceptually mappings between names and values. Both 1374 * mechanisms can be used to pass user-defined information to a 1375 * Java process. Environment variables have a more global effect, 1376 * because they are visible to all descendants of the process 1377 * which defines them, not just the immediate Java subprocess. 1378 * They can have subtly different semantics, such as case 1379 * insensitivity, on different operating systems. For these 1380 * reasons, environment variables are more likely to have 1381 * unintended side effects. It is best to use system properties 1382 * where possible. Environment variables should be used when a 1383 * global effect is desired, or when an external system interface 1384 * requires an environment variable (such as <code>PATH</code>). 1385 * 1386 * <p>On UNIX systems the alphabetic case of <code>name</code> is 1387 * typically significant, while on Microsoft Windows systems it is 1388 * typically not. For example, the expression 1389 * <code>System.getenv("FOO").equals(System.getenv("foo"))</code> 1390 * is likely to be true on Microsoft Windows. 1391 * 1392 * @param name the name of the environment variable 1393 * @return the string value of the variable, or <code>null</code> 1394 * if the variable is not defined in the system environment 1395 * @throws NullPointerException if <code>name</code> is <code>null</code> 1396 * @throws SecurityException 1397 * if a security manager exists and its 1398 * {@link SecurityManager#checkPermission checkPermission} 1399 * method doesn't allow access to the environment variable 1400 * <code>name</code> 1401 * @see #getenv() 1402 * @see ProcessBuilder#environment() 1403 */ getenv(String name)1404 public static String getenv(String name) { 1405 if (name == null) { 1406 throw new NullPointerException("name == null"); 1407 } 1408 1409 return Libcore.os.getenv(name); 1410 } 1411 1412 1413 /** 1414 * Returns an unmodifiable string map view of the current system environment. 1415 * The environment is a system-dependent mapping from names to 1416 * values which is passed from parent to child processes. 1417 * 1418 * <p>If the system does not support environment variables, an 1419 * empty map is returned. 1420 * 1421 * <p>The returned map will never contain null keys or values. 1422 * Attempting to query the presence of a null key or value will 1423 * throw a {@link NullPointerException}. Attempting to query 1424 * the presence of a key or value which is not of type 1425 * {@link String} will throw a {@link ClassCastException}. 1426 * 1427 * <p>The returned map and its collection views may not obey the 1428 * general contract of the {@link Object#equals} and 1429 * {@link Object#hashCode} methods. 1430 * 1431 * <p>The returned map is typically case-sensitive on all platforms. 1432 * 1433 * <p>If a security manager exists, its 1434 * {@link SecurityManager#checkPermission checkPermission} 1435 * method is called with a 1436 * <code>{@link RuntimePermission}("getenv.*")</code> 1437 * permission. This may result in a {@link SecurityException} being 1438 * thrown. 1439 * 1440 * <p>When passing information to a Java subprocess, 1441 * <a href=#EnvironmentVSSystemProperties>system properties</a> 1442 * are generally preferred over environment variables. 1443 * 1444 * @return the environment as a map of variable names to values 1445 * @throws SecurityException 1446 * if a security manager exists and its 1447 * {@link SecurityManager#checkPermission checkPermission} 1448 * method doesn't allow access to the process environment 1449 * @see #getenv(String) 1450 * @see ProcessBuilder#environment() 1451 * @since 1.5 1452 */ getenv()1453 public static java.util.Map<String,String> getenv() { 1454 SecurityManager sm = getSecurityManager(); 1455 if (sm != null) { 1456 sm.checkPermission(new RuntimePermission("getenv.*")); 1457 } 1458 1459 return ProcessEnvironment.getenv(); 1460 } 1461 1462 /** 1463 * Terminates the currently running Java Virtual Machine. The 1464 * argument serves as a status code; by convention, a nonzero status 1465 * code indicates abnormal termination. 1466 * <p> 1467 * This method calls the <code>exit</code> method in class 1468 * <code>Runtime</code>. This method never returns normally. 1469 * <p> 1470 * The call <code>System.exit(n)</code> is effectively equivalent to 1471 * the call: 1472 * <blockquote><pre> 1473 * Runtime.getRuntime().exit(n) 1474 * </pre></blockquote> 1475 * 1476 * @param status exit status. 1477 * @throws SecurityException 1478 * if a security manager exists and its <code>checkExit</code> 1479 * method doesn't allow exit with the specified status. 1480 * @see java.lang.Runtime#exit(int) 1481 */ exit(int status)1482 public static void exit(int status) { 1483 Runtime.getRuntime().exit(status); 1484 } 1485 1486 /** 1487 * Runs the garbage collector. 1488 * <p> 1489 * Calling the <code>gc</code> method suggests that the Java Virtual 1490 * Machine expend effort toward recycling unused objects in order to 1491 * make the memory they currently occupy available for quick reuse. 1492 * When control returns from the method call, the Java Virtual 1493 * Machine has made a best effort to reclaim space from all discarded 1494 * objects. 1495 * <p> 1496 * The call <code>System.gc()</code> is effectively equivalent to the 1497 * call: 1498 * <blockquote><pre> 1499 * Runtime.getRuntime().gc() 1500 * </pre></blockquote> 1501 * 1502 * @see java.lang.Runtime#gc() 1503 */ gc()1504 public static void gc() { 1505 boolean shouldRunGC; 1506 synchronized (LOCK) { 1507 shouldRunGC = justRanFinalization; 1508 if (shouldRunGC) { 1509 justRanFinalization = false; 1510 } else { 1511 runGC = true; 1512 } 1513 } 1514 if (shouldRunGC) { 1515 Runtime.getRuntime().gc(); 1516 } 1517 } 1518 1519 /** 1520 * Runs the finalization methods of any objects pending finalization. 1521 * <p> 1522 * Calling this method suggests that the Java Virtual Machine expend 1523 * effort toward running the <code>finalize</code> methods of objects 1524 * that have been found to be discarded but whose <code>finalize</code> 1525 * methods have not yet been run. When control returns from the 1526 * method call, the Java Virtual Machine has made a best effort to 1527 * complete all outstanding finalizations. 1528 * <p> 1529 * The call <code>System.runFinalization()</code> is effectively 1530 * equivalent to the call: 1531 * <blockquote><pre> 1532 * Runtime.getRuntime().runFinalization() 1533 * </pre></blockquote> 1534 * 1535 * @see java.lang.Runtime#runFinalization() 1536 */ runFinalization()1537 public static void runFinalization() { 1538 boolean shouldRunGC; 1539 synchronized (LOCK) { 1540 shouldRunGC = runGC; 1541 runGC = false; 1542 } 1543 if (shouldRunGC) { 1544 Runtime.getRuntime().gc(); 1545 } 1546 Runtime.getRuntime().runFinalization(); 1547 synchronized (LOCK) { 1548 justRanFinalization = true; 1549 } 1550 } 1551 1552 /** 1553 * Enable or disable finalization on exit; doing so specifies that the 1554 * finalizers of all objects that have finalizers that have not yet been 1555 * automatically invoked are to be run before the Java runtime exits. 1556 * By default, finalization on exit is disabled. 1557 * 1558 * <p>If there is a security manager, 1559 * its <code>checkExit</code> method is first called 1560 * with 0 as its argument to ensure the exit is allowed. 1561 * This could result in a SecurityException. 1562 * 1563 * @deprecated This method is inherently unsafe. It may result in 1564 * finalizers being called on live objects while other threads are 1565 * concurrently manipulating those objects, resulting in erratic 1566 * behavior or deadlock. 1567 * @param value indicating enabling or disabling of finalization 1568 * @throws SecurityException 1569 * if a security manager exists and its <code>checkExit</code> 1570 * method doesn't allow the exit. 1571 * 1572 * @see java.lang.Runtime#exit(int) 1573 * @see java.lang.Runtime#gc() 1574 * @see java.lang.SecurityManager#checkExit(int) 1575 * @since JDK1.1 1576 */ 1577 @Deprecated runFinalizersOnExit(boolean value)1578 public static void runFinalizersOnExit(boolean value) { 1579 Runtime.runFinalizersOnExit(value); 1580 } 1581 1582 /** 1583 * Loads the native library specified by the filename argument. The filename 1584 * argument must be an absolute path name. 1585 * 1586 * If the filename argument, when stripped of any platform-specific library 1587 * prefix, path, and file extension, indicates a library whose name is, 1588 * for example, L, and a native library called L is statically linked 1589 * with the VM, then the JNI_OnLoad_L function exported by the library 1590 * is invoked rather than attempting to load a dynamic library. 1591 * A filename matching the argument does not have to exist in the 1592 * file system. 1593 * See the JNI Specification for more details. 1594 * 1595 * Otherwise, the filename argument is mapped to a native library image in 1596 * an implementation-dependent manner. 1597 * 1598 * <p> 1599 * The call <code>System.load(name)</code> is effectively equivalent 1600 * to the call: 1601 * <blockquote><pre> 1602 * Runtime.getRuntime().load(name) 1603 * </pre></blockquote> 1604 * 1605 * @param filename the file to load. 1606 * @exception SecurityException if a security manager exists and its 1607 * <code>checkLink</code> method doesn't allow 1608 * loading of the specified dynamic library 1609 * @exception UnsatisfiedLinkError if either the filename is not an 1610 * absolute path name, the native library is not statically 1611 * linked with the VM, or the library cannot be mapped to 1612 * a native library image by the host system. 1613 * @exception NullPointerException if <code>filename</code> is 1614 * <code>null</code> 1615 * @see java.lang.Runtime#load(java.lang.String) 1616 * @see java.lang.SecurityManager#checkLink(java.lang.String) 1617 */ 1618 @CallerSensitive load(String filename)1619 public static void load(String filename) { 1620 Runtime.getRuntime().load0(Reflection.getCallerClass(), filename); 1621 } 1622 1623 /** 1624 * Loads the native library specified by the <code>libname</code> 1625 * argument. The <code>libname</code> argument must not contain any platform 1626 * specific prefix, file extension or path. If a native library 1627 * called <code>libname</code> is statically linked with the VM, then the 1628 * JNI_OnLoad_<code>libname</code> function exported by the library is invoked. 1629 * See the JNI Specification for more details. 1630 * 1631 * Otherwise, the libname argument is loaded from a system library 1632 * location and mapped to a native library image in an implementation- 1633 * dependent manner. 1634 * <p> 1635 * The call <code>System.loadLibrary(name)</code> is effectively 1636 * equivalent to the call 1637 * <blockquote><pre> 1638 * Runtime.getRuntime().loadLibrary(name) 1639 * </pre></blockquote> 1640 * 1641 * @param libname the name of the library. 1642 * @exception SecurityException if a security manager exists and its 1643 * <code>checkLink</code> method doesn't allow 1644 * loading of the specified dynamic library 1645 * @exception UnsatisfiedLinkError if either the libname argument 1646 * contains a file path, the native library is not statically 1647 * linked with the VM, or the library cannot be mapped to a 1648 * native library image by the host system. 1649 * @exception NullPointerException if <code>libname</code> is 1650 * <code>null</code> 1651 * @see java.lang.Runtime#loadLibrary(java.lang.String) 1652 * @see java.lang.SecurityManager#checkLink(java.lang.String) 1653 */ 1654 @CallerSensitive loadLibrary(String libname)1655 public static void loadLibrary(String libname) { 1656 Runtime.getRuntime().loadLibrary0(Reflection.getCallerClass(), libname); 1657 } 1658 1659 /** 1660 * Maps a library name into a platform-specific string representing 1661 * a native library. 1662 * 1663 * @param libname the name of the library. 1664 * @return a platform-dependent native library name. 1665 * @exception NullPointerException if <code>libname</code> is 1666 * <code>null</code> 1667 * @see java.lang.System#loadLibrary(java.lang.String) 1668 * @see java.lang.ClassLoader#findLibrary(java.lang.String) 1669 * @since 1.2 1670 */ mapLibraryName(String libname)1671 public static native String mapLibraryName(String libname); 1672 1673 /** 1674 * Create PrintStream for stdout/err based on encoding. 1675 */ newPrintStream(FileOutputStream fos, String enc)1676 private static PrintStream newPrintStream(FileOutputStream fos, String enc) { 1677 if (enc != null) { 1678 try { 1679 return new PrintStream(new BufferedOutputStream(fos, 128), true, enc); 1680 } catch (UnsupportedEncodingException uee) {} 1681 } 1682 return new PrintStream(new BufferedOutputStream(fos, 128), true); 1683 } 1684 1685 1686 /** 1687 * Initialize the system class. Called after thread initialization. 1688 */ 1689 static { 1690 unchangeableProps = initUnchangeableSystemProperties(); 1691 props = initProperties(); addLegacyLocaleSystemProperties()1692 addLegacyLocaleSystemProperties(); sun.misc.Version.initSystemProperties()1693 sun.misc.Version.initSystemProperties(); 1694 1695 // TODO: Confirm that this isn't something super important. 1696 // sun.misc.VM.saveAndRemoveProperties(props); 1697 1698 lineSeparator = props.getProperty("line.separator"); 1699 1700 FileInputStream fdIn = new FileInputStream(FileDescriptor.in); 1701 FileOutputStream fdOut = new FileOutputStream(FileDescriptor.out); 1702 FileOutputStream fdErr = new FileOutputStream(FileDescriptor.err); 1703 // BEGIN Android-changed: lower buffer size. 1704 // in = new BufferedInputStream(fdIn); 1705 in = new BufferedInputStream(fdIn, 128); 1706 // END Android-changed: lower buffer size. 1707 out = newPrintStream(fdOut, props.getProperty("sun.stdout.encoding")); 1708 err = newPrintStream(fdErr, props.getProperty("sun.stderr.encoding")); 1709 1710 // Initialize any miscellenous operating system settings that need to be 1711 // set for the class libraries. Currently this is no-op everywhere except 1712 // for Windows where the process-wide error mode is set before the java.io 1713 // classes are used. sun.misc.VM.initializeOSEnvironment()1714 sun.misc.VM.initializeOSEnvironment(); 1715 1716 // Subsystems that are invoked during initialization can invoke 1717 // sun.misc.VM.isBooted() in order to avoid doing things that should 1718 // wait until the application class loader has been set up. 1719 // IMPORTANT: Ensure that this remains the last initialization action! sun.misc.VM.booted()1720 sun.misc.VM.booted(); 1721 } 1722 1723 /** 1724 * @hide internal use only 1725 */ logE(String message)1726 public static void logE(String message) { 1727 log('E', message, null); 1728 } 1729 1730 /** 1731 * @hide internal use only 1732 */ logE(String message, Throwable th)1733 public static void logE(String message, Throwable th) { 1734 log('E', message, th); 1735 } 1736 1737 /** 1738 * @hide internal use only 1739 */ logI(String message)1740 public static void logI(String message) { 1741 log('I', message, null); 1742 } 1743 1744 /** 1745 * @hide internal use only 1746 */ logI(String message, Throwable th)1747 public static void logI(String message, Throwable th) { 1748 log('I', message, th); 1749 } 1750 1751 /** 1752 * @hide internal use only 1753 */ logW(String message)1754 public static void logW(String message) { 1755 log('W', message, null); 1756 } 1757 1758 /** 1759 * @hide internal use only 1760 */ logW(String message, Throwable th)1761 public static void logW(String message, Throwable th) { 1762 log('W', message, th); 1763 } 1764 log(char type, String message, Throwable th)1765 private static native void log(char type, String message, Throwable th); 1766 } 1767