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