Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/solaris/native/java/lang/childproc.c
32287 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 <stdlib.h>29#include <string.h>30#include <unistd.h>31#include <limits.h>3233#include "childproc.h"3435const char * const *parentPathv;3637ssize_t38restartableWrite(int fd, const void *buf, size_t count)39{40ssize_t result;41RESTARTABLE(write(fd, buf, count), result);42return result;43}4445int46restartableDup2(int fd_from, int fd_to)47{48int err;49RESTARTABLE(dup2(fd_from, fd_to), err);50return err;51}5253int54closeSafely(int fd)55{56return (fd == -1) ? 0 : close(fd);57}5859int60isAsciiDigit(char c)61{62return c >= '0' && c <= '9';63}6465#ifdef _ALLBSD_SOURCE66#define FD_DIR "/dev/fd"67#define dirent64 dirent68#define readdir64 readdir69#elif defined(_AIX)70/* AIX does not understand '/proc/self' - it requires the real process ID */71#define FD_DIR aix_fd_dir72#else73#define FD_DIR "/proc/self/fd"74#endif7576int77closeDescriptors(void)78{79DIR *dp;80struct dirent64 *dirp;81int from_fd = FAIL_FILENO + 1;8283/* We're trying to close all file descriptors, but opendir() might84* itself be implemented using a file descriptor, and we certainly85* don't want to close that while it's in use. We assume that if86* opendir() is implemented using a file descriptor, then it uses87* the lowest numbered file descriptor, just like open(). So we88* close a couple explicitly. */8990close(from_fd); /* for possible use by opendir() */91close(from_fd + 1); /* another one for good luck */9293#if defined(_AIX)94/* AIX does not understand '/proc/self' - it requires the real process ID */95char aix_fd_dir[32]; /* the pid has at most 19 digits */96snprintf(aix_fd_dir, 32, "/proc/%d/fd", getpid());97#endif9899if ((dp = opendir(FD_DIR)) == NULL)100return 0;101102/* We use readdir64 instead of readdir to work around Solaris bug103* 6395699: /proc/self/fd fails to report file descriptors >= 1024 on Solaris 9104*/105while ((dirp = readdir64(dp)) != NULL) {106int fd;107if (isAsciiDigit(dirp->d_name[0]) &&108(fd = strtol(dirp->d_name, NULL, 10)) >= from_fd + 2)109close(fd);110}111112closedir(dp);113114return 1;115}116117int118moveDescriptor(int fd_from, int fd_to)119{120if (fd_from != fd_to) {121if ((restartableDup2(fd_from, fd_to) == -1) ||122(close(fd_from) == -1))123return -1;124}125return 0;126}127128int129magicNumber() {130return 43110;131}132133/*134* Reads nbyte bytes from file descriptor fd into buf,135* The read operation is retried in case of EINTR or partial reads.136*137* Returns number of bytes read (normally nbyte, but may be less in138* case of EOF). In case of read errors, returns -1 and sets errno.139*/140ssize_t141readFully(int fd, void *buf, size_t nbyte)142{143ssize_t remaining = nbyte;144for (;;) {145ssize_t n = read(fd, buf, remaining);146if (n == 0) {147return nbyte - remaining;148} else if (n > 0) {149remaining -= n;150if (remaining <= 0)151return nbyte;152/* We were interrupted in the middle of reading the bytes.153* Unlikely, but possible. */154buf = (void *) (((char *)buf) + n);155} else if (errno == EINTR) {156/* Strange signals like SIGJVM1 are possible at any time.157* See http://www.dreamsongs.com/WorseIsBetter.html */158} else {159return -1;160}161}162}163164void165initVectorFromBlock(const char**vector, const char* block, int count)166{167int i;168const char *p;169for (i = 0, p = block; i < count; i++) {170/* Invariant: p always points to the start of a C string. */171vector[i] = p;172while (*(p++));173}174vector[count] = NULL;175}176177/**178* Exec FILE as a traditional Bourne shell script (i.e. one without #!).179* If we could do it over again, we would probably not support such an ancient180* misfeature, but compatibility wins over sanity. The original support for181* this was imported accidentally from execvp().182*/183void184execve_as_traditional_shell_script(const char *file,185const char *argv[],186const char *const envp[])187{188/* Use the extra word of space provided for us in argv by caller. */189const char *argv0 = argv[0];190const char *const *end = argv;191while (*end != NULL)192++end;193memmove(argv+2, argv+1, (end-argv) * sizeof(*end));194argv[0] = "/bin/sh";195argv[1] = file;196execve(argv[0], (char **) argv, (char **) envp);197/* Can't even exec /bin/sh? Big trouble, but let's soldier on... */198memmove(argv+1, argv+2, (end-argv) * sizeof(*end));199argv[0] = argv0;200}201202/**203* Like execve(2), except that in case of ENOEXEC, FILE is assumed to204* be a shell script and the system default shell is invoked to run it.205*/206void207execve_with_shell_fallback(int mode, const char *file,208const char *argv[],209const char *const envp[])210{211if (mode == MODE_CLONE || mode == MODE_VFORK) {212/* shared address space; be very careful. */213execve(file, (char **) argv, (char **) envp);214if (errno == ENOEXEC)215execve_as_traditional_shell_script(file, argv, envp);216} else {217/* unshared address space; we can mutate environ. */218environ = (char **) envp;219execvp(file, (char **) argv);220}221}222223/**224* 'execvpe' should have been included in the Unix standards,225* and is a GNU extension in glibc 2.10.226*227* JDK_execvpe is identical to execvp, except that the child environment is228* specified via the 3rd argument instead of being inherited from environ.229*/230void231JDK_execvpe(int mode, const char *file,232const char *argv[],233const char *const envp[])234{235if (envp == NULL || (char **) envp == environ) {236execvp(file, (char **) argv);237return;238}239240if (*file == '\0') {241errno = ENOENT;242return;243}244245if (strchr(file, '/') != NULL) {246execve_with_shell_fallback(mode, file, argv, envp);247} else {248/* We must search PATH (parent's, not child's) */249char expanded_file[PATH_MAX];250int filelen = strlen(file);251int sticky_errno = 0;252const char * const * dirs;253for (dirs = parentPathv; *dirs; dirs++) {254const char * dir = *dirs;255int dirlen = strlen(dir);256if (filelen + dirlen + 2 >= PATH_MAX) {257errno = ENAMETOOLONG;258continue;259}260memcpy(expanded_file, dir, dirlen);261if (expanded_file[dirlen - 1] != '/')262expanded_file[dirlen++] = '/';263memcpy(expanded_file + dirlen, file, filelen);264expanded_file[dirlen + filelen] = '\0';265execve_with_shell_fallback(mode, expanded_file, argv, envp);266/* There are 3 responses to various classes of errno:267* return immediately, continue (especially for ENOENT),268* or continue with "sticky" errno.269*270* From exec(3):271*272* If permission is denied for a file (the attempted273* execve returned EACCES), these functions will continue274* searching the rest of the search path. If no other275* file is found, however, they will return with the276* global variable errno set to EACCES.277*/278switch (errno) {279case EACCES:280sticky_errno = errno;281/* FALLTHRU */282case ENOENT:283case ENOTDIR:284#ifdef ELOOP285case ELOOP:286#endif287#ifdef ESTALE288case ESTALE:289#endif290#ifdef ENODEV291case ENODEV:292#endif293#ifdef ETIMEDOUT294case ETIMEDOUT:295#endif296break; /* Try other directories in PATH */297default:298return;299}300}301if (sticky_errno != 0)302errno = sticky_errno;303}304}305306/**307* Child process after a successful fork() or clone().308* This function must not return, and must be prepared for either all309* of its address space to be shared with its parent, or to be a copy.310* It must not modify global variables such as "environ".311*/312int313childProcess(void *arg)314{315const ChildStuff* p = (const ChildStuff*) arg;316317/* Close the parent sides of the pipes.318Closing pipe fds here is redundant, since closeDescriptors()319would do it anyways, but a little paranoia is a good thing. */320if ((closeSafely(p->in[1]) == -1) ||321(closeSafely(p->out[0]) == -1) ||322(closeSafely(p->err[0]) == -1) ||323(closeSafely(p->childenv[0]) == -1) ||324(closeSafely(p->childenv[1]) == -1) ||325(closeSafely(p->fail[0]) == -1))326goto WhyCantJohnnyExec;327328/* Give the child sides of the pipes the right fileno's. */329/* Note: it is possible for in[0] == 0 */330if ((moveDescriptor(p->in[0] != -1 ? p->in[0] : p->fds[0],331STDIN_FILENO) == -1) ||332(moveDescriptor(p->out[1]!= -1 ? p->out[1] : p->fds[1],333STDOUT_FILENO) == -1))334goto WhyCantJohnnyExec;335336if (p->redirectErrorStream) {337if ((closeSafely(p->err[1]) == -1) ||338(restartableDup2(STDOUT_FILENO, STDERR_FILENO) == -1))339goto WhyCantJohnnyExec;340} else {341if (moveDescriptor(p->err[1] != -1 ? p->err[1] : p->fds[2],342STDERR_FILENO) == -1)343goto WhyCantJohnnyExec;344}345346if (moveDescriptor(p->fail[1], FAIL_FILENO) == -1)347goto WhyCantJohnnyExec;348349/* close everything */350if (closeDescriptors() == 0) { /* failed, close the old way */351int max_fd = (int)sysconf(_SC_OPEN_MAX);352int fd;353for (fd = FAIL_FILENO + 1; fd < max_fd; fd++)354if (close(fd) == -1 && errno != EBADF)355goto WhyCantJohnnyExec;356}357358/* change to the new working directory */359if (p->pdir != NULL && chdir(p->pdir) < 0)360goto WhyCantJohnnyExec;361362if (fcntl(FAIL_FILENO, F_SETFD, FD_CLOEXEC) == -1)363goto WhyCantJohnnyExec;364365JDK_execvpe(p->mode, p->argv[0], p->argv, p->envv);366367WhyCantJohnnyExec:368/* We used to go to an awful lot of trouble to predict whether the369* child would fail, but there is no reliable way to predict the370* success of an operation without *trying* it, and there's no way371* to try a chdir or exec in the parent. Instead, all we need is a372* way to communicate any failure back to the parent. Easy; we just373* send the errno back to the parent over a pipe in case of failure.374* The tricky thing is, how do we communicate the *success* of exec?375* We use FD_CLOEXEC together with the fact that a read() on a pipe376* yields EOF when the write ends (we have two of them!) are closed.377*/378{379int errnum = errno;380restartableWrite(FAIL_FILENO, &errnum, sizeof(errnum));381}382close(FAIL_FILENO);383_exit(-1);384return 0; /* Suppress warning "no return value from function" */385}386387388