System.java revision 12745:f068a4ffddd2
1/*
2 * Copyright (c) 1994, 2014, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.  Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25package java.lang;
26
27import java.io.*;
28import java.lang.reflect.Executable;
29import java.lang.annotation.Annotation;
30import java.security.AccessControlContext;
31import java.util.Properties;
32import java.util.PropertyPermission;
33import java.util.StringTokenizer;
34import java.util.Map;
35import java.security.AccessController;
36import java.security.PrivilegedAction;
37import java.security.AllPermission;
38import java.nio.channels.Channel;
39import java.nio.channels.spi.SelectorProvider;
40import sun.nio.ch.Interruptible;
41import sun.reflect.CallerSensitive;
42import sun.reflect.Reflection;
43import sun.security.util.SecurityConstants;
44import sun.reflect.annotation.AnnotationType;
45import jdk.internal.HotSpotIntrinsicCandidate;
46
47/**
48 * The <code>System</code> class contains several useful class fields
49 * and methods. It cannot be instantiated.
50 *
51 * <p>Among the facilities provided by the <code>System</code> class
52 * are standard input, standard output, and error output streams;
53 * access to externally defined properties and environment
54 * variables; a means of loading files and libraries; and a utility
55 * method for quickly copying a portion of an array.
56 *
57 * @author  unascribed
58 * @since   1.0
59 */
60public final class System {
61
62    /* register the natives via the static initializer.
63     *
64     * VM will invoke the initializeSystemClass method to complete
65     * the initialization for this class separated from clinit.
66     * Note that to use properties set by the VM, see the constraints
67     * described in the initializeSystemClass method.
68     */
69    private static native void registerNatives();
70    static {
71        registerNatives();
72    }
73
74    /** Don't let anyone instantiate this class */
75    private System() {
76    }
77
78    /**
79     * The "standard" input stream. This stream is already
80     * open and ready to supply input data. Typically this stream
81     * corresponds to keyboard input or another input source specified by
82     * the host environment or user.
83     */
84    public static final InputStream in = null;
85
86    /**
87     * The "standard" output stream. This stream is already
88     * open and ready to accept output data. Typically this stream
89     * corresponds to display output or another output destination
90     * specified by the host environment or user.
91     * <p>
92     * For simple stand-alone Java applications, a typical way to write
93     * a line of output data is:
94     * <blockquote><pre>
95     *     System.out.println(data)
96     * </pre></blockquote>
97     * <p>
98     * See the <code>println</code> methods in class <code>PrintStream</code>.
99     *
100     * @see     java.io.PrintStream#println()
101     * @see     java.io.PrintStream#println(boolean)
102     * @see     java.io.PrintStream#println(char)
103     * @see     java.io.PrintStream#println(char[])
104     * @see     java.io.PrintStream#println(double)
105     * @see     java.io.PrintStream#println(float)
106     * @see     java.io.PrintStream#println(int)
107     * @see     java.io.PrintStream#println(long)
108     * @see     java.io.PrintStream#println(java.lang.Object)
109     * @see     java.io.PrintStream#println(java.lang.String)
110     */
111    public static final PrintStream out = null;
112
113    /**
114     * The "standard" error output stream. This stream is already
115     * open and ready to accept output data.
116     * <p>
117     * Typically this stream corresponds to display output or another
118     * output destination specified by the host environment or user. By
119     * convention, this output stream is used to display error messages
120     * or other information that should come to the immediate attention
121     * of a user even if the principal output stream, the value of the
122     * variable <code>out</code>, has been redirected to a file or other
123     * destination that is typically not continuously monitored.
124     */
125    public static final PrintStream err = null;
126
127    /* The security manager for the system.
128     */
129    private static volatile SecurityManager security = null;
130
131    /**
132     * Reassigns the "standard" input stream.
133     *
134     * <p>First, if there is a security manager, its <code>checkPermission</code>
135     * method is called with a <code>RuntimePermission("setIO")</code> permission
136     *  to see if it's ok to reassign the "standard" input stream.
137     *
138     * @param in the new standard input stream.
139     *
140     * @throws SecurityException
141     *        if a security manager exists and its
142     *        <code>checkPermission</code> method doesn't allow
143     *        reassigning of the standard input stream.
144     *
145     * @see SecurityManager#checkPermission
146     * @see java.lang.RuntimePermission
147     *
148     * @since   1.1
149     */
150    public static void setIn(InputStream in) {
151        checkIO();
152        setIn0(in);
153    }
154
155    /**
156     * Reassigns the "standard" output stream.
157     *
158     * <p>First, if there is a security manager, its <code>checkPermission</code>
159     * method is called with a <code>RuntimePermission("setIO")</code> permission
160     *  to see if it's ok to reassign the "standard" output stream.
161     *
162     * @param out the new standard output stream
163     *
164     * @throws SecurityException
165     *        if a security manager exists and its
166     *        <code>checkPermission</code> method doesn't allow
167     *        reassigning of the standard output stream.
168     *
169     * @see SecurityManager#checkPermission
170     * @see java.lang.RuntimePermission
171     *
172     * @since   1.1
173     */
174    public static void setOut(PrintStream out) {
175        checkIO();
176        setOut0(out);
177    }
178
179    /**
180     * Reassigns the "standard" error output stream.
181     *
182     * <p>First, if there is a security manager, its <code>checkPermission</code>
183     * method is called with a <code>RuntimePermission("setIO")</code> permission
184     *  to see if it's ok to reassign the "standard" error output stream.
185     *
186     * @param err the new standard error output stream.
187     *
188     * @throws SecurityException
189     *        if a security manager exists and its
190     *        <code>checkPermission</code> method doesn't allow
191     *        reassigning of the standard error output stream.
192     *
193     * @see SecurityManager#checkPermission
194     * @see java.lang.RuntimePermission
195     *
196     * @since   1.1
197     */
198    public static void setErr(PrintStream err) {
199        checkIO();
200        setErr0(err);
201    }
202
203    private static volatile Console cons = null;
204    /**
205     * Returns the unique {@link java.io.Console Console} object associated
206     * with the current Java virtual machine, if any.
207     *
208     * @return  The system console, if any, otherwise {@code null}.
209     *
210     * @since   1.6
211     */
212     public static Console console() {
213         if (cons == null) {
214             synchronized (System.class) {
215                 cons = sun.misc.SharedSecrets.getJavaIOAccess().console();
216             }
217         }
218         return cons;
219     }
220
221    /**
222     * Returns the channel inherited from the entity that created this
223     * Java virtual machine.
224     *
225     * <p> This method returns the channel obtained by invoking the
226     * {@link java.nio.channels.spi.SelectorProvider#inheritedChannel
227     * inheritedChannel} method of the system-wide default
228     * {@link java.nio.channels.spi.SelectorProvider} object. </p>
229     *
230     * <p> In addition to the network-oriented channels described in
231     * {@link java.nio.channels.spi.SelectorProvider#inheritedChannel
232     * inheritedChannel}, this method may return other kinds of
233     * channels in the future.
234     *
235     * @return  The inherited channel, if any, otherwise {@code null}.
236     *
237     * @throws  IOException
238     *          If an I/O error occurs
239     *
240     * @throws  SecurityException
241     *          If a security manager is present and it does not
242     *          permit access to the channel.
243     *
244     * @since 1.5
245     */
246    public static Channel inheritedChannel() throws IOException {
247        return SelectorProvider.provider().inheritedChannel();
248    }
249
250    private static void checkIO() {
251        SecurityManager sm = getSecurityManager();
252        if (sm != null) {
253            sm.checkPermission(new RuntimePermission("setIO"));
254        }
255    }
256
257    private static native void setIn0(InputStream in);
258    private static native void setOut0(PrintStream out);
259    private static native void setErr0(PrintStream err);
260
261    /**
262     * Sets the System security.
263     *
264     * <p> If there is a security manager already installed, this method first
265     * calls the security manager's <code>checkPermission</code> method
266     * with a <code>RuntimePermission("setSecurityManager")</code>
267     * permission to ensure it's ok to replace the existing
268     * security manager.
269     * This may result in throwing a <code>SecurityException</code>.
270     *
271     * <p> Otherwise, the argument is established as the current
272     * security manager. If the argument is <code>null</code> and no
273     * security manager has been established, then no action is taken and
274     * the method simply returns.
275     *
276     * @param      s   the security manager.
277     * @exception  SecurityException  if the security manager has already
278     *             been set and its <code>checkPermission</code> method
279     *             doesn't allow it to be replaced.
280     * @see #getSecurityManager
281     * @see SecurityManager#checkPermission
282     * @see java.lang.RuntimePermission
283     */
284    public static
285    void setSecurityManager(final SecurityManager s) {
286        try {
287            s.checkPackageAccess("java.lang");
288        } catch (Exception e) {
289            // no-op
290        }
291        setSecurityManager0(s);
292    }
293
294    private static synchronized
295    void setSecurityManager0(final SecurityManager s) {
296        SecurityManager sm = getSecurityManager();
297        if (sm != null) {
298            // ask the currently installed security manager if we
299            // can replace it.
300            sm.checkPermission(new RuntimePermission
301                                     ("setSecurityManager"));
302        }
303
304        if ((s != null) && (s.getClass().getClassLoader() != null)) {
305            // New security manager class is not on bootstrap classpath.
306            // Cause policy to get initialized before we install the new
307            // security manager, in order to prevent infinite loops when
308            // trying to initialize the policy (which usually involves
309            // accessing some security and/or system properties, which in turn
310            // calls the installed security manager's checkPermission method
311            // which will loop infinitely if there is a non-system class
312            // (in this case: the new security manager class) on the stack).
313            AccessController.doPrivileged(new PrivilegedAction<>() {
314                public Object run() {
315                    s.getClass().getProtectionDomain().implies
316                        (SecurityConstants.ALL_PERMISSION);
317                    return null;
318                }
319            });
320        }
321
322        security = s;
323    }
324
325    /**
326     * Gets the system security interface.
327     *
328     * @return  if a security manager has already been established for the
329     *          current application, then that security manager is returned;
330     *          otherwise, <code>null</code> is returned.
331     * @see     #setSecurityManager
332     */
333    public static SecurityManager getSecurityManager() {
334        return security;
335    }
336
337    /**
338     * Returns the current time in milliseconds.  Note that
339     * while the unit of time of the return value is a millisecond,
340     * the granularity of the value depends on the underlying
341     * operating system and may be larger.  For example, many
342     * operating systems measure time in units of tens of
343     * milliseconds.
344     *
345     * <p> See the description of the class <code>Date</code> for
346     * a discussion of slight discrepancies that may arise between
347     * "computer time" and coordinated universal time (UTC).
348     *
349     * @return  the difference, measured in milliseconds, between
350     *          the current time and midnight, January 1, 1970 UTC.
351     * @see     java.util.Date
352     */
353    @HotSpotIntrinsicCandidate
354    public static native long currentTimeMillis();
355
356    /**
357     * Returns the current value of the running Java Virtual Machine's
358     * high-resolution time source, in nanoseconds.
359     *
360     * <p>This method can only be used to measure elapsed time and is
361     * not related to any other notion of system or wall-clock time.
362     * The value returned represents nanoseconds since some fixed but
363     * arbitrary <i>origin</i> time (perhaps in the future, so values
364     * may be negative).  The same origin is used by all invocations of
365     * this method in an instance of a Java virtual machine; other
366     * virtual machine instances are likely to use a different origin.
367     *
368     * <p>This method provides nanosecond precision, but not necessarily
369     * nanosecond resolution (that is, how frequently the value changes)
370     * - no guarantees are made except that the resolution is at least as
371     * good as that of {@link #currentTimeMillis()}.
372     *
373     * <p>Differences in successive calls that span greater than
374     * approximately 292 years (2<sup>63</sup> nanoseconds) will not
375     * correctly compute elapsed time due to numerical overflow.
376     *
377     * <p>The values returned by this method become meaningful only when
378     * the difference between two such values, obtained within the same
379     * instance of a Java virtual machine, is computed.
380     *
381     * <p>For example, to measure how long some code takes to execute:
382     * <pre> {@code
383     * long startTime = System.nanoTime();
384     * // ... the code being measured ...
385     * long elapsedNanos = System.nanoTime() - startTime;}</pre>
386     *
387     * <p>To compare elapsed time against a timeout, use <pre> {@code
388     * if (System.nanoTime() - startTime >= timeoutNanos) ...}</pre>
389     * instead of <pre> {@code
390     * if (System.nanoTime() >= startTime + timeoutNanos) ...}</pre>
391     * because of the possibility of numerical overflow.
392     *
393     * @return the current value of the running Java Virtual Machine's
394     *         high-resolution time source, in nanoseconds
395     * @since 1.5
396     */
397    @HotSpotIntrinsicCandidate
398    public static native long nanoTime();
399
400    /**
401     * Copies an array from the specified source array, beginning at the
402     * specified position, to the specified position of the destination array.
403     * A subsequence of array components are copied from the source
404     * array referenced by <code>src</code> to the destination array
405     * referenced by <code>dest</code>. The number of components copied is
406     * equal to the <code>length</code> argument. The components at
407     * positions <code>srcPos</code> through
408     * <code>srcPos+length-1</code> in the source array are copied into
409     * positions <code>destPos</code> through
410     * <code>destPos+length-1</code>, respectively, of the destination
411     * array.
412     * <p>
413     * If the <code>src</code> and <code>dest</code> arguments refer to the
414     * same array object, then the copying is performed as if the
415     * components at positions <code>srcPos</code> through
416     * <code>srcPos+length-1</code> were first copied to a temporary
417     * array with <code>length</code> components and then the contents of
418     * the temporary array were copied into positions
419     * <code>destPos</code> through <code>destPos+length-1</code> of the
420     * destination array.
421     * <p>
422     * If <code>dest</code> is <code>null</code>, then a
423     * <code>NullPointerException</code> is thrown.
424     * <p>
425     * If <code>src</code> is <code>null</code>, then a
426     * <code>NullPointerException</code> is thrown and the destination
427     * array is not modified.
428     * <p>
429     * Otherwise, if any of the following is true, an
430     * <code>ArrayStoreException</code> is thrown and the destination is
431     * not modified:
432     * <ul>
433     * <li>The <code>src</code> argument refers to an object that is not an
434     *     array.
435     * <li>The <code>dest</code> argument refers to an object that is not an
436     *     array.
437     * <li>The <code>src</code> argument and <code>dest</code> argument refer
438     *     to arrays whose component types are different primitive types.
439     * <li>The <code>src</code> argument refers to an array with a primitive
440     *    component type and the <code>dest</code> argument refers to an array
441     *     with a reference component type.
442     * <li>The <code>src</code> argument refers to an array with a reference
443     *    component type and the <code>dest</code> argument refers to an array
444     *     with a primitive component type.
445     * </ul>
446     * <p>
447     * Otherwise, if any of the following is true, an
448     * <code>IndexOutOfBoundsException</code> is
449     * thrown and the destination is not modified:
450     * <ul>
451     * <li>The <code>srcPos</code> argument is negative.
452     * <li>The <code>destPos</code> argument is negative.
453     * <li>The <code>length</code> argument is negative.
454     * <li><code>srcPos+length</code> is greater than
455     *     <code>src.length</code>, the length of the source array.
456     * <li><code>destPos+length</code> is greater than
457     *     <code>dest.length</code>, the length of the destination array.
458     * </ul>
459     * <p>
460     * Otherwise, if any actual component of the source array from
461     * position <code>srcPos</code> through
462     * <code>srcPos+length-1</code> cannot be converted to the component
463     * type of the destination array by assignment conversion, an
464     * <code>ArrayStoreException</code> is thrown. In this case, let
465     * <b><i>k</i></b> be the smallest nonnegative integer less than
466     * length such that <code>src[srcPos+</code><i>k</i><code>]</code>
467     * cannot be converted to the component type of the destination
468     * array; when the exception is thrown, source array components from
469     * positions <code>srcPos</code> through
470     * <code>srcPos+</code><i>k</i><code>-1</code>
471     * will already have been copied to destination array positions
472     * <code>destPos</code> through
473     * <code>destPos+</code><i>k</I><code>-1</code> and no other
474     * positions of the destination array will have been modified.
475     * (Because of the restrictions already itemized, this
476     * paragraph effectively applies only to the situation where both
477     * arrays have component types that are reference types.)
478     *
479     * @param      src      the source array.
480     * @param      srcPos   starting position in the source array.
481     * @param      dest     the destination array.
482     * @param      destPos  starting position in the destination data.
483     * @param      length   the number of array elements to be copied.
484     * @exception  IndexOutOfBoundsException  if copying would cause
485     *               access of data outside array bounds.
486     * @exception  ArrayStoreException  if an element in the <code>src</code>
487     *               array could not be stored into the <code>dest</code> array
488     *               because of a type mismatch.
489     * @exception  NullPointerException if either <code>src</code> or
490     *               <code>dest</code> is <code>null</code>.
491     */
492    @HotSpotIntrinsicCandidate
493    public static native void arraycopy(Object src,  int  srcPos,
494                                        Object dest, int destPos,
495                                        int length);
496
497    /**
498     * Returns the same hash code for the given object as
499     * would be returned by the default method hashCode(),
500     * whether or not the given object's class overrides
501     * hashCode().
502     * The hash code for the null reference is zero.
503     *
504     * @param x object for which the hashCode is to be calculated
505     * @return  the hashCode
506     * @since   1.1
507     */
508    @HotSpotIntrinsicCandidate
509    public static native int identityHashCode(Object x);
510
511    /**
512     * System properties. The following properties are guaranteed to be defined:
513     * <dl>
514     * <dt>java.version         <dd>Java version number
515     * <dt>java.vendor          <dd>Java vendor specific string
516     * <dt>java.vendor.url      <dd>Java vendor URL
517     * <dt>java.home            <dd>Java installation directory
518     * <dt>java.class.version   <dd>Java class version number
519     * <dt>java.class.path      <dd>Java classpath
520     * <dt>os.name              <dd>Operating System Name
521     * <dt>os.arch              <dd>Operating System Architecture
522     * <dt>os.version           <dd>Operating System Version
523     * <dt>file.separator       <dd>File separator ("/" on Unix)
524     * <dt>path.separator       <dd>Path separator (":" on Unix)
525     * <dt>line.separator       <dd>Line separator ("\n" on Unix)
526     * <dt>user.name            <dd>User account name
527     * <dt>user.home            <dd>User home directory
528     * <dt>user.dir             <dd>User's current working directory
529     * </dl>
530     */
531
532    private static Properties props;
533    private static native Properties initProperties(Properties props);
534
535    /**
536     * Determines the current system properties.
537     * <p>
538     * First, if there is a security manager, its
539     * <code>checkPropertiesAccess</code> method is called with no
540     * arguments. This may result in a security exception.
541     * <p>
542     * The current set of system properties for use by the
543     * {@link #getProperty(String)} method is returned as a
544     * <code>Properties</code> object. If there is no current set of
545     * system properties, a set of system properties is first created and
546     * initialized. This set of system properties always includes values
547     * for the following keys:
548     * <table summary="Shows property keys and associated values">
549     * <tr><th>Key</th>
550     *     <th>Description of Associated Value</th></tr>
551     * <tr><td><code>java.version</code></td>
552     *     <td>Java Runtime Environment version</td></tr>
553     * <tr><td><code>java.vendor</code></td>
554     *     <td>Java Runtime Environment vendor</td></tr>
555     * <tr><td><code>java.vendor.url</code></td>
556     *     <td>Java vendor URL</td></tr>
557     * <tr><td><code>java.home</code></td>
558     *     <td>Java installation directory</td></tr>
559     * <tr><td><code>java.vm.specification.version</code></td>
560     *     <td>Java Virtual Machine specification version</td></tr>
561     * <tr><td><code>java.vm.specification.vendor</code></td>
562     *     <td>Java Virtual Machine specification vendor</td></tr>
563     * <tr><td><code>java.vm.specification.name</code></td>
564     *     <td>Java Virtual Machine specification name</td></tr>
565     * <tr><td><code>java.vm.version</code></td>
566     *     <td>Java Virtual Machine implementation version</td></tr>
567     * <tr><td><code>java.vm.vendor</code></td>
568     *     <td>Java Virtual Machine implementation vendor</td></tr>
569     * <tr><td><code>java.vm.name</code></td>
570     *     <td>Java Virtual Machine implementation name</td></tr>
571     * <tr><td><code>java.specification.version</code></td>
572     *     <td>Java Runtime Environment specification  version</td></tr>
573     * <tr><td><code>java.specification.vendor</code></td>
574     *     <td>Java Runtime Environment specification  vendor</td></tr>
575     * <tr><td><code>java.specification.name</code></td>
576     *     <td>Java Runtime Environment specification  name</td></tr>
577     * <tr><td><code>java.class.version</code></td>
578     *     <td>Java class format version number</td></tr>
579     * <tr><td><code>java.class.path</code></td>
580     *     <td>Java class path</td></tr>
581     * <tr><td><code>java.library.path</code></td>
582     *     <td>List of paths to search when loading libraries</td></tr>
583     * <tr><td><code>java.io.tmpdir</code></td>
584     *     <td>Default temp file path</td></tr>
585     * <tr><td><code>java.compiler</code></td>
586     *     <td>Name of JIT compiler to use</td></tr>
587     * <tr><td><code>os.name</code></td>
588     *     <td>Operating system name</td></tr>
589     * <tr><td><code>os.arch</code></td>
590     *     <td>Operating system architecture</td></tr>
591     * <tr><td><code>os.version</code></td>
592     *     <td>Operating system version</td></tr>
593     * <tr><td><code>file.separator</code></td>
594     *     <td>File separator ("/" on UNIX)</td></tr>
595     * <tr><td><code>path.separator</code></td>
596     *     <td>Path separator (":" on UNIX)</td></tr>
597     * <tr><td><code>line.separator</code></td>
598     *     <td>Line separator ("\n" on UNIX)</td></tr>
599     * <tr><td><code>user.name</code></td>
600     *     <td>User's account name</td></tr>
601     * <tr><td><code>user.home</code></td>
602     *     <td>User's home directory</td></tr>
603     * <tr><td><code>user.dir</code></td>
604     *     <td>User's current working directory</td></tr>
605     * </table>
606     * <p>
607     * Multiple paths in a system property value are separated by the path
608     * separator character of the platform.
609     * <p>
610     * Note that even if the security manager does not permit the
611     * <code>getProperties</code> operation, it may choose to permit the
612     * {@link #getProperty(String)} operation.
613     *
614     * @return     the system properties
615     * @exception  SecurityException  if a security manager exists and its
616     *             <code>checkPropertiesAccess</code> method doesn't allow access
617     *              to the system properties.
618     * @see        #setProperties
619     * @see        java.lang.SecurityException
620     * @see        java.lang.SecurityManager#checkPropertiesAccess()
621     * @see        java.util.Properties
622     */
623    public static Properties getProperties() {
624        SecurityManager sm = getSecurityManager();
625        if (sm != null) {
626            sm.checkPropertiesAccess();
627        }
628
629        return props;
630    }
631
632    /**
633     * Returns the system-dependent line separator string.  It always
634     * returns the same value - the initial value of the {@linkplain
635     * #getProperty(String) system property} {@code line.separator}.
636     *
637     * <p>On UNIX systems, it returns {@code "\n"}; on Microsoft
638     * Windows systems it returns {@code "\r\n"}.
639     *
640     * @return the system-dependent line separator string
641     * @since 1.7
642     */
643    public static String lineSeparator() {
644        return lineSeparator;
645    }
646
647    private static String lineSeparator;
648
649    /**
650     * Sets the system properties to the <code>Properties</code>
651     * argument.
652     * <p>
653     * First, if there is a security manager, its
654     * <code>checkPropertiesAccess</code> method is called with no
655     * arguments. This may result in a security exception.
656     * <p>
657     * The argument becomes the current set of system properties for use
658     * by the {@link #getProperty(String)} method. If the argument is
659     * <code>null</code>, then the current set of system properties is
660     * forgotten.
661     *
662     * @param      props   the new system properties.
663     * @exception  SecurityException  if a security manager exists and its
664     *             <code>checkPropertiesAccess</code> method doesn't allow access
665     *              to the system properties.
666     * @see        #getProperties
667     * @see        java.util.Properties
668     * @see        java.lang.SecurityException
669     * @see        java.lang.SecurityManager#checkPropertiesAccess()
670     */
671    public static void setProperties(Properties props) {
672        SecurityManager sm = getSecurityManager();
673        if (sm != null) {
674            sm.checkPropertiesAccess();
675        }
676        if (props == null) {
677            props = new Properties();
678            initProperties(props);
679        }
680        System.props = props;
681    }
682
683    /**
684     * Gets the system property indicated by the specified key.
685     * <p>
686     * First, if there is a security manager, its
687     * <code>checkPropertyAccess</code> method is called with the key as
688     * its argument. This may result in a SecurityException.
689     * <p>
690     * If there is no current set of system properties, a set of system
691     * properties is first created and initialized in the same manner as
692     * for the <code>getProperties</code> method.
693     *
694     * @param      key   the name of the system property.
695     * @return     the string value of the system property,
696     *             or <code>null</code> if there is no property with that key.
697     *
698     * @exception  SecurityException  if a security manager exists and its
699     *             <code>checkPropertyAccess</code> method doesn't allow
700     *              access to the specified system property.
701     * @exception  NullPointerException if <code>key</code> is
702     *             <code>null</code>.
703     * @exception  IllegalArgumentException if <code>key</code> is empty.
704     * @see        #setProperty
705     * @see        java.lang.SecurityException
706     * @see        java.lang.SecurityManager#checkPropertyAccess(java.lang.String)
707     * @see        java.lang.System#getProperties()
708     */
709    public static String getProperty(String key) {
710        checkKey(key);
711        SecurityManager sm = getSecurityManager();
712        if (sm != null) {
713            sm.checkPropertyAccess(key);
714        }
715
716        return props.getProperty(key);
717    }
718
719    /**
720     * Gets the system property indicated by the specified key.
721     * <p>
722     * First, if there is a security manager, its
723     * <code>checkPropertyAccess</code> method is called with the
724     * <code>key</code> as its argument.
725     * <p>
726     * If there is no current set of system properties, a set of system
727     * properties is first created and initialized in the same manner as
728     * for the <code>getProperties</code> method.
729     *
730     * @param      key   the name of the system property.
731     * @param      def   a default value.
732     * @return     the string value of the system property,
733     *             or the default value if there is no property with that key.
734     *
735     * @exception  SecurityException  if a security manager exists and its
736     *             <code>checkPropertyAccess</code> method doesn't allow
737     *             access to the specified system property.
738     * @exception  NullPointerException if <code>key</code> is
739     *             <code>null</code>.
740     * @exception  IllegalArgumentException if <code>key</code> is empty.
741     * @see        #setProperty
742     * @see        java.lang.SecurityManager#checkPropertyAccess(java.lang.String)
743     * @see        java.lang.System#getProperties()
744     */
745    public static String getProperty(String key, String def) {
746        checkKey(key);
747        SecurityManager sm = getSecurityManager();
748        if (sm != null) {
749            sm.checkPropertyAccess(key);
750        }
751
752        return props.getProperty(key, def);
753    }
754
755    /**
756     * Sets the system property indicated by the specified key.
757     * <p>
758     * First, if a security manager exists, its
759     * <code>SecurityManager.checkPermission</code> method
760     * is called with a <code>PropertyPermission(key, "write")</code>
761     * permission. This may result in a SecurityException being thrown.
762     * If no exception is thrown, the specified property is set to the given
763     * value.
764     *
765     * @param      key   the name of the system property.
766     * @param      value the value of the system property.
767     * @return     the previous value of the system property,
768     *             or <code>null</code> if it did not have one.
769     *
770     * @exception  SecurityException  if a security manager exists and its
771     *             <code>checkPermission</code> method doesn't allow
772     *             setting of the specified property.
773     * @exception  NullPointerException if <code>key</code> or
774     *             <code>value</code> is <code>null</code>.
775     * @exception  IllegalArgumentException if <code>key</code> is empty.
776     * @see        #getProperty
777     * @see        java.lang.System#getProperty(java.lang.String)
778     * @see        java.lang.System#getProperty(java.lang.String, java.lang.String)
779     * @see        java.util.PropertyPermission
780     * @see        SecurityManager#checkPermission
781     * @since      1.2
782     */
783    public static String setProperty(String key, String value) {
784        checkKey(key);
785        SecurityManager sm = getSecurityManager();
786        if (sm != null) {
787            sm.checkPermission(new PropertyPermission(key,
788                SecurityConstants.PROPERTY_WRITE_ACTION));
789        }
790
791        return (String) props.setProperty(key, value);
792    }
793
794    /**
795     * Removes the system property indicated by the specified key.
796     * <p>
797     * First, if a security manager exists, its
798     * <code>SecurityManager.checkPermission</code> method
799     * is called with a <code>PropertyPermission(key, "write")</code>
800     * permission. This may result in a SecurityException being thrown.
801     * If no exception is thrown, the specified property is removed.
802     *
803     * @param      key   the name of the system property to be removed.
804     * @return     the previous string value of the system property,
805     *             or <code>null</code> if there was no property with that key.
806     *
807     * @exception  SecurityException  if a security manager exists and its
808     *             <code>checkPropertyAccess</code> method doesn't allow
809     *              access to the specified system property.
810     * @exception  NullPointerException if <code>key</code> is
811     *             <code>null</code>.
812     * @exception  IllegalArgumentException if <code>key</code> is empty.
813     * @see        #getProperty
814     * @see        #setProperty
815     * @see        java.util.Properties
816     * @see        java.lang.SecurityException
817     * @see        java.lang.SecurityManager#checkPropertiesAccess()
818     * @since 1.5
819     */
820    public static String clearProperty(String key) {
821        checkKey(key);
822        SecurityManager sm = getSecurityManager();
823        if (sm != null) {
824            sm.checkPermission(new PropertyPermission(key, "write"));
825        }
826
827        return (String) props.remove(key);
828    }
829
830    private static void checkKey(String key) {
831        if (key == null) {
832            throw new NullPointerException("key can't be null");
833        }
834        if (key.equals("")) {
835            throw new IllegalArgumentException("key can't be empty");
836        }
837    }
838
839    /**
840     * Gets the value of the specified environment variable. An
841     * environment variable is a system-dependent external named
842     * value.
843     *
844     * <p>If a security manager exists, its
845     * {@link SecurityManager#checkPermission checkPermission}
846     * method is called with a
847     * <code>{@link RuntimePermission}("getenv."+name)</code>
848     * permission.  This may result in a {@link SecurityException}
849     * being thrown.  If no exception is thrown the value of the
850     * variable <code>name</code> is returned.
851     *
852     * <p><a name="EnvironmentVSSystemProperties"><i>System
853     * properties</i> and <i>environment variables</i></a> are both
854     * conceptually mappings between names and values.  Both
855     * mechanisms can be used to pass user-defined information to a
856     * Java process.  Environment variables have a more global effect,
857     * because they are visible to all descendants of the process
858     * which defines them, not just the immediate Java subprocess.
859     * They can have subtly different semantics, such as case
860     * insensitivity, on different operating systems.  For these
861     * reasons, environment variables are more likely to have
862     * unintended side effects.  It is best to use system properties
863     * where possible.  Environment variables should be used when a
864     * global effect is desired, or when an external system interface
865     * requires an environment variable (such as <code>PATH</code>).
866     *
867     * <p>On UNIX systems the alphabetic case of <code>name</code> is
868     * typically significant, while on Microsoft Windows systems it is
869     * typically not.  For example, the expression
870     * <code>System.getenv("FOO").equals(System.getenv("foo"))</code>
871     * is likely to be true on Microsoft Windows.
872     *
873     * @param  name the name of the environment variable
874     * @return the string value of the variable, or <code>null</code>
875     *         if the variable is not defined in the system environment
876     * @throws NullPointerException if <code>name</code> is <code>null</code>
877     * @throws SecurityException
878     *         if a security manager exists and its
879     *         {@link SecurityManager#checkPermission checkPermission}
880     *         method doesn't allow access to the environment variable
881     *         <code>name</code>
882     * @see    #getenv()
883     * @see    ProcessBuilder#environment()
884     */
885    public static String getenv(String name) {
886        SecurityManager sm = getSecurityManager();
887        if (sm != null) {
888            sm.checkPermission(new RuntimePermission("getenv."+name));
889        }
890
891        return ProcessEnvironment.getenv(name);
892    }
893
894
895    /**
896     * Returns an unmodifiable string map view of the current system environment.
897     * The environment is a system-dependent mapping from names to
898     * values which is passed from parent to child processes.
899     *
900     * <p>If the system does not support environment variables, an
901     * empty map is returned.
902     *
903     * <p>The returned map will never contain null keys or values.
904     * Attempting to query the presence of a null key or value will
905     * throw a {@link NullPointerException}.  Attempting to query
906     * the presence of a key or value which is not of type
907     * {@link String} will throw a {@link ClassCastException}.
908     *
909     * <p>The returned map and its collection views may not obey the
910     * general contract of the {@link Object#equals} and
911     * {@link Object#hashCode} methods.
912     *
913     * <p>The returned map is typically case-sensitive on all platforms.
914     *
915     * <p>If a security manager exists, its
916     * {@link SecurityManager#checkPermission checkPermission}
917     * method is called with a
918     * <code>{@link RuntimePermission}("getenv.*")</code>
919     * permission.  This may result in a {@link SecurityException} being
920     * thrown.
921     *
922     * <p>When passing information to a Java subprocess,
923     * <a href=#EnvironmentVSSystemProperties>system properties</a>
924     * are generally preferred over environment variables.
925     *
926     * @return the environment as a map of variable names to values
927     * @throws SecurityException
928     *         if a security manager exists and its
929     *         {@link SecurityManager#checkPermission checkPermission}
930     *         method doesn't allow access to the process environment
931     * @see    #getenv(String)
932     * @see    ProcessBuilder#environment()
933     * @since  1.5
934     */
935    public static java.util.Map<String,String> getenv() {
936        SecurityManager sm = getSecurityManager();
937        if (sm != null) {
938            sm.checkPermission(new RuntimePermission("getenv.*"));
939        }
940
941        return ProcessEnvironment.getenv();
942    }
943
944    /**
945     * Terminates the currently running Java Virtual Machine. The
946     * argument serves as a status code; by convention, a nonzero status
947     * code indicates abnormal termination.
948     * <p>
949     * This method calls the <code>exit</code> method in class
950     * <code>Runtime</code>. This method never returns normally.
951     * <p>
952     * The call <code>System.exit(n)</code> is effectively equivalent to
953     * the call:
954     * <blockquote><pre>
955     * Runtime.getRuntime().exit(n)
956     * </pre></blockquote>
957     *
958     * @param      status   exit status.
959     * @throws  SecurityException
960     *        if a security manager exists and its <code>checkExit</code>
961     *        method doesn't allow exit with the specified status.
962     * @see        java.lang.Runtime#exit(int)
963     */
964    public static void exit(int status) {
965        Runtime.getRuntime().exit(status);
966    }
967
968    /**
969     * Runs the garbage collector.
970     * <p>
971     * Calling the <code>gc</code> method suggests that the Java Virtual
972     * Machine expend effort toward recycling unused objects in order to
973     * make the memory they currently occupy available for quick reuse.
974     * When control returns from the method call, the Java Virtual
975     * Machine has made a best effort to reclaim space from all discarded
976     * objects.
977     * <p>
978     * The call <code>System.gc()</code> is effectively equivalent to the
979     * call:
980     * <blockquote><pre>
981     * Runtime.getRuntime().gc()
982     * </pre></blockquote>
983     *
984     * @see     java.lang.Runtime#gc()
985     */
986    public static void gc() {
987        Runtime.getRuntime().gc();
988    }
989
990    /**
991     * Runs the finalization methods of any objects pending finalization.
992     * <p>
993     * Calling this method suggests that the Java Virtual Machine expend
994     * effort toward running the <code>finalize</code> methods of objects
995     * that have been found to be discarded but whose <code>finalize</code>
996     * methods have not yet been run. When control returns from the
997     * method call, the Java Virtual Machine has made a best effort to
998     * complete all outstanding finalizations.
999     * <p>
1000     * The call <code>System.runFinalization()</code> is effectively
1001     * equivalent to the call:
1002     * <blockquote><pre>
1003     * Runtime.getRuntime().runFinalization()
1004     * </pre></blockquote>
1005     *
1006     * @see     java.lang.Runtime#runFinalization()
1007     */
1008    public static void runFinalization() {
1009        Runtime.getRuntime().runFinalization();
1010    }
1011
1012    /**
1013     * Enable or disable finalization on exit; doing so specifies that the
1014     * finalizers of all objects that have finalizers that have not yet been
1015     * automatically invoked are to be run before the Java runtime exits.
1016     * By default, finalization on exit is disabled.
1017     *
1018     * <p>If there is a security manager,
1019     * its <code>checkExit</code> method is first called
1020     * with 0 as its argument to ensure the exit is allowed.
1021     * This could result in a SecurityException.
1022     *
1023     * @deprecated  This method is inherently unsafe.  It may result in
1024     *      finalizers being called on live objects while other threads are
1025     *      concurrently manipulating those objects, resulting in erratic
1026     *      behavior or deadlock.
1027     * @param value indicating enabling or disabling of finalization
1028     * @throws  SecurityException
1029     *        if a security manager exists and its <code>checkExit</code>
1030     *        method doesn't allow the exit.
1031     *
1032     * @see     java.lang.Runtime#exit(int)
1033     * @see     java.lang.Runtime#gc()
1034     * @see     java.lang.SecurityManager#checkExit(int)
1035     * @since   1.1
1036     */
1037    @Deprecated
1038    public static void runFinalizersOnExit(boolean value) {
1039        Runtime.runFinalizersOnExit(value);
1040    }
1041
1042    /**
1043     * Loads the native library specified by the filename argument.  The filename
1044     * argument must be an absolute path name.
1045     *
1046     * If the filename argument, when stripped of any platform-specific library
1047     * prefix, path, and file extension, indicates a library whose name is,
1048     * for example, L, and a native library called L is statically linked
1049     * with the VM, then the JNI_OnLoad_L function exported by the library
1050     * is invoked rather than attempting to load a dynamic library.
1051     * A filename matching the argument does not have to exist in the
1052     * file system.
1053     * See the JNI Specification for more details.
1054     *
1055     * Otherwise, the filename argument is mapped to a native library image in
1056     * an implementation-dependent manner.
1057     *
1058     * <p>
1059     * The call <code>System.load(name)</code> is effectively equivalent
1060     * to the call:
1061     * <blockquote><pre>
1062     * Runtime.getRuntime().load(name)
1063     * </pre></blockquote>
1064     *
1065     * @param      filename   the file to load.
1066     * @exception  SecurityException  if a security manager exists and its
1067     *             <code>checkLink</code> method doesn't allow
1068     *             loading of the specified dynamic library
1069     * @exception  UnsatisfiedLinkError  if either the filename is not an
1070     *             absolute path name, the native library is not statically
1071     *             linked with the VM, or the library cannot be mapped to
1072     *             a native library image by the host system.
1073     * @exception  NullPointerException if <code>filename</code> is
1074     *             <code>null</code>
1075     * @see        java.lang.Runtime#load(java.lang.String)
1076     * @see        java.lang.SecurityManager#checkLink(java.lang.String)
1077     */
1078    @CallerSensitive
1079    public static void load(String filename) {
1080        Runtime.getRuntime().load0(Reflection.getCallerClass(), filename);
1081    }
1082
1083    /**
1084     * Loads the native library specified by the <code>libname</code>
1085     * argument.  The <code>libname</code> argument must not contain any platform
1086     * specific prefix, file extension or path. If a native library
1087     * called <code>libname</code> is statically linked with the VM, then the
1088     * JNI_OnLoad_<code>libname</code> function exported by the library is invoked.
1089     * See the JNI Specification for more details.
1090     *
1091     * Otherwise, the libname argument is loaded from a system library
1092     * location and mapped to a native library image in an implementation-
1093     * dependent manner.
1094     * <p>
1095     * The call <code>System.loadLibrary(name)</code> is effectively
1096     * equivalent to the call
1097     * <blockquote><pre>
1098     * Runtime.getRuntime().loadLibrary(name)
1099     * </pre></blockquote>
1100     *
1101     * @param      libname   the name of the library.
1102     * @exception  SecurityException  if a security manager exists and its
1103     *             <code>checkLink</code> method doesn't allow
1104     *             loading of the specified dynamic library
1105     * @exception  UnsatisfiedLinkError if either the libname argument
1106     *             contains a file path, the native library is not statically
1107     *             linked with the VM,  or the library cannot be mapped to a
1108     *             native library image by the host system.
1109     * @exception  NullPointerException if <code>libname</code> is
1110     *             <code>null</code>
1111     * @see        java.lang.Runtime#loadLibrary(java.lang.String)
1112     * @see        java.lang.SecurityManager#checkLink(java.lang.String)
1113     */
1114    @CallerSensitive
1115    public static void loadLibrary(String libname) {
1116        Runtime.getRuntime().loadLibrary0(Reflection.getCallerClass(), libname);
1117    }
1118
1119    /**
1120     * Maps a library name into a platform-specific string representing
1121     * a native library.
1122     *
1123     * @param      libname the name of the library.
1124     * @return     a platform-dependent native library name.
1125     * @exception  NullPointerException if <code>libname</code> is
1126     *             <code>null</code>
1127     * @see        java.lang.System#loadLibrary(java.lang.String)
1128     * @see        java.lang.ClassLoader#findLibrary(java.lang.String)
1129     * @since      1.2
1130     */
1131    public static native String mapLibraryName(String libname);
1132
1133    /**
1134     * Create PrintStream for stdout/err based on encoding.
1135     */
1136    private static PrintStream newPrintStream(FileOutputStream fos, String enc) {
1137       if (enc != null) {
1138            try {
1139                return new PrintStream(new BufferedOutputStream(fos, 128), true, enc);
1140            } catch (UnsupportedEncodingException uee) {}
1141        }
1142        return new PrintStream(new BufferedOutputStream(fos, 128), true);
1143    }
1144
1145
1146    /**
1147     * Initialize the system class.  Called after thread initialization.
1148     */
1149    private static void initializeSystemClass() {
1150
1151        // VM might invoke JNU_NewStringPlatform() to set those encoding
1152        // sensitive properties (user.home, user.name, boot.class.path, etc.)
1153        // during "props" initialization, in which it may need access, via
1154        // System.getProperty(), to the related system encoding property that
1155        // have been initialized (put into "props") at early stage of the
1156        // initialization. So make sure the "props" is available at the
1157        // very beginning of the initialization and all system properties to
1158        // be put into it directly.
1159        props = new Properties();
1160        initProperties(props);  // initialized by the VM
1161
1162        // There are certain system configurations that may be controlled by
1163        // VM options such as the maximum amount of direct memory and
1164        // Integer cache size used to support the object identity semantics
1165        // of autoboxing.  Typically, the library will obtain these values
1166        // from the properties set by the VM.  If the properties are for
1167        // internal implementation use only, these properties should be
1168        // removed from the system properties.
1169        //
1170        // See java.lang.Integer.IntegerCache and the
1171        // sun.misc.VM.saveAndRemoveProperties method for example.
1172        //
1173        // Save a private copy of the system properties object that
1174        // can only be accessed by the internal implementation.  Remove
1175        // certain system properties that are not intended for public access.
1176        sun.misc.VM.saveAndRemoveProperties(props);
1177
1178
1179        lineSeparator = props.getProperty("line.separator");
1180        sun.misc.Version.init();
1181
1182        FileInputStream fdIn = new FileInputStream(FileDescriptor.in);
1183        FileOutputStream fdOut = new FileOutputStream(FileDescriptor.out);
1184        FileOutputStream fdErr = new FileOutputStream(FileDescriptor.err);
1185        setIn0(new BufferedInputStream(fdIn));
1186        setOut0(newPrintStream(fdOut, props.getProperty("sun.stdout.encoding")));
1187        setErr0(newPrintStream(fdErr, props.getProperty("sun.stderr.encoding")));
1188
1189        // Load the zip library now in order to keep java.util.zip.ZipFile
1190        // from trying to use itself to load this library later.
1191        loadLibrary("zip");
1192
1193        // Setup Java signal handlers for HUP, TERM, and INT (where available).
1194        Terminator.setup();
1195
1196        // Initialize any miscellaneous operating system settings that need to be
1197        // set for the class libraries. Currently this is no-op everywhere except
1198        // for Windows where the process-wide error mode is set before the java.io
1199        // classes are used.
1200        sun.misc.VM.initializeOSEnvironment();
1201
1202        // The main thread is not added to its thread group in the same
1203        // way as other threads; we must do it ourselves here.
1204        Thread current = Thread.currentThread();
1205        current.getThreadGroup().add(current);
1206
1207        // register shared secrets
1208        setJavaLangAccess();
1209
1210        // Subsystems that are invoked during initialization can invoke
1211        // sun.misc.VM.isBooted() in order to avoid doing things that should
1212        // wait until the application class loader has been set up.
1213        // IMPORTANT: Ensure that this remains the last initialization action!
1214        sun.misc.VM.booted();
1215    }
1216
1217    private static void setJavaLangAccess() {
1218        // Allow privileged classes outside of java.lang
1219        sun.misc.SharedSecrets.setJavaLangAccess(new sun.misc.JavaLangAccess(){
1220            public sun.reflect.ConstantPool getConstantPool(Class<?> klass) {
1221                return klass.getConstantPool();
1222            }
1223            public boolean casAnnotationType(Class<?> klass, AnnotationType oldType, AnnotationType newType) {
1224                return klass.casAnnotationType(oldType, newType);
1225            }
1226            public AnnotationType getAnnotationType(Class<?> klass) {
1227                return klass.getAnnotationType();
1228            }
1229            public Map<Class<? extends Annotation>, Annotation> getDeclaredAnnotationMap(Class<?> klass) {
1230                return klass.getDeclaredAnnotationMap();
1231            }
1232            public byte[] getRawClassAnnotations(Class<?> klass) {
1233                return klass.getRawAnnotations();
1234            }
1235            public byte[] getRawClassTypeAnnotations(Class<?> klass) {
1236                return klass.getRawTypeAnnotations();
1237            }
1238            public byte[] getRawExecutableTypeAnnotations(Executable executable) {
1239                return Class.getExecutableTypeAnnotationBytes(executable);
1240            }
1241            public <E extends Enum<E>>
1242                    E[] getEnumConstantsShared(Class<E> klass) {
1243                return klass.getEnumConstantsShared();
1244            }
1245            public void blockedOn(Thread t, Interruptible b) {
1246                t.blockedOn(b);
1247            }
1248            public void registerShutdownHook(int slot, boolean registerShutdownInProgress, Runnable hook) {
1249                Shutdown.add(slot, registerShutdownInProgress, hook);
1250            }
1251            public int getStackTraceDepth(Throwable t) {
1252                return t.getStackTraceDepth();
1253            }
1254            public StackTraceElement getStackTraceElement(Throwable t, int i) {
1255                return t.getStackTraceElement(i);
1256            }
1257            public String newStringUnsafe(char[] chars) {
1258                return new String(chars, true);
1259            }
1260            public Thread newThreadWithAcc(Runnable target, AccessControlContext acc) {
1261                return new Thread(target, acc);
1262            }
1263            public void invokeFinalize(Object o) throws Throwable {
1264                o.finalize();
1265            }
1266            public void formatUnsignedLong(long val, int shift, char[] buf, int offset, int len) {
1267                Long.formatUnsignedLong(val, shift, buf, offset, len);
1268            }
1269            public void formatUnsignedInt(int val, int shift, char[] buf, int offset, int len) {
1270                Integer.formatUnsignedInt(val, shift, buf, offset, len);
1271            }
1272        });
1273    }
1274}
1275