1 /*
   2  * Copyright (c) 1995, 2012, 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.BufferedInputStream;
  29 import java.io.BufferedOutputStream;
  30 import java.io.ByteArrayInputStream;
  31 import java.io.FileDescriptor;
  32 import java.io.FileInputStream;
  33 import java.io.FileOutputStream;
  34 import java.io.IOException;
  35 import java.io.InputStream;
  36 import java.io.OutputStream;
  37 import java.util.Arrays;
  38 import java.util.concurrent.Executors;
  39 import java.util.concurrent.Executor;
  40 import java.util.concurrent.ThreadFactory;
  41 import java.util.concurrent.TimeUnit;
  42 import java.security.AccessController;
  43 import static java.security.AccessController.doPrivileged;
  44 import java.security.PrivilegedAction;
  45 import java.security.PrivilegedActionException;
  46 import java.security.PrivilegedExceptionAction;
  47 
  48 /**
  49  * java.lang.Process subclass in the UNIX environment.
  50  *
  51  * @author Mario Wolczko and Ross Knippel.
  52  * @author Konstantin Kladko (ported to Linux)
  53  * @author Martin Buchholz
  54  */
  55 final class UNIXProcess extends Process {
  56     private static final sun.misc.JavaIOFileDescriptorAccess fdAccess
  57         = sun.misc.SharedSecrets.getJavaIOFileDescriptorAccess();
  58 
  59     private final int pid;
  60     private int exitcode;
  61     private boolean hasExited;
  62 
  63     private /* final */ OutputStream stdin;
  64     private /* final */ InputStream  stdout;
  65     private /* final */ InputStream  stderr;
  66 
  67     /* this is for the reaping thread */
  68     private native int waitForProcessExit(int pid);
  69 
  70     /**
  71      * Create a process using fork(2) and exec(2).
  72      *
  73      * @param fds an array of three file descriptors.
  74      *        Indexes 0, 1, and 2 correspond to standard input,
  75      *        standard output and standard error, respectively.  On
  76      *        input, a value of -1 means to create a pipe to connect
  77      *        child and parent processes.  On output, a value which
  78      *        is not -1 is the parent pipe fd corresponding to the
  79      *        pipe which has been created.  An element of this array
  80      *        is -1 on input if and only if it is <em>not</em> -1 on
  81      *        output.
  82      * @return the pid of the subprocess
  83      */
  84     private native int forkAndExec(byte[] prog,
  85                                    byte[] argBlock, int argc,
  86                                    byte[] envBlock, int envc,
  87                                    byte[] dir,
  88                                    int[] fds,
  89                                    boolean redirectErrorStream)
  90         throws IOException;
  91 
  92     /**
  93      * The thread factory used to create "process reaper" daemon threads.
  94      */
  95     private static class ProcessReaperThreadFactory implements ThreadFactory {
  96         private final static ThreadGroup group = getRootThreadGroup();
  97 
  98         private static ThreadGroup getRootThreadGroup() {
  99             return doPrivileged(new PrivilegedAction<ThreadGroup> () {
 100                 public ThreadGroup run() {
 101                     ThreadGroup root = Thread.currentThread().getThreadGroup();
 102                     while (root.getParent() != null)
 103                         root = root.getParent();
 104                     return root;
 105                 }});
 106         }
 107 
 108         public Thread newThread(Runnable grimReaper) {
 109             // Our thread stack requirement is quite modest.
 110             Thread t = new Thread(group, grimReaper, "process reaper", 32768);
 111             t.setDaemon(true);
 112             // A small attempt (probably futile) to avoid priority inversion
 113             t.setPriority(Thread.MAX_PRIORITY);
 114             return t;
 115         }
 116     }
 117 
 118     /**
 119      * The thread pool of "process reaper" daemon threads.
 120      */
 121     private static final Executor processReaperExecutor =
 122         doPrivileged(new PrivilegedAction<Executor>() {
 123             public Executor run() {
 124                 return Executors.newCachedThreadPool
 125                     (new ProcessReaperThreadFactory());
 126             }});
 127 
 128     UNIXProcess(final byte[] prog,
 129                 final byte[] argBlock, final int argc,
 130                 final byte[] envBlock, final int envc,
 131                 final byte[] dir,
 132                 final int[] fds,
 133                 final boolean redirectErrorStream)
 134             throws IOException {
 135 
 136         pid = forkAndExec(prog,
 137                           argBlock, argc,
 138                           envBlock, envc,
 139                           dir,
 140                           fds,
 141                           redirectErrorStream);
 142 
 143         try {
 144             doPrivileged(new PrivilegedExceptionAction<Void>() {
 145                 public Void run() throws IOException {
 146                     initStreams(fds);
 147                     return null;
 148                 }});
 149         } catch (PrivilegedActionException ex) {
 150             throw (IOException) ex.getException();
 151         }
 152     }
 153 
 154     static FileDescriptor newFileDescriptor(int fd) {
 155         FileDescriptor fileDescriptor = new FileDescriptor();
 156         fdAccess.set(fileDescriptor, fd);
 157         return fileDescriptor;
 158     }
 159 
 160     void initStreams(int[] fds) throws IOException {
 161         stdin = (fds[0] == -1) ?
 162             ProcessBuilder.NullOutputStream.INSTANCE :
 163             new ProcessPipeOutputStream(fds[0]);
 164 
 165         stdout = (fds[1] == -1) ?
 166             ProcessBuilder.NullInputStream.INSTANCE :
 167             new ProcessPipeInputStream(fds[1]);
 168 
 169         stderr = (fds[2] == -1) ?
 170             ProcessBuilder.NullInputStream.INSTANCE :
 171             new ProcessPipeInputStream(fds[2]);
 172 
 173         processReaperExecutor.execute(new Runnable() {
 174             public void run() {
 175                 int exitcode = waitForProcessExit(pid);
 176                 UNIXProcess.this.processExited(exitcode);
 177             }});
 178     }
 179 
 180     void processExited(int exitcode) {
 181         synchronized (this) {
 182             this.exitcode = exitcode;
 183             hasExited = true;
 184             notifyAll();
 185         }
 186 
 187         if (stdout instanceof ProcessPipeInputStream)
 188             ((ProcessPipeInputStream) stdout).processExited();
 189 
 190         if (stderr instanceof ProcessPipeInputStream)
 191             ((ProcessPipeInputStream) stderr).processExited();
 192 
 193         if (stdin instanceof ProcessPipeOutputStream)
 194             ((ProcessPipeOutputStream) stdin).processExited();
 195     }
 196 
 197     public OutputStream getOutputStream() {
 198         return stdin;
 199     }
 200 
 201     public InputStream getInputStream() {
 202         return stdout;
 203     }
 204 
 205     public InputStream getErrorStream() {
 206         return stderr;
 207     }
 208 
 209     public synchronized int waitFor() throws InterruptedException {
 210         while (!hasExited) {
 211             wait();
 212         }
 213         return exitcode;
 214     }
 215     
 216     @Override
 217     public synchronized boolean waitFor(long timeout, TimeUnit unit) 
 218         throws InterruptedException {
 219         if (hasExited) return true;
 220         if (timeout <= 0) return false;              
 221                 
 222         long now = System.nanoTime();
 223         long end = now + TimeUnit.NANOSECONDS.convert(timeout, unit);
 224         if (end <= 0) // overflow
 225             end = Long.MAX_VALUE;
 226         
 227         long rem = end - now;
 228         while (!hasExited && (rem > 0)) {
 229             wait(TimeUnit.NANOSECONDS.toMillis(rem));
 230             rem = end - System.nanoTime();
 231         }
 232         return hasExited;
 233     }
 234 
 235     public synchronized int exitValue() {
 236         if (!hasExited) {
 237             throw new IllegalThreadStateException("process hasn't exited");
 238         }
 239         return exitcode;
 240     }
 241 
 242     private static native void destroyProcess(int pid, boolean force);
 243     private void destroy(boolean force) {
 244         // There is a risk that pid will be recycled, causing us to
 245         // kill the wrong process!  So we only terminate processes
 246         // that appear to still be running.  Even with this check,
 247         // there is an unavoidable race condition here, but the window
 248         // is very small, and OSes try hard to not recycle pids too
 249         // soon, so this is quite safe.
 250         synchronized (this) {
 251             if (!hasExited)
 252                 destroyProcess(pid, force);
 253         }
 254         try { stdin.close();  } catch (IOException ignored) {}
 255         try { stdout.close(); } catch (IOException ignored) {}
 256         try { stderr.close(); } catch (IOException ignored) {}
 257     }
 258 
 259     public void destroy() {
 260         destroy(false);
 261     }
 262 
 263     @Override
 264     public Process destroyForcibly() {
 265         destroy(true);
 266         return this;
 267     }
 268 
 269     @Override
 270     public synchronized boolean isAlive() {
 271         return !hasExited;
 272     }
 273 
 274     /* This routine initializes JNI field offsets for the class */
 275     private static native void initIDs();
 276 
 277     static {
 278         initIDs();
 279     }
 280 
 281     /**
 282      * A buffered input stream for a subprocess pipe file descriptor
 283      * that allows the underlying file descriptor to be reclaimed when
 284      * the process exits, via the processExited hook.
 285      *
 286      * This is tricky because we do not want the user-level InputStream to be
 287      * closed until the user invokes close(), and we need to continue to be
 288      * able to read any buffered data lingering in the OS pipe buffer.
 289      */
 290     static class ProcessPipeInputStream extends BufferedInputStream {
 291         ProcessPipeInputStream(int fd) {
 292             super(new FileInputStream(newFileDescriptor(fd)));
 293         }
 294 
 295         private static byte[] drainInputStream(InputStream in)
 296                 throws IOException {
 297             if (in == null) return null;
 298             int n = 0;
 299             int j;
 300             byte[] a = null;
 301             while ((j = in.available()) > 0) {
 302                 a = (a == null) ? new byte[j] : Arrays.copyOf(a, n + j);
 303                 n += in.read(a, n, j);
 304             }
 305             return (a == null || n == a.length) ? a : Arrays.copyOf(a, n);
 306         }
 307 
 308         /** Called by the process reaper thread when the process exits. */
 309         synchronized void processExited() {
 310             // Most BufferedInputStream methods are synchronized, but close()
 311             // is not, and so we have to handle concurrent racing close().
 312             try {
 313                 InputStream in = this.in;
 314                 if (in != null) {
 315                     byte[] stragglers = drainInputStream(in);
 316                     in.close();
 317                     this.in = (stragglers == null) ?
 318                         ProcessBuilder.NullInputStream.INSTANCE :
 319                         new ByteArrayInputStream(stragglers);
 320                     if (buf == null) // asynchronous close()?
 321                         this.in = null;
 322                 }
 323             } catch (IOException ignored) {
 324                 // probably an asynchronous close().
 325             }
 326         }
 327     }
 328 
 329     /**
 330      * A buffered output stream for a subprocess pipe file descriptor
 331      * that allows the underlying file descriptor to be reclaimed when
 332      * the process exits, via the processExited hook.
 333      */
 334     static class ProcessPipeOutputStream extends BufferedOutputStream {
 335         ProcessPipeOutputStream(int fd) {
 336             super(new FileOutputStream(newFileDescriptor(fd)));
 337         }
 338 
 339         /** Called by the process reaper thread when the process exits. */
 340         synchronized void processExited() {
 341             OutputStream out = this.out;
 342             if (out != null) {
 343                 try {
 344                     out.close();
 345                 } catch (IOException ignored) {
 346                     // We know of no reason to get an IOException, but if
 347                     // we do, there's nothing else to do but carry on.
 348                 }
 349                 this.out = ProcessBuilder.NullOutputStream.INSTANCE;
 350             }
 351         }
 352     }
 353 }