1 /*
   2  * Copyright (c) 1995, 2012, 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 #include <errno.h>
  47 #include <dirent.h>
  48 #include <unistd.h>
  49 #include <fcntl.h>
  50 #include <limits.h>
  51 
  52 #ifdef __APPLE__
  53 #include <crt_externs.h>
  54 #define environ (*_NSGetEnviron())
  55 #endif
  56 
  57 /*
  58  * There are 3 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  * Based on the above analysis, we are currently using vfork() on
  94  * Linux and fork() on other Unix systems, but the code to use clone()
  95  * remains.
  96  */
  97 
  98 #define START_CHILD_USE_CLONE 0  /* clone() currently disabled; see above. */
  99 
 100 #ifndef START_CHILD_USE_CLONE
 101   #ifdef __linux__
 102     #define START_CHILD_USE_CLONE 1
 103   #else
 104     #define START_CHILD_USE_CLONE 0
 105   #endif
 106 #endif
 107 
 108 /* By default, use vfork() on Linux. */
 109 #ifndef START_CHILD_USE_VFORK
 110   #ifdef __linux__
 111     #define START_CHILD_USE_VFORK 1
 112   #else
 113     #define START_CHILD_USE_VFORK 0
 114   #endif
 115 #endif
 116 
 117 #if START_CHILD_USE_CLONE
 118 #include <sched.h>
 119 #define START_CHILD_SYSTEM_CALL "clone"
 120 #elif START_CHILD_USE_VFORK
 121 #define START_CHILD_SYSTEM_CALL "vfork"
 122 #else
 123 #define START_CHILD_SYSTEM_CALL "fork"
 124 #endif
 125 
 126 #ifndef STDIN_FILENO
 127 #define STDIN_FILENO 0
 128 #endif
 129 
 130 #ifndef STDOUT_FILENO
 131 #define STDOUT_FILENO 1
 132 #endif
 133 
 134 #ifndef STDERR_FILENO
 135 #define STDERR_FILENO 2
 136 #endif
 137 
 138 #ifndef SA_NOCLDSTOP
 139 #define SA_NOCLDSTOP 0
 140 #endif
 141 
 142 #ifndef SA_RESTART
 143 #define SA_RESTART 0
 144 #endif
 145 
 146 #define FAIL_FILENO (STDERR_FILENO + 1)
 147 
 148 /* TODO: Refactor. */
 149 #define RESTARTABLE(_cmd, _result) do { \
 150   do { \
 151     _result = _cmd; \
 152   } while((_result == -1) && (errno == EINTR)); \
 153 } while(0)
 154 
 155 /* This is one of the rare times it's more portable to declare an
 156  * external symbol explicitly, rather than via a system header.
 157  * The declaration is standardized as part of UNIX98, but there is
 158  * no standard (not even de-facto) header file where the
 159  * declaration is to be found.  See:
 160  * http://www.opengroup.org/onlinepubs/009695399/functions/environ.html
 161  * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_02.html
 162  *
 163  * "All identifiers in this volume of IEEE Std 1003.1-2001, except
 164  * environ, are defined in at least one of the headers" (!)
 165  */
 166 extern char **environ;
 167 
 168 
 169 static void
 170 setSIGCHLDHandler(JNIEnv *env)
 171 {
 172     /* There is a subtle difference between having the signal handler
 173      * for SIGCHLD be SIG_DFL and SIG_IGN.  We cannot obtain process
 174      * termination information for child processes if the signal
 175      * handler is SIG_IGN.  It must be SIG_DFL.
 176      *
 177      * We used to set the SIGCHLD handler only on Linux, but it's
 178      * safest to set it unconditionally.
 179      *
 180      * Consider what happens if java's parent process sets the SIGCHLD
 181      * handler to SIG_IGN.  Normally signal handlers are inherited by
 182      * children, but SIGCHLD is a controversial case.  Solaris appears
 183      * to always reset it to SIG_DFL, but this behavior may be
 184      * non-standard-compliant, and we shouldn't rely on it.
 185      *
 186      * References:
 187      * http://www.opengroup.org/onlinepubs/7908799/xsh/exec.html
 188      * http://www.pasc.org/interps/unofficial/db/p1003.1/pasc-1003.1-132.html
 189      */
 190     struct sigaction sa;
 191     sa.sa_handler = SIG_DFL;
 192     sigemptyset(&sa.sa_mask);
 193     sa.sa_flags = SA_NOCLDSTOP | SA_RESTART;
 194     if (sigaction(SIGCHLD, &sa, NULL) < 0)
 195         JNU_ThrowInternalError(env, "Can't set SIGCHLD handler");
 196 }
 197 
 198 static void*
 199 xmalloc(JNIEnv *env, size_t size)
 200 {
 201     void *p = malloc(size);
 202     if (p == NULL)
 203         JNU_ThrowOutOfMemoryError(env, NULL);
 204     return p;
 205 }
 206 
 207 #define NEW(type, n) ((type *) xmalloc(env, (n) * sizeof(type)))
 208 
 209 /**
 210  * If PATH is not defined, the OS provides some default value.
 211  * Unfortunately, there's no portable way to get this value.
 212  * Fortunately, it's only needed if the child has PATH while we do not.
 213  */
 214 static const char*
 215 defaultPath(void)
 216 {
 217 #ifdef __solaris__
 218     /* These really are the Solaris defaults! */
 219     return (geteuid() == 0 || getuid() == 0) ?
 220         "/usr/xpg4/bin:/usr/ccs/bin:/usr/bin:/opt/SUNWspro/bin:/usr/sbin" :
 221         "/usr/xpg4/bin:/usr/ccs/bin:/usr/bin:/opt/SUNWspro/bin:";
 222 #else
 223     return ":/bin:/usr/bin";    /* glibc */
 224 #endif
 225 }
 226 
 227 static const char*
 228 effectivePath(void)
 229 {
 230     const char *s = getenv("PATH");
 231     return (s != NULL) ? s : defaultPath();
 232 }
 233 
 234 static int
 235 countOccurrences(const char *s, char c)
 236 {
 237     int count;
 238     for (count = 0; *s != '\0'; s++)
 239         count += (*s == c);
 240     return count;
 241 }
 242 
 243 static const char * const *
 244 splitPath(JNIEnv *env, const char *path)
 245 {
 246     const char *p, *q;
 247     char **pathv;
 248     int i;
 249     int count = countOccurrences(path, ':') + 1;
 250 
 251     pathv = NEW(char*, count+1);
 252     pathv[count] = NULL;
 253     for (p = path, i = 0; i < count; i++, p = q + 1) {
 254         for (q = p; (*q != ':') && (*q != '\0'); q++)
 255             ;
 256         if (q == p)             /* empty PATH component => "." */
 257             pathv[i] = "./";
 258         else {
 259             int addSlash = ((*(q - 1)) != '/');
 260             pathv[i] = NEW(char, q - p + addSlash + 1);
 261             memcpy(pathv[i], p, q - p);
 262             if (addSlash)
 263                 pathv[i][q - p] = '/';
 264             pathv[i][q - p + addSlash] = '\0';
 265         }
 266     }
 267     return (const char * const *) pathv;
 268 }
 269 
 270 /**
 271  * Cached value of JVM's effective PATH.
 272  * (We don't support putenv("PATH=...") in native code)
 273  */
 274 static const char *parentPath;
 275 
 276 /**
 277  * Split, canonicalized version of parentPath
 278  */
 279 static const char * const *parentPathv;
 280 
 281 static jfieldID field_exitcode;
 282 
 283 JNIEXPORT void JNICALL
 284 Java_java_lang_UNIXProcess_initIDs(JNIEnv *env, jclass clazz)
 285 {
 286     field_exitcode = (*env)->GetFieldID(env, clazz, "exitcode", "I");
 287 
 288     parentPath  = effectivePath();
 289     parentPathv = splitPath(env, parentPath);
 290 
 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 /* Block until a child process exits and return its exit code.
 312    Note, can only be called once for any given pid. */
 313 JNIEXPORT jint JNICALL
 314 Java_java_lang_UNIXProcess_waitForProcessExit(JNIEnv* env,
 315                                               jobject junk,
 316                                               jint pid)
 317 {
 318     /* We used to use waitid() on Solaris, waitpid() on Linux, but
 319      * waitpid() is more standard, so use it on all POSIX platforms. */
 320     int status;
 321     /* Wait for the child process to exit.  This returns immediately if
 322        the child has already exited. */
 323     while (waitpid(pid, &status, 0) < 0) {
 324         switch (errno) {
 325         case ECHILD: return 0;
 326         case EINTR: break;
 327         default: return -1;
 328         }
 329     }
 330 
 331     if (WIFEXITED(status)) {
 332         /*
 333          * The child exited normally; get its exit code.
 334          */
 335         return WEXITSTATUS(status);
 336     } else if (WIFSIGNALED(status)) {
 337         /* The child exited because of a signal.
 338          * The best value to return is 0x80 + signal number,
 339          * because that is what all Unix shells do, and because
 340          * it allows callers to distinguish between process exit and
 341          * process death by signal.
 342          * Unfortunately, the historical behavior on Solaris is to return
 343          * the signal number, and we preserve this for compatibility. */
 344 #ifdef __solaris__
 345         return WTERMSIG(status);
 346 #else
 347         return 0x80 + WTERMSIG(status);
 348 #endif
 349     } else {
 350         /*
 351          * Unknown exit code; pass it through.
 352          */
 353         return status;
 354     }
 355 }
 356 
 357 static ssize_t
 358 restartableWrite(int fd, const void *buf, size_t count)
 359 {
 360     ssize_t result;
 361     RESTARTABLE(write(fd, buf, count), result);
 362     return result;
 363 }
 364 
 365 static int
 366 restartableDup2(int fd_from, int fd_to)
 367 {
 368     int err;
 369     RESTARTABLE(dup2(fd_from, fd_to), err);
 370     return err;
 371 }
 372 
 373 static int
 374 restartableClose(int fd)
 375 {
 376     int err;
 377     RESTARTABLE(close(fd), err);
 378     return err;
 379 }
 380 
 381 static int
 382 closeSafely(int fd)
 383 {
 384     return (fd == -1) ? 0 : restartableClose(fd);
 385 }
 386 
 387 static int
 388 isAsciiDigit(char c)
 389 {
 390   return c >= '0' && c <= '9';
 391 }
 392 
 393 #ifdef _ALLBSD_SOURCE
 394 #define FD_DIR "/dev/fd"
 395 #define dirent64 dirent
 396 #define readdir64 readdir
 397 #else
 398 #define FD_DIR "/proc/self/fd"
 399 #endif
 400 
 401 static int
 402 closeDescriptors(void)
 403 {
 404     DIR *dp;
 405     struct dirent64 *dirp;
 406     int from_fd = FAIL_FILENO + 1;
 407 
 408     /* We're trying to close all file descriptors, but opendir() might
 409      * itself be implemented using a file descriptor, and we certainly
 410      * don't want to close that while it's in use.  We assume that if
 411      * opendir() is implemented using a file descriptor, then it uses
 412      * the lowest numbered file descriptor, just like open().  So we
 413      * close a couple explicitly.  */
 414 
 415     restartableClose(from_fd);          /* for possible use by opendir() */
 416     restartableClose(from_fd + 1);      /* another one for good luck */
 417 
 418     if ((dp = opendir(FD_DIR)) == NULL)
 419         return 0;
 420 
 421     /* We use readdir64 instead of readdir to work around Solaris bug
 422      * 6395699: /proc/self/fd fails to report file descriptors >= 1024 on Solaris 9
 423      */
 424     while ((dirp = readdir64(dp)) != NULL) {
 425         int fd;
 426         if (isAsciiDigit(dirp->d_name[0]) &&
 427             (fd = strtol(dirp->d_name, NULL, 10)) >= from_fd + 2)
 428             restartableClose(fd);
 429     }
 430 
 431     closedir(dp);
 432 
 433     return 1;
 434 }
 435 
 436 static int
 437 moveDescriptor(int fd_from, int fd_to)
 438 {
 439     if (fd_from != fd_to) {
 440         if ((restartableDup2(fd_from, fd_to) == -1) ||
 441             (restartableClose(fd_from) == -1))
 442             return -1;
 443     }
 444     return 0;
 445 }
 446 
 447 static const char *
 448 getBytes(JNIEnv *env, jbyteArray arr)
 449 {
 450     return arr == NULL ? NULL :
 451         (const char*) (*env)->GetByteArrayElements(env, arr, NULL);
 452 }
 453 
 454 static void
 455 releaseBytes(JNIEnv *env, jbyteArray arr, const char* parr)
 456 {
 457     if (parr != NULL)
 458         (*env)->ReleaseByteArrayElements(env, arr, (jbyte*) parr, JNI_ABORT);
 459 }
 460 
 461 static void
 462 initVectorFromBlock(const char**vector, const char* block, int count)
 463 {
 464     int i;
 465     const char *p;
 466     for (i = 0, p = block; i < count; i++) {
 467         /* Invariant: p always points to the start of a C string. */
 468         vector[i] = p;
 469         while (*(p++));
 470     }
 471     vector[count] = NULL;
 472 }
 473 
 474 static void
 475 throwIOException(JNIEnv *env, int errnum, const char *defaultDetail)
 476 {
 477     static const char * const format = "error=%d, %s";
 478     const char *detail = defaultDetail;
 479     char *errmsg;
 480     jstring s;
 481 
 482     if (errnum != 0) {
 483         const char *s = strerror(errnum);
 484         if (strcmp(s, "Unknown error") != 0)
 485             detail = s;
 486     }
 487     /* ASCII Decimal representation uses 2.4 times as many bits as binary. */
 488     errmsg = NEW(char, strlen(format) + strlen(detail) + 3 * sizeof(errnum));
 489     sprintf(errmsg, format, errnum, detail);
 490     s = JNU_NewStringPlatform(env, errmsg);
 491     if (s != NULL) {
 492         jobject x = JNU_NewObjectByName(env, "java/io/IOException",
 493                                         "(Ljava/lang/String;)V", s);
 494         if (x != NULL)
 495             (*env)->Throw(env, x);
 496     }
 497     free(errmsg);
 498 }
 499 
 500 #ifdef DEBUG_PROCESS
 501 /* Debugging process code is difficult; where to write debug output? */
 502 static void
 503 debugPrint(char *format, ...)
 504 {
 505     FILE *tty = fopen("/dev/tty", "w");
 506     va_list ap;
 507     va_start(ap, format);
 508     vfprintf(tty, format, ap);
 509     va_end(ap);
 510     fclose(tty);
 511 }
 512 #endif /* DEBUG_PROCESS */
 513 
 514 /**
 515  * Exec FILE as a traditional Bourne shell script (i.e. one without #!).
 516  * If we could do it over again, we would probably not support such an ancient
 517  * misfeature, but compatibility wins over sanity.  The original support for
 518  * this was imported accidentally from execvp().
 519  */
 520 static void
 521 execve_as_traditional_shell_script(const char *file,
 522                                    const char *argv[],
 523                                    const char *const envp[])
 524 {
 525     /* Use the extra word of space provided for us in argv by caller. */
 526     const char *argv0 = argv[0];
 527     const char *const *end = argv;
 528     while (*end != NULL)
 529         ++end;
 530     memmove(argv+2, argv+1, (end-argv) * sizeof (*end));
 531     argv[0] = "/bin/sh";
 532     argv[1] = file;
 533     execve(argv[0], (char **) argv, (char **) envp);
 534     /* Can't even exec /bin/sh?  Big trouble, but let's soldier on... */
 535     memmove(argv+1, argv+2, (end-argv) * sizeof (*end));
 536     argv[0] = argv0;
 537 }
 538 
 539 /**
 540  * Like execve(2), except that in case of ENOEXEC, FILE is assumed to
 541  * be a shell script and the system default shell is invoked to run it.
 542  */
 543 static void
 544 execve_with_shell_fallback(const char *file,
 545                            const char *argv[],
 546                            const char *const envp[])
 547 {
 548 #if START_CHILD_USE_CLONE || START_CHILD_USE_VFORK
 549     /* shared address space; be very careful. */
 550     execve(file, (char **) argv, (char **) envp);
 551     if (errno == ENOEXEC)
 552         execve_as_traditional_shell_script(file, argv, envp);
 553 #else
 554     /* unshared address space; we can mutate environ. */
 555     environ = (char **) envp;
 556     execvp(file, (char **) argv);
 557 #endif
 558 }
 559 
 560 /**
 561  * 'execvpe' should have been included in the Unix standards,
 562  * and is a GNU extension in glibc 2.10.
 563  *
 564  * JDK_execvpe is identical to execvp, except that the child environment is
 565  * specified via the 3rd argument instead of being inherited from environ.
 566  */
 567 static void
 568 JDK_execvpe(const char *file,
 569             const char *argv[],
 570             const char *const envp[])
 571 {
 572     if (envp == NULL || (char **) envp == environ) {
 573         execvp(file, (char **) argv);
 574         return;
 575     }
 576 
 577     if (*file == '\0') {
 578         errno = ENOENT;
 579         return;
 580     }
 581 
 582     if (strchr(file, '/') != NULL) {
 583         execve_with_shell_fallback(file, argv, envp);
 584     } else {
 585         /* We must search PATH (parent's, not child's) */
 586         char expanded_file[PATH_MAX];
 587         int filelen = strlen(file);
 588         int sticky_errno = 0;
 589         const char * const * dirs;
 590         for (dirs = parentPathv; *dirs; dirs++) {
 591             const char * dir = *dirs;
 592             int dirlen = strlen(dir);
 593             if (filelen + dirlen + 1 >= PATH_MAX) {
 594                 errno = ENAMETOOLONG;
 595                 continue;
 596             }
 597             memcpy(expanded_file, dir, dirlen);
 598             memcpy(expanded_file + dirlen, file, filelen);
 599             expanded_file[dirlen + filelen] = '\0';
 600             execve_with_shell_fallback(expanded_file, argv, envp);
 601             /* There are 3 responses to various classes of errno:
 602              * return immediately, continue (especially for ENOENT),
 603              * or continue with "sticky" errno.
 604              *
 605              * From exec(3):
 606              *
 607              * If permission is denied for a file (the attempted
 608              * execve returned EACCES), these functions will continue
 609              * searching the rest of the search path.  If no other
 610              * file is found, however, they will return with the
 611              * global variable errno set to EACCES.
 612              */
 613             switch (errno) {
 614             case EACCES:
 615                 sticky_errno = errno;
 616                 /* FALLTHRU */
 617             case ENOENT:
 618             case ENOTDIR:
 619 #ifdef ELOOP
 620             case ELOOP:
 621 #endif
 622 #ifdef ESTALE
 623             case ESTALE:
 624 #endif
 625 #ifdef ENODEV
 626             case ENODEV:
 627 #endif
 628 #ifdef ETIMEDOUT
 629             case ETIMEDOUT:
 630 #endif
 631                 break; /* Try other directories in PATH */
 632             default:
 633                 return;
 634             }
 635         }
 636         if (sticky_errno != 0)
 637             errno = sticky_errno;
 638     }
 639 }
 640 
 641 /*
 642  * Reads nbyte bytes from file descriptor fd into buf,
 643  * The read operation is retried in case of EINTR or partial reads.
 644  *
 645  * Returns number of bytes read (normally nbyte, but may be less in
 646  * case of EOF).  In case of read errors, returns -1 and sets errno.
 647  */
 648 static ssize_t
 649 readFully(int fd, void *buf, size_t nbyte)
 650 {
 651     ssize_t remaining = nbyte;
 652     for (;;) {
 653         ssize_t n = read(fd, buf, remaining);
 654         if (n == 0) {
 655             return nbyte - remaining;
 656         } else if (n > 0) {
 657             remaining -= n;
 658             if (remaining <= 0)
 659                 return nbyte;
 660             /* We were interrupted in the middle of reading the bytes.
 661              * Unlikely, but possible. */
 662             buf = (void *) (((char *)buf) + n);
 663         } else if (errno == EINTR) {
 664             /* Strange signals like SIGJVM1 are possible at any time.
 665              * See http://www.dreamsongs.com/WorseIsBetter.html */
 666         } else {
 667             return -1;
 668         }
 669     }
 670 }
 671 
 672 typedef struct _ChildStuff
 673 {
 674     int in[2];
 675     int out[2];
 676     int err[2];
 677     int fail[2];
 678     int fds[3];
 679     const char **argv;
 680     const char **envv;
 681     const char *pdir;
 682     jboolean redirectErrorStream;
 683 #if START_CHILD_USE_CLONE
 684     void *clone_stack;
 685 #endif
 686 } ChildStuff;
 687 
 688 static void
 689 copyPipe(int from[2], int to[2])
 690 {
 691     to[0] = from[0];
 692     to[1] = from[1];
 693 }
 694 
 695 /**
 696  * Child process after a successful fork() or clone().
 697  * This function must not return, and must be prepared for either all
 698  * of its address space to be shared with its parent, or to be a copy.
 699  * It must not modify global variables such as "environ".
 700  */
 701 static int
 702 childProcess(void *arg)
 703 {
 704     const ChildStuff* p = (const ChildStuff*) arg;
 705 
 706     /* Close the parent sides of the pipes.
 707        Closing pipe fds here is redundant, since closeDescriptors()
 708        would do it anyways, but a little paranoia is a good thing. */
 709     if ((closeSafely(p->in[1])   == -1) ||
 710         (closeSafely(p->out[0])  == -1) ||
 711         (closeSafely(p->err[0])  == -1) ||
 712         (closeSafely(p->fail[0]) == -1))
 713         goto WhyCantJohnnyExec;
 714 
 715     /* Give the child sides of the pipes the right fileno's. */
 716     /* Note: it is possible for in[0] == 0 */
 717     if ((moveDescriptor(p->in[0] != -1 ?  p->in[0] : p->fds[0],
 718                         STDIN_FILENO) == -1) ||
 719         (moveDescriptor(p->out[1]!= -1 ? p->out[1] : p->fds[1],
 720                         STDOUT_FILENO) == -1))
 721         goto WhyCantJohnnyExec;
 722 
 723     if (p->redirectErrorStream) {
 724         if ((closeSafely(p->err[1]) == -1) ||
 725             (restartableDup2(STDOUT_FILENO, STDERR_FILENO) == -1))
 726             goto WhyCantJohnnyExec;
 727     } else {
 728         if (moveDescriptor(p->err[1] != -1 ? p->err[1] : p->fds[2],
 729                            STDERR_FILENO) == -1)
 730             goto WhyCantJohnnyExec;
 731     }
 732 
 733     if (moveDescriptor(p->fail[1], FAIL_FILENO) == -1)
 734         goto WhyCantJohnnyExec;
 735 
 736     /* close everything */
 737     if (closeDescriptors() == 0) { /* failed,  close the old way */
 738         int max_fd = (int)sysconf(_SC_OPEN_MAX);
 739         int fd;
 740         for (fd = FAIL_FILENO + 1; fd < max_fd; fd++)
 741             if (restartableClose(fd) == -1 && errno != EBADF)
 742                 goto WhyCantJohnnyExec;
 743     }
 744 
 745     /* change to the new working directory */
 746     if (p->pdir != NULL && chdir(p->pdir) < 0)
 747         goto WhyCantJohnnyExec;
 748 
 749     if (fcntl(FAIL_FILENO, F_SETFD, FD_CLOEXEC) == -1)
 750         goto WhyCantJohnnyExec;
 751 
 752     JDK_execvpe(p->argv[0], p->argv, p->envv);
 753 
 754  WhyCantJohnnyExec:
 755     /* We used to go to an awful lot of trouble to predict whether the
 756      * child would fail, but there is no reliable way to predict the
 757      * success of an operation without *trying* it, and there's no way
 758      * to try a chdir or exec in the parent.  Instead, all we need is a
 759      * way to communicate any failure back to the parent.  Easy; we just
 760      * send the errno back to the parent over a pipe in case of failure.
 761      * The tricky thing is, how do we communicate the *success* of exec?
 762      * We use FD_CLOEXEC together with the fact that a read() on a pipe
 763      * yields EOF when the write ends (we have two of them!) are closed.
 764      */
 765     {
 766         int errnum = errno;
 767         restartableWrite(FAIL_FILENO, &errnum, sizeof(errnum));
 768     }
 769     restartableClose(FAIL_FILENO);
 770     _exit(-1);
 771     return 0;  /* Suppress warning "no return value from function" */
 772 }
 773 
 774 /**
 775  * Start a child process running function childProcess.
 776  * This function only returns in the parent.
 777  * We are unusually paranoid; use of clone/vfork is
 778  * especially likely to tickle gcc/glibc bugs.
 779  */
 780 #ifdef __attribute_noinline__  /* See: sys/cdefs.h */
 781 __attribute_noinline__
 782 #endif
 783 static pid_t
 784 startChild(ChildStuff *c) {
 785 #if START_CHILD_USE_CLONE
 786 #define START_CHILD_CLONE_STACK_SIZE (64 * 1024)
 787     /*
 788      * See clone(2).
 789      * Instead of worrying about which direction the stack grows, just
 790      * allocate twice as much and start the stack in the middle.
 791      */
 792     if ((c->clone_stack = malloc(2 * START_CHILD_CLONE_STACK_SIZE)) == NULL)
 793         /* errno will be set to ENOMEM */
 794         return -1;
 795     return clone(childProcess,
 796                  c->clone_stack + START_CHILD_CLONE_STACK_SIZE,
 797                  CLONE_VFORK | CLONE_VM | SIGCHLD, c);
 798 #else
 799   #if START_CHILD_USE_VFORK
 800     /*
 801      * We separate the call to vfork into a separate function to make
 802      * very sure to keep stack of child from corrupting stack of parent,
 803      * as suggested by the scary gcc warning:
 804      *  warning: variable 'foo' might be clobbered by 'longjmp' or 'vfork'
 805      */
 806     volatile pid_t resultPid = vfork();
 807   #else
 808     /*
 809      * From Solaris fork(2): In Solaris 10, a call to fork() is
 810      * identical to a call to fork1(); only the calling thread is
 811      * replicated in the child process. This is the POSIX-specified
 812      * behavior for fork().
 813      */
 814     pid_t resultPid = fork();
 815   #endif
 816     if (resultPid == 0)
 817         childProcess(c);
 818     assert(resultPid != 0);  /* childProcess never returns */
 819     return resultPid;
 820 #endif /* ! START_CHILD_USE_CLONE */
 821 }
 822 
 823 JNIEXPORT jint JNICALL
 824 Java_java_lang_UNIXProcess_forkAndExec(JNIEnv *env,
 825                                        jobject process,
 826                                        jbyteArray prog,
 827                                        jbyteArray argBlock, jint argc,
 828                                        jbyteArray envBlock, jint envc,
 829                                        jbyteArray dir,
 830                                        jintArray std_fds,
 831                                        jboolean redirectErrorStream)
 832 {
 833     int errnum;
 834     int resultPid = -1;
 835     int in[2], out[2], err[2], fail[2];
 836     jint *fds = NULL;
 837     const char *pprog = NULL;
 838     const char *pargBlock = NULL;
 839     const char *penvBlock = NULL;
 840     ChildStuff *c;
 841 
 842     in[0] = in[1] = out[0] = out[1] = err[0] = err[1] = fail[0] = fail[1] = -1;
 843 
 844     if ((c = NEW(ChildStuff, 1)) == NULL) return -1;
 845     c->argv = NULL;
 846     c->envv = NULL;
 847     c->pdir = NULL;
 848 #if START_CHILD_USE_CLONE
 849     c->clone_stack = NULL;
 850 #endif
 851 
 852     /* Convert prog + argBlock into a char ** argv.
 853      * Add one word room for expansion of argv for use by
 854      * execve_as_traditional_shell_script.
 855      */
 856     assert(prog != NULL && argBlock != NULL);
 857     if ((pprog     = getBytes(env, prog))       == NULL) goto Catch;
 858     if ((pargBlock = getBytes(env, argBlock))   == NULL) goto Catch;
 859     if ((c->argv = NEW(const char *, argc + 3)) == NULL) goto Catch;
 860     c->argv[0] = pprog;
 861     initVectorFromBlock(c->argv+1, pargBlock, argc);
 862 
 863     if (envBlock != NULL) {
 864         /* Convert envBlock into a char ** envv */
 865         if ((penvBlock = getBytes(env, envBlock))   == NULL) goto Catch;
 866         if ((c->envv = NEW(const char *, envc + 1)) == NULL) goto Catch;
 867         initVectorFromBlock(c->envv, penvBlock, envc);
 868     }
 869 
 870     if (dir != NULL) {
 871         if ((c->pdir = getBytes(env, dir)) == NULL) goto Catch;
 872     }
 873 
 874     assert(std_fds != NULL);
 875     fds = (*env)->GetIntArrayElements(env, std_fds, NULL);
 876     if (fds == NULL) goto Catch;
 877 
 878     if ((fds[0] == -1 && pipe(in)  < 0) ||
 879         (fds[1] == -1 && pipe(out) < 0) ||
 880         (fds[2] == -1 && pipe(err) < 0) ||
 881         (pipe(fail) < 0)) {
 882         throwIOException(env, errno, "Bad file descriptor");
 883         goto Catch;
 884     }
 885     c->fds[0] = fds[0];
 886     c->fds[1] = fds[1];
 887     c->fds[2] = fds[2];
 888 
 889     copyPipe(in,   c->in);
 890     copyPipe(out,  c->out);
 891     copyPipe(err,  c->err);
 892     copyPipe(fail, c->fail);
 893 
 894     c->redirectErrorStream = redirectErrorStream;
 895 
 896     resultPid = startChild(c);
 897     assert(resultPid != 0);
 898 
 899     if (resultPid < 0) {
 900         throwIOException(env, errno, START_CHILD_SYSTEM_CALL " failed");
 901         goto Catch;
 902     }
 903 
 904     restartableClose(fail[1]); fail[1] = -1; /* See: WhyCantJohnnyExec */
 905 
 906     switch (readFully(fail[0], &errnum, sizeof(errnum))) {
 907     case 0: break; /* Exec succeeded */
 908     case sizeof(errnum):
 909         waitpid(resultPid, NULL, 0);
 910         throwIOException(env, errnum, "Exec failed");
 911         goto Catch;
 912     default:
 913         throwIOException(env, errno, "Read failed");
 914         goto Catch;
 915     }
 916 
 917     fds[0] = (in [1] != -1) ? in [1] : -1;
 918     fds[1] = (out[0] != -1) ? out[0] : -1;
 919     fds[2] = (err[0] != -1) ? err[0] : -1;
 920 
 921  Finally:
 922 #if START_CHILD_USE_CLONE
 923     free(c->clone_stack);
 924 #endif
 925 
 926     /* Always clean up the child's side of the pipes */
 927     closeSafely(in [0]);
 928     closeSafely(out[1]);
 929     closeSafely(err[1]);
 930 
 931     /* Always clean up fail descriptors */
 932     closeSafely(fail[0]);
 933     closeSafely(fail[1]);
 934 
 935     releaseBytes(env, prog,     pprog);
 936     releaseBytes(env, argBlock, pargBlock);
 937     releaseBytes(env, envBlock, penvBlock);
 938     releaseBytes(env, dir,      c->pdir);
 939 
 940     free(c->argv);
 941     free(c->envv);
 942     free(c);
 943 
 944     if (fds != NULL)
 945         (*env)->ReleaseIntArrayElements(env, std_fds, fds, 0);
 946 
 947     return resultPid;
 948 
 949  Catch:
 950     /* Clean up the parent's side of the pipes in case of failure only */
 951     closeSafely(in [1]);
 952     closeSafely(out[0]);
 953     closeSafely(err[0]);
 954     goto Finally;
 955 }
 956 
 957 JNIEXPORT void JNICALL
 958 Java_java_lang_UNIXProcess_destroyProcess(JNIEnv *env,
 959                                           jobject junk,
 960                                           jint pid,
 961                                           jboolean force)
 962 {
 963     int sig = (force == JNI_TRUE) ? SIGKILL : SIGTERM;
 964     kill(pid, sig);
 965 }