1 /*
   2  * Copyright (c) 1995, 2013, 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     private static enum LaunchMechanism {
  68         FORK(1),
  69         VFORK(3);
  70 
  71         private int value;
  72         LaunchMechanism(int x) {value = x;}
  73     };
  74 
  75     /* default is VFORK on Linux */
  76     private static final LaunchMechanism launchMechanism;
  77     private static byte[] helperpath;
  78 
  79     private static byte[] toCString(String s) {
  80         if (s == null)
  81             return null;
  82         byte[] bytes = s.getBytes();
  83         byte[] result = new byte[bytes.length + 1];
  84         System.arraycopy(bytes, 0,
  85                          result, 0,
  86                          bytes.length);
  87         result[result.length-1] = (byte)0;
  88         return result;
  89     }
  90 
  91     static {
  92         launchMechanism = AccessController.doPrivileged(
  93                 new PrivilegedAction<LaunchMechanism>()
  94         {
  95             public LaunchMechanism run() {
  96                 String javahome = System.getProperty("java.home");
  97                 String osArch = System.getProperty("os.arch");
  98 
  99                 helperpath = toCString(javahome + "/lib/" + osArch + "/jspawnhelper");
 100                 String s = System.getProperty(
 101                     "jdk.lang.Process.launchMechanism", "vfork");
 102 
 103                 try {
 104                     return LaunchMechanism.valueOf(s.toUpperCase());
 105                 } catch (IllegalArgumentException e) {
 106                     throw new Error(s + " is not a supported " +
 107                         "process launch mechanism on this platform.");
 108                 }
 109             }
 110         });
 111     }
 112 
 113     /* this is for the reaping thread */
 114     private native int waitForProcessExit(int pid);
 115 
 116     /**
 117      * Create a process. Depending on the mode flag, this is done by
 118      * one of the following mechanisms.
 119      * - fork(2) and exec(2)
 120      * - clone(2) and exec(2)
 121      * - vfork(2) and exec(2)
 122      *
 123      * @param fds an array of three file descriptors.
 124      *        Indexes 0, 1, and 2 correspond to standard input,
 125      *        standard output and standard error, respectively.  On
 126      *        input, a value of -1 means to create a pipe to connect
 127      *        child and parent processes.  On output, a value which
 128      *        is not -1 is the parent pipe fd corresponding to the
 129      *        pipe which has been created.  An element of this array
 130      *        is -1 on input if and only if it is <em>not</em> -1 on
 131      *        output.
 132      * @return the pid of the subprocess
 133      */
 134     private native int forkAndExec(int mode, byte[] helperpath,
 135                                    byte[] prog,
 136                                    byte[] argBlock, int argc,
 137                                    byte[] envBlock, int envc,
 138                                    byte[] dir,
 139                                    int[] fds,
 140                                    boolean redirectErrorStream)
 141         throws IOException;
 142 
 143     /**
 144      * The thread factory used to create "process reaper" daemon threads.
 145      */
 146     private static class ProcessReaperThreadFactory implements ThreadFactory {
 147         private final static ThreadGroup group = getRootThreadGroup();
 148 
 149         private static ThreadGroup getRootThreadGroup() {
 150             return doPrivileged(new PrivilegedAction<ThreadGroup> () {
 151                 public ThreadGroup run() {
 152                     ThreadGroup root = Thread.currentThread().getThreadGroup();
 153                     while (root.getParent() != null)
 154                         root = root.getParent();
 155                     return root;
 156                 }});
 157         }
 158 
 159         public Thread newThread(Runnable grimReaper) {
 160             // Our thread stack requirement is quite modest.
 161             Thread t = new Thread(group, grimReaper, "process reaper", 32768);
 162             t.setDaemon(true);
 163             // A small attempt (probably futile) to avoid priority inversion
 164             t.setPriority(Thread.MAX_PRIORITY);
 165             return t;
 166         }
 167     }
 168 
 169     /**
 170      * The thread pool of "process reaper" daemon threads.
 171      */
 172     private static final Executor processReaperExecutor =
 173         doPrivileged(new PrivilegedAction<Executor>() {
 174             public Executor run() {
 175                 return Executors.newCachedThreadPool
 176                     (new ProcessReaperThreadFactory());
 177             }});
 178 
 179     UNIXProcess(final byte[] prog,
 180                 final byte[] argBlock, final int argc,
 181                 final byte[] envBlock, final int envc,
 182                 final byte[] dir,
 183                 final int[] fds,
 184                 final boolean redirectErrorStream)
 185             throws IOException {
 186 
 187         pid = forkAndExec(launchMechanism.value,
 188                           helperpath,
 189                           prog,
 190                           argBlock, argc,
 191                           envBlock, envc,
 192                           dir,
 193                           fds,
 194                           redirectErrorStream);
 195 
 196         try {
 197             doPrivileged(new PrivilegedExceptionAction<Void>() {
 198                 public Void run() throws IOException {
 199                     initStreams(fds);
 200                     return null;
 201                 }});
 202         } catch (PrivilegedActionException ex) {
 203             throw (IOException) ex.getException();
 204         }
 205     }
 206 
 207     static FileDescriptor newFileDescriptor(int fd) {
 208         FileDescriptor fileDescriptor = new FileDescriptor();
 209         fdAccess.set(fileDescriptor, fd);
 210         return fileDescriptor;
 211     }
 212 
 213     void initStreams(int[] fds) throws IOException {
 214         stdin = (fds[0] == -1) ?
 215             ProcessBuilder.NullOutputStream.INSTANCE :
 216             new ProcessPipeOutputStream(fds[0]);
 217 
 218         stdout = (fds[1] == -1) ?
 219             ProcessBuilder.NullInputStream.INSTANCE :
 220             new ProcessPipeInputStream(fds[1]);
 221 
 222         stderr = (fds[2] == -1) ?
 223             ProcessBuilder.NullInputStream.INSTANCE :
 224             new ProcessPipeInputStream(fds[2]);
 225 
 226         processReaperExecutor.execute(new Runnable() {
 227             public void run() {
 228                 int exitcode = waitForProcessExit(pid);
 229                 UNIXProcess.this.processExited(exitcode);
 230             }});
 231     }
 232 
 233     void processExited(int exitcode) {
 234         synchronized (this) {
 235             this.exitcode = exitcode;
 236             hasExited = true;
 237             notifyAll();
 238         }
 239 
 240         if (stdout instanceof ProcessPipeInputStream)
 241             ((ProcessPipeInputStream) stdout).processExited();
 242 
 243         if (stderr instanceof ProcessPipeInputStream)
 244             ((ProcessPipeInputStream) stderr).processExited();
 245 
 246         if (stdin instanceof ProcessPipeOutputStream)
 247             ((ProcessPipeOutputStream) stdin).processExited();
 248     }
 249 
 250     public OutputStream getOutputStream() {
 251         return stdin;
 252     }
 253 
 254     public InputStream getInputStream() {
 255         return stdout;
 256     }
 257 
 258     public InputStream getErrorStream() {
 259         return stderr;
 260     }
 261 
 262     public synchronized int waitFor() throws InterruptedException {
 263         while (!hasExited) {
 264             wait();
 265         }
 266         return exitcode;
 267     }
 268 
 269     @Override
 270     public synchronized boolean waitFor(long timeout, TimeUnit unit)
 271         throws InterruptedException
 272     {
 273         if (hasExited) return true;
 274         if (timeout <= 0) return false;
 275 
 276         long timeoutAsNanos = unit.toNanos(timeout);
 277         long startTime = System.nanoTime();
 278         long rem = timeoutAsNanos;
 279 
 280         while (!hasExited && (rem > 0)) {
 281             wait(Math.max(TimeUnit.NANOSECONDS.toMillis(rem), 1));
 282             rem = timeoutAsNanos - (System.nanoTime() - startTime);
 283         }
 284         return hasExited;
 285     }
 286 
 287     public synchronized int exitValue() {
 288         if (!hasExited) {
 289             throw new IllegalThreadStateException("process hasn't exited");
 290         }
 291         return exitcode;
 292     }
 293 
 294     private static native void destroyProcess(int pid, boolean force);
 295     private void destroy(boolean force) {
 296         // There is a risk that pid will be recycled, causing us to
 297         // kill the wrong process!  So we only terminate processes
 298         // that appear to still be running.  Even with this check,
 299         // there is an unavoidable race condition here, but the window
 300         // is very small, and OSes try hard to not recycle pids too
 301         // soon, so this is quite safe.
 302         synchronized (this) {
 303             if (!hasExited)
 304                 destroyProcess(pid, force);
 305         }
 306         try { stdin.close();  } catch (IOException ignored) {}
 307         try { stdout.close(); } catch (IOException ignored) {}
 308         try { stderr.close(); } catch (IOException ignored) {}
 309     }
 310 
 311     public void destroy() {
 312         destroy(false);
 313     }
 314 
 315     @Override
 316     public Process destroyForcibly() {
 317         destroy(true);
 318         return this;
 319     }
 320 
 321     @Override
 322     public synchronized boolean isAlive() {
 323         return !hasExited;
 324     }
 325 
 326     private static native void init();
 327 
 328     static {
 329         init();
 330     }
 331 
 332     /**
 333      * A buffered input stream for a subprocess pipe file descriptor
 334      * that allows the underlying file descriptor to be reclaimed when
 335      * the process exits, via the processExited hook.
 336      *
 337      * This is tricky because we do not want the user-level InputStream to be
 338      * closed until the user invokes close(), and we need to continue to be
 339      * able to read any buffered data lingering in the OS pipe buffer.
 340      */
 341     static class ProcessPipeInputStream extends BufferedInputStream {
 342         private final Object closeLock = new Object();
 343 
 344         ProcessPipeInputStream(int fd) {
 345             super(new FileInputStream(newFileDescriptor(fd)));
 346         }
 347         private static byte[] drainInputStream(InputStream in)
 348                 throws IOException {
 349             int n = 0;
 350             int j;
 351             byte[] a = null;
 352             while ((j = in.available()) > 0) {
 353                 a = (a == null) ? new byte[j] : Arrays.copyOf(a, n + j);
 354                 n += in.read(a, n, j);
 355             }
 356             return (a == null || n == a.length) ? a : Arrays.copyOf(a, n);
 357         }
 358 
 359         /** Called by the process reaper thread when the process exits. */
 360         synchronized void processExited() {
 361             synchronized (closeLock) {
 362                 try {
 363                     InputStream in = this.in;
 364                     // this stream is closed if and only if: in == null
 365                     if (in != null) {
 366                         byte[] stragglers = drainInputStream(in);
 367                         in.close();
 368                         this.in = (stragglers == null) ?
 369                             ProcessBuilder.NullInputStream.INSTANCE :
 370                             new ByteArrayInputStream(stragglers);
 371                     }
 372                 } catch (IOException ignored) {}
 373             }
 374         }
 375 
 376         @Override
 377         public void close() throws IOException {
 378             // BufferedInputStream#close() is not synchronized unlike most other methods.
 379             // Synchronizing helps avoid race with processExited().
 380             synchronized (closeLock) {
 381                 super.close();
 382             }
 383         }
 384     }
 385 
 386     /**
 387      * A buffered output stream for a subprocess pipe file descriptor
 388      * that allows the underlying file descriptor to be reclaimed when
 389      * the process exits, via the processExited hook.
 390      */
 391     static class ProcessPipeOutputStream extends BufferedOutputStream {
 392         ProcessPipeOutputStream(int fd) {
 393             super(new FileOutputStream(newFileDescriptor(fd)));
 394         }
 395 
 396         /** Called by the process reaper thread when the process exits. */
 397         synchronized void processExited() {
 398             OutputStream out = this.out;
 399             if (out != null) {
 400                 try {
 401                     out.close();
 402                 } catch (IOException ignored) {
 403                     // We know of no reason to get an IOException, but if
 404                     // we do, there's nothing else to do but carry on.
 405                 }
 406                 this.out = ProcessBuilder.NullOutputStream.INSTANCE;
 407             }
 408         }
 409     }
 410 }