1 /*
   2  * Copyright (c) 1995, 2008, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 #undef  _LARGEFILE64_SOURCE
  27 #define _LARGEFILE64_SOURCE 1
  28 
  29 #include "jni.h"
  30 #include "jvm.h"
  31 #include "jvm_md.h"
  32 #include "jni_util.h"
  33 #include "io_util.h"
  34 
  35 /*
  36  * Platform-specific support for java.lang.Process
  37  */
  38 #include <assert.h>
  39 #include <stddef.h>
  40 #include <stdlib.h>
  41 #include <sys/types.h>
  42 #include <ctype.h>
  43 #ifdef _ALLBSD_SOURCE
  44 #include <sys/wait.h>
  45 #else
  46 #include <wait.h>
  47 #endif
  48 #include <signal.h>
  49 #include <string.h>
  50 #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
 193      */
 194     struct sigaction sa;
 195     sa.sa_handler = SIG_DFL;
 196     sigemptyset(&sa.sa_mask);
 197     sa.sa_flags = SA_NOCLDSTOP | SA_RESTART;
 198     if (sigaction(SIGCHLD, &sa, NULL) < 0)
 199         JNU_ThrowInternalError(env, "Can't set SIGCHLD handler");
 200 }
 201 
 202 static void*
 203 xmalloc(JNIEnv *env, size_t size)
 204 {
 205     void *p = malloc(size);
 206     if (p == NULL)
 207         JNU_ThrowOutOfMemoryError(env, NULL);
 208     return p;
 209 }
 210 
 211 #define NEW(type, n) ((type *) xmalloc(env, (n) * sizeof(type)))
 212 
 213 /**
 214  * If PATH is not defined, the OS provides some default value.
 215  * Unfortunately, there's no portable way to get this value.
 216  * Fortunately, it's only needed if the child has PATH while we do not.
 217  */
 218 static const char*
 219 defaultPath(void)
 220 {
 221 #ifdef __solaris__
 222     /* These really are the Solaris defaults! */
 223     return (geteuid() == 0 || getuid() == 0) ?
 224         "/usr/xpg4/bin:/usr/ccs/bin:/usr/bin:/opt/SUNWspro/bin:/usr/sbin" :
 225         "/usr/xpg4/bin:/usr/ccs/bin:/usr/bin:/opt/SUNWspro/bin:";
 226 #else
 227     return ":/bin:/usr/bin";    /* glibc */
 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 
 315 /* Block until a child process exits and return its exit code.
 316    Note, can only be called once for any given pid. */
 317 JNIEXPORT jint JNICALL
 318 Java_java_lang_UNIXProcess_waitForProcessExit(JNIEnv* env,
 319                                               jobject junk,
 320                                               jint pid)
 321 {
 322     /* We used to use waitid() on Solaris, waitpid() on Linux, but
 323      * waitpid() is more standard, so use it on all POSIX platforms. */
 324     int status;
 325     /* Wait for the child process to exit.  This returns immediately if
 326        the child has already exited. */
 327     while (waitpid(pid, &status, 0) < 0) {
 328         switch (errno) {
 329         case ECHILD: return 0;
 330         case EINTR: break;
 331         default: return -1;
 332         }
 333     }
 334 
 335     if (WIFEXITED(status)) {
 336         /*
 337          * The child exited normally; get its exit code.
 338          */
 339         return WEXITSTATUS(status);
 340     } else if (WIFSIGNALED(status)) {
 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 }