1 /* 2 * Copyright (c) 1995, 2013, 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.FileDescriptor; 31 import java.io.FileInputStream; 32 import java.io.FileOutputStream; 33 import java.io.IOException; 34 import java.io.InputStream; 35 import java.io.OutputStream; 36 import java.util.concurrent.Executors; 37 import java.util.concurrent.Executor; 38 import java.util.concurrent.ThreadFactory; 39 import java.util.concurrent.TimeUnit; 40 import java.security.AccessController; 41 import static java.security.AccessController.doPrivileged; 42 import java.security.PrivilegedAction; 43 import java.security.PrivilegedActionException; 44 import java.security.PrivilegedExceptionAction; 45 46 /* java.lang.Process subclass in the UNIX environment. 47 * 48 * @author Mario Wolczko and Ross Knippel. 49 */ 50 51 final class UNIXProcess extends Process { 52 private static final sun.misc.JavaIOFileDescriptorAccess fdAccess 53 = sun.misc.SharedSecrets.getJavaIOFileDescriptorAccess(); 54 55 private final int pid; 56 private int exitcode; 57 private boolean hasExited; 58 59 private OutputStream stdin_stream; 60 private InputStream stdout_stream; 61 private DeferredCloseInputStream stdout_inner_stream; 62 private InputStream stderr_stream; 63 64 private static enum LaunchMechanism { 65 FORK(1), 66 POSIX_SPAWN(2); 67 68 private int value; 69 LaunchMechanism(int x) {value = x;} 70 }; 71 72 /* On Solaris, the default is to spawn */ 73 private static final LaunchMechanism launchMechanism; 74 private static byte[] helperpath; 75 76 private static byte[] toCString(String s) { 77 if (s == null) 78 return null; 79 byte[] bytes = s.getBytes(); 80 byte[] result = new byte[bytes.length + 1]; 81 System.arraycopy(bytes, 0, 82 result, 0, 83 bytes.length); 84 result[result.length-1] = (byte)0; 85 return result; 86 } 87 88 static { 89 launchMechanism = AccessController.doPrivileged( 90 new PrivilegedAction<LaunchMechanism>() 91 { 92 public LaunchMechanism run() { 93 String javahome = System.getProperty("java.home"); 94 String osArch = System.getProperty("os.arch"); 95 if (osArch.equals("x86")) { 96 osArch = "i386"; 97 } else if (osArch.equals("x86_64")) { 98 osArch = "amd64"; 99 } 100 101 helperpath = toCString(javahome + "/lib/" + osArch + "/jspawnhelper"); 102 String s = System.getProperty( 103 "jdk.lang.Process.launchMechanism", "posix_spawn"); 104 105 try { 106 return LaunchMechanism.valueOf(s.toUpperCase()); 107 } catch (IllegalArgumentException e) { 108 throw new Error(s + " is not a supported " + 109 "process launch mechanism on this platform."); 110 } 111 } 112 }); 113 } 114 115 /* this is for the reaping thread */ 116 private native int waitForProcessExit(int pid); 117 118 /** 119 * Create a process. Depending on the mode flag, this is done by 120 * one of the following mechanisms. 121 * - fork(2) and exec(2) 122 * - posix_spawn(2) 123 * 124 * @param fds an array of three file descriptors. 125 * Indexes 0, 1, and 2 correspond to standard input, 126 * standard output and standard error, respectively. On 127 * input, a value of -1 means to create a pipe to connect 128 * child and parent processes. On output, a value which 129 * is not -1 is the parent pipe fd corresponding to the 130 * pipe which has been created. An element of this array 131 * is -1 on input if and only if it is <em>not</em> -1 on 132 * output. 133 * @return the pid of the subprocess 134 */ 135 private native int forkAndExec(int mode, byte[] helperpath, 136 byte[] prog, 137 byte[] argBlock, int argc, 138 byte[] envBlock, int envc, 139 byte[] dir, 140 int[] fds, 141 boolean redirectErrorStream) 142 throws IOException; 143 144 /** 145 * The thread factory used to create "process reaper" daemon threads. 146 */ 147 private static class ProcessReaperThreadFactory implements ThreadFactory { 148 private final static ThreadGroup group = getRootThreadGroup(); 149 150 private static ThreadGroup getRootThreadGroup() { 151 return doPrivileged(new PrivilegedAction<ThreadGroup> () { 152 public ThreadGroup run() { 153 ThreadGroup root = Thread.currentThread().getThreadGroup(); 154 while (root.getParent() != null) 155 root = root.getParent(); 156 return root; 157 }}); 158 } 159 160 public Thread newThread(Runnable grimReaper) { 161 // Our thread stack requirement is quite modest. 162 Thread t = new Thread(group, grimReaper, "process reaper", 32768); 163 t.setDaemon(true); 164 // A small attempt (probably futile) to avoid priority inversion 165 t.setPriority(Thread.MAX_PRIORITY); 166 return t; 167 } 168 } 169 170 /** 171 * The thread pool of "process reaper" daemon threads. 172 */ 173 private static final Executor processReaperExecutor = 174 doPrivileged(new PrivilegedAction<Executor>() { 175 public Executor run() { 176 return Executors.newCachedThreadPool 177 (new ProcessReaperThreadFactory()); 178 }}); 179 180 UNIXProcess(final byte[] prog, 181 final byte[] argBlock, int argc, 182 final byte[] envBlock, int envc, 183 final byte[] dir, 184 final int[] fds, 185 final boolean redirectErrorStream) 186 throws IOException { 187 pid = forkAndExec(launchMechanism.value, 188 helperpath, 189 prog, 190 argBlock, argc, 191 envBlock, envc, 192 dir, 193 fds, 194 redirectErrorStream); 195 196 try { 197 doPrivileged( 198 new PrivilegedExceptionAction<Void>() { 199 public Void run() throws IOException { 200 initStreams(fds); 201 return null; 202 } 203 }); 204 } catch (PrivilegedActionException ex) { 205 throw (IOException) ex.getException(); 206 } 207 } 208 209 void initStreams(int[] fds) throws IOException { 210 if (fds[0] == -1) 211 stdin_stream = ProcessBuilder.NullOutputStream.INSTANCE; 212 else { 213 FileDescriptor stdin_fd = new FileDescriptor(); 214 fdAccess.set(stdin_fd, fds[0]); 215 stdin_stream = new BufferedOutputStream( 216 new FileOutputStream(stdin_fd)); 217 } 218 219 if (fds[1] == -1) 220 stdout_stream = ProcessBuilder.NullInputStream.INSTANCE; 221 else { 222 FileDescriptor stdout_fd = new FileDescriptor(); 223 fdAccess.set(stdout_fd, fds[1]); 224 stdout_inner_stream = new DeferredCloseInputStream(stdout_fd); 225 stdout_stream = new BufferedInputStream(stdout_inner_stream); 226 } 227 228 if (fds[2] == -1) 229 stderr_stream = ProcessBuilder.NullInputStream.INSTANCE; 230 else { 231 FileDescriptor stderr_fd = new FileDescriptor(); 232 fdAccess.set(stderr_fd, fds[2]); 233 stderr_stream = new DeferredCloseInputStream(stderr_fd); 234 } 235 236 processReaperExecutor.execute(new Runnable() { 237 public void run() { 238 int exitcode = waitForProcessExit(pid); 239 UNIXProcess.this.processExited(exitcode); 240 }}); 241 } 242 243 void processExited(int exitcode) { 244 synchronized (this) { 245 this.exitcode = exitcode; 246 hasExited = true; 247 notifyAll(); 248 } 249 } 250 251 public OutputStream getOutputStream() { 252 return stdin_stream; 253 } 254 255 public InputStream getInputStream() { 256 return stdout_stream; 257 } 258 259 public InputStream getErrorStream() { 260 return stderr_stream; 261 } 262 263 public synchronized int waitFor() throws InterruptedException { 264 while (!hasExited) { 265 wait(); 266 } 267 return exitcode; 268 } 269 270 @Override 271 public synchronized boolean waitFor(long timeout, TimeUnit unit) 272 throws InterruptedException 273 { 274 if (hasExited) return true; 275 if (timeout <= 0) return false; 276 277 long timeoutAsNanos = unit.toNanos(timeout); 278 long startTime = System.nanoTime(); 279 long rem = timeoutAsNanos; 280 281 while (!hasExited && (rem > 0)) { 282 wait(Math.max(TimeUnit.NANOSECONDS.toMillis(rem), 1)); 283 rem = timeoutAsNanos - (System.nanoTime() - startTime); 284 } 285 return hasExited; 286 } 287 288 public synchronized int exitValue() { 289 if (!hasExited) { 290 throw new IllegalThreadStateException("process hasn't exited"); 291 } 292 return exitcode; 293 } 294 295 private static native void destroyProcess(int pid, boolean force); 296 private synchronized void destroy(boolean force) { 297 // There is a risk that pid will be recycled, causing us to 298 // kill the wrong process! So we only terminate processes 299 // that appear to still be running. Even with this check, 300 // there is an unavoidable race condition here, but the window 301 // is very small, and OSes try hard to not recycle pids too 302 // soon, so this is quite safe. 303 if (!hasExited) 304 destroyProcess(pid, force); 305 try { 306 stdin_stream.close(); 307 if (stdout_inner_stream != null) 308 stdout_inner_stream.closeDeferred(stdout_stream); 309 if (stderr_stream instanceof DeferredCloseInputStream) 310 ((DeferredCloseInputStream) stderr_stream) 311 .closeDeferred(stderr_stream); 312 } catch (IOException e) { 313 // ignore 314 } 315 } 316 317 public void destroy() { 318 destroy(false); 319 } 320 321 @Override 322 public Process destroyForcibly() { 323 destroy(true); 324 return this; 325 } 326 327 @Override 328 public synchronized boolean isAlive() { 329 return !hasExited; 330 } 331 332 // A FileInputStream that supports the deferment of the actual close 333 // operation until the last pending I/O operation on the stream has 334 // finished. This is required on Solaris because we must close the stdin 335 // and stdout streams in the destroy method in order to reclaim the 336 // underlying file descriptors. Doing so, however, causes any thread 337 // currently blocked in a read on one of those streams to receive an 338 // IOException("Bad file number"), which is incompatible with historical 339 // behavior. By deferring the close we allow any pending reads to see -1 340 // (EOF) as they did before. 341 // 342 private static class DeferredCloseInputStream 343 extends FileInputStream 344 { 345 346 private DeferredCloseInputStream(FileDescriptor fd) { 347 super(fd); 348 } 349 350 private Object lock = new Object(); // For the following fields 351 private boolean closePending = false; 352 private int useCount = 0; 353 private InputStream streamToClose; 354 355 private void raise() { 356 synchronized (lock) { 357 useCount++; 358 } 359 } 360 361 private void lower() throws IOException { 362 synchronized (lock) { 363 useCount--; 364 if (useCount == 0 && closePending) { 365 streamToClose.close(); 366 } 367 } 368 } 369 370 // stc is the actual stream to be closed; it might be this object, or 371 // it might be an upstream object for which this object is downstream. 372 // 373 private void closeDeferred(InputStream stc) throws IOException { 374 synchronized (lock) { 375 if (useCount == 0) { 376 stc.close(); 377 } else { 378 closePending = true; 379 streamToClose = stc; 380 } 381 } 382 } 383 384 public void close() throws IOException { 385 synchronized (lock) { 386 useCount = 0; 387 closePending = false; 388 } 389 super.close(); 390 } 391 392 public int read() throws IOException { 393 raise(); 394 try { 395 return super.read(); 396 } finally { 397 lower(); 398 } 399 } 400 401 public int read(byte[] b) throws IOException { 402 raise(); 403 try { 404 return super.read(b); 405 } finally { 406 lower(); 407 } 408 } 409 410 public int read(byte[] b, int off, int len) throws IOException { 411 raise(); 412 try { 413 return super.read(b, off, len); 414 } finally { 415 lower(); 416 } 417 } 418 419 public long skip(long n) throws IOException { 420 raise(); 421 try { 422 return super.skip(n); 423 } finally { 424 lower(); 425 } 426 } 427 428 public int available() throws IOException { 429 raise(); 430 try { 431 return super.available(); 432 } finally { 433 lower(); 434 } 435 } 436 437 } 438 439 private static native void init(); 440 441 static { 442 init(); 443 } 444 }