Path: blob/master/src/java.base/unix/native/libjava/childproc.c
41119 views
/*1* Copyright (c) 2013, 2020, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425#include <dirent.h>26#include <errno.h>27#include <fcntl.h>28#include <stdio.h>29#include <stdlib.h>30#include <string.h>31#include <unistd.h>32#include <limits.h>3334#include "childproc.h"3536const char * const *parentPathv;3738ssize_t39restartableWrite(int fd, const void *buf, size_t count)40{41ssize_t result;42RESTARTABLE(write(fd, buf, count), result);43return result;44}4546int47restartableDup2(int fd_from, int fd_to)48{49int err;50RESTARTABLE(dup2(fd_from, fd_to), err);51return err;52}5354int55closeSafely(int fd)56{57return (fd == -1) ? 0 : close(fd);58}5960int61isAsciiDigit(char c)62{63return c >= '0' && c <= '9';64}6566#if defined(_AIX)67/* AIX does not understand '/proc/self' - it requires the real process ID */68#define FD_DIR aix_fd_dir69#define DIR DIR6470#define dirent dirent6471#define opendir opendir6472#define readdir readdir6473#define closedir closedir6474#elif defined(_ALLBSD_SOURCE)75#define FD_DIR "/dev/fd"76#else77#define FD_DIR "/proc/self/fd"78#endif7980int81closeDescriptors(void)82{83DIR *dp;84struct dirent *dirp;85int from_fd = FAIL_FILENO + 1;8687/* We're trying to close all file descriptors, but opendir() might88* itself be implemented using a file descriptor, and we certainly89* don't want to close that while it's in use. We assume that if90* opendir() is implemented using a file descriptor, then it uses91* the lowest numbered file descriptor, just like open(). So we92* close a couple explicitly. */9394close(from_fd); /* for possible use by opendir() */95close(from_fd + 1); /* another one for good luck */9697#if defined(_AIX)98/* AIX does not understand '/proc/self' - it requires the real process ID */99char aix_fd_dir[32]; /* the pid has at most 19 digits */100snprintf(aix_fd_dir, 32, "/proc/%d/fd", getpid());101#endif102103if ((dp = opendir(FD_DIR)) == NULL)104return 0;105106while ((dirp = readdir(dp)) != NULL) {107int fd;108if (isAsciiDigit(dirp->d_name[0]) &&109(fd = strtol(dirp->d_name, NULL, 10)) >= from_fd + 2)110close(fd);111}112113closedir(dp);114115return 1;116}117118int119moveDescriptor(int fd_from, int fd_to)120{121if (fd_from != fd_to) {122if ((restartableDup2(fd_from, fd_to) == -1) ||123(close(fd_from) == -1))124return -1;125}126return 0;127}128129int130magicNumber() {131return 43110;132}133134/*135* Reads nbyte bytes from file descriptor fd into buf,136* The read operation is retried in case of EINTR or partial reads.137*138* Returns number of bytes read (normally nbyte, but may be less in139* case of EOF). In case of read errors, returns -1 and sets errno.140*/141ssize_t142readFully(int fd, void *buf, size_t nbyte)143{144ssize_t remaining = nbyte;145for (;;) {146ssize_t n = read(fd, buf, remaining);147if (n == 0) {148return nbyte - remaining;149} else if (n > 0) {150remaining -= n;151if (remaining <= 0)152return nbyte;153/* We were interrupted in the middle of reading the bytes.154* Unlikely, but possible. */155buf = (void *) (((char *)buf) + n);156} else if (errno == EINTR) {157/* Strange signals like SIGJVM1 are possible at any time.158* See http://www.dreamsongs.com/WorseIsBetter.html */159} else {160return -1;161}162}163}164165void166initVectorFromBlock(const char**vector, const char* block, int count)167{168int i;169const char *p;170for (i = 0, p = block; i < count; i++) {171/* Invariant: p always points to the start of a C string. */172vector[i] = p;173while (*(p++));174}175vector[count] = NULL;176}177178/**179* Exec FILE as a traditional Bourne shell script (i.e. one without #!).180* If we could do it over again, we would probably not support such an ancient181* misfeature, but compatibility wins over sanity. The original support for182* this was imported accidentally from execvp().183*/184void185execve_as_traditional_shell_script(const char *file,186const char *argv[],187const char *const envp[])188{189/* Use the extra word of space provided for us in argv by caller. */190const char *argv0 = argv[0];191const char *const *end = argv;192while (*end != NULL)193++end;194memmove(argv+2, argv+1, (end-argv) * sizeof(*end));195argv[0] = "/bin/sh";196argv[1] = file;197execve(argv[0], (char **) argv, (char **) envp);198/* Can't even exec /bin/sh? Big trouble, but let's soldier on... */199memmove(argv+1, argv+2, (end-argv) * sizeof(*end));200argv[0] = argv0;201}202203/**204* Like execve(2), except that in case of ENOEXEC, FILE is assumed to205* be a shell script and the system default shell is invoked to run it.206*/207void208execve_with_shell_fallback(int mode, const char *file,209const char *argv[],210const char *const envp[])211{212if (mode == MODE_CLONE || mode == MODE_VFORK) {213/* shared address space; be very careful. */214execve(file, (char **) argv, (char **) envp);215if (errno == ENOEXEC)216execve_as_traditional_shell_script(file, argv, envp);217} else {218/* unshared address space; we can mutate environ. */219environ = (char **) envp;220execvp(file, (char **) argv);221}222}223224/**225* 'execvpe' should have been included in the Unix standards,226* and is a GNU extension in glibc 2.10.227*228* JDK_execvpe is identical to execvp, except that the child environment is229* specified via the 3rd argument instead of being inherited from environ.230*/231void232JDK_execvpe(int mode, const char *file,233const char *argv[],234const char *const envp[])235{236if (envp == NULL || (char **) envp == environ) {237execvp(file, (char **) argv);238return;239}240241if (*file == '\0') {242errno = ENOENT;243return;244}245246if (strchr(file, '/') != NULL) {247execve_with_shell_fallback(mode, file, argv, envp);248} else {249/* We must search PATH (parent's, not child's) */250char expanded_file[PATH_MAX];251int filelen = strlen(file);252int sticky_errno = 0;253const char * const * dirs;254for (dirs = parentPathv; *dirs; dirs++) {255const char * dir = *dirs;256int dirlen = strlen(dir);257if (filelen + dirlen + 2 >= PATH_MAX) {258errno = ENAMETOOLONG;259continue;260}261memcpy(expanded_file, dir, dirlen);262if (expanded_file[dirlen - 1] != '/')263expanded_file[dirlen++] = '/';264memcpy(expanded_file + dirlen, file, filelen);265expanded_file[dirlen + filelen] = '\0';266execve_with_shell_fallback(mode, expanded_file, argv, envp);267/* There are 3 responses to various classes of errno:268* return immediately, continue (especially for ENOENT),269* or continue with "sticky" errno.270*271* From exec(3):272*273* If permission is denied for a file (the attempted274* execve returned EACCES), these functions will continue275* searching the rest of the search path. If no other276* file is found, however, they will return with the277* global variable errno set to EACCES.278*/279switch (errno) {280case EACCES:281sticky_errno = errno;282/* FALLTHRU */283case ENOENT:284case ENOTDIR:285#ifdef ELOOP286case ELOOP:287#endif288#ifdef ESTALE289case ESTALE:290#endif291#ifdef ENODEV292case ENODEV:293#endif294#ifdef ETIMEDOUT295case ETIMEDOUT:296#endif297break; /* Try other directories in PATH */298default:299return;300}301}302if (sticky_errno != 0)303errno = sticky_errno;304}305}306307/**308* Child process after a successful fork().309* This function must not return, and must be prepared for either all310* of its address space to be shared with its parent, or to be a copy.311* It must not modify global variables such as "environ".312*/313int314childProcess(void *arg)315{316const ChildStuff* p = (const ChildStuff*) arg;317int fail_pipe_fd = p->fail[1];318319if (p->sendAlivePing) {320/* Child shall signal aliveness to parent at the very first321* moment. */322int code = CHILD_IS_ALIVE;323restartableWrite(fail_pipe_fd, &code, sizeof(code));324}325326/* Close the parent sides of the pipes.327Closing pipe fds here is redundant, since closeDescriptors()328would do it anyways, but a little paranoia is a good thing. */329if ((closeSafely(p->in[1]) == -1) ||330(closeSafely(p->out[0]) == -1) ||331(closeSafely(p->err[0]) == -1) ||332(closeSafely(p->childenv[0]) == -1) ||333(closeSafely(p->childenv[1]) == -1) ||334(closeSafely(p->fail[0]) == -1))335goto WhyCantJohnnyExec;336337/* Give the child sides of the pipes the right fileno's. */338/* Note: it is possible for in[0] == 0 */339if ((moveDescriptor(p->in[0] != -1 ? p->in[0] : p->fds[0],340STDIN_FILENO) == -1) ||341(moveDescriptor(p->out[1]!= -1 ? p->out[1] : p->fds[1],342STDOUT_FILENO) == -1))343goto WhyCantJohnnyExec;344345if (p->redirectErrorStream) {346if ((closeSafely(p->err[1]) == -1) ||347(restartableDup2(STDOUT_FILENO, STDERR_FILENO) == -1))348goto WhyCantJohnnyExec;349} else {350if (moveDescriptor(p->err[1] != -1 ? p->err[1] : p->fds[2],351STDERR_FILENO) == -1)352goto WhyCantJohnnyExec;353}354355if (moveDescriptor(fail_pipe_fd, FAIL_FILENO) == -1)356goto WhyCantJohnnyExec;357358/* We moved the fail pipe fd */359fail_pipe_fd = FAIL_FILENO;360361/* close everything */362if (closeDescriptors() == 0) { /* failed, close the old way */363int max_fd = (int)sysconf(_SC_OPEN_MAX);364int fd;365for (fd = FAIL_FILENO + 1; fd < max_fd; fd++)366if (close(fd) == -1 && errno != EBADF)367goto WhyCantJohnnyExec;368}369370/* change to the new working directory */371if (p->pdir != NULL && chdir(p->pdir) < 0)372goto WhyCantJohnnyExec;373374if (fcntl(FAIL_FILENO, F_SETFD, FD_CLOEXEC) == -1)375goto WhyCantJohnnyExec;376377JDK_execvpe(p->mode, p->argv[0], p->argv, p->envv);378379WhyCantJohnnyExec:380/* We used to go to an awful lot of trouble to predict whether the381* child would fail, but there is no reliable way to predict the382* success of an operation without *trying* it, and there's no way383* to try a chdir or exec in the parent. Instead, all we need is a384* way to communicate any failure back to the parent. Easy; we just385* send the errno back to the parent over a pipe in case of failure.386* The tricky thing is, how do we communicate the *success* of exec?387* We use FD_CLOEXEC together with the fact that a read() on a pipe388* yields EOF when the write ends (we have two of them!) are closed.389*/390{391int errnum = errno;392restartableWrite(fail_pipe_fd, &errnum, sizeof(errnum));393}394close(fail_pipe_fd);395_exit(-1);396return 0; /* Suppress warning "no return value from function" */397}398399400