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