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