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