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