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