1 /*
   2  * Copyright (c) 1995, 2010, 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  */
  25 
  26 package java.lang;
  27 
  28 import java.io.IOException;
  29 import java.io.File;
  30 import java.io.InputStream;
  31 import java.io.OutputStream;
  32 import java.io.FileInputStream;
  33 import java.io.FileOutputStream;
  34 import java.io.FileDescriptor;
  35 import java.io.BufferedInputStream;
  36 import java.io.BufferedOutputStream;
  37 import java.lang.ProcessBuilder.Redirect;
  38 import java.security.AccessController;
  39 import java.security.PrivilegedAction;
  40 
  41 /* This class is for the exclusive use of ProcessBuilder.start() to
  42  * create new processes.
  43  *
  44  * @author Martin Buchholz
  45  * @since   1.5
  46  */
  47 
  48 final class ProcessImpl extends Process {
  49     private static final sun.misc.JavaIOFileDescriptorAccess fdAccess
  50         = sun.misc.SharedSecrets.getJavaIOFileDescriptorAccess();
  51 
  52     /**
  53      * Open a file for writing. If {@code append} is {@code true} then the file
  54      * is opened for atomic append directly and a FileOutputStream constructed
  55      * with the resulting handle. This is because a FileOutputStream created
  56      * to append to a file does not open the file in a manner that guarantees
  57      * that writes by the child process will be atomic.
  58      */
  59     private static FileOutputStream newFileOutputStream(File f, boolean append)
  60         throws IOException
  61     {
  62         if (append) {
  63             String path = f.getPath();
  64             SecurityManager sm = System.getSecurityManager();
  65             if (sm != null)
  66                 sm.checkWrite(path);
  67             long handle = openForAtomicAppend(path);
  68             final FileDescriptor fd = new FileDescriptor();
  69             fdAccess.setHandle(fd, handle);
  70             return AccessController.doPrivileged(
  71                 new PrivilegedAction<FileOutputStream>() {
  72                     public FileOutputStream run() {
  73                         return new FileOutputStream(fd);
  74                     }
  75                 }
  76             );
  77         } else {
  78             return new FileOutputStream(f);
  79         }
  80     }
  81 
  82     // System-dependent portion of ProcessBuilder.start()
  83     static Process start(String cmdarray[],
  84                          java.util.Map<String,String> environment,
  85                          String dir,
  86                          ProcessBuilder.Redirect[] redirects,
  87                          boolean redirectErrorStream)
  88         throws IOException
  89     {
  90         String envblock = ProcessEnvironment.toEnvironmentBlock(environment);
  91 
  92         FileInputStream  f0 = null;
  93         FileOutputStream f1 = null;
  94         FileOutputStream f2 = null;
  95 
  96         try {
  97             long[] stdHandles;
  98             if (redirects == null) {
  99                 stdHandles = new long[] { -1L, -1L, -1L };
 100             } else {
 101                 stdHandles = new long[3];
 102 
 103                 if (redirects[0] == Redirect.PIPE)
 104                     stdHandles[0] = -1L;
 105                 else if (redirects[0] == Redirect.INHERIT)
 106                     stdHandles[0] = fdAccess.getHandle(FileDescriptor.in);
 107                 else {
 108                     f0 = new FileInputStream(redirects[0].file());
 109                     stdHandles[0] = fdAccess.getHandle(f0.getFD());
 110                 }
 111 
 112                 if (redirects[1] == Redirect.PIPE)
 113                     stdHandles[1] = -1L;
 114                 else if (redirects[1] == Redirect.INHERIT)
 115                     stdHandles[1] = fdAccess.getHandle(FileDescriptor.out);
 116                 else {
 117                     f1 = newFileOutputStream(redirects[1].file(),
 118                                              redirects[1].append());
 119                     stdHandles[1] = fdAccess.getHandle(f1.getFD());
 120                 }
 121 
 122                 if (redirects[2] == Redirect.PIPE)
 123                     stdHandles[2] = -1L;
 124                 else if (redirects[2] == Redirect.INHERIT)
 125                     stdHandles[2] = fdAccess.getHandle(FileDescriptor.err);
 126                 else {
 127                     f2 = newFileOutputStream(redirects[2].file(),
 128                                              redirects[2].append());
 129                     stdHandles[2] = fdAccess.getHandle(f2.getFD());
 130                 }
 131             }
 132 
 133             return new ProcessImpl(cmdarray, envblock, dir,
 134                                    stdHandles, redirectErrorStream);
 135         } finally {
 136             // In theory, close() can throw IOException
 137             // (although it is rather unlikely to happen here)
 138             try { if (f0 != null) f0.close(); }
 139             finally {
 140                 try { if (f1 != null) f1.close(); }
 141                 finally { if (f2 != null) f2.close(); }
 142             }
 143         }
 144 
 145     }
 146 
 147     private long handle = 0;
 148     private OutputStream stdin_stream;
 149     private InputStream stdout_stream;
 150     private InputStream stderr_stream;
 151 
 152     private ProcessImpl(final String cmd[],
 153                         final String envblock,
 154                         final String path,
 155                         final long[] stdHandles,
 156                         final boolean redirectErrorStream)
 157         throws IOException
 158     {
 159         // Win32 CreateProcess requires cmd[0] to be normalized
 160         cmd[0] = new File(cmd[0]).getPath();
 161 
 162         StringBuilder cmdbuf = new StringBuilder(80);
 163         for (int i = 0; i < cmd.length; i++) {
 164             if (i > 0) {
 165                 cmdbuf.append(' ');
 166             }
 167             String s = cmd[i];
 168             if (s.indexOf(' ') >= 0 || s.indexOf('\t') >= 0) {
 169                 if (s.charAt(0) != '"') {
 170                     cmdbuf.append('"');
 171                     cmdbuf.append(s);
 172                     if (s.endsWith("\\")) {
 173                         cmdbuf.append("\\");
 174                     }
 175                     cmdbuf.append('"');
 176                 } else if (s.endsWith("\"")) {
 177                     /* The argument has already been quoted. */
 178                     cmdbuf.append(s);
 179                 } else {
 180                     /* Unmatched quote for the argument. */
 181                     throw new IllegalArgumentException();
 182                 }
 183             } else {
 184                 cmdbuf.append(s);
 185             }
 186         }
 187         String cmdstr = cmdbuf.toString();
 188 
 189         handle = create(cmdstr, envblock, path,
 190                         stdHandles, redirectErrorStream);
 191 
 192         java.security.AccessController.doPrivileged(
 193         new java.security.PrivilegedAction<Void>() {
 194         public Void run() {
 195             if (stdHandles[0] == -1L)
 196                 stdin_stream = ProcessBuilder.NullOutputStream.INSTANCE;
 197             else {
 198                 FileDescriptor stdin_fd = new FileDescriptor();
 199                 fdAccess.setHandle(stdin_fd, stdHandles[0]);
 200                 stdin_stream = new BufferedOutputStream(
 201                     new FileOutputStream(stdin_fd));
 202             }
 203 
 204             if (stdHandles[1] == -1L)
 205                 stdout_stream = ProcessBuilder.NullInputStream.INSTANCE;
 206             else {
 207                 FileDescriptor stdout_fd = new FileDescriptor();
 208                 fdAccess.setHandle(stdout_fd, stdHandles[1]);
 209                 stdout_stream = new BufferedInputStream(
 210                     new FileInputStream(stdout_fd));
 211             }
 212 
 213             if (stdHandles[2] == -1L)
 214                 stderr_stream = ProcessBuilder.NullInputStream.INSTANCE;
 215             else {
 216                 FileDescriptor stderr_fd = new FileDescriptor();
 217                 fdAccess.setHandle(stderr_fd, stdHandles[2]);
 218                 stderr_stream = new FileInputStream(stderr_fd);
 219             }
 220 
 221             return null; }});
 222     }
 223 
 224     public OutputStream getOutputStream() {
 225         return stdin_stream;
 226     }
 227 
 228     public InputStream getInputStream() {
 229         return stdout_stream;
 230     }
 231 
 232     public InputStream getErrorStream() {
 233         return stderr_stream;
 234     }
 235 
 236     public void finalize() {
 237         closeHandle(handle);
 238     }
 239 
 240     private static final int STILL_ACTIVE = getStillActive();
 241     private static native int getStillActive();
 242 
 243     public int exitValue() {
 244         int exitCode = getExitCodeProcess(handle);
 245         if (exitCode == STILL_ACTIVE)
 246             throw new IllegalThreadStateException("process has not exited");
 247         return exitCode;
 248     }
 249     private static native int getExitCodeProcess(long handle);
 250 
 251     public int waitFor() throws InterruptedException {
 252         waitForInterruptibly(handle);
 253         if (Thread.interrupted())
 254             throw new InterruptedException();
 255         return exitValue();
 256     }
 257     private static native void waitForInterruptibly(long handle);
 258 
 259     public void destroy() { terminateProcess(handle); }
 260     private static native void terminateProcess(long handle);
 261 
 262     /**
 263      * Create a process using the win32 function CreateProcess.
 264      *
 265      * @param cmdstr the Windows commandline
 266      * @param envblock NUL-separated, double-NUL-terminated list of
 267      *        environment strings in VAR=VALUE form
 268      * @param dir the working directory of the process, or null if
 269      *        inheriting the current directory from the parent process
 270      * @param stdHandles array of windows HANDLEs.  Indexes 0, 1, and
 271      *        2 correspond to standard input, standard output and
 272      *        standard error, respectively.  On input, a value of -1
 273      *        means to create a pipe to connect child and parent
 274      *        processes.  On output, a value which is not -1 is the
 275      *        parent pipe handle corresponding to the pipe which has
 276      *        been created.  An element of this array is -1 on input
 277      *        if and only if it is <em>not</em> -1 on output.
 278      * @param redirectErrorStream redirectErrorStream attribute
 279      * @return the native subprocess HANDLE returned by CreateProcess
 280      */
 281     private static native long create(String cmdstr,
 282                                       String envblock,
 283                                       String dir,
 284                                       long[] stdHandles,
 285                                       boolean redirectErrorStream)
 286         throws IOException;
 287 
 288     /**
 289      * Opens a file for atomic append. The file is created if it doesn't
 290      * already exist.
 291      *
 292      * @param file the file to open or create
 293      * @return the native HANDLE
 294      */
 295     private static native long openForAtomicAppend(String path)
 296         throws IOException;
 297 
 298     private static native boolean closeHandle(long handle);
 299 }