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