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