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.security.AccessController;
  42 import static java.security.AccessController.doPrivileged;
  43 import java.security.PrivilegedAction;
  44 import java.security.PrivilegedActionException;
  45 import java.security.PrivilegedExceptionAction;
  46 
  47 /**
  48  * java.lang.Process subclass in the UNIX environment.
  49  *
  50  * @author Mario Wolczko and Ross Knippel.
  51  * @author Konstantin Kladko (ported to Linux)
  52  * @author Martin Buchholz
  53  * @author Volker Simonis (ported to AIX)
  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         POSIX_SPAWN(2);
  70 
  71         private int value;
  72         LaunchMechanism(int x) {value = x;}
  73     };
  74 
  75     /* On AIX, the default is to spawn */
  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", "posix_spawn");
 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     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);
 277     public void destroy() {
 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);
 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     private static native void init();
 294 
 295     static {
 296         init();
 297     }
 298 
 299     /**
 300      * A buffered input stream for a subprocess pipe file descriptor
 301      * that allows the underlying file descriptor to be reclaimed when
 302      * the process exits, via the processExited hook.
 303      *
 304      * This is tricky because we do not want the user-level InputStream to be
 305      * closed until the user invokes close(), and we need to continue to be
 306      * able to read any buffered data lingering in the OS pipe buffer.
 307      *
 308      * On AIX this is especially tricky, because the 'close()' system call
 309      * will block if another thread is at the same time blocked in a file
 310      * operation (e.g. 'read()') on the same file descriptor. We therefore
 311      * combine this 'ProcessPipeInputStream' with the DeferredCloseInputStream
 312      * approach used on Solaris (see "UNIXProcess.java.solaris"). This means
 313      * that every potentially blocking operation on the file descriptor
 314      * increments a counter before it is executed and decrements it once it
 315      * finishes. The 'close()' operation will only be executed if there are
 316      * no pending operations. Otherwise it is deferred after the last pending
 317      * operation has finished.
 318      *
 319      */
 320     static class ProcessPipeInputStream extends BufferedInputStream {
 321         private final Object closeLock = new Object();
 322         private int useCount = 0;
 323         private boolean closePending = false;
 324 
 325         ProcessPipeInputStream(int fd) {
 326             super(new FileInputStream(newFileDescriptor(fd)));
 327         }
 328 
 329         private InputStream drainInputStream(InputStream in)
 330                 throws IOException {
 331             int n = 0;
 332             int j;
 333             byte[] a = null;
 334             synchronized (closeLock) {
 335                 if (buf == null) // asynchronous close()?
 336                     return null; // discard
 337                 j = in.available();
 338             }
 339             while (j > 0) {
 340                 a = (a == null) ? new byte[j] : Arrays.copyOf(a, n + j);
 341                 synchronized (closeLock) {
 342                     if (buf == null) // asynchronous close()?
 343                         return null; // discard
 344                     n += in.read(a, n, j);
 345                     j = in.available();
 346                 }
 347             }
 348             return (a == null) ?
 349                     ProcessBuilder.NullInputStream.INSTANCE :
 350                     new ByteArrayInputStream(n == a.length ? a : Arrays.copyOf(a, n));
 351         }
 352 
 353         /** Called by the process reaper thread when the process exits. */
 354         synchronized void processExited() {
 355             try {
 356                 InputStream in = this.in;
 357                 if (in != null) {
 358                     InputStream stragglers = drainInputStream(in);
 359                     in.close();
 360                     this.in = stragglers;
 361                 }
 362             } catch (IOException ignored) { }
 363         }
 364 
 365         private void raise() {
 366             synchronized (closeLock) {
 367                 useCount++;
 368             }
 369         }
 370 
 371         private void lower() throws IOException {
 372             synchronized (closeLock) {
 373                 useCount--;
 374                 if (useCount == 0 && closePending) {
 375                     closePending = false;
 376                     super.close();
 377                 }
 378             }
 379         }
 380 
 381         @Override
 382         public int read() throws IOException {
 383             raise();
 384             try {
 385                 return super.read();
 386             } finally {
 387                 lower();
 388             }
 389         }
 390 
 391         @Override
 392         public int read(byte[] b) throws IOException {
 393             raise();
 394             try {
 395                 return super.read(b);
 396             } finally {
 397                 lower();
 398             }
 399         }
 400 
 401         @Override
 402         public int read(byte[] b, int off, int len) throws IOException {
 403             raise();
 404             try {
 405                 return super.read(b, off, len);
 406             } finally {
 407                 lower();
 408             }
 409         }
 410 
 411         @Override
 412         public long skip(long n) throws IOException {
 413             raise();
 414             try {
 415                 return super.skip(n);
 416             } finally {
 417                 lower();
 418             }
 419         }
 420 
 421         @Override
 422         public int available() throws IOException {
 423             raise();
 424             try {
 425                 return super.available();
 426             } finally {
 427                 lower();
 428             }
 429         }
 430 
 431         @Override
 432         public void close() throws IOException {
 433             // BufferedInputStream#close() is not synchronized unlike most other methods.
 434             // Synchronizing helps avoid racing with drainInputStream().
 435             synchronized (closeLock) {
 436                 if (useCount == 0) {
 437                     super.close();
 438                 }
 439                 else {
 440                     closePending = true;
 441                 }
 442             }
 443         }
 444     }
 445 
 446     /**
 447      * A buffered output stream for a subprocess pipe file descriptor
 448      * that allows the underlying file descriptor to be reclaimed when
 449      * the process exits, via the processExited hook.
 450      */
 451     static class ProcessPipeOutputStream extends BufferedOutputStream {
 452         ProcessPipeOutputStream(int fd) {
 453             super(new FileOutputStream(newFileDescriptor(fd)));
 454         }
 455 
 456         /** Called by the process reaper thread when the process exits. */
 457         synchronized void processExited() {
 458             OutputStream out = this.out;
 459             if (out != null) {
 460                 try {
 461                     out.close();
 462                 } catch (IOException ignored) {
 463                     // We know of no reason to get an IOException, but if
 464                     // we do, there's nothing else to do but carry on.
 465                 }
 466                 this.out = ProcessBuilder.NullOutputStream.INSTANCE;
 467             }
 468         }
 469     }
 470 }