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