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 <sys/stat.h>
  43 #include <ctype.h>
  44 #include <sys/wait.h>
  45 #include <signal.h>
  46 #include <string.h>
  47 
  48 #include <spawn.h>
  49 
  50 #include "childproc.h"
  51 
  52 /*
  53  *
  54  * When starting a child on Unix, we need to do three things:
  55  * - fork off
  56  * - in the child process, do some pre-exec work: duping/closing file
  57  *   descriptors to set up stdio-redirection, setting environment variables,
  58  *   changing paths...
  59  * - then exec(2) the target binary
  60  *
  61  * There are three ways to fork off:
  62  *
  63  * A) fork(2). Portable and safe (no side effects) but may fail with ENOMEM on
  64  *    all Unices when invoked from a VM with a high memory footprint. On Unices
  65  *    with strict no-overcommit policy this problem is most visible.
  66  *
  67  *    This is because forking the VM will first create a child process with
  68  *    theoretically the same memory footprint as the parent - even if you plan
  69  *    to follow up with exec'ing a tiny binary. In reality techniques like
  70  *    copy-on-write etc mitigate the problem somewhat but we still run the risk
  71  *    of hitting system limits.
  72  *
  73  *    For a Linux centric description of this problem, see the documentation on
  74  *    /proc/sys/vm/overcommit_memory in Linux proc(5).
  75  *
  76  * B) vfork(2): Portable and fast but very unsafe. It bypasses the memory
  77  *    problems related to fork(2) by starting the child in the memory image of
  78  *    the parent. Things that can go wrong include:
  79  *    - Programming errors in the child process before the exec(2) call may
  80  *      trash memory in the parent process, most commonly the stack of the
  81  *      thread invoking vfork.
  82  *    - Signals received by the child before the exec(2) call may be at best
  83  *      misdirected to the parent, at worst immediately kill child and parent.
  84  *
  85  *    This is mitigated by very strict rules about what one is allowed to do in
  86  *    the child process between vfork(2) and exec(2), which is basically nothing.
  87  *    However, we always broke this rule by doing the pre-exec work between
  88  *    vfork(2) and exec(2).
  89  *
  90  *    Also note that vfork(2) has been deprecated by the OpenGroup, presumably
  91  *    because of its many dangers.
  92  *
  93  * C) clone(2): This is a Linux specific call which gives the caller fine
  94  *    grained control about how exactly the process fork is executed. It is
  95  *    powerful, but Linux-specific.
  96  *
  97  * Aside from these three possibilities there is a forth option:  posix_spawn(3).
  98  * Where fork/vfork/clone all fork off the process and leave pre-exec work and
  99  * calling exec(2) to the user, posix_spawn(3) offers the user fork+exec-like
 100  * functionality in one package, similar to CreateProcess() on Windows.
 101  *
 102  * It is not a system call in itself, but usually a wrapper implemented within
 103  * the libc in terms of one of (fork|vfork|clone)+exec - so whether or not it
 104  * has advantages over calling the naked (fork|vfork|clone) functions depends
 105  * on how posix_spawn(3) is implemented.
 106  *
 107  * Note that when using posix_spawn(3), we exec twice: first a tiny binary called
 108  * the jspawnhelper, then in the jspawnhelper we do the pre-exec work and exec a
 109  * second time, this time the target binary (similar to the "exec-twice-technique"
 110  * described in http://mail.openjdk.java.net/pipermail/core-libs-dev/2018-September/055333.html).
 111  *
 112  * This is a JDK-specific implementation detail which just happens to be
 113  * implemented for jdk.lang.Process.launchMechanism=POSIX_SPAWN.
 114  *
 115  * --- Linux-specific ---
 116  *
 117  * How does glibc implement posix_spawn?
 118  * (see: sysdeps/posix/spawni.c for glibc < 2.24,
 119  *       sysdeps/unix/sysv/linux/spawni.c for glibc >= 2.24):
 120  *
 121  * 1) Before glibc 2.4 (released 2006), posix_spawn(3) used just fork(2)/exec(2).
 122  *    This would be bad for the JDK since we would risk the known memory issues with
 123  *    fork(2). But since this only affects glibc variants which have long been
 124  *    phased out by modern distributions, this is irrelevant.
 125  *
 126  * 2) Between glibc 2.4 and glibc 2.23, posix_spawn uses either fork(2) or
 127  *    vfork(2) depending on how exactly the user called posix_spawn(3):
 128  *
 129  * <quote>
 130  *       The child process is created using vfork(2) instead of fork(2) when
 131  *       either of the following is true:
 132  *
 133  *       * the spawn-flags element of the attributes object pointed to by
 134  *          attrp contains the GNU-specific flag POSIX_SPAWN_USEVFORK; or
 135  *
 136  *       * file_actions is NULL and the spawn-flags element of the attributes
 137  *          object pointed to by attrp does not contain
 138  *          POSIX_SPAWN_SETSIGMASK, POSIX_SPAWN_SETSIGDEF,
 139  *          POSIX_SPAWN_SETSCHEDPARAM, POSIX_SPAWN_SETSCHEDULER,
 140  *          POSIX_SPAWN_SETPGROUP, or POSIX_SPAWN_RESETIDS.
 141  * </quote>
 142  *
 143  * Due to the way the JDK calls posix_spawn(3), it would therefore call vfork(2).
 144  * So we would avoid the fork(2) memory problems. However, there still remains the
 145  * risk associated with vfork(2). But it is smaller than were we to call vfork(2)
 146  * directly since we use the jspawnhelper, moving all pre-exec work off to after
 147  * the first exec, thereby reducing the vulnerable time window.
 148  *
 149  * 3) Since glibc >= 2.24, glibc uses clone+exec:
 150  *
 151  *    new_pid = CLONE (__spawni_child, STACK (stack, stack_size), stack_size,
 152  *                     CLONE_VM | CLONE_VFORK | SIGCHLD, &args);
 153  *
 154  * This is even better than (2):
 155  *
 156  * CLONE_VM means we run in the parent's memory image, as with (2)
 157  * CLONE_VFORK means parent waits until we exec, as with (2)
 158  *
 159  * However, error possibilities are further reduced since:
 160  * - posix_spawn(3) passes a separate stack for the child to run on, eliminating
 161  *   the danger of trashing the forking thread's stack in the parent process.
 162  * - posix_spawn(3) takes care to temporarily block all incoming signals to the
 163  *   child process until the first exec(2) has been called,
 164  *
 165  * TL;DR
 166  * Calling posix_spawn(3) for glibc
 167  * (2) < 2.24 is not perfect but still better than using plain vfork(2), since
 168  *     the chance of an error happening is greatly reduced
 169  * (3) >= 2.24 is the best option - portable, fast and as safe as possible.
 170  *
 171  * ---
 172  *
 173  * How does muslc implement posix_spawn?
 174  *
 175  * They always did use the clone (.. CLONE_VM | CLONE_VFORK ...)
 176  * technique. So we are safe to use posix_spawn() here regardless of muslc
 177  * version.
 178  *
 179  * </Linux-specific>
 180  *
 181  *
 182  * Based on the above analysis, we are currently defaulting to posix_spawn()
 183  * on all Unices including Linux.
 184  */
 185 
 186 static void
 187 setSIGCHLDHandler(JNIEnv *env)
 188 {
 189     /* There is a subtle difference between having the signal handler
 190      * for SIGCHLD be SIG_DFL and SIG_IGN.  We cannot obtain process
 191      * termination information for child processes if the signal
 192      * handler is SIG_IGN.  It must be SIG_DFL.
 193      *
 194      * We used to set the SIGCHLD handler only on Linux, but it's
 195      * safest to set it unconditionally.
 196      *
 197      * Consider what happens if java's parent process sets the SIGCHLD
 198      * handler to SIG_IGN.  Normally signal handlers are inherited by
 199      * children, but SIGCHLD is a controversial case.  Solaris appears
 200      * to always reset it to SIG_DFL, but this behavior may be
 201      * non-standard-compliant, and we shouldn't rely on it.
 202      *
 203      * References:
 204      * http://www.opengroup.org/onlinepubs/7908799/xsh/exec.html
 205      * http://www.pasc.org/interps/unofficial/db/p1003.1/pasc-1003.1-132.html
 206      */
 207     struct sigaction sa;
 208     sa.sa_handler = SIG_DFL;
 209     sigemptyset(&sa.sa_mask);
 210     sa.sa_flags = SA_NOCLDSTOP | SA_RESTART;
 211     if (sigaction(SIGCHLD, &sa, NULL) < 0)
 212         JNU_ThrowInternalError(env, "Can't set SIGCHLD handler");
 213 }
 214 
 215 static void*
 216 xmalloc(JNIEnv *env, size_t size)
 217 {
 218     void *p = malloc(size);
 219     if (p == NULL)
 220         JNU_ThrowOutOfMemoryError(env, NULL);
 221     return p;
 222 }
 223 
 224 #define NEW(type, n) ((type *) xmalloc(env, (n) * sizeof(type)))
 225 
 226 /**
 227  * If PATH is not defined, the OS provides some default value.
 228  * Unfortunately, there's no portable way to get this value.
 229  * Fortunately, it's only needed if the child has PATH while we do not.
 230  */
 231 static const char*
 232 defaultPath(void)
 233 {
 234 #ifdef __solaris__
 235     /* These really are the Solaris defaults! */
 236     return (geteuid() == 0 || getuid() == 0) ?
 237         "/usr/xpg4/bin:/usr/bin:/opt/SUNWspro/bin:/usr/sbin" :
 238         "/usr/xpg4/bin:/usr/bin:/opt/SUNWspro/bin:";
 239 #else
 240     return ":/bin:/usr/bin";    /* glibc */
 241 #endif
 242 }
 243 
 244 static const char*
 245 effectivePath(void)
 246 {
 247     const char *s = getenv("PATH");
 248     return (s != NULL) ? s : defaultPath();
 249 }
 250 
 251 static int
 252 countOccurrences(const char *s, char c)
 253 {
 254     int count;
 255     for (count = 0; *s != '\0'; s++)
 256         count += (*s == c);
 257     return count;
 258 }
 259 
 260 static const char * const *
 261 effectivePathv(JNIEnv *env)
 262 {
 263     char *p;
 264     int i;
 265     const char *path = effectivePath();
 266     int count = countOccurrences(path, ':') + 1;
 267     size_t pathvsize = sizeof(const char *) * (count+1);
 268     size_t pathsize = strlen(path) + 1;
 269     const char **pathv = (const char **) xmalloc(env, pathvsize + pathsize);
 270 
 271     if (pathv == NULL)
 272         return NULL;
 273     p = (char *) pathv + pathvsize;
 274     memcpy(p, path, pathsize);
 275     /* split PATH by replacing ':' with NULs; empty components => "." */
 276     for (i = 0; i < count; i++) {
 277         char *q = p + strcspn(p, ":");
 278         pathv[i] = (p == q) ? "." : p;
 279         *q = '\0';
 280         p = q + 1;
 281     }
 282     pathv[count] = NULL;
 283     return pathv;
 284 }
 285 
 286 JNIEXPORT void JNICALL
 287 Java_java_lang_ProcessImpl_init(JNIEnv *env, jclass clazz)
 288 {
 289     parentPathv = effectivePathv(env);
 290     CHECK_NULL(parentPathv);
 291     setSIGCHLDHandler(env);
 292 }
 293 
 294 
 295 #ifndef WIFEXITED
 296 #define WIFEXITED(status) (((status)&0xFF) == 0)
 297 #endif
 298 
 299 #ifndef WEXITSTATUS
 300 #define WEXITSTATUS(status) (((status)>>8)&0xFF)
 301 #endif
 302 
 303 #ifndef WIFSIGNALED
 304 #define WIFSIGNALED(status) (((status)&0xFF) > 0 && ((status)&0xFF00) == 0)
 305 #endif
 306 
 307 #ifndef WTERMSIG
 308 #define WTERMSIG(status) ((status)&0x7F)
 309 #endif
 310 
 311 static const char *
 312 getBytes(JNIEnv *env, jbyteArray arr)
 313 {
 314     return arr == NULL ? NULL :
 315         (const char*) (*env)->GetByteArrayElements(env, arr, NULL);
 316 }
 317 
 318 static void
 319 releaseBytes(JNIEnv *env, jbyteArray arr, const char* parr)
 320 {
 321     if (parr != NULL)
 322         (*env)->ReleaseByteArrayElements(env, arr, (jbyte*) parr, JNI_ABORT);
 323 }
 324 
 325 #define IOE_FORMAT "error=%d, %s"
 326 
 327 static void
 328 throwIOException(JNIEnv *env, int errnum, const char *defaultDetail)
 329 {
 330     const char *detail = defaultDetail;
 331     char *errmsg;
 332     size_t fmtsize;
 333     char tmpbuf[1024];
 334     jstring s;
 335 
 336     if (errnum != 0) {
 337         int ret = getErrorString(errnum, tmpbuf, sizeof(tmpbuf));
 338         if (ret != EINVAL)
 339             detail = tmpbuf;
 340     }
 341     /* ASCII Decimal representation uses 2.4 times as many bits as binary. */
 342     fmtsize = sizeof(IOE_FORMAT) + strlen(detail) + 3 * sizeof(errnum);
 343     errmsg = NEW(char, fmtsize);
 344     if (errmsg == NULL)
 345         return;
 346 
 347     snprintf(errmsg, fmtsize, IOE_FORMAT, errnum, detail);
 348     s = JNU_NewStringPlatform(env, errmsg);
 349     if (s != NULL) {
 350         jobject x = JNU_NewObjectByName(env, "java/io/IOException",
 351                                         "(Ljava/lang/String;)V", s);
 352         if (x != NULL)
 353             (*env)->Throw(env, x);
 354     }
 355     free(errmsg);
 356 }
 357 
 358 #ifdef DEBUG_PROCESS
 359 /* Debugging process code is difficult; where to write debug output? */
 360 static void
 361 debugPrint(char *format, ...)
 362 {
 363     FILE *tty = fopen("/dev/tty", "w");
 364     va_list ap;
 365     va_start(ap, format);
 366     vfprintf(tty, format, ap);
 367     va_end(ap);
 368     fclose(tty);
 369 }
 370 #endif /* DEBUG_PROCESS */
 371 
 372 static void
 373 copyPipe(int from[2], int to[2])
 374 {
 375     to[0] = from[0];
 376     to[1] = from[1];
 377 }
 378 
 379 /* arg is an array of pointers to 0 terminated strings. array is terminated
 380  * by a null element.
 381  *
 382  * *nelems and *nbytes receive the number of elements of array (incl 0)
 383  * and total number of bytes (incl. 0)
 384  * Note. An empty array will have one null element
 385  * But if arg is null, then *nelems set to 0, and *nbytes to 0
 386  */
 387 static void arraysize(const char * const *arg, int *nelems, int *nbytes)
 388 {
 389     int i, bytes, count;
 390     const char * const *a = arg;
 391     char *p;
 392     int *q;
 393     if (arg == 0) {
 394         *nelems = 0;
 395         *nbytes = 0;
 396         return;
 397     }
 398     /* count the array elements and number of bytes */
 399     for (count=0, bytes=0; *a != 0; count++, a++) {
 400         bytes += strlen(*a)+1;
 401     }
 402     *nbytes = bytes;
 403     *nelems = count+1;
 404 }
 405 
 406 /* copy the strings from arg[] into buf, starting at given offset
 407  * return new offset to next free byte
 408  */
 409 static int copystrings(char *buf, int offset, const char * const *arg) {
 410     char *p;
 411     const char * const *a;
 412     int count=0;
 413 
 414     if (arg == 0) {
 415         return offset;
 416     }
 417     for (p=buf+offset, a=arg; *a != 0; a++) {
 418         int len = strlen(*a) +1;
 419         memcpy(p, *a, len);
 420         p += len;
 421         count += len;
 422     }
 423     return offset+count;
 424 }
 425 
 426 /**
 427  * We are unusually paranoid; use of vfork is
 428  * especially likely to tickle gcc/glibc bugs.
 429  */
 430 #ifdef __attribute_noinline__  /* See: sys/cdefs.h */
 431 __attribute_noinline__
 432 #endif
 433 
 434 /* vfork(2) is deprecated on Solaris */
 435 #ifndef __solaris__
 436 static pid_t
 437 vforkChild(ChildStuff *c) {
 438     volatile pid_t resultPid;
 439 
 440     /*
 441      * We separate the call to vfork into a separate function to make
 442      * very sure to keep stack of child from corrupting stack of parent,
 443      * as suggested by the scary gcc warning:
 444      *  warning: variable 'foo' might be clobbered by 'longjmp' or 'vfork'
 445      */
 446     resultPid = vfork();
 447 
 448     if (resultPid == 0) {
 449         childProcess(c);
 450     }
 451     assert(resultPid != 0);  /* childProcess never returns */
 452     return resultPid;
 453 }
 454 #endif
 455 
 456 static pid_t
 457 forkChild(ChildStuff *c) {
 458     pid_t resultPid;
 459 
 460     /*
 461      * From Solaris fork(2): In Solaris 10, a call to fork() is
 462      * identical to a call to fork1(); only the calling thread is
 463      * replicated in the child process. This is the POSIX-specified
 464      * behavior for fork().
 465      */
 466     resultPid = fork();
 467 
 468     if (resultPid == 0) {
 469         childProcess(c);
 470     }
 471     assert(resultPid != 0);  /* childProcess never returns */
 472     return resultPid;
 473 }
 474 
 475 /* Returns 1 if spawnhelper executable bits are set as expected. */
 476 static int check_helper(const char* helperpath) {
 477     struct stat s;
 478     int rc = stat(helperpath, &s);
 479     if (rc == 0) {
 480         /* Require all bits set since this is how jspawnhelper
 481          * is set up in a canonical installation */
 482         if (s.st_mode & S_IXUSR &&
 483             s.st_mode & S_IXGRP &&
 484             s.st_mode & S_IXOTH) {
 485             return 1;
 486         } else {
 487             return 0;
 488         }
 489     } else {
 490         return 0;
 491     }
 492 }
 493 
 494 static pid_t
 495 spawnChild(JNIEnv *env, jobject process, ChildStuff *c, const char *helperpath) {
 496     pid_t resultPid;
 497     jboolean isCopy;
 498     int i, offset, rval, bufsize, magic;
 499     char *buf, buf1[16];
 500     char *hlpargs[2];
 501     SpawnInfo sp;
 502 
 503     /* Some posix_spawn() implementations do not report exec() errors back to the caller;
 504      * POSIX leaves that up to the implementor, it only requires the child process to fail with
 505      * error code 127.
 506      * Since we cannot use that information (the payload binary may also use exit code 127 for
 507      * its own purposes), lets do at least a basic guess if exec(jspawnhelper) will succeed.
 508      * There are many reasons why it could fail, most of which one cannot be tested without
 509      * exec'ing, but we can at least check permissions. Since jspawnhelper is part of the JDK
 510      * it should have the execute permissions set correctly. */
 511     if (check_helper(helperpath) == 0) {
 512         throwIOException(env, 0, "jspawnhelper is not accessible.");
 513         return -1;
 514     }
 515 
 516     /* need to tell helper which fd is for receiving the childstuff
 517      * and which fd to send response back on
 518      */
 519     snprintf(buf1, sizeof(buf1), "%d:%d", c->childenv[0], c->fail[1]);
 520     /* put the fd string as argument to the helper cmd */
 521     hlpargs[0] = buf1;
 522     hlpargs[1] = 0;
 523 
 524     /* Following items are sent down the pipe to the helper
 525      * after it is spawned.
 526      * All strings are null terminated. All arrays of strings
 527      * have an empty string for termination.
 528      * - the ChildStuff struct
 529      * - the SpawnInfo struct
 530      * - the argv strings array
 531      * - the envv strings array
 532      * - the home directory string
 533      * - the parentPath string
 534      * - the parentPathv array
 535      */
 536     /* First calculate the sizes */
 537     arraysize(c->argv, &sp.nargv, &sp.argvBytes);
 538     bufsize = sp.argvBytes;
 539     arraysize(c->envv, &sp.nenvv, &sp.envvBytes);
 540     bufsize += sp.envvBytes;
 541     sp.dirlen = c->pdir == 0 ? 0 : strlen(c->pdir)+1;
 542     bufsize += sp.dirlen;
 543     arraysize(parentPathv, &sp.nparentPathv, &sp.parentPathvBytes);
 544     bufsize += sp.parentPathvBytes;
 545     /* We need to clear FD_CLOEXEC if set in the fds[].
 546      * Files are created FD_CLOEXEC in Java.
 547      * Otherwise, they will be closed when the target gets exec'd */
 548     for (i=0; i<3; i++) {
 549         if (c->fds[i] != -1) {
 550             int flags = fcntl(c->fds[i], F_GETFD);
 551             if (flags & FD_CLOEXEC) {
 552                 fcntl(c->fds[i], F_SETFD, flags & (~1));
 553             }
 554         }
 555     }
 556 
 557     rval = posix_spawn(&resultPid, helperpath, 0, 0, (char * const *) hlpargs, environ);
 558 
 559     if (rval != 0) {
 560         return -1;
 561     }
 562 
 563     /* now the lengths are known, copy the data */
 564     buf = NEW(char, bufsize);
 565     if (buf == 0) {
 566         return -1;
 567     }
 568     offset = copystrings(buf, 0, &c->argv[0]);
 569     offset = copystrings(buf, offset, &c->envv[0]);
 570     memcpy(buf+offset, c->pdir, sp.dirlen);
 571     offset += sp.dirlen;
 572     offset = copystrings(buf, offset, parentPathv);
 573     assert(offset == bufsize);
 574 
 575     magic = magicNumber();
 576 
 577     /* write the two structs and the data buffer */
 578     write(c->childenv[1], (char *)&magic, sizeof(magic)); // magic number first
 579     write(c->childenv[1], (char *)c, sizeof(*c));
 580     write(c->childenv[1], (char *)&sp, sizeof(sp));
 581     write(c->childenv[1], buf, bufsize);
 582     free(buf);
 583 
 584     /* In this mode an external main() in invoked which calls back into
 585      * childProcess() in this file, rather than directly
 586      * via the statement below */
 587     return resultPid;
 588 }
 589 
 590 /*
 591  * Start a child process running function childProcess.
 592  * This function only returns in the parent.
 593  */
 594 static pid_t
 595 startChild(JNIEnv *env, jobject process, ChildStuff *c, const char *helperpath) {
 596     switch (c->mode) {
 597 /* vfork(2) is deprecated on Solaris */
 598 #ifndef __solaris__
 599       case MODE_VFORK:
 600         return vforkChild(c);
 601 #endif
 602       case MODE_FORK:
 603         return forkChild(c);
 604       case MODE_POSIX_SPAWN:
 605         return spawnChild(env, process, c, helperpath);
 606       default:
 607         return -1;
 608     }
 609 }
 610 
 611 JNIEXPORT jint JNICALL
 612 Java_java_lang_ProcessImpl_forkAndExec(JNIEnv *env,
 613                                        jobject process,
 614                                        jint mode,
 615                                        jbyteArray helperpath,
 616                                        jbyteArray prog,
 617                                        jbyteArray argBlock, jint argc,
 618                                        jbyteArray envBlock, jint envc,
 619                                        jbyteArray dir,
 620                                        jintArray std_fds,
 621                                        jboolean redirectErrorStream)
 622 {
 623     int errnum;
 624     int resultPid = -1;
 625     int in[2], out[2], err[2], fail[2], childenv[2];
 626     jint *fds = NULL;
 627     const char *phelperpath = NULL;
 628     const char *pprog = NULL;
 629     const char *pargBlock = NULL;
 630     const char *penvBlock = NULL;
 631     ChildStuff *c;
 632 
 633     in[0] = in[1] = out[0] = out[1] = err[0] = err[1] = fail[0] = fail[1] = -1;
 634     childenv[0] = childenv[1] = -1;
 635 
 636     if ((c = NEW(ChildStuff, 1)) == NULL) return -1;
 637     c->argv = NULL;
 638     c->envv = NULL;
 639     c->pdir = NULL;
 640 
 641     /* Convert prog + argBlock into a char ** argv.
 642      * Add one word room for expansion of argv for use by
 643      * execve_as_traditional_shell_script.
 644      * This word is also used when using posix_spawn mode
 645      */
 646     assert(prog != NULL && argBlock != NULL);
 647     if ((phelperpath = getBytes(env, helperpath))   == NULL) goto Catch;
 648     if ((pprog       = getBytes(env, prog))         == NULL) goto Catch;
 649     if ((pargBlock   = getBytes(env, argBlock))     == NULL) goto Catch;
 650     if ((c->argv     = NEW(const char *, argc + 3)) == NULL) goto Catch;
 651     c->argv[0] = pprog;
 652     c->argc = argc + 2;
 653     initVectorFromBlock(c->argv+1, pargBlock, argc);
 654 
 655     if (envBlock != NULL) {
 656         /* Convert envBlock into a char ** envv */
 657         if ((penvBlock = getBytes(env, envBlock))   == NULL) goto Catch;
 658         if ((c->envv = NEW(const char *, envc + 1)) == NULL) goto Catch;
 659         initVectorFromBlock(c->envv, penvBlock, envc);
 660     }
 661 
 662     if (dir != NULL) {
 663         if ((c->pdir = getBytes(env, dir)) == NULL) goto Catch;
 664     }
 665 
 666     assert(std_fds != NULL);
 667     fds = (*env)->GetIntArrayElements(env, std_fds, NULL);
 668     if (fds == NULL) goto Catch;
 669 
 670     if ((fds[0] == -1 && pipe(in)  < 0) ||
 671         (fds[1] == -1 && pipe(out) < 0) ||
 672         (fds[2] == -1 && pipe(err) < 0) ||
 673         (pipe(childenv) < 0) ||
 674         (pipe(fail) < 0)) {
 675         throwIOException(env, errno, "Bad file descriptor");
 676         goto Catch;
 677     }
 678     c->fds[0] = fds[0];
 679     c->fds[1] = fds[1];
 680     c->fds[2] = fds[2];
 681 
 682     copyPipe(in,   c->in);
 683     copyPipe(out,  c->out);
 684     copyPipe(err,  c->err);
 685     copyPipe(fail, c->fail);
 686     copyPipe(childenv, c->childenv);
 687 
 688     c->redirectErrorStream = redirectErrorStream;
 689     c->mode = mode;
 690 
 691     resultPid = startChild(env, process, c, phelperpath);
 692     assert(resultPid != 0);
 693 
 694     if (resultPid < 0) {
 695         /* Throw an IOException with a generic text unless an exception was already raised. */
 696         if (!(*env)->ExceptionCheck(env)) {
 697             switch (c->mode) {
 698               case MODE_VFORK:
 699                 throwIOException(env, errno, "vfork failed");
 700                 break;
 701               case MODE_FORK:
 702                 throwIOException(env, errno, "fork failed");
 703                 break;
 704               case MODE_POSIX_SPAWN:
 705                 throwIOException(env, errno, "posix_spawn failed");
 706                 break;
 707             }
 708         }
 709         goto Catch;
 710     }
 711     close(fail[1]); fail[1] = -1; /* See: WhyCantJohnnyExec  (childproc.c)  */
 712 
 713     switch (readFully(fail[0], &errnum, sizeof(errnum))) {
 714     case 0: break; /* Exec succeeded */
 715     case sizeof(errnum):
 716         waitpid(resultPid, NULL, 0);
 717         throwIOException(env, errnum, "Exec failed");
 718         goto Catch;
 719     default:
 720         throwIOException(env, errno, "Read failed");
 721         goto Catch;
 722     }
 723 
 724     fds[0] = (in [1] != -1) ? in [1] : -1;
 725     fds[1] = (out[0] != -1) ? out[0] : -1;
 726     fds[2] = (err[0] != -1) ? err[0] : -1;
 727 
 728  Finally:
 729     /* Always clean up the child's side of the pipes */
 730     closeSafely(in [0]);
 731     closeSafely(out[1]);
 732     closeSafely(err[1]);
 733 
 734     /* Always clean up fail and childEnv descriptors */
 735     closeSafely(fail[0]);
 736     closeSafely(fail[1]);
 737     closeSafely(childenv[0]);
 738     closeSafely(childenv[1]);
 739 
 740     releaseBytes(env, helperpath, phelperpath);
 741     releaseBytes(env, prog,       pprog);
 742     releaseBytes(env, argBlock,   pargBlock);
 743     releaseBytes(env, envBlock,   penvBlock);
 744     releaseBytes(env, dir,        c->pdir);
 745 
 746     free(c->argv);
 747     free(c->envv);
 748     free(c);
 749 
 750     if (fds != NULL)
 751         (*env)->ReleaseIntArrayElements(env, std_fds, fds, 0);
 752 
 753     return resultPid;
 754 
 755  Catch:
 756     /* Clean up the parent's side of the pipes in case of failure only */
 757     closeSafely(in [1]); in[1] = -1;
 758     closeSafely(out[0]); out[0] = -1;
 759     closeSafely(err[0]); err[0] = -1;
 760     goto Finally;
 761 }
 762