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