< prev index next >

src/java.base/share/classes/java/lang/System.java

Print this page

  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  */
  25 package java.lang;
  26 
  27 import java.io.BufferedInputStream;
  28 import java.io.BufferedOutputStream;
  29 import java.io.Console;
  30 import java.io.FileDescriptor;
  31 import java.io.FileInputStream;
  32 import java.io.FileOutputStream;
  33 import java.io.IOException;
  34 import java.io.InputStream;

  35 import java.io.PrintStream;
  36 import java.io.UnsupportedEncodingException;
  37 import java.lang.annotation.Annotation;
  38 import java.lang.invoke.MethodHandle;
  39 import java.lang.invoke.MethodType;
  40 import java.lang.invoke.StringConcatFactory;
  41 import java.lang.module.ModuleDescriptor;
  42 import java.lang.reflect.Constructor;
  43 import java.lang.reflect.Executable;
  44 import java.lang.reflect.Method;
  45 import java.lang.reflect.Modifier;
  46 import java.net.URI;
  47 import java.net.URL;
  48 import java.nio.charset.CharacterCodingException;
  49 import java.nio.channels.Channel;
  50 import java.nio.channels.spi.SelectorProvider;
  51 import java.nio.charset.Charset;
  52 import java.security.AccessControlContext;
  53 import java.security.AccessController;
  54 import java.security.CodeSource;
  55 import java.security.PrivilegedAction;
  56 import java.security.ProtectionDomain;
  57 import java.util.Collections;
  58 import java.util.List;
  59 import java.util.Map;
  60 import java.util.Objects;
  61 import java.util.Properties;
  62 import java.util.PropertyPermission;
  63 import java.util.ResourceBundle;
  64 import java.util.Set;
  65 import java.util.WeakHashMap;

  66 import java.util.function.Supplier;
  67 import java.util.concurrent.ConcurrentHashMap;
  68 import java.util.stream.Stream;
  69 import jdk.internal.misc.Unsafe;
  70 import jdk.internal.util.StaticProperty;
  71 import jdk.internal.module.ModuleBootstrap;
  72 import jdk.internal.module.ServicesCatalog;
  73 import jdk.internal.reflect.CallerSensitive;
  74 import jdk.internal.reflect.Reflection;
  75 import jdk.internal.access.JavaLangAccess;
  76 import jdk.internal.access.SharedSecrets;
  77 import jdk.internal.misc.VM;
  78 import jdk.internal.logger.LoggerFinderLoader;
  79 import jdk.internal.logger.LazyLoggers;
  80 import jdk.internal.logger.LocalizedLoggerWrapper;
  81 import jdk.internal.util.SystemProps;



  82 import jdk.internal.vm.annotation.IntrinsicCandidate;
  83 import jdk.internal.vm.annotation.Stable;


  84 import sun.nio.fs.DefaultFileSystemProvider;
  85 import sun.reflect.annotation.AnnotationType;
  86 import sun.nio.ch.Interruptible;
  87 import sun.security.util.SecurityConstants;
  88 
  89 /**
  90  * The {@code System} class contains several useful class fields
  91  * and methods. It cannot be instantiated.
  92  *
  93  * Among the facilities provided by the {@code System} class
  94  * are standard input, standard output, and error output streams;
  95  * access to externally defined properties and environment
  96  * variables; a means of loading files and libraries; and a utility
  97  * method for quickly copying a portion of an array.
  98  *
  99  * @since   1.0
 100  */
 101 public final class System {
 102     /* Register the natives via the static initializer.
 103      *

1997     public static void loadLibrary(String libname) {
1998         Runtime.getRuntime().loadLibrary0(Reflection.getCallerClass(), libname);
1999     }
2000 
2001     /**
2002      * Maps a library name into a platform-specific string representing
2003      * a native library.
2004      *
2005      * @param      libname the name of the library.
2006      * @return     a platform-dependent native library name.
2007      * @throws     NullPointerException if {@code libname} is {@code null}
2008      * @see        java.lang.System#loadLibrary(java.lang.String)
2009      * @see        java.lang.ClassLoader#findLibrary(java.lang.String)
2010      * @since      1.2
2011      */
2012     public static native String mapLibraryName(String libname);
2013 
2014     /**
2015      * Create PrintStream for stdout/err based on encoding.
2016      */
2017     private static PrintStream newPrintStream(FileOutputStream fos, String enc) {
2018        if (enc != null) {
2019             try {
2020                 return new PrintStream(new BufferedOutputStream(fos, 128), true, enc);
2021             } catch (UnsupportedEncodingException uee) {}
2022         }
2023         return new PrintStream(new BufferedOutputStream(fos, 128), true);
2024     }
2025 
2026     /**
2027      * Logs an exception/error at initialization time to stdout or stderr.
2028      *
2029      * @param printToStderr to print to stderr rather than stdout
2030      * @param printStackTrace to print the stack trace
2031      * @param msg the message to print before the exception, can be {@code null}
2032      * @param e the exception or error
2033      */
2034     private static void logInitException(boolean printToStderr,
2035                                          boolean printStackTrace,
2036                                          String msg,
2037                                          Throwable e) {
2038         if (VM.initLevel() < 1) {
2039             throw new InternalError("system classes not initialized");
2040         }
2041         PrintStream log = (printToStderr) ? err : out;
2042         if (msg != null) {
2043             log.println(msg);

2108         //
2109         // Save a private copy of the system properties object that
2110         // can only be accessed by the internal implementation.
2111         VM.saveProperties(tempProps);
2112         props = createProperties(tempProps);
2113 
2114         StaticProperty.javaHome();          // Load StaticProperty to cache the property values
2115 
2116         lineSeparator = props.getProperty("line.separator");
2117 
2118         FileInputStream fdIn = new FileInputStream(FileDescriptor.in);
2119         FileOutputStream fdOut = new FileOutputStream(FileDescriptor.out);
2120         FileOutputStream fdErr = new FileOutputStream(FileDescriptor.err);
2121         setIn0(new BufferedInputStream(fdIn));
2122         // sun.stdout/err.encoding are set when the VM is associated with the terminal,
2123         // thus they are equivalent to Console.charset(), otherwise the encoding
2124         // defaults to native.encoding
2125         setOut0(newPrintStream(fdOut, props.getProperty("sun.stdout.encoding", StaticProperty.nativeEncoding())));
2126         setErr0(newPrintStream(fdErr, props.getProperty("sun.stderr.encoding", StaticProperty.nativeEncoding())));
2127 




2128         // Setup Java signal handlers for HUP, TERM, and INT (where available).
2129         Terminator.setup();
2130 
2131         // Initialize any miscellaneous operating system settings that need to be
2132         // set for the class libraries. Currently this is no-op everywhere except
2133         // for Windows where the process-wide error mode is set before the java.io
2134         // classes are used.
2135         VM.initializeOSEnvironment();
2136 
2137         // The main thread is not added to its thread group in the same
2138         // way as other threads; we must do it ourselves here.
2139         Thread current = Thread.currentThread();
2140         current.getThreadGroup().add(current);
2141 
2142 
2143         // Subsystems that are invoked during initialization can invoke
2144         // VM.isBooted() in order to avoid doing things that should
2145         // wait until the VM is fully initialized. The initialization level
2146         // is incremented from 0 to 1 here to indicate the first phase of
2147         // initialization has completed.
2148         // IMPORTANT: Ensure that this remains the last initialization action!
2149         VM.initLevel(1);
2150     }
2151 
2152     // @see #initPhase2()
2153     static ModuleLayer bootLayer;
2154 
2155     /*
2156      * Invoked by VM.  Phase 2 module system initialization.
2157      * Only classes in java.base can be loaded in this phase.
2158      *
2159      * @param printToStderr print exceptions to stderr rather than stdout
2160      * @param printStackTrace print stack trace when exception occurs
2161      *
2162      * @return JNI_OK for success, JNI_ERR for failure

2409 
2410             public byte[] getBytesUTF8NoRepl(String s) {
2411                 return String.getBytesUTF8NoRepl(s);
2412             }
2413 
2414             public void inflateBytesToChars(byte[] src, int srcOff, char[] dst, int dstOff, int len) {
2415                 StringLatin1.inflate(src, srcOff, dst, dstOff, len);
2416             }
2417 
2418             public int decodeASCII(byte[] src, int srcOff, char[] dst, int dstOff, int len) {
2419                 return String.decodeASCII(src, srcOff, dst, dstOff, len);
2420             }
2421 
2422             public int encodeASCII(char[] src, int srcOff, byte[] dst, int dstOff, int len) {
2423                 return StringCoding.implEncodeAsciiArray(src, srcOff, dst, dstOff, len);
2424             }
2425 
2426             public void setCause(Throwable t, Throwable cause) {
2427                 t.setCause(cause);
2428             }
2429 
2430             public ProtectionDomain protectionDomain(Class<?> c) {
2431                 return c.protectionDomain();
2432             }
2433 
2434             public MethodHandle stringConcatHelper(String name, MethodType methodType) {
2435                 return StringConcatHelper.lookupStatic(name, methodType);
2436             }
2437 
2438             public long stringConcatInitialCoder() {
2439                 return StringConcatHelper.initialCoder();
2440             }
2441 
2442             public long stringConcatMix(long lengthCoder, String constant) {
2443                 return StringConcatHelper.mix(lengthCoder, constant);
2444             }
2445 
2446             public String join(String prefix, String suffix, String delimiter, String[] elements, int size) {
2447                 return String.join(prefix, suffix, delimiter, elements, size);
2448             }
2449 
2450             public Object classData(Class<?> c) {
2451                 return c.getClassData();
2452             }
2453 
2454             @Override
2455             public long findNative(ClassLoader loader, String entry) {
2456                 return ClassLoader.findNative(loader, entry);
2457             }
2458 
2459             @Override
2460             public void exit(int statusCode) {
2461                 Shutdown.exit(statusCode);
2462             }






















































































2463         });
2464     }
2465 }

  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  */
  25 package java.lang;
  26 
  27 import java.io.BufferedInputStream;
  28 import java.io.BufferedOutputStream;
  29 import java.io.Console;
  30 import java.io.FileDescriptor;
  31 import java.io.FileInputStream;
  32 import java.io.FileOutputStream;
  33 import java.io.IOException;
  34 import java.io.InputStream;
  35 import java.io.OutputStream;
  36 import java.io.PrintStream;
  37 import java.io.UnsupportedEncodingException;
  38 import java.lang.annotation.Annotation;
  39 import java.lang.invoke.MethodHandle;
  40 import java.lang.invoke.MethodType;
  41 import java.lang.invoke.StringConcatFactory;
  42 import java.lang.module.ModuleDescriptor;
  43 import java.lang.reflect.Constructor;
  44 import java.lang.reflect.Executable;
  45 import java.lang.reflect.Method;
  46 import java.lang.reflect.Modifier;
  47 import java.net.URI;
  48 import java.net.URL;
  49 import java.nio.charset.CharacterCodingException;
  50 import java.nio.channels.Channel;
  51 import java.nio.channels.spi.SelectorProvider;
  52 import java.nio.charset.Charset;
  53 import java.security.AccessControlContext;
  54 import java.security.AccessController;
  55 import java.security.CodeSource;
  56 import java.security.PrivilegedAction;
  57 import java.security.ProtectionDomain;
  58 import java.util.Collections;
  59 import java.util.List;
  60 import java.util.Map;
  61 import java.util.Objects;
  62 import java.util.Properties;
  63 import java.util.PropertyPermission;
  64 import java.util.ResourceBundle;
  65 import java.util.Set;
  66 import java.util.WeakHashMap;
  67 import java.util.concurrent.Callable;
  68 import java.util.function.Supplier;
  69 import java.util.concurrent.ConcurrentHashMap;
  70 import java.util.stream.Stream;
  71 import jdk.internal.misc.Unsafe;
  72 import jdk.internal.util.StaticProperty;
  73 import jdk.internal.module.ModuleBootstrap;
  74 import jdk.internal.module.ServicesCatalog;
  75 import jdk.internal.reflect.CallerSensitive;
  76 import jdk.internal.reflect.Reflection;
  77 import jdk.internal.access.JavaLangAccess;
  78 import jdk.internal.access.SharedSecrets;
  79 import jdk.internal.misc.VM;
  80 import jdk.internal.logger.LoggerFinderLoader;
  81 import jdk.internal.logger.LazyLoggers;
  82 import jdk.internal.logger.LocalizedLoggerWrapper;
  83 import jdk.internal.util.SystemProps;
  84 import jdk.internal.vm.Continuation;
  85 import jdk.internal.vm.ContinuationScope;
  86 import jdk.internal.vm.ThreadContainer;
  87 import jdk.internal.vm.annotation.IntrinsicCandidate;
  88 import jdk.internal.vm.annotation.Stable;
  89 import jdk.internal.vm.annotation.ChangesCurrentThread;
  90 import sun.nio.ch.ConsoleStreams;
  91 import sun.nio.fs.DefaultFileSystemProvider;
  92 import sun.reflect.annotation.AnnotationType;
  93 import sun.nio.ch.Interruptible;
  94 import sun.security.util.SecurityConstants;
  95 
  96 /**
  97  * The {@code System} class contains several useful class fields
  98  * and methods. It cannot be instantiated.
  99  *
 100  * Among the facilities provided by the {@code System} class
 101  * are standard input, standard output, and error output streams;
 102  * access to externally defined properties and environment
 103  * variables; a means of loading files and libraries; and a utility
 104  * method for quickly copying a portion of an array.
 105  *
 106  * @since   1.0
 107  */
 108 public final class System {
 109     /* Register the natives via the static initializer.
 110      *

2004     public static void loadLibrary(String libname) {
2005         Runtime.getRuntime().loadLibrary0(Reflection.getCallerClass(), libname);
2006     }
2007 
2008     /**
2009      * Maps a library name into a platform-specific string representing
2010      * a native library.
2011      *
2012      * @param      libname the name of the library.
2013      * @return     a platform-dependent native library name.
2014      * @throws     NullPointerException if {@code libname} is {@code null}
2015      * @see        java.lang.System#loadLibrary(java.lang.String)
2016      * @see        java.lang.ClassLoader#findLibrary(java.lang.String)
2017      * @since      1.2
2018      */
2019     public static native String mapLibraryName(String libname);
2020 
2021     /**
2022      * Create PrintStream for stdout/err based on encoding.
2023      */
2024     private static PrintStream newPrintStream(OutputStream out, String enc) {
2025        if (enc != null) {
2026             try {
2027                 return new PrintStream(new BufferedOutputStream(out, 128), true, enc);
2028             } catch (UnsupportedEncodingException uee) {}
2029         }
2030         return new PrintStream(new BufferedOutputStream(out, 128), true);
2031     }
2032 
2033     /**
2034      * Logs an exception/error at initialization time to stdout or stderr.
2035      *
2036      * @param printToStderr to print to stderr rather than stdout
2037      * @param printStackTrace to print the stack trace
2038      * @param msg the message to print before the exception, can be {@code null}
2039      * @param e the exception or error
2040      */
2041     private static void logInitException(boolean printToStderr,
2042                                          boolean printStackTrace,
2043                                          String msg,
2044                                          Throwable e) {
2045         if (VM.initLevel() < 1) {
2046             throw new InternalError("system classes not initialized");
2047         }
2048         PrintStream log = (printToStderr) ? err : out;
2049         if (msg != null) {
2050             log.println(msg);

2115         //
2116         // Save a private copy of the system properties object that
2117         // can only be accessed by the internal implementation.
2118         VM.saveProperties(tempProps);
2119         props = createProperties(tempProps);
2120 
2121         StaticProperty.javaHome();          // Load StaticProperty to cache the property values
2122 
2123         lineSeparator = props.getProperty("line.separator");
2124 
2125         FileInputStream fdIn = new FileInputStream(FileDescriptor.in);
2126         FileOutputStream fdOut = new FileOutputStream(FileDescriptor.out);
2127         FileOutputStream fdErr = new FileOutputStream(FileDescriptor.err);
2128         setIn0(new BufferedInputStream(fdIn));
2129         // sun.stdout/err.encoding are set when the VM is associated with the terminal,
2130         // thus they are equivalent to Console.charset(), otherwise the encoding
2131         // defaults to native.encoding
2132         setOut0(newPrintStream(fdOut, props.getProperty("sun.stdout.encoding", StaticProperty.nativeEncoding())));
2133         setErr0(newPrintStream(fdErr, props.getProperty("sun.stderr.encoding", StaticProperty.nativeEncoding())));
2134 
2135 //        setIn0(new BufferedInputStream(ConsoleStreams.in));
2136 //        setOut0(newPrintStream(ConsoleStreams.out, props.getProperty("sun.stdout.encoding")));
2137 //        setErr0(newPrintStream(ConsoleStreams.err, props.getProperty("sun.stderr.encoding")));
2138 
2139         // Setup Java signal handlers for HUP, TERM, and INT (where available).
2140         Terminator.setup();
2141 
2142         // Initialize any miscellaneous operating system settings that need to be
2143         // set for the class libraries. Currently this is no-op everywhere except
2144         // for Windows where the process-wide error mode is set before the java.io
2145         // classes are used.
2146         VM.initializeOSEnvironment();
2147 






2148         // Subsystems that are invoked during initialization can invoke
2149         // VM.isBooted() in order to avoid doing things that should
2150         // wait until the VM is fully initialized. The initialization level
2151         // is incremented from 0 to 1 here to indicate the first phase of
2152         // initialization has completed.
2153         // IMPORTANT: Ensure that this remains the last initialization action!
2154         VM.initLevel(1);
2155     }
2156 
2157     // @see #initPhase2()
2158     static ModuleLayer bootLayer;
2159 
2160     /*
2161      * Invoked by VM.  Phase 2 module system initialization.
2162      * Only classes in java.base can be loaded in this phase.
2163      *
2164      * @param printToStderr print exceptions to stderr rather than stdout
2165      * @param printStackTrace print stack trace when exception occurs
2166      *
2167      * @return JNI_OK for success, JNI_ERR for failure

2414 
2415             public byte[] getBytesUTF8NoRepl(String s) {
2416                 return String.getBytesUTF8NoRepl(s);
2417             }
2418 
2419             public void inflateBytesToChars(byte[] src, int srcOff, char[] dst, int dstOff, int len) {
2420                 StringLatin1.inflate(src, srcOff, dst, dstOff, len);
2421             }
2422 
2423             public int decodeASCII(byte[] src, int srcOff, char[] dst, int dstOff, int len) {
2424                 return String.decodeASCII(src, srcOff, dst, dstOff, len);
2425             }
2426 
2427             public int encodeASCII(char[] src, int srcOff, byte[] dst, int dstOff, int len) {
2428                 return StringCoding.implEncodeAsciiArray(src, srcOff, dst, dstOff, len);
2429             }
2430 
2431             public void setCause(Throwable t, Throwable cause) {
2432                 t.setCause(cause);
2433             }
2434             
2435             public ProtectionDomain protectionDomain(Class<?> c) {
2436                 return c.protectionDomain();
2437             }
2438             
2439             public MethodHandle stringConcatHelper(String name, MethodType methodType) {
2440                 return StringConcatHelper.lookupStatic(name, methodType);
2441             }
2442 
2443             public long stringConcatInitialCoder() {
2444                 return StringConcatHelper.initialCoder();
2445             }
2446 
2447             public long stringConcatMix(long lengthCoder, String constant) {
2448                 return StringConcatHelper.mix(lengthCoder, constant);
2449             }
2450 
2451             public String join(String prefix, String suffix, String delimiter, String[] elements, int size) {
2452                 return String.join(prefix, suffix, delimiter, elements, size);
2453             }
2454 
2455             public Object classData(Class<?> c) {
2456                 return c.getClassData();
2457             }
2458 
2459             @Override
2460             public long findNative(ClassLoader loader, String entry) {
2461                 return ClassLoader.findNative(loader, entry);
2462             }
2463 
2464             @Override
2465             public void exit(int statusCode) {
2466                 Shutdown.exit(statusCode);
2467             }
2468             
2469             public Thread[] getAllThreads() {
2470                 return Thread.getAllThreads();
2471             }
2472 
2473             public ThreadContainer threadContainer(Thread thread) {
2474                 return thread.threadContainer();
2475             }
2476 
2477             public void start(Thread thread, ThreadContainer container) {
2478                 thread.start(container);
2479             }
2480 
2481             public ThreadContainer headThreadContainer(Thread thread) {
2482                 return thread.headThreadContainer();
2483             }
2484 
2485             public Object pushThreadContainer(ThreadContainer container) {
2486                 return Thread.currentThread().pushThreadContainer(container);
2487             }
2488 
2489             public void popThreadContainer(ThreadContainer container) {
2490                 Thread.currentThread().popThreadContainer(container);
2491             }
2492 
2493             public Thread currentCarrierThread() {
2494                 return Thread.currentCarrierThread();
2495             }
2496 
2497             @ChangesCurrentThread
2498             public <V> V executeOnCarrierThread(Callable<V> task) throws Exception {
2499                 Thread thread = Thread.currentThread();
2500                 if (thread.isVirtual()) {
2501                     Thread carrier = Thread.currentCarrierThread();
2502                     carrier.setCurrentThread(carrier);
2503                     try {
2504                         return task.call();
2505                     } finally {
2506                         carrier.setCurrentThread(thread);
2507                     }
2508                 } else {
2509                     return task.call();
2510                 }
2511             }
2512 
2513             public <T> T getCarrierThreadLocal(ThreadLocal<T> local) {
2514                 return local.getCarrierThreadLocal();
2515             }
2516 
2517             public <T> void setCarrierThreadLocal(ThreadLocal<T> local, T value) {
2518                 local.setCarrierThreadLocal(value);
2519             }
2520 
2521             public Object[] scopeLocalCache() {
2522                 return Thread.scopeLocalCache();
2523             }
2524 
2525             public void setScopeLocalCache(Object[] cache) {
2526                 Thread.setScopeLocalCache(cache);
2527             }
2528 
2529             public Continuation getContinuation(Thread thread) {
2530                 return thread.getContinuation();
2531             }
2532 
2533             public void setContinuation(Thread thread, Continuation continuation) {
2534                 thread.setContinuation(continuation);
2535             }
2536 
2537             public void parkVirtualThread() {
2538                 ((VirtualThread) Thread.currentThread()).park();
2539             }
2540 
2541             public void parkVirtualThread(long nanos) {
2542                 ((VirtualThread) Thread.currentThread()).parkNanos(nanos);
2543             }
2544 
2545             public void unparkVirtualThread(Thread thread) {
2546                 ((VirtualThread) thread).unpark();
2547             }
2548 
2549             public StackWalker newStackWalkerInstance(Set<StackWalker.Option> options,
2550                                                       ContinuationScope contScope,
2551                                                       Continuation continuation) {
2552                 return StackWalker.newInstance(options, null, contScope, continuation);
2553             }
2554         });
2555     }
2556 }
< prev index next >