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