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.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 * @author Volker Simonis (ported to AIX) |
|
55 */ |
|
56 final class UNIXProcess extends Process { |
|
57 private static final sun.misc.JavaIOFileDescriptorAccess fdAccess |
|
58 = sun.misc.SharedSecrets.getJavaIOFileDescriptorAccess(); |
|
59 |
|
60 private final int pid; |
|
61 private int exitcode; |
|
62 private boolean hasExited; |
|
63 |
|
64 private /* final */ OutputStream stdin; |
|
65 private /* final */ InputStream stdout; |
|
66 private /* final */ InputStream stderr; |
|
67 |
|
68 private static enum LaunchMechanism { |
|
69 FORK(1), |
|
70 POSIX_SPAWN(2); |
|
71 |
|
72 private int value; |
|
73 LaunchMechanism(int x) {value = x;} |
|
74 }; |
|
75 |
|
76 /* On AIX, the default is to spawn */ |
|
77 private static final LaunchMechanism launchMechanism; |
|
78 private static byte[] helperpath; |
|
79 |
|
80 private static byte[] toCString(String s) { |
|
81 if (s == null) |
|
82 return null; |
|
83 byte[] bytes = s.getBytes(); |
|
84 byte[] result = new byte[bytes.length + 1]; |
|
85 System.arraycopy(bytes, 0, |
|
86 result, 0, |
|
87 bytes.length); |
|
88 result[result.length-1] = (byte)0; |
|
89 return result; |
|
90 } |
|
91 |
|
92 static { |
|
93 launchMechanism = AccessController.doPrivileged( |
|
94 new PrivilegedAction<LaunchMechanism>() |
|
95 { |
|
96 public LaunchMechanism run() { |
|
97 String javahome = System.getProperty("java.home"); |
|
98 String osArch = System.getProperty("os.arch"); |
|
99 |
|
100 helperpath = toCString(javahome + "/lib/" + osArch + "/jspawnhelper"); |
|
101 String s = System.getProperty( |
|
102 "jdk.lang.Process.launchMechanism", "posix_spawn"); |
|
103 |
|
104 try { |
|
105 return LaunchMechanism.valueOf(s.toUpperCase()); |
|
106 } catch (IllegalArgumentException e) { |
|
107 throw new Error(s + " is not a supported " + |
|
108 "process launch mechanism on this platform."); |
|
109 } |
|
110 } |
|
111 }); |
|
112 } |
|
113 |
|
114 /* this is for the reaping thread */ |
|
115 private native int waitForProcessExit(int pid); |
|
116 |
|
117 /** |
|
118 * Create a process. Depending on the mode flag, this is done by |
|
119 * one of the following mechanisms. |
|
120 * - fork(2) and exec(2) |
|
121 * - clone(2) and exec(2) |
|
122 * - vfork(2) and exec(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, final int argc, |
|
182 final byte[] envBlock, final int envc, |
|
183 final byte[] dir, |
|
184 final int[] fds, |
|
185 final boolean redirectErrorStream) |
|
186 throws IOException { |
|
187 |
|
188 pid = forkAndExec(launchMechanism.value, |
|
189 helperpath, |
|
190 prog, |
|
191 argBlock, argc, |
|
192 envBlock, envc, |
|
193 dir, |
|
194 fds, |
|
195 redirectErrorStream); |
|
196 |
|
197 try { |
|
198 doPrivileged(new PrivilegedExceptionAction<Void>() { |
|
199 public Void run() throws IOException { |
|
200 initStreams(fds); |
|
201 return null; |
|
202 }}); |
|
203 } catch (PrivilegedActionException ex) { |
|
204 throw (IOException) ex.getException(); |
|
205 } |
|
206 } |
|
207 |
|
208 static FileDescriptor newFileDescriptor(int fd) { |
|
209 FileDescriptor fileDescriptor = new FileDescriptor(); |
|
210 fdAccess.set(fileDescriptor, fd); |
|
211 return fileDescriptor; |
|
212 } |
|
213 |
|
214 void initStreams(int[] fds) throws IOException { |
|
215 stdin = (fds[0] == -1) ? |
|
216 ProcessBuilder.NullOutputStream.INSTANCE : |
|
217 new ProcessPipeOutputStream(fds[0]); |
|
218 |
|
219 stdout = (fds[1] == -1) ? |
|
220 ProcessBuilder.NullInputStream.INSTANCE : |
|
221 new ProcessPipeInputStream(fds[1]); |
|
222 |
|
223 stderr = (fds[2] == -1) ? |
|
224 ProcessBuilder.NullInputStream.INSTANCE : |
|
225 new ProcessPipeInputStream(fds[2]); |
|
226 |
|
227 processReaperExecutor.execute(new Runnable() { |
|
228 public void run() { |
|
229 int exitcode = waitForProcessExit(pid); |
|
230 UNIXProcess.this.processExited(exitcode); |
|
231 }}); |
|
232 } |
|
233 |
|
234 void processExited(int exitcode) { |
|
235 synchronized (this) { |
|
236 this.exitcode = exitcode; |
|
237 hasExited = true; |
|
238 notifyAll(); |
|
239 } |
|
240 |
|
241 if (stdout instanceof ProcessPipeInputStream) |
|
242 ((ProcessPipeInputStream) stdout).processExited(); |
|
243 |
|
244 if (stderr instanceof ProcessPipeInputStream) |
|
245 ((ProcessPipeInputStream) stderr).processExited(); |
|
246 |
|
247 if (stdin instanceof ProcessPipeOutputStream) |
|
248 ((ProcessPipeOutputStream) stdin).processExited(); |
|
249 } |
|
250 |
|
251 public OutputStream getOutputStream() { |
|
252 return stdin; |
|
253 } |
|
254 |
|
255 public InputStream getInputStream() { |
|
256 return stdout; |
|
257 } |
|
258 |
|
259 public InputStream getErrorStream() { |
|
260 return stderr; |
|
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 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 synchronized (this) { |
|
304 if (!hasExited) |
|
305 destroyProcess(pid, force); |
|
306 } |
|
307 try { stdin.close(); } catch (IOException ignored) {} |
|
308 try { stdout.close(); } catch (IOException ignored) {} |
|
309 try { stderr.close(); } catch (IOException ignored) {} |
|
310 } |
|
311 |
|
312 public void destroy() { |
|
313 destroy(false); |
|
314 } |
|
315 |
|
316 @Override |
|
317 public Process destroyForcibly() { |
|
318 destroy(true); |
|
319 return this; |
|
320 } |
|
321 |
|
322 @Override |
|
323 public synchronized boolean isAlive() { |
|
324 return !hasExited; |
|
325 } |
|
326 |
|
327 private static native void init(); |
|
328 |
|
329 static { |
|
330 init(); |
|
331 } |
|
332 |
|
333 /** |
|
334 * A buffered input stream for a subprocess pipe file descriptor |
|
335 * that allows the underlying file descriptor to be reclaimed when |
|
336 * the process exits, via the processExited hook. |
|
337 * |
|
338 * This is tricky because we do not want the user-level InputStream to be |
|
339 * closed until the user invokes close(), and we need to continue to be |
|
340 * able to read any buffered data lingering in the OS pipe buffer. |
|
341 * |
|
342 * On AIX this is especially tricky, because the 'close()' system call |
|
343 * will block if another thread is at the same time blocked in a file |
|
344 * operation (e.g. 'read()') on the same file descriptor. We therefore |
|
345 * combine this 'ProcessPipeInputStream' with the DeferredCloseInputStream |
|
346 * approach used on Solaris (see "UNIXProcess.java.solaris"). This means |
|
347 * that every potentially blocking operation on the file descriptor |
|
348 * increments a counter before it is executed and decrements it once it |
|
349 * finishes. The 'close()' operation will only be executed if there are |
|
350 * no pending operations. Otherwise it is deferred after the last pending |
|
351 * operation has finished. |
|
352 * |
|
353 */ |
|
354 static class ProcessPipeInputStream extends BufferedInputStream { |
|
355 private final Object closeLock = new Object(); |
|
356 private int useCount = 0; |
|
357 private boolean closePending = false; |
|
358 |
|
359 ProcessPipeInputStream(int fd) { |
|
360 super(new FileInputStream(newFileDescriptor(fd))); |
|
361 } |
|
362 |
|
363 private InputStream drainInputStream(InputStream in) |
|
364 throws IOException { |
|
365 int n = 0; |
|
366 int j; |
|
367 byte[] a = null; |
|
368 synchronized (closeLock) { |
|
369 if (buf == null) // asynchronous close()? |
|
370 return null; // discard |
|
371 j = in.available(); |
|
372 } |
|
373 while (j > 0) { |
|
374 a = (a == null) ? new byte[j] : Arrays.copyOf(a, n + j); |
|
375 synchronized (closeLock) { |
|
376 if (buf == null) // asynchronous close()? |
|
377 return null; // discard |
|
378 n += in.read(a, n, j); |
|
379 j = in.available(); |
|
380 } |
|
381 } |
|
382 return (a == null) ? |
|
383 ProcessBuilder.NullInputStream.INSTANCE : |
|
384 new ByteArrayInputStream(n == a.length ? a : Arrays.copyOf(a, n)); |
|
385 } |
|
386 |
|
387 /** Called by the process reaper thread when the process exits. */ |
|
388 synchronized void processExited() { |
|
389 try { |
|
390 InputStream in = this.in; |
|
391 if (in != null) { |
|
392 InputStream stragglers = drainInputStream(in); |
|
393 in.close(); |
|
394 this.in = stragglers; |
|
395 } |
|
396 } catch (IOException ignored) { } |
|
397 } |
|
398 |
|
399 private void raise() { |
|
400 synchronized (closeLock) { |
|
401 useCount++; |
|
402 } |
|
403 } |
|
404 |
|
405 private void lower() throws IOException { |
|
406 synchronized (closeLock) { |
|
407 useCount--; |
|
408 if (useCount == 0 && closePending) { |
|
409 closePending = false; |
|
410 super.close(); |
|
411 } |
|
412 } |
|
413 } |
|
414 |
|
415 @Override |
|
416 public int read() throws IOException { |
|
417 raise(); |
|
418 try { |
|
419 return super.read(); |
|
420 } finally { |
|
421 lower(); |
|
422 } |
|
423 } |
|
424 |
|
425 @Override |
|
426 public int read(byte[] b) throws IOException { |
|
427 raise(); |
|
428 try { |
|
429 return super.read(b); |
|
430 } finally { |
|
431 lower(); |
|
432 } |
|
433 } |
|
434 |
|
435 @Override |
|
436 public int read(byte[] b, int off, int len) throws IOException { |
|
437 raise(); |
|
438 try { |
|
439 return super.read(b, off, len); |
|
440 } finally { |
|
441 lower(); |
|
442 } |
|
443 } |
|
444 |
|
445 @Override |
|
446 public long skip(long n) throws IOException { |
|
447 raise(); |
|
448 try { |
|
449 return super.skip(n); |
|
450 } finally { |
|
451 lower(); |
|
452 } |
|
453 } |
|
454 |
|
455 @Override |
|
456 public int available() throws IOException { |
|
457 raise(); |
|
458 try { |
|
459 return super.available(); |
|
460 } finally { |
|
461 lower(); |
|
462 } |
|
463 } |
|
464 |
|
465 @Override |
|
466 public void close() throws IOException { |
|
467 // BufferedInputStream#close() is not synchronized unlike most other methods. |
|
468 // Synchronizing helps avoid racing with drainInputStream(). |
|
469 synchronized (closeLock) { |
|
470 if (useCount == 0) { |
|
471 super.close(); |
|
472 } |
|
473 else { |
|
474 closePending = true; |
|
475 } |
|
476 } |
|
477 } |
|
478 } |
|
479 |
|
480 /** |
|
481 * A buffered output stream for a subprocess pipe file descriptor |
|
482 * that allows the underlying file descriptor to be reclaimed when |
|
483 * the process exits, via the processExited hook. |
|
484 */ |
|
485 static class ProcessPipeOutputStream extends BufferedOutputStream { |
|
486 ProcessPipeOutputStream(int fd) { |
|
487 super(new FileOutputStream(newFileDescriptor(fd))); |
|
488 } |
|
489 |
|
490 /** Called by the process reaper thread when the process exits. */ |
|
491 synchronized void processExited() { |
|
492 OutputStream out = this.out; |
|
493 if (out != null) { |
|
494 try { |
|
495 out.close(); |
|
496 } catch (IOException ignored) { |
|
497 // We know of no reason to get an IOException, but if |
|
498 // we do, there's nothing else to do but carry on. |
|
499 } |
|
500 this.out = ProcessBuilder.NullOutputStream.INSTANCE; |
|
501 } |
|
502 } |
|
503 } |
|
504 } |
|