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