src/solaris/native/java/lang/UNIXProcess_md.c

Print this page




  30 #include "jvm.h"
  31 #include "jvm_md.h"
  32 #include "jni_util.h"
  33 #include "io_util.h"
  34 
  35 /*
  36  * Platform-specific support for java.lang.Process
  37  */
  38 #include <assert.h>
  39 #include <stddef.h>
  40 #include <stdlib.h>
  41 #include <sys/types.h>
  42 #include <ctype.h>
  43 #ifdef _ALLBSD_SOURCE
  44 #include <sys/wait.h>
  45 #else
  46 #include <wait.h>
  47 #endif
  48 #include <signal.h>
  49 #include <string.h>
  50 #include <errno.h>
  51 #include <dirent.h>
  52 #include <unistd.h>
  53 #include <fcntl.h>
  54 #include <limits.h>
  55 
  56 #ifdef __APPLE__
  57 #include <crt_externs.h>
  58 #define environ (*_NSGetEnviron())
  59 #endif
  60 


  61 /*
  62  * There are 3 possible strategies we might use to "fork":
  63  *
  64  * - fork(2).  Very portable and reliable but subject to
  65  *   failure due to overcommit (see the documentation on
  66  *   /proc/sys/vm/overcommit_memory in Linux proc(5)).
  67  *   This is the ancient problem of spurious failure whenever a large
  68  *   process starts a small subprocess.
  69  *
  70  * - vfork().  Using this is scary because all relevant man pages
  71  *   contain dire warnings, e.g. Linux vfork(2).  But at least it's
  72  *   documented in the glibc docs and is standardized by XPG4.
  73  *   http://www.opengroup.org/onlinepubs/000095399/functions/vfork.html
  74  *   On Linux, one might think that vfork() would be implemented using
  75  *   the clone system call with flag CLONE_VFORK, but in fact vfork is
  76  *   a separate system call (which is a good sign, suggesting that
  77  *   vfork will continue to be supported at least on Linux).
  78  *   Another good sign is that glibc implements posix_spawn using
  79  *   vfork whenever possible.  Note that we cannot use posix_spawn
  80  *   ourselves because there's no reliable way to close all inherited
  81  *   file descriptors.
  82  *
  83  * - clone() with flags CLONE_VM but not CLONE_THREAD.  clone() is
  84  *   Linux-specific, but this ought to work - at least the glibc
  85  *   sources contain code to handle different combinations of CLONE_VM
  86  *   and CLONE_THREAD.  However, when this was implemented, it
  87  *   appeared to fail on 32-bit i386 (but not 64-bit x86_64) Linux with
  88  *   the simple program
  89  *     Runtime.getRuntime().exec("/bin/true").waitFor();
  90  *   with:
  91  *     #  Internal Error (os_linux_x86.cpp:683), pid=19940, tid=2934639536
  92  *     #  Error: pthread_getattr_np failed with errno = 3 (ESRCH)
  93  *   We believe this is a glibc bug, reported here:
  94  *     http://sources.redhat.com/bugzilla/show_bug.cgi?id=10311
  95  *   but the glibc maintainers closed it as WONTFIX.
  96  *










  97  * Based on the above analysis, we are currently using vfork() on
  98  * Linux and fork() on other Unix systems, but the code to use clone()
  99  * remains.
 100  */
 101 
 102 #define START_CHILD_USE_CLONE 0  /* clone() currently disabled; see above. */
 103 
 104 #ifndef START_CHILD_USE_CLONE
 105   #ifdef __linux__
 106     #define START_CHILD_USE_CLONE 1
 107   #else
 108     #define START_CHILD_USE_CLONE 0
 109   #endif
 110 #endif
 111 
 112 /* By default, use vfork() on Linux. */
 113 #ifndef START_CHILD_USE_VFORK
 114   #ifdef __linux__
 115     #define START_CHILD_USE_VFORK 1
 116   #else
 117     #define START_CHILD_USE_VFORK 0
 118   #endif
 119 #endif
 120 
 121 #if START_CHILD_USE_CLONE
 122 #include <sched.h>
 123 #define START_CHILD_SYSTEM_CALL "clone"
 124 #elif START_CHILD_USE_VFORK
 125 #define START_CHILD_SYSTEM_CALL "vfork"
 126 #else
 127 #define START_CHILD_SYSTEM_CALL "fork"
 128 #endif
 129 
 130 #ifndef STDIN_FILENO
 131 #define STDIN_FILENO 0
 132 #endif
 133 
 134 #ifndef STDOUT_FILENO
 135 #define STDOUT_FILENO 1
 136 #endif
 137 
 138 #ifndef STDERR_FILENO
 139 #define STDERR_FILENO 2
 140 #endif
 141 
 142 #ifndef SA_NOCLDSTOP
 143 #define SA_NOCLDSTOP 0
 144 #endif
 145 
 146 #ifndef SA_RESTART
 147 #define SA_RESTART 0
 148 #endif
 149 
 150 #define FAIL_FILENO (STDERR_FILENO + 1)
 151 
 152 /* TODO: Refactor. */
 153 #define RESTARTABLE(_cmd, _result) do { \
 154   do { \
 155     _result = _cmd; \
 156   } while((_result == -1) && (errno == EINTR)); \
 157 } while(0)
 158 
 159 /* This is one of the rare times it's more portable to declare an
 160  * external symbol explicitly, rather than via a system header.
 161  * The declaration is standardized as part of UNIX98, but there is
 162  * no standard (not even de-facto) header file where the
 163  * declaration is to be found.  See:
 164  * http://www.opengroup.org/onlinepubs/009695399/functions/environ.html
 165  * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_02.html
 166  *
 167  * "All identifiers in this volume of IEEE Std 1003.1-2001, except
 168  * environ, are defined in at least one of the headers" (!)
 169  */
 170 extern char **environ;
 171 
 172 
 173 static void
 174 setSIGCHLDHandler(JNIEnv *env)
 175 {
 176     /* There is a subtle difference between having the signal handler
 177      * for SIGCHLD be SIG_DFL and SIG_IGN.  We cannot obtain process
 178      * termination information for child processes if the signal
 179      * handler is SIG_IGN.  It must be SIG_DFL.
 180      *
 181      * We used to set the SIGCHLD handler only on Linux, but it's
 182      * safest to set it unconditionally.
 183      *
 184      * Consider what happens if java's parent process sets the SIGCHLD
 185      * handler to SIG_IGN.  Normally signal handlers are inherited by
 186      * children, but SIGCHLD is a controversial case.  Solaris appears
 187      * to always reset it to SIG_DFL, but this behavior may be
 188      * non-standard-compliant, and we shouldn't rely on it.
 189      *
 190      * References:
 191      * http://www.opengroup.org/onlinepubs/7908799/xsh/exec.html
 192      * http://www.pasc.org/interps/unofficial/db/p1003.1/pasc-1003.1-132.html


 228 #endif
 229 }
 230 
 231 static const char*
 232 effectivePath(void)
 233 {
 234     const char *s = getenv("PATH");
 235     return (s != NULL) ? s : defaultPath();
 236 }
 237 
 238 static int
 239 countOccurrences(const char *s, char c)
 240 {
 241     int count;
 242     for (count = 0; *s != '\0'; s++)
 243         count += (*s == c);
 244     return count;
 245 }
 246 
 247 static const char * const *
 248 splitPath(JNIEnv *env, const char *path)
 249 {
 250     const char *p, *q;
 251     char **pathv;
 252     int i;

 253     int count = countOccurrences(path, ':') + 1;



 254 
 255     pathv = NEW(char*, count+1);
 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             memcpy(pathv[i], p, q - p);
 266             if (addSlash)
 267                 pathv[i][q - p] = '/';
 268             pathv[i][q - p + addSlash] = '\0';
 269         }
 270     }
 271     return (const char * const *) pathv;
 272 }
 273 
 274 /**
 275  * Cached value of JVM's effective PATH.
 276  * (We don't support putenv("PATH=...") in native code)
 277  */
 278 static const char *parentPath;
 279 
 280 /**
 281  * Split, canonicalized version of parentPath
 282  */
 283 static const char * const *parentPathv;
 284 
 285 static jfieldID field_exitcode;
 286 
 287 JNIEXPORT void JNICALL
 288 Java_java_lang_UNIXProcess_initIDs(JNIEnv *env, jclass clazz)
 289 {
 290     field_exitcode = (*env)->GetFieldID(env, clazz, "exitcode", "I");
 291 
 292     parentPath  = effectivePath();
 293     parentPathv = splitPath(env, parentPath);
 294 
 295     setSIGCHLDHandler(env);
 296 }
 297 
 298 
 299 #ifndef WIFEXITED
 300 #define WIFEXITED(status) (((status)&0xFF) == 0)
 301 #endif
 302 
 303 #ifndef WEXITSTATUS
 304 #define WEXITSTATUS(status) (((status)>>8)&0xFF)
 305 #endif
 306 
 307 #ifndef WIFSIGNALED
 308 #define WIFSIGNALED(status) (((status)&0xFF) > 0 && ((status)&0xFF00) == 0)
 309 #endif
 310 
 311 #ifndef WTERMSIG
 312 #define WTERMSIG(status) ((status)&0x7F)
 313 #endif
 314 


 341         /* The child exited because of a signal.
 342          * The best value to return is 0x80 + signal number,
 343          * because that is what all Unix shells do, and because
 344          * it allows callers to distinguish between process exit and
 345          * process death by signal.
 346          * Unfortunately, the historical behavior on Solaris is to return
 347          * the signal number, and we preserve this for compatibility. */
 348 #ifdef __solaris__
 349         return WTERMSIG(status);
 350 #else
 351         return 0x80 + WTERMSIG(status);
 352 #endif
 353     } else {
 354         /*
 355          * Unknown exit code; pass it through.
 356          */
 357         return status;
 358     }
 359 }
 360 
 361 static ssize_t
 362 restartableWrite(int fd, const void *buf, size_t count)
 363 {
 364     ssize_t result;
 365     RESTARTABLE(write(fd, buf, count), result);
 366     return result;
 367 }
 368 
 369 static int
 370 restartableDup2(int fd_from, int fd_to)
 371 {
 372     int err;
 373     RESTARTABLE(dup2(fd_from, fd_to), err);
 374     return err;
 375 }
 376 
 377 static int
 378 restartableClose(int fd)
 379 {
 380     int err;
 381     RESTARTABLE(close(fd), err);
 382     return err;
 383 }
 384 
 385 static int
 386 closeSafely(int fd)
 387 {
 388     return (fd == -1) ? 0 : restartableClose(fd);
 389 }
 390 
 391 static int
 392 isAsciiDigit(char c)
 393 {
 394   return c >= '0' && c <= '9';
 395 }
 396 
 397 #ifdef _ALLBSD_SOURCE
 398 #define FD_DIR "/dev/fd"
 399 #define dirent64 dirent
 400 #define readdir64 readdir
 401 #else
 402 #define FD_DIR "/proc/self/fd"
 403 #endif
 404 
 405 static int
 406 closeDescriptors(void)
 407 {
 408     DIR *dp;
 409     struct dirent64 *dirp;
 410     int from_fd = FAIL_FILENO + 1;
 411 
 412     /* We're trying to close all file descriptors, but opendir() might
 413      * itself be implemented using a file descriptor, and we certainly
 414      * don't want to close that while it's in use.  We assume that if
 415      * opendir() is implemented using a file descriptor, then it uses
 416      * the lowest numbered file descriptor, just like open().  So we
 417      * close a couple explicitly.  */
 418 
 419     restartableClose(from_fd);          /* for possible use by opendir() */
 420     restartableClose(from_fd + 1);      /* another one for good luck */
 421 
 422     if ((dp = opendir(FD_DIR)) == NULL)
 423         return 0;
 424 
 425     /* We use readdir64 instead of readdir to work around Solaris bug
 426      * 6395699: /proc/self/fd fails to report file descriptors >= 1024 on Solaris 9
 427      */
 428     while ((dirp = readdir64(dp)) != NULL) {
 429         int fd;
 430         if (isAsciiDigit(dirp->d_name[0]) &&
 431             (fd = strtol(dirp->d_name, NULL, 10)) >= from_fd + 2)
 432             restartableClose(fd);
 433     }
 434 
 435     closedir(dp);
 436 
 437     return 1;
 438 }
 439 
 440 static int
 441 moveDescriptor(int fd_from, int fd_to)
 442 {
 443     if (fd_from != fd_to) {
 444         if ((restartableDup2(fd_from, fd_to) == -1) ||
 445             (restartableClose(fd_from) == -1))
 446             return -1;
 447     }
 448     return 0;
 449 }
 450 
 451 static const char *
 452 getBytes(JNIEnv *env, jbyteArray arr)
 453 {
 454     return arr == NULL ? NULL :
 455         (const char*) (*env)->GetByteArrayElements(env, arr, NULL);
 456 }
 457 
 458 static void
 459 releaseBytes(JNIEnv *env, jbyteArray arr, const char* parr)
 460 {
 461     if (parr != NULL)
 462         (*env)->ReleaseByteArrayElements(env, arr, (jbyte*) parr, JNI_ABORT);
 463 }
 464 
 465 static void
 466 initVectorFromBlock(const char**vector, const char* block, int count)
 467 {
 468     int i;
 469     const char *p;
 470     for (i = 0, p = block; i < count; i++) {
 471         /* Invariant: p always points to the start of a C string. */
 472         vector[i] = p;
 473         while (*(p++));
 474     }
 475     vector[count] = NULL;
 476 }
 477 
 478 static void
 479 throwIOException(JNIEnv *env, int errnum, const char *defaultDetail)
 480 {
 481     static const char * const format = "error=%d, %s";
 482     const char *detail = defaultDetail;
 483     char *errmsg;
 484     jstring s;
 485 
 486     if (errnum != 0) {
 487         const char *s = strerror(errnum);
 488         if (strcmp(s, "Unknown error") != 0)
 489             detail = s;
 490     }
 491     /* ASCII Decimal representation uses 2.4 times as many bits as binary. */
 492     errmsg = NEW(char, strlen(format) + strlen(detail) + 3 * sizeof(errnum));



 493     sprintf(errmsg, format, errnum, detail);
 494     s = JNU_NewStringPlatform(env, errmsg);
 495     if (s != NULL) {
 496         jobject x = JNU_NewObjectByName(env, "java/io/IOException",
 497                                         "(Ljava/lang/String;)V", s);
 498         if (x != NULL)
 499             (*env)->Throw(env, x);
 500     }
 501     free(errmsg);
 502 }
 503 
 504 #ifdef DEBUG_PROCESS
 505 /* Debugging process code is difficult; where to write debug output? */
 506 static void
 507 debugPrint(char *format, ...)
 508 {
 509     FILE *tty = fopen("/dev/tty", "w");
 510     va_list ap;
 511     va_start(ap, format);
 512     vfprintf(tty, format, ap);
 513     va_end(ap);
 514     fclose(tty);
 515 }
 516 #endif /* DEBUG_PROCESS */
 517 
 518 /**
 519  * Exec FILE as a traditional Bourne shell script (i.e. one without #!).
 520  * If we could do it over again, we would probably not support such an ancient
 521  * misfeature, but compatibility wins over sanity.  The original support for
 522  * this was imported accidentally from execvp().
 523  */
 524 static void
 525 execve_as_traditional_shell_script(const char *file,
 526                                    const char *argv[],
 527                                    const char *const envp[])
 528 {
 529     /* Use the extra word of space provided for us in argv by caller. */
 530     const char *argv0 = argv[0];
 531     const char *const *end = argv;
 532     while (*end != NULL)
 533         ++end;
 534     memmove(argv+2, argv+1, (end-argv) * sizeof (*end));
 535     argv[0] = "/bin/sh";
 536     argv[1] = file;
 537     execve(argv[0], (char **) argv, (char **) envp);
 538     /* Can't even exec /bin/sh?  Big trouble, but let's soldier on... */
 539     memmove(argv+1, argv+2, (end-argv) * sizeof (*end));
 540     argv[0] = argv0;
 541 }
 542 
 543 /**
 544  * Like execve(2), except that in case of ENOEXEC, FILE is assumed to
 545  * be a shell script and the system default shell is invoked to run it.
 546  */
 547 static void
 548 execve_with_shell_fallback(const char *file,
 549                            const char *argv[],
 550                            const char *const envp[])
 551 {
 552 #if START_CHILD_USE_CLONE || START_CHILD_USE_VFORK
 553     /* shared address space; be very careful. */
 554     execve(file, (char **) argv, (char **) envp);
 555     if (errno == ENOEXEC)
 556         execve_as_traditional_shell_script(file, argv, envp);
 557 #else
 558     /* unshared address space; we can mutate environ. */
 559     environ = (char **) envp;
 560     execvp(file, (char **) argv);
 561 #endif
 562 }
 563 
 564 /**
 565  * 'execvpe' should have been included in the Unix standards,
 566  * and is a GNU extension in glibc 2.10.
 567  *
 568  * JDK_execvpe is identical to execvp, except that the child environment is
 569  * specified via the 3rd argument instead of being inherited from environ.


 570  */
 571 static void
 572 JDK_execvpe(const char *file,
 573             const char *argv[],
 574             const char *const envp[])
 575 {
 576     if (envp == NULL || (char **) envp == environ) {
 577         execvp(file, (char **) argv);





 578         return;
 579     }
 580 
 581     if (*file == '\0') {
 582         errno = ENOENT;
 583         return;
 584     }
 585 
 586     if (strchr(file, '/') != NULL) {
 587         execve_with_shell_fallback(file, argv, envp);
 588     } else {
 589         /* We must search PATH (parent's, not child's) */
 590         char expanded_file[PATH_MAX];
 591         int filelen = strlen(file);
 592         int sticky_errno = 0;
 593         const char * const * dirs;
 594         for (dirs = parentPathv; *dirs; dirs++) {
 595             const char * dir = *dirs;
 596             int dirlen = strlen(dir);
 597             if (filelen + dirlen + 1 >= PATH_MAX) {
 598                 errno = ENAMETOOLONG;
 599                 continue;
 600             }
 601             memcpy(expanded_file, dir, dirlen);
 602             memcpy(expanded_file + dirlen, file, filelen);
 603             expanded_file[dirlen + filelen] = '\0';
 604             execve_with_shell_fallback(expanded_file, argv, envp);
 605             /* There are 3 responses to various classes of errno:
 606              * return immediately, continue (especially for ENOENT),
 607              * or continue with "sticky" errno.
 608              *
 609              * From exec(3):
 610              *
 611              * If permission is denied for a file (the attempted
 612              * execve returned EACCES), these functions will continue
 613              * searching the rest of the search path.  If no other
 614              * file is found, however, they will return with the
 615              * global variable errno set to EACCES.
 616              */
 617             switch (errno) {
 618             case EACCES:
 619                 sticky_errno = errno;
 620                 /* FALLTHRU */
 621             case ENOENT:
 622             case ENOTDIR:
 623 #ifdef ELOOP
 624             case ELOOP:
 625 #endif
 626 #ifdef ESTALE
 627             case ESTALE:
 628 #endif
 629 #ifdef ENODEV
 630             case ENODEV:
 631 #endif
 632 #ifdef ETIMEDOUT
 633             case ETIMEDOUT:
 634 #endif
 635                 break; /* Try other directories in PATH */
 636             default:
 637                 return;
 638             }
 639         }
 640         if (sticky_errno != 0)
 641             errno = sticky_errno;
 642     }
 643 }
 644 
 645 /*
 646  * Reads nbyte bytes from file descriptor fd into buf,
 647  * The read operation is retried in case of EINTR or partial reads.
 648  *
 649  * Returns number of bytes read (normally nbyte, but may be less in
 650  * case of EOF).  In case of read errors, returns -1 and sets errno.
 651  */
 652 static ssize_t
 653 readFully(int fd, void *buf, size_t nbyte)
 654 {
 655     ssize_t remaining = nbyte;
 656     for (;;) {
 657         ssize_t n = read(fd, buf, remaining);
 658         if (n == 0) {
 659             return nbyte - remaining;
 660         } else if (n > 0) {
 661             remaining -= n;
 662             if (remaining <= 0)
 663                 return nbyte;
 664             /* We were interrupted in the middle of reading the bytes.
 665              * Unlikely, but possible. */
 666             buf = (void *) (((char *)buf) + n);
 667         } else if (errno == EINTR) {
 668             /* Strange signals like SIGJVM1 are possible at any time.
 669              * See http://www.dreamsongs.com/WorseIsBetter.html */
 670         } else {
 671             return -1;
 672         }
 673     }
 674 }
 675 
 676 typedef struct _ChildStuff
 677 {
 678     int in[2];
 679     int out[2];
 680     int err[2];
 681     int fail[2];
 682     int fds[3];
 683     const char **argv;
 684     const char **envv;
 685     const char *pdir;
 686     jboolean redirectErrorStream;
 687 #if START_CHILD_USE_CLONE
 688     void *clone_stack;
 689 #endif
 690 } ChildStuff;
 691 
 692 static void
 693 copyPipe(int from[2], int to[2])
 694 {
 695     to[0] = from[0];
 696     to[1] = from[1];
 697 }
 698 
 699 /**
 700  * Child process after a successful fork() or clone().
 701  * This function must not return, and must be prepared for either all
 702  * of its address space to be shared with its parent, or to be a copy.
 703  * It must not modify global variables such as "environ".
 704  */
 705 static int
 706 childProcess(void *arg)
 707 {
 708     const ChildStuff* p = (const ChildStuff*) arg;
 709 
 710     /* Close the parent sides of the pipes.
 711        Closing pipe fds here is redundant, since closeDescriptors()
 712        would do it anyways, but a little paranoia is a good thing. */
 713     if ((closeSafely(p->in[1])   == -1) ||
 714         (closeSafely(p->out[0])  == -1) ||
 715         (closeSafely(p->err[0])  == -1) ||
 716         (closeSafely(p->fail[0]) == -1))
 717         goto WhyCantJohnnyExec;
 718 
 719     /* Give the child sides of the pipes the right fileno's. */
 720     /* Note: it is possible for in[0] == 0 */
 721     if ((moveDescriptor(p->in[0] != -1 ?  p->in[0] : p->fds[0],
 722                         STDIN_FILENO) == -1) ||
 723         (moveDescriptor(p->out[1]!= -1 ? p->out[1] : p->fds[1],
 724                         STDOUT_FILENO) == -1))
 725         goto WhyCantJohnnyExec;
 726 
 727     if (p->redirectErrorStream) {
 728         if ((closeSafely(p->err[1]) == -1) ||
 729             (restartableDup2(STDOUT_FILENO, STDERR_FILENO) == -1))
 730             goto WhyCantJohnnyExec;
 731     } else {
 732         if (moveDescriptor(p->err[1] != -1 ? p->err[1] : p->fds[2],
 733                            STDERR_FILENO) == -1)
 734             goto WhyCantJohnnyExec;
 735     }
 736 
 737     if (moveDescriptor(p->fail[1], FAIL_FILENO) == -1)
 738         goto WhyCantJohnnyExec;
 739 
 740     /* close everything */
 741     if (closeDescriptors() == 0) { /* failed,  close the old way */
 742         int max_fd = (int)sysconf(_SC_OPEN_MAX);
 743         int fd;
 744         for (fd = FAIL_FILENO + 1; fd < max_fd; fd++)
 745             if (restartableClose(fd) == -1 && errno != EBADF)
 746                 goto WhyCantJohnnyExec;
 747     }
 748 
 749     /* change to the new working directory */
 750     if (p->pdir != NULL && chdir(p->pdir) < 0)
 751         goto WhyCantJohnnyExec;
 752 
 753     if (fcntl(FAIL_FILENO, F_SETFD, FD_CLOEXEC) == -1)
 754         goto WhyCantJohnnyExec;
 755 
 756     JDK_execvpe(p->argv[0], p->argv, p->envv);
 757 
 758  WhyCantJohnnyExec:
 759     /* We used to go to an awful lot of trouble to predict whether the
 760      * child would fail, but there is no reliable way to predict the
 761      * success of an operation without *trying* it, and there's no way
 762      * to try a chdir or exec in the parent.  Instead, all we need is a
 763      * way to communicate any failure back to the parent.  Easy; we just
 764      * send the errno back to the parent over a pipe in case of failure.
 765      * The tricky thing is, how do we communicate the *success* of exec?
 766      * We use FD_CLOEXEC together with the fact that a read() on a pipe
 767      * yields EOF when the write ends (we have two of them!) are closed.
 768      */
 769     {
 770         int errnum = errno;
 771         restartableWrite(FAIL_FILENO, &errnum, sizeof(errnum));
 772     }
 773     restartableClose(FAIL_FILENO);
 774     _exit(-1);
 775     return 0;  /* Suppress warning "no return value from function" */
 776 }
 777 
 778 /**
 779  * Start a child process running function childProcess.
 780  * This function only returns in the parent.
 781  * We are unusually paranoid; use of clone/vfork is
 782  * especially likely to tickle gcc/glibc bugs.
 783  */
 784 #ifdef __attribute_noinline__  /* See: sys/cdefs.h */
 785 __attribute_noinline__
 786 #endif




 787 static pid_t
 788 startChild(ChildStuff *c) {
 789 #if START_CHILD_USE_CLONE
 790 #define START_CHILD_CLONE_STACK_SIZE (64 * 1024)
 791     /*
 792      * See clone(2).
 793      * Instead of worrying about which direction the stack grows, just
 794      * allocate twice as much and start the stack in the middle.
 795      */
 796     if ((c->clone_stack = malloc(2 * START_CHILD_CLONE_STACK_SIZE)) == NULL)
 797         /* errno will be set to ENOMEM */
 798         return -1;
 799     return clone(childProcess,
 800                  c->clone_stack + START_CHILD_CLONE_STACK_SIZE,
 801                  CLONE_VFORK | CLONE_VM | SIGCHLD, c);
 802 #else
 803   #if START_CHILD_USE_VFORK










 804     /*
 805      * We separate the call to vfork into a separate function to make
 806      * very sure to keep stack of child from corrupting stack of parent,
 807      * as suggested by the scary gcc warning:
 808      *  warning: variable 'foo' might be clobbered by 'longjmp' or 'vfork'
 809      */
 810     volatile pid_t resultPid = vfork();
 811   #else











 812     /*
 813      * From Solaris fork(2): In Solaris 10, a call to fork() is
 814      * identical to a call to fork1(); only the calling thread is
 815      * replicated in the child process. This is the POSIX-specified
 816      * behavior for fork().
 817      */
 818     pid_t resultPid = fork();
 819   #endif
 820     if (resultPid == 0)
 821         childProcess(c);

 822     assert(resultPid != 0);  /* childProcess never returns */
 823     return resultPid;
 824 #endif /* ! START_CHILD_USE_CLONE */
 825 }
 826 









































































































 827 JNIEXPORT jint JNICALL
 828 Java_java_lang_UNIXProcess_forkAndExec(JNIEnv *env,
 829                                        jobject process,


 830                                        jbyteArray prog,
 831                                        jbyteArray argBlock, jint argc,
 832                                        jbyteArray envBlock, jint envc,
 833                                        jbyteArray dir,
 834                                        jintArray std_fds,
 835                                        jboolean redirectErrorStream)
 836 {
 837     int errnum;
 838     int resultPid = -1;
 839     int in[2], out[2], err[2], fail[2];
 840     jint *fds = NULL;

 841     const char *pprog = NULL;
 842     const char *pargBlock = NULL;
 843     const char *penvBlock = NULL;
 844     ChildStuff *c;
 845 
 846     in[0] = in[1] = out[0] = out[1] = err[0] = err[1] = fail[0] = fail[1] = -1;

 847 
 848     if ((c = NEW(ChildStuff, 1)) == NULL) return -1;
 849     c->argv = NULL;
 850     c->envv = NULL;
 851     c->pdir = NULL;
 852 #if START_CHILD_USE_CLONE
 853     c->clone_stack = NULL;
 854 #endif
 855 
 856     /* Convert prog + argBlock into a char ** argv.
 857      * Add one word room for expansion of argv for use by
 858      * execve_as_traditional_shell_script.

 859      */
 860     assert(prog != NULL && argBlock != NULL);

 861     if ((pprog     = getBytes(env, prog))       == NULL) goto Catch;
 862     if ((pargBlock = getBytes(env, argBlock))   == NULL) goto Catch;
 863     if ((c->argv = NEW(const char *, argc + 3)) == NULL) goto Catch;
 864     c->argv[0] = pprog;

 865     initVectorFromBlock(c->argv+1, pargBlock, argc);
 866 
 867     if (envBlock != NULL) {
 868         /* Convert envBlock into a char ** envv */
 869         if ((penvBlock = getBytes(env, envBlock))   == NULL) goto Catch;
 870         if ((c->envv = NEW(const char *, envc + 1)) == NULL) goto Catch;
 871         initVectorFromBlock(c->envv, penvBlock, envc);
 872     }
 873 
 874     if (dir != NULL) {
 875         if ((c->pdir = getBytes(env, dir)) == NULL) goto Catch;
 876     }
 877 
 878     assert(std_fds != NULL);
 879     fds = (*env)->GetIntArrayElements(env, std_fds, NULL);
 880     if (fds == NULL) goto Catch;
 881 
 882     if ((fds[0] == -1 && pipe(in)  < 0) ||
 883         (fds[1] == -1 && pipe(out) < 0) ||
 884         (fds[2] == -1 && pipe(err) < 0) ||

 885         (pipe(fail) < 0)) {
 886         throwIOException(env, errno, "Bad file descriptor");
 887         goto Catch;
 888     }
 889     c->fds[0] = fds[0];
 890     c->fds[1] = fds[1];
 891     c->fds[2] = fds[2];
 892 
 893     copyPipe(in,   c->in);
 894     copyPipe(out,  c->out);
 895     copyPipe(err,  c->err);
 896     copyPipe(fail, c->fail);

 897 
 898     c->redirectErrorStream = redirectErrorStream;

 899 
 900     resultPid = startChild(c);
 901     assert(resultPid != 0);
 902 
 903     if (resultPid < 0) {
 904         throwIOException(env, errno, START_CHILD_SYSTEM_CALL " failed");










 905         goto Catch;
 906     }

 907 
 908     restartableClose(fail[1]); fail[1] = -1; /* See: WhyCantJohnnyExec */
 909 
 910     switch (readFully(fail[0], &errnum, sizeof(errnum))) {
 911     case 0: break; /* Exec succeeded */
 912     case sizeof(errnum):
 913         waitpid(resultPid, NULL, 0);
 914         throwIOException(env, errnum, "Exec failed");
 915         goto Catch;
 916     default:
 917         throwIOException(env, errno, "Read failed");
 918         goto Catch;
 919     }
 920 
 921     fds[0] = (in [1] != -1) ? in [1] : -1;
 922     fds[1] = (out[0] != -1) ? out[0] : -1;
 923     fds[2] = (err[0] != -1) ? err[0] : -1;
 924 
 925  Finally:
 926 #if START_CHILD_USE_CLONE
 927     free(c->clone_stack);
 928 #endif
 929 
 930     /* Always clean up the child's side of the pipes */
 931     closeSafely(in [0]);
 932     closeSafely(out[1]);
 933     closeSafely(err[1]);
 934 
 935     /* Always clean up fail descriptors */
 936     closeSafely(fail[0]);
 937     closeSafely(fail[1]);


 938 
 939     releaseBytes(env, prog,     pprog);
 940     releaseBytes(env, argBlock, pargBlock);
 941     releaseBytes(env, envBlock, penvBlock);
 942     releaseBytes(env, dir,      c->pdir);
 943 
 944     free(c->argv);
 945     free(c->envv);
 946     free(c);
 947 
 948     if (fds != NULL)
 949         (*env)->ReleaseIntArrayElements(env, std_fds, fds, 0);
 950 
 951     return resultPid;
 952 
 953  Catch:
 954     /* Clean up the parent's side of the pipes in case of failure only */
 955     closeSafely(in [1]);
 956     closeSafely(out[0]);
 957     closeSafely(err[0]);
 958     goto Finally;
 959 }
 960 
 961 JNIEXPORT void JNICALL
 962 Java_java_lang_UNIXProcess_destroyProcess(JNIEnv *env, jobject junk, jint pid)
 963 {
 964     kill(pid, SIGTERM);
 965 }


  30 #include "jvm.h"
  31 #include "jvm_md.h"
  32 #include "jni_util.h"
  33 #include "io_util.h"
  34 
  35 /*
  36  * Platform-specific support for java.lang.Process
  37  */
  38 #include <assert.h>
  39 #include <stddef.h>
  40 #include <stdlib.h>
  41 #include <sys/types.h>
  42 #include <ctype.h>
  43 #ifdef _ALLBSD_SOURCE
  44 #include <sys/wait.h>
  45 #else
  46 #include <wait.h>
  47 #endif
  48 #include <signal.h>
  49 #include <string.h>





  50 
  51 #if defined(__solaris__) || defined(_ALLBSD_SOURCE)
  52 #include <spawn.h>

  53 #endif
  54 
  55 #include "childproc.h"
  56 
  57 /*
  58  * There are 4 possible strategies we might use to "fork":
  59  *
  60  * - fork(2).  Very portable and reliable but subject to
  61  *   failure due to overcommit (see the documentation on
  62  *   /proc/sys/vm/overcommit_memory in Linux proc(5)).
  63  *   This is the ancient problem of spurious failure whenever a large
  64  *   process starts a small subprocess.
  65  *
  66  * - vfork().  Using this is scary because all relevant man pages
  67  *   contain dire warnings, e.g. Linux vfork(2).  But at least it's
  68  *   documented in the glibc docs and is standardized by XPG4.
  69  *   http://www.opengroup.org/onlinepubs/000095399/functions/vfork.html
  70  *   On Linux, one might think that vfork() would be implemented using
  71  *   the clone system call with flag CLONE_VFORK, but in fact vfork is
  72  *   a separate system call (which is a good sign, suggesting that
  73  *   vfork will continue to be supported at least on Linux).
  74  *   Another good sign is that glibc implements posix_spawn using
  75  *   vfork whenever possible.  Note that we cannot use posix_spawn
  76  *   ourselves because there's no reliable way to close all inherited
  77  *   file descriptors.
  78  *
  79  * - clone() with flags CLONE_VM but not CLONE_THREAD.  clone() is
  80  *   Linux-specific, but this ought to work - at least the glibc
  81  *   sources contain code to handle different combinations of CLONE_VM
  82  *   and CLONE_THREAD.  However, when this was implemented, it
  83  *   appeared to fail on 32-bit i386 (but not 64-bit x86_64) Linux with
  84  *   the simple program
  85  *     Runtime.getRuntime().exec("/bin/true").waitFor();
  86  *   with:
  87  *     #  Internal Error (os_linux_x86.cpp:683), pid=19940, tid=2934639536
  88  *     #  Error: pthread_getattr_np failed with errno = 3 (ESRCH)
  89  *   We believe this is a glibc bug, reported here:
  90  *     http://sources.redhat.com/bugzilla/show_bug.cgi?id=10311
  91  *   but the glibc maintainers closed it as WONTFIX.
  92  *
  93  * - posix_spawn(). While posix_spawn() is a fairly elaborate and
  94  *   complicated system call, it can't quite do everything that the old
  95  *   fork()/exec() combination can do, so the only feasible way to do
  96  *   this, is to use posix_spawn to launch a new helper executable
  97  *   "jprochelper", which in turn execs the target (after cleaning
  98  *   up file-descriptors etc.) The end result is the same as before,
  99  *   a child process linked to the parent in the same way, but it
 100  *   avoids the problem of duplicating the parent (VM) process
 101  *   address space temporarily, before launching the target command.
 102  *
 103  * Based on the above analysis, we are currently using vfork() on
 104  * Linux, posix_spawn() on Mac and fork() on Solaris, but the code to
 105  * use clone() and fork() remains.
 106  */
 107 

 108 





































































 109 static void
 110 setSIGCHLDHandler(JNIEnv *env)
 111 {
 112     /* There is a subtle difference between having the signal handler
 113      * for SIGCHLD be SIG_DFL and SIG_IGN.  We cannot obtain process
 114      * termination information for child processes if the signal
 115      * handler is SIG_IGN.  It must be SIG_DFL.
 116      *
 117      * We used to set the SIGCHLD handler only on Linux, but it's
 118      * safest to set it unconditionally.
 119      *
 120      * Consider what happens if java's parent process sets the SIGCHLD
 121      * handler to SIG_IGN.  Normally signal handlers are inherited by
 122      * children, but SIGCHLD is a controversial case.  Solaris appears
 123      * to always reset it to SIG_DFL, but this behavior may be
 124      * non-standard-compliant, and we shouldn't rely on it.
 125      *
 126      * References:
 127      * http://www.opengroup.org/onlinepubs/7908799/xsh/exec.html
 128      * http://www.pasc.org/interps/unofficial/db/p1003.1/pasc-1003.1-132.html


 164 #endif
 165 }
 166 
 167 static const char*
 168 effectivePath(void)
 169 {
 170     const char *s = getenv("PATH");
 171     return (s != NULL) ? s : defaultPath();
 172 }
 173 
 174 static int
 175 countOccurrences(const char *s, char c)
 176 {
 177     int count;
 178     for (count = 0; *s != '\0'; s++)
 179         count += (*s == c);
 180     return count;
 181 }
 182 
 183 static const char * const *
 184 effectivePathv(JNIEnv *env)
 185 {
 186     char *p;

 187     int i;
 188     const char *path = effectivePath();
 189     int count = countOccurrences(path, ':') + 1;
 190     size_t pathvsize = sizeof(const char *) * (count+1);
 191     size_t pathsize = strlen(path) + 1;
 192     const char **pathv = (const char **) xmalloc(env, pathvsize + pathsize);
 193 
 194     if (pathv == NULL)
 195         return NULL;
 196     p = (char *) pathv + pathvsize;
 197     memcpy(p, path, pathsize);
 198     /* split PATH by replacing ':' with NULs; empty components => "." */
 199     for (i = 0; i < count; i++) {
 200         char *q = p + strcspn(p, ":");
 201         pathv[i] = (p == q) ? "." : p;
 202         *q = '\0';
 203         p = q + 1;




 204     }
 205     pathv[count] = NULL;
 206     return pathv;
 207 }
 208 













 209 JNIEXPORT void JNICALL
 210 Java_java_lang_UNIXProcess_init(JNIEnv *env, jclass clazz)
 211 {
 212     parentPathv = effectivePathv(env);




 213     setSIGCHLDHandler(env);
 214 }
 215 
 216 
 217 #ifndef WIFEXITED
 218 #define WIFEXITED(status) (((status)&0xFF) == 0)
 219 #endif
 220 
 221 #ifndef WEXITSTATUS
 222 #define WEXITSTATUS(status) (((status)>>8)&0xFF)
 223 #endif
 224 
 225 #ifndef WIFSIGNALED
 226 #define WIFSIGNALED(status) (((status)&0xFF) > 0 && ((status)&0xFF00) == 0)
 227 #endif
 228 
 229 #ifndef WTERMSIG
 230 #define WTERMSIG(status) ((status)&0x7F)
 231 #endif
 232 


 259         /* The child exited because of a signal.
 260          * The best value to return is 0x80 + signal number,
 261          * because that is what all Unix shells do, and because
 262          * it allows callers to distinguish between process exit and
 263          * process death by signal.
 264          * Unfortunately, the historical behavior on Solaris is to return
 265          * the signal number, and we preserve this for compatibility. */
 266 #ifdef __solaris__
 267         return WTERMSIG(status);
 268 #else
 269         return 0x80 + WTERMSIG(status);
 270 #endif
 271     } else {
 272         /*
 273          * Unknown exit code; pass it through.
 274          */
 275         return status;
 276     }
 277 }
 278 


























































































 279 static const char *
 280 getBytes(JNIEnv *env, jbyteArray arr)
 281 {
 282     return arr == NULL ? NULL :
 283         (const char*) (*env)->GetByteArrayElements(env, arr, NULL);
 284 }
 285 
 286 static void
 287 releaseBytes(JNIEnv *env, jbyteArray arr, const char* parr)
 288 {
 289     if (parr != NULL)
 290         (*env)->ReleaseByteArrayElements(env, arr, (jbyte*) parr, JNI_ABORT);
 291 }
 292 
 293 static void













 294 throwIOException(JNIEnv *env, int errnum, const char *defaultDetail)
 295 {
 296     static const char * const format = "error=%d, %s";
 297     const char *detail = defaultDetail;
 298     char *errmsg;
 299     jstring s;
 300 
 301     if (errnum != 0) {
 302         const char *s = strerror(errnum);
 303         if (strcmp(s, "Unknown error") != 0)
 304             detail = s;
 305     }
 306     /* ASCII Decimal representation uses 2.4 times as many bits as binary. */
 307     errmsg = NEW(char, strlen(format) + strlen(detail) + 3 * sizeof(errnum));
 308     if (errmsg == NULL)
 309         return;
 310 
 311     sprintf(errmsg, format, errnum, detail);
 312     s = JNU_NewStringPlatform(env, errmsg);
 313     if (s != NULL) {
 314         jobject x = JNU_NewObjectByName(env, "java/io/IOException",
 315                                         "(Ljava/lang/String;)V", s);
 316         if (x != NULL)
 317             (*env)->Throw(env, x);
 318     }
 319     free(errmsg);
 320 }
 321 
 322 #ifdef DEBUG_PROCESS
 323 /* Debugging process code is difficult; where to write debug output? */
 324 static void
 325 debugPrint(char *format, ...)
 326 {
 327     FILE *tty = fopen("/dev/tty", "w");
 328     va_list ap;
 329     va_start(ap, format);
 330     vfprintf(tty, format, ap);
 331     va_end(ap);
 332     fclose(tty);
 333 }
 334 #endif /* DEBUG_PROCESS */
 335 






 336 static void
 337 copyPipe(int from[2], int to[2])


 338 {
 339     to[0] = from[0];
 340     to[1] = from[1];










 341 }
 342 
 343 /* arg is an array of pointers to 0 terminated strings. array is terminated
 344  * by a null element.






















 345  *
 346  * *nelems and *nbytes receive the number of elements of array (incl 0)
 347  * and total number of bytes (incl. 0)
 348  * Note. An empty array will have one null element
 349  * But if arg is null, then *nelems set to 0, and *nbytes to 0
 350  */
 351 static void arraysize(const char * const *arg, int *nelems, int *nbytes)



 352 {
 353     int i, bytes, count;
 354     const char * const *a = arg;
 355     char *p;
 356     int *q;
 357     if (arg == 0) {
 358         *nelems = 0;
 359         *nbytes = 0;
 360         return;
 361     }
 362     /* count the array elements and number of bytes */
 363     for (count=0, bytes=0; *a != 0; count++, a++) {
 364         bytes += strlen(*a)+1;

 365     }
 366     *nbytes = bytes;
 367     *nelems = count+1;
























































 368 }
 369 
 370 /* copy the strings from arg[] into buf, starting at given offset
 371  * return new offset to next free byte




 372  */
 373 static int copystrings(char *buf, int offset, const char * const *arg) {
 374     char *p;
 375     const char * const *a;
 376     int count=0;



















 377 
 378     if (arg == 0) {
 379         return offset;

























































 380     }
 381     for (p=buf+offset, a=arg; *a != 0; a++) {
 382         int len = strlen(*a) +1;
 383         memcpy(p, *a, len);
 384         p += len;
 385         count += len;






 386     }
 387     return offset+count;



























 388 }
 389 
 390 /**


 391  * We are unusually paranoid; use of clone/vfork is
 392  * especially likely to tickle gcc/glibc bugs.
 393  */
 394 #ifdef __attribute_noinline__  /* See: sys/cdefs.h */
 395 __attribute_noinline__
 396 #endif
 397 
 398 #define START_CHILD_USE_CLONE 0  /* clone() currently disabled; see above. */
 399 
 400 #ifdef START_CHILD_USE_CLONE
 401 static pid_t
 402 cloneChild(ChildStuff *c) {
 403 #ifdef __linux__
 404 #define START_CHILD_CLONE_STACK_SIZE (64 * 1024)
 405     /*
 406      * See clone(2).
 407      * Instead of worrying about which direction the stack grows, just
 408      * allocate twice as much and start the stack in the middle.
 409      */
 410     if ((c->clone_stack = malloc(2 * START_CHILD_CLONE_STACK_SIZE)) == NULL)
 411         /* errno will be set to ENOMEM */
 412         return -1;
 413     return clone(childProcess,
 414                  c->clone_stack + START_CHILD_CLONE_STACK_SIZE,
 415                  CLONE_VFORK | CLONE_VM | SIGCHLD, c);
 416 #else
 417 /* not available on Solaris / Mac */
 418     assert(0);
 419     return -1;
 420 #endif
 421 }
 422 #endif
 423 
 424 static pid_t
 425 vforkChild(ChildStuff *c) {
 426     volatile pid_t resultPid;
 427 
 428     /*
 429      * We separate the call to vfork into a separate function to make
 430      * very sure to keep stack of child from corrupting stack of parent,
 431      * as suggested by the scary gcc warning:
 432      *  warning: variable 'foo' might be clobbered by 'longjmp' or 'vfork'
 433      */
 434     resultPid = vfork();
 435 
 436     if (resultPid == 0) {
 437         childProcess(c);
 438     }
 439     assert(resultPid != 0);  /* childProcess never returns */
 440     return resultPid;
 441 }
 442 
 443 static pid_t
 444 forkChild(ChildStuff *c) {
 445     pid_t resultPid;
 446 
 447     /*
 448      * From Solaris fork(2): In Solaris 10, a call to fork() is
 449      * identical to a call to fork1(); only the calling thread is
 450      * replicated in the child process. This is the POSIX-specified
 451      * behavior for fork().
 452      */
 453     resultPid = fork();
 454 
 455     if (resultPid == 0) {
 456         childProcess(c);
 457     }
 458     assert(resultPid != 0);  /* childProcess never returns */
 459     return resultPid;

 460 }
 461 
 462 #if defined(__solaris__) || defined(_ALLBSD_SOURCE)
 463 static pid_t
 464 spawnChild(JNIEnv *env, jobject process, ChildStuff *c, const char *helperpath) {
 465     pid_t resultPid;
 466     jboolean isCopy;
 467     int i, offset, rval, bufsize, magic;
 468     char *buf, buf1[16];
 469     char *hlpargs[2];
 470     SpawnInfo sp;
 471 
 472     /* need to tell helper which fd is for receiving the childstuff
 473      * and which fd to send response back on
 474      */
 475     snprintf(buf1, sizeof(buf1), "%d:%d", c->childenv[0], c->fail[1]);
 476     /* put the fd string as argument to the helper cmd */
 477     hlpargs[0] = buf1;
 478     hlpargs[1] = 0;
 479 
 480     /* Following items are sent down the pipe to the helper
 481      * after it is spawned.
 482      * All strings are null terminated. All arrays of strings
 483      * have an empty string for termination.
 484      * - the ChildStuff struct
 485      * - the SpawnInfo struct
 486      * - the argv strings array
 487      * - the envv strings array
 488      * - the home directory string
 489      * - the parentPath string
 490      * - the parentPathv array
 491      */
 492     /* First calculate the sizes */
 493     arraysize(c->argv, &sp.nargv, &sp.argvBytes);
 494     bufsize = sp.argvBytes;
 495     arraysize(c->envv, &sp.nenvv, &sp.envvBytes);
 496     bufsize += sp.envvBytes;
 497     sp.dirlen = c->pdir == 0 ? 0 : strlen(c->pdir)+1;
 498     bufsize += sp.dirlen;
 499     arraysize(parentPathv, &sp.nparentPathv, &sp.parentPathvBytes);
 500     bufsize += sp.parentPathvBytes;
 501     /* We need to clear FD_CLOEXEC if set in the fds[].
 502      * Files are created FD_CLOEXEC in Java.
 503      * Otherwise, they will be closed when the target gets exec'd */
 504     for (i=0; i<3; i++) {
 505         if (c->fds[i] != -1) {
 506             int flags = fcntl(c->fds[i], F_GETFD);
 507             if (flags & FD_CLOEXEC) {
 508                 fcntl(c->fds[i], F_SETFD, flags & (~1));
 509             }
 510         }
 511     }
 512 
 513     rval = posix_spawn(&resultPid, helperpath, 0, 0, (char * const *) hlpargs, environ);
 514 
 515     if (rval != 0) {
 516         return -1;
 517     }
 518 
 519     /* now the lengths are known, copy the data */
 520     buf = NEW(char, bufsize);
 521     if (buf == 0) {
 522         return -1;
 523     }
 524     offset = copystrings(buf, 0, &c->argv[0]);
 525     offset = copystrings(buf, offset, &c->envv[0]);
 526     memcpy(buf+offset, c->pdir, sp.dirlen);
 527     offset += sp.dirlen;
 528     offset = copystrings(buf, offset, parentPathv);
 529     assert(offset == bufsize);
 530 
 531     magic = magicNumber();
 532 
 533     /* write the two structs and the data buffer */
 534     write(c->childenv[1], (char *)&magic, sizeof(magic)); // magic number first
 535     write(c->childenv[1], (char *)c, sizeof(*c));
 536     write(c->childenv[1], (char *)&sp, sizeof(sp));
 537     write(c->childenv[1], buf, bufsize);
 538     free(buf);
 539 
 540     /* In this mode an external main() in invoked which calls back into
 541      * childProcess() in this file, rather than directly
 542      * via the statement below */
 543     return resultPid;
 544 }
 545 #endif
 546 
 547 /*
 548  * Start a child process running function childProcess.
 549  * This function only returns in the parent.
 550  */
 551 static pid_t
 552 startChild(JNIEnv *env, jobject process, ChildStuff *c, const char *helperpath) {
 553     switch (c->mode) {
 554       case MODE_VFORK:
 555         return vforkChild(c);
 556       case MODE_FORK:
 557         return forkChild(c);
 558 #if defined(__solaris__) || defined(_ALLBSD_SOURCE)
 559       case MODE_POSIX_SPAWN:
 560         return spawnChild(env, process, c, helperpath);
 561 #endif
 562       default:
 563         return -1;
 564     }
 565 }
 566 
 567 JNIEXPORT jint JNICALL
 568 Java_java_lang_UNIXProcess_forkAndExec(JNIEnv *env,
 569                                        jobject process,
 570                                        jint mode,
 571                                        jbyteArray helperpath,
 572                                        jbyteArray prog,
 573                                        jbyteArray argBlock, jint argc,
 574                                        jbyteArray envBlock, jint envc,
 575                                        jbyteArray dir,
 576                                        jintArray std_fds,
 577                                        jboolean redirectErrorStream)
 578 {
 579     int errnum;
 580     int resultPid = -1;
 581     int in[2], out[2], err[2], fail[2], childenv[2];
 582     jint *fds = NULL;
 583     const char *phelperpath = NULL;
 584     const char *pprog = NULL;
 585     const char *pargBlock = NULL;
 586     const char *penvBlock = NULL;
 587     ChildStuff *c;
 588 
 589     in[0] = in[1] = out[0] = out[1] = err[0] = err[1] = fail[0] = fail[1] = -1;
 590     childenv[0] = childenv[1] = -1;
 591 
 592     if ((c = NEW(ChildStuff, 1)) == NULL) return -1;
 593     c->argv = NULL;
 594     c->envv = NULL;
 595     c->pdir = NULL;

 596     c->clone_stack = NULL;

 597 
 598     /* Convert prog + argBlock into a char ** argv.
 599      * Add one word room for expansion of argv for use by
 600      * execve_as_traditional_shell_script.
 601      * This word is also used when using spawn mode
 602      */
 603     assert(prog != NULL && argBlock != NULL);
 604     if ((phelperpath = getBytes(env, helperpath))   == NULL) goto Catch;
 605     if ((pprog     = getBytes(env, prog))       == NULL) goto Catch;
 606     if ((pargBlock = getBytes(env, argBlock))   == NULL) goto Catch;
 607     if ((c->argv = NEW(const char *, argc + 3)) == NULL) goto Catch;
 608     c->argv[0] = pprog;
 609     c->argc = argc + 2;
 610     initVectorFromBlock(c->argv+1, pargBlock, argc);
 611 
 612     if (envBlock != NULL) {
 613         /* Convert envBlock into a char ** envv */
 614         if ((penvBlock = getBytes(env, envBlock))   == NULL) goto Catch;
 615         if ((c->envv = NEW(const char *, envc + 1)) == NULL) goto Catch;
 616         initVectorFromBlock(c->envv, penvBlock, envc);
 617     }
 618 
 619     if (dir != NULL) {
 620         if ((c->pdir = getBytes(env, dir)) == NULL) goto Catch;
 621     }
 622 
 623     assert(std_fds != NULL);
 624     fds = (*env)->GetIntArrayElements(env, std_fds, NULL);
 625     if (fds == NULL) goto Catch;
 626 
 627     if ((fds[0] == -1 && pipe(in)  < 0) ||
 628         (fds[1] == -1 && pipe(out) < 0) ||
 629         (fds[2] == -1 && pipe(err) < 0) ||
 630         (pipe(childenv) < 0) ||
 631         (pipe(fail) < 0)) {
 632         throwIOException(env, errno, "Bad file descriptor");
 633         goto Catch;
 634     }
 635     c->fds[0] = fds[0];
 636     c->fds[1] = fds[1];
 637     c->fds[2] = fds[2];
 638 
 639     copyPipe(in,   c->in);
 640     copyPipe(out,  c->out);
 641     copyPipe(err,  c->err);
 642     copyPipe(fail, c->fail);
 643     copyPipe(childenv, c->childenv);
 644 
 645     c->redirectErrorStream = redirectErrorStream;
 646     c->mode = mode;
 647 
 648     resultPid = startChild(env, process, c, phelperpath);
 649     assert(resultPid != 0);
 650 
 651     if (resultPid < 0) {
 652         switch (c->mode) {
 653           case MODE_VFORK:
 654             throwIOException(env, errno, "vfork failed");
 655             break;
 656           case MODE_FORK:
 657             throwIOException(env, errno, "fork failed");
 658             break;
 659           case MODE_POSIX_SPAWN:
 660             throwIOException(env, errno, "spawn failed");
 661             break;
 662         }
 663         goto Catch;
 664     }
 665     close(fail[1]); fail[1] = -1; /* See: WhyCantJohnnyExec  (childproc.c)  */
 666 


 667     switch (readFully(fail[0], &errnum, sizeof(errnum))) {
 668     case 0: break; /* Exec succeeded */
 669     case sizeof(errnum):
 670         waitpid(resultPid, NULL, 0);
 671         throwIOException(env, errnum, "Exec failed");
 672         goto Catch;
 673     default:
 674         throwIOException(env, errno, "Read failed");
 675         goto Catch;
 676     }
 677 
 678     fds[0] = (in [1] != -1) ? in [1] : -1;
 679     fds[1] = (out[0] != -1) ? out[0] : -1;
 680     fds[2] = (err[0] != -1) ? err[0] : -1;
 681 
 682  Finally:

 683     free(c->clone_stack);

 684 
 685     /* Always clean up the child's side of the pipes */
 686     closeSafely(in [0]);
 687     closeSafely(out[1]);
 688     closeSafely(err[1]);
 689 
 690     /* Always clean up fail and childEnv descriptors */
 691     closeSafely(fail[0]);
 692     closeSafely(fail[1]);
 693     closeSafely(childenv[0]);
 694     closeSafely(childenv[1]);
 695 
 696     releaseBytes(env, prog,     pprog);
 697     releaseBytes(env, argBlock, pargBlock);
 698     releaseBytes(env, envBlock, penvBlock);
 699     releaseBytes(env, dir,      c->pdir);
 700 
 701     free(c->argv);
 702     free(c->envv);
 703     free(c);
 704 
 705     if (fds != NULL)
 706         (*env)->ReleaseIntArrayElements(env, std_fds, fds, 0);
 707 
 708     return resultPid;
 709 
 710  Catch:
 711     /* Clean up the parent's side of the pipes in case of failure only */
 712     closeSafely(in [1]); in[1] = -1;
 713     closeSafely(out[0]); out[0] = -1;
 714     closeSafely(err[0]); err[0] = -1;
 715     goto Finally;
 716 }
 717 
 718 JNIEXPORT void JNICALL
 719 Java_java_lang_UNIXProcess_destroyProcess(JNIEnv *env, jobject junk, jint pid)
 720 {
 721     kill(pid, SIGTERM);
 722 }