1 /*
2  * Copyright (c) 1995, 2018, 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 #undef  _LARGEFILE64_SOURCE
27 #define _LARGEFILE64_SOURCE 1
28 
29 #include "jni.h"
30 #include "jvm.h"
31 #include "jvm_md.h"
32 #include "jni_util.h"
33 #include "io_util.h"
34 
35 /*
36  * Platform-specific support for java.lang.Process
37  */
38 #include <assert.h>
39 #include <stddef.h>
40 #include <stdlib.h>
41 #include <sys/types.h>
42 #include <ctype.h>
43 #include <sys/wait.h>
44 #include <signal.h>
45 #include <string.h>
46 
47 #include <spawn.h>
48 
49 #include "childproc.h"
50 
51 /*
52  * There are 4 possible strategies we might use to "fork":
53  *
54  * - fork(2).  Very portable and reliable but subject to
55  *   failure due to overcommit (see the documentation on
56  *   /proc/sys/vm/overcommit_memory in Linux proc(5)).
57  *   This is the ancient problem of spurious failure whenever a large
58  *   process starts a small subprocess.
59  *
60  * - vfork().  Using this is scary because all relevant man pages
61  *   contain dire warnings, e.g. Linux vfork(2).  But at least it's
62  *   documented in the glibc docs and is standardized by XPG4.
63  *   http://www.opengroup.org/onlinepubs/000095399/functions/vfork.html
64  *   On Linux, one might think that vfork() would be implemented using
65  *   the clone system call with flag CLONE_VFORK, but in fact vfork is
66  *   a separate system call (which is a good sign, suggesting that
67  *   vfork will continue to be supported at least on Linux).
68  *   Another good sign is that glibc implements posix_spawn using
69  *   vfork whenever possible.  Note that we cannot use posix_spawn
70  *   ourselves because there's no reliable way to close all inherited
71  *   file descriptors.
72  *
73  * - clone() with flags CLONE_VM but not CLONE_THREAD.  clone() is
74  *   Linux-specific, but this ought to work - at least the glibc
75  *   sources contain code to handle different combinations of CLONE_VM
76  *   and CLONE_THREAD.  However, when this was implemented, it
77  *   appeared to fail on 32-bit i386 (but not 64-bit x86_64) Linux with
78  *   the simple program
79  *     Runtime.getRuntime().exec("/bin/true").waitFor();
80  *   with:
81  *     #  Internal Error (os_linux_x86.cpp:683), pid=19940, tid=2934639536
82  *     #  Error: pthread_getattr_np failed with errno = 3 (ESRCH)
83  *   We believe this is a glibc bug, reported here:
84  *     http://sources.redhat.com/bugzilla/show_bug.cgi?id=10311
85  *   but the glibc maintainers closed it as WONTFIX.
86  *
87  * - posix_spawn(). While posix_spawn() is a fairly elaborate and
88  *   complicated system call, it can't quite do everything that the old
89  *   fork()/exec() combination can do, so the only feasible way to do
90  *   this, is to use posix_spawn to launch a new helper executable
91  *   "jprochelper", which in turn execs the target (after cleaning
92  *   up file-descriptors etc.) The end result is the same as before,
93  *   a child process linked to the parent in the same way, but it
94  *   avoids the problem of duplicating the parent (VM) process
95  *   address space temporarily, before launching the target command.
96  *
97  * Based on the above analysis, we are currently using vfork() on
98  * Linux and posix_spawn() on other Unix systems.
99  */
100 
101 
102 static void
setSIGCHLDHandler(JNIEnv * env)103 setSIGCHLDHandler(JNIEnv *env)
104 {
105     /* There is a subtle difference between having the signal handler
106      * for SIGCHLD be SIG_DFL and SIG_IGN.  We cannot obtain process
107      * termination information for child processes if the signal
108      * handler is SIG_IGN.  It must be SIG_DFL.
109      *
110      * We used to set the SIGCHLD handler only on Linux, but it's
111      * safest to set it unconditionally.
112      *
113      * Consider what happens if java's parent process sets the SIGCHLD
114      * handler to SIG_IGN.  Normally signal handlers are inherited by
115      * children, but SIGCHLD is a controversial case.  Solaris appears
116      * to always reset it to SIG_DFL, but this behavior may be
117      * non-standard-compliant, and we shouldn't rely on it.
118      *
119      * References:
120      * http://www.opengroup.org/onlinepubs/7908799/xsh/exec.html
121      * http://www.pasc.org/interps/unofficial/db/p1003.1/pasc-1003.1-132.html
122      */
123     struct sigaction sa;
124     sa.sa_handler = SIG_DFL;
125     sigemptyset(&sa.sa_mask);
126     sa.sa_flags = SA_NOCLDSTOP | SA_RESTART;
127     if (sigaction(SIGCHLD, &sa, NULL) < 0)
128         JNU_ThrowInternalError(env, "Can't set SIGCHLD handler");
129 }
130 
131 static void*
xmalloc(JNIEnv * env,size_t size)132 xmalloc(JNIEnv *env, size_t size)
133 {
134     void *p = malloc(size);
135     if (p == NULL)
136         JNU_ThrowOutOfMemoryError(env, NULL);
137     return p;
138 }
139 
140 #define NEW(type, n) ((type *) xmalloc(env, (n) * sizeof(type)))
141 
142 /**
143  * If PATH is not defined, the OS provides some default value.
144  * Unfortunately, there's no portable way to get this value.
145  * Fortunately, it's only needed if the child has PATH while we do not.
146  */
147 static const char*
defaultPath(void)148 defaultPath(void)
149 {
150 #ifdef __solaris__
151     /* These really are the Solaris defaults! */
152     return (geteuid() == 0 || getuid() == 0) ?
153         "/usr/xpg4/bin:/usr/bin:/opt/SUNWspro/bin:/usr/sbin" :
154         "/usr/xpg4/bin:/usr/bin:/opt/SUNWspro/bin:";
155 #else
156     return ":/bin:/usr/bin";    /* glibc */
157 #endif
158 }
159 
160 static const char*
effectivePath(void)161 effectivePath(void)
162 {
163     const char *s = getenv("PATH");
164     return (s != NULL) ? s : defaultPath();
165 }
166 
167 static int
countOccurrences(const char * s,char c)168 countOccurrences(const char *s, char c)
169 {
170     int count;
171     for (count = 0; *s != '\0'; s++)
172         count += (*s == c);
173     return count;
174 }
175 
176 static const char * const *
effectivePathv(JNIEnv * env)177 effectivePathv(JNIEnv *env)
178 {
179     char *p;
180     int i;
181     const char *path = effectivePath();
182     int count = countOccurrences(path, ':') + 1;
183     size_t pathvsize = sizeof(const char *) * (count+1);
184     size_t pathsize = strlen(path) + 1;
185     const char **pathv = (const char **) xmalloc(env, pathvsize + pathsize);
186 
187     if (pathv == NULL)
188         return NULL;
189     p = (char *) pathv + pathvsize;
190     memcpy(p, path, pathsize);
191     /* split PATH by replacing ':' with NULs; empty components => "." */
192     for (i = 0; i < count; i++) {
193         char *q = p + strcspn(p, ":");
194         pathv[i] = (p == q) ? "." : p;
195         *q = '\0';
196         p = q + 1;
197     }
198     pathv[count] = NULL;
199     return pathv;
200 }
201 
202 JNIEXPORT void JNICALL
Java_java_lang_ProcessImpl_init(JNIEnv * env,jclass clazz)203 Java_java_lang_ProcessImpl_init(JNIEnv *env, jclass clazz)
204 {
205     parentPathv = effectivePathv(env);
206     CHECK_NULL(parentPathv);
207     setSIGCHLDHandler(env);
208 }
209 
210 
211 #ifndef WIFEXITED
212 #define WIFEXITED(status) (((status)&0xFF) == 0)
213 #endif
214 
215 #ifndef WEXITSTATUS
216 #define WEXITSTATUS(status) (((status)>>8)&0xFF)
217 #endif
218 
219 #ifndef WIFSIGNALED
220 #define WIFSIGNALED(status) (((status)&0xFF) > 0 && ((status)&0xFF00) == 0)
221 #endif
222 
223 #ifndef WTERMSIG
224 #define WTERMSIG(status) ((status)&0x7F)
225 #endif
226 
227 static const char *
getBytes(JNIEnv * env,jbyteArray arr)228 getBytes(JNIEnv *env, jbyteArray arr)
229 {
230     return arr == NULL ? NULL :
231         (const char*) (*env)->GetByteArrayElements(env, arr, NULL);
232 }
233 
234 static void
releaseBytes(JNIEnv * env,jbyteArray arr,const char * parr)235 releaseBytes(JNIEnv *env, jbyteArray arr, const char* parr)
236 {
237     if (parr != NULL)
238         (*env)->ReleaseByteArrayElements(env, arr, (jbyte*) parr, JNI_ABORT);
239 }
240 
241 #define IOE_FORMAT "error=%d, %s"
242 
243 static void
throwIOException(JNIEnv * env,int errnum,const char * defaultDetail)244 throwIOException(JNIEnv *env, int errnum, const char *defaultDetail)
245 {
246     const char *detail = defaultDetail;
247     char *errmsg;
248     size_t fmtsize;
249     char tmpbuf[1024];
250     jstring s;
251 
252     if (errnum != 0) {
253         int ret = getErrorString(errnum, tmpbuf, sizeof(tmpbuf));
254         if (ret != EINVAL)
255             detail = tmpbuf;
256     }
257     /* ASCII Decimal representation uses 2.4 times as many bits as binary. */
258     fmtsize = sizeof(IOE_FORMAT) + strlen(detail) + 3 * sizeof(errnum);
259     errmsg = NEW(char, fmtsize);
260     if (errmsg == NULL)
261         return;
262 
263     snprintf(errmsg, fmtsize, IOE_FORMAT, errnum, detail);
264     s = JNU_NewStringPlatform(env, errmsg);
265     if (s != NULL) {
266         jobject x = JNU_NewObjectByName(env, "java/io/IOException",
267                                         "(Ljava/lang/String;)V", s);
268         if (x != NULL)
269             (*env)->Throw(env, x);
270     }
271     free(errmsg);
272 }
273 
274 #ifdef DEBUG_PROCESS
275 /* Debugging process code is difficult; where to write debug output? */
276 static void
debugPrint(char * format,...)277 debugPrint(char *format, ...)
278 {
279     FILE *tty = fopen("/dev/tty", "w");
280     va_list ap;
281     va_start(ap, format);
282     vfprintf(tty, format, ap);
283     va_end(ap);
284     fclose(tty);
285 }
286 #endif /* DEBUG_PROCESS */
287 
288 static void
copyPipe(int from[2],int to[2])289 copyPipe(int from[2], int to[2])
290 {
291     to[0] = from[0];
292     to[1] = from[1];
293 }
294 
295 /* arg is an array of pointers to 0 terminated strings. array is terminated
296  * by a null element.
297  *
298  * *nelems and *nbytes receive the number of elements of array (incl 0)
299  * and total number of bytes (incl. 0)
300  * Note. An empty array will have one null element
301  * But if arg is null, then *nelems set to 0, and *nbytes to 0
302  */
arraysize(const char * const * arg,int * nelems,int * nbytes)303 static void arraysize(const char * const *arg, int *nelems, int *nbytes)
304 {
305     int i, bytes, count;
306     const char * const *a = arg;
307     char *p;
308     int *q;
309     if (arg == 0) {
310         *nelems = 0;
311         *nbytes = 0;
312         return;
313     }
314     /* count the array elements and number of bytes */
315     for (count=0, bytes=0; *a != 0; count++, a++) {
316         bytes += strlen(*a)+1;
317     }
318     *nbytes = bytes;
319     *nelems = count+1;
320 }
321 
322 /* copy the strings from arg[] into buf, starting at given offset
323  * return new offset to next free byte
324  */
copystrings(char * buf,int offset,const char * const * arg)325 static int copystrings(char *buf, int offset, const char * const *arg) {
326     char *p;
327     const char * const *a;
328     int count=0;
329 
330     if (arg == 0) {
331         return offset;
332     }
333     for (p=buf+offset, a=arg; *a != 0; a++) {
334         int len = strlen(*a) +1;
335         memcpy(p, *a, len);
336         p += len;
337         count += len;
338     }
339     return offset+count;
340 }
341 
342 /**
343  * We are unusually paranoid; use of vfork is
344  * especially likely to tickle gcc/glibc bugs.
345  */
346 #ifdef __attribute_noinline__  /* See: sys/cdefs.h */
347 __attribute_noinline__
348 #endif
349 
350 /* vfork(2) is deprecated on Solaris */
351 #ifndef __solaris__
352 static pid_t
vforkChild(ChildStuff * c)353 vforkChild(ChildStuff *c) {
354     volatile pid_t resultPid;
355 
356     /*
357      * We separate the call to vfork into a separate function to make
358      * very sure to keep stack of child from corrupting stack of parent,
359      * as suggested by the scary gcc warning:
360      *  warning: variable 'foo' might be clobbered by 'longjmp' or 'vfork'
361      */
362     resultPid = vfork();
363 
364     if (resultPid == 0) {
365         childProcess(c);
366     }
367     assert(resultPid != 0);  /* childProcess never returns */
368     return resultPid;
369 }
370 #endif
371 
372 static pid_t
forkChild(ChildStuff * c)373 forkChild(ChildStuff *c) {
374     pid_t resultPid;
375 
376     /*
377      * From Solaris fork(2): In Solaris 10, a call to fork() is
378      * identical to a call to fork1(); only the calling thread is
379      * replicated in the child process. This is the POSIX-specified
380      * behavior for fork().
381      */
382     resultPid = fork();
383 
384     if (resultPid == 0) {
385         childProcess(c);
386     }
387     assert(resultPid != 0);  /* childProcess never returns */
388     return resultPid;
389 }
390 
391 static pid_t
spawnChild(JNIEnv * env,jobject process,ChildStuff * c,const char * helperpath)392 spawnChild(JNIEnv *env, jobject process, ChildStuff *c, const char *helperpath) {
393     pid_t resultPid;
394     jboolean isCopy;
395     int i, offset, rval, bufsize, magic;
396     char *buf, buf1[16];
397     char *hlpargs[2];
398     SpawnInfo sp;
399 
400     /* need to tell helper which fd is for receiving the childstuff
401      * and which fd to send response back on
402      */
403     snprintf(buf1, sizeof(buf1), "%d:%d", c->childenv[0], c->fail[1]);
404     /* put the fd string as argument to the helper cmd */
405     hlpargs[0] = buf1;
406     hlpargs[1] = 0;
407 
408     /* Following items are sent down the pipe to the helper
409      * after it is spawned.
410      * All strings are null terminated. All arrays of strings
411      * have an empty string for termination.
412      * - the ChildStuff struct
413      * - the SpawnInfo struct
414      * - the argv strings array
415      * - the envv strings array
416      * - the home directory string
417      * - the parentPath string
418      * - the parentPathv array
419      */
420     /* First calculate the sizes */
421     arraysize(c->argv, &sp.nargv, &sp.argvBytes);
422     bufsize = sp.argvBytes;
423     arraysize(c->envv, &sp.nenvv, &sp.envvBytes);
424     bufsize += sp.envvBytes;
425     sp.dirlen = c->pdir == 0 ? 0 : strlen(c->pdir)+1;
426     bufsize += sp.dirlen;
427     arraysize(parentPathv, &sp.nparentPathv, &sp.parentPathvBytes);
428     bufsize += sp.parentPathvBytes;
429     /* We need to clear FD_CLOEXEC if set in the fds[].
430      * Files are created FD_CLOEXEC in Java.
431      * Otherwise, they will be closed when the target gets exec'd */
432     for (i=0; i<3; i++) {
433         if (c->fds[i] != -1) {
434             int flags = fcntl(c->fds[i], F_GETFD);
435             if (flags & FD_CLOEXEC) {
436                 fcntl(c->fds[i], F_SETFD, flags & (~1));
437             }
438         }
439     }
440 
441     rval = posix_spawn(&resultPid, helperpath, 0, 0, (char * const *) hlpargs, environ);
442 
443     if (rval != 0) {
444         return -1;
445     }
446 
447     /* now the lengths are known, copy the data */
448     buf = NEW(char, bufsize);
449     if (buf == 0) {
450         return -1;
451     }
452     offset = copystrings(buf, 0, &c->argv[0]);
453     offset = copystrings(buf, offset, &c->envv[0]);
454     memcpy(buf+offset, c->pdir, sp.dirlen);
455     offset += sp.dirlen;
456     offset = copystrings(buf, offset, parentPathv);
457     assert(offset == bufsize);
458 
459     magic = magicNumber();
460 
461     /* write the two structs and the data buffer */
462     write(c->childenv[1], (char *)&magic, sizeof(magic)); // magic number first
463     write(c->childenv[1], (char *)c, sizeof(*c));
464     write(c->childenv[1], (char *)&sp, sizeof(sp));
465     write(c->childenv[1], buf, bufsize);
466     free(buf);
467 
468     /* In this mode an external main() in invoked which calls back into
469      * childProcess() in this file, rather than directly
470      * via the statement below */
471     return resultPid;
472 }
473 
474 /*
475  * Start a child process running function childProcess.
476  * This function only returns in the parent.
477  */
478 static pid_t
startChild(JNIEnv * env,jobject process,ChildStuff * c,const char * helperpath)479 startChild(JNIEnv *env, jobject process, ChildStuff *c, const char *helperpath) {
480     switch (c->mode) {
481 /* vfork(2) is deprecated on Solaris */
482 #ifndef __solaris__
483       case MODE_VFORK:
484         return vforkChild(c);
485 #endif
486       case MODE_FORK:
487         return forkChild(c);
488       case MODE_POSIX_SPAWN:
489         return spawnChild(env, process, c, helperpath);
490       default:
491         return -1;
492     }
493 }
494 
495 JNIEXPORT jint JNICALL
Java_java_lang_ProcessImpl_forkAndExec(JNIEnv * env,jobject process,jint mode,jbyteArray helperpath,jbyteArray prog,jbyteArray argBlock,jint argc,jbyteArray envBlock,jint envc,jbyteArray dir,jintArray std_fds,jboolean redirectErrorStream)496 Java_java_lang_ProcessImpl_forkAndExec(JNIEnv *env,
497                                        jobject process,
498                                        jint mode,
499                                        jbyteArray helperpath,
500                                        jbyteArray prog,
501                                        jbyteArray argBlock, jint argc,
502                                        jbyteArray envBlock, jint envc,
503                                        jbyteArray dir,
504                                        jintArray std_fds,
505                                        jboolean redirectErrorStream)
506 {
507     int errnum;
508     int resultPid = -1;
509     int in[2], out[2], err[2], fail[2], childenv[2];
510     jint *fds = NULL;
511     const char *phelperpath = NULL;
512     const char *pprog = NULL;
513     const char *pargBlock = NULL;
514     const char *penvBlock = NULL;
515     ChildStuff *c;
516 
517     in[0] = in[1] = out[0] = out[1] = err[0] = err[1] = fail[0] = fail[1] = -1;
518     childenv[0] = childenv[1] = -1;
519 
520     if ((c = NEW(ChildStuff, 1)) == NULL) return -1;
521     c->argv = NULL;
522     c->envv = NULL;
523     c->pdir = NULL;
524 
525     /* Convert prog + argBlock into a char ** argv.
526      * Add one word room for expansion of argv for use by
527      * execve_as_traditional_shell_script.
528      * This word is also used when using posix_spawn mode
529      */
530     assert(prog != NULL && argBlock != NULL);
531     if ((phelperpath = getBytes(env, helperpath))   == NULL) goto Catch;
532     if ((pprog       = getBytes(env, prog))         == NULL) goto Catch;
533     if ((pargBlock   = getBytes(env, argBlock))     == NULL) goto Catch;
534     if ((c->argv     = NEW(const char *, argc + 3)) == NULL) goto Catch;
535     c->argv[0] = pprog;
536     c->argc = argc + 2;
537     initVectorFromBlock(c->argv+1, pargBlock, argc);
538 
539     if (envBlock != NULL) {
540         /* Convert envBlock into a char ** envv */
541         if ((penvBlock = getBytes(env, envBlock))   == NULL) goto Catch;
542         if ((c->envv = NEW(const char *, envc + 1)) == NULL) goto Catch;
543         initVectorFromBlock(c->envv, penvBlock, envc);
544     }
545 
546     if (dir != NULL) {
547         if ((c->pdir = getBytes(env, dir)) == NULL) goto Catch;
548     }
549 
550     assert(std_fds != NULL);
551     fds = (*env)->GetIntArrayElements(env, std_fds, NULL);
552     if (fds == NULL) goto Catch;
553 
554     if ((fds[0] == -1 && pipe(in)  < 0) ||
555         (fds[1] == -1 && pipe(out) < 0) ||
556         (fds[2] == -1 && pipe(err) < 0) ||
557         (pipe(childenv) < 0) ||
558         (pipe(fail) < 0)) {
559         throwIOException(env, errno, "Bad file descriptor");
560         goto Catch;
561     }
562     c->fds[0] = fds[0];
563     c->fds[1] = fds[1];
564     c->fds[2] = fds[2];
565 
566     copyPipe(in,   c->in);
567     copyPipe(out,  c->out);
568     copyPipe(err,  c->err);
569     copyPipe(fail, c->fail);
570     copyPipe(childenv, c->childenv);
571 
572     c->redirectErrorStream = redirectErrorStream;
573     c->mode = mode;
574 
575     /* In posix_spawn mode, require the child process to signal aliveness
576      * right after it comes up. This is because there are implementations of
577      * posix_spawn() which do not report failed exec()s back to the caller
578      * (e.g. glibc, see JDK-8223777). In those cases, the fork() will have
579      * worked and successfully started the child process, but the exec() will
580      * have failed. There is no way for us to distinguish this from a target
581      * binary just exiting right after start.
582      *
583      * Note that we could do this additional handshake in all modes but for
584      * prudence only do it when it is needed (in posix_spawn mode). */
585     c->sendAlivePing = (mode == MODE_POSIX_SPAWN) ? 1 : 0;
586 
587     resultPid = startChild(env, process, c, phelperpath);
588     assert(resultPid != 0);
589 
590     if (resultPid < 0) {
591         switch (c->mode) {
592           case MODE_VFORK:
593             throwIOException(env, errno, "vfork failed");
594             break;
595           case MODE_FORK:
596             throwIOException(env, errno, "fork failed");
597             break;
598           case MODE_POSIX_SPAWN:
599             throwIOException(env, errno, "posix_spawn failed");
600             break;
601         }
602         goto Catch;
603     }
604     close(fail[1]); fail[1] = -1; /* See: WhyCantJohnnyExec  (childproc.c)  */
605 
606     /* If we expect the child to ping aliveness, wait for it. */
607     if (c->sendAlivePing) {
608         switch(readFully(fail[0], &errnum, sizeof(errnum))) {
609         case 0: /* First exec failed; */
610             waitpid(resultPid, NULL, 0);
611             throwIOException(env, 0, "Failed to exec spawn helper.");
612             goto Catch;
613         case sizeof(errnum):
614             assert(errnum == CHILD_IS_ALIVE);
615             if (errnum != CHILD_IS_ALIVE) {
616                 /* Should never happen since the first thing the spawn
617                  * helper should do is to send an alive ping to the parent,
618                  * before doing any subsequent work. */
619                 throwIOException(env, 0, "Bad code from spawn helper "
620                                          "(Failed to exec spawn helper.");
621                 goto Catch;
622             }
623             break;
624         default:
625             throwIOException(env, errno, "Read failed");
626             goto Catch;
627         }
628     }
629 
630     switch (readFully(fail[0], &errnum, sizeof(errnum))) {
631     case 0: break; /* Exec succeeded */
632     case sizeof(errnum):
633         waitpid(resultPid, NULL, 0);
634         throwIOException(env, errnum, "Exec failed");
635         goto Catch;
636     default:
637         throwIOException(env, errno, "Read failed");
638         goto Catch;
639     }
640 
641     fds[0] = (in [1] != -1) ? in [1] : -1;
642     fds[1] = (out[0] != -1) ? out[0] : -1;
643     fds[2] = (err[0] != -1) ? err[0] : -1;
644 
645  Finally:
646     /* Always clean up the child's side of the pipes */
647     closeSafely(in [0]);
648     closeSafely(out[1]);
649     closeSafely(err[1]);
650 
651     /* Always clean up fail and childEnv descriptors */
652     closeSafely(fail[0]);
653     closeSafely(fail[1]);
654     closeSafely(childenv[0]);
655     closeSafely(childenv[1]);
656 
657     releaseBytes(env, helperpath, phelperpath);
658     releaseBytes(env, prog,       pprog);
659     releaseBytes(env, argBlock,   pargBlock);
660     releaseBytes(env, envBlock,   penvBlock);
661     releaseBytes(env, dir,        c->pdir);
662 
663     free(c->argv);
664     free(c->envv);
665     free(c);
666 
667     if (fds != NULL)
668         (*env)->ReleaseIntArrayElements(env, std_fds, fds, 0);
669 
670     return resultPid;
671 
672  Catch:
673     /* Clean up the parent's side of the pipes in case of failure only */
674     closeSafely(in [1]); in[1] = -1;
675     closeSafely(out[0]); out[0] = -1;
676     closeSafely(err[0]); err[0] = -1;
677     goto Finally;
678 }
679 
680