int
isAsciiDigit(char c)
{ return c >= '0' && c <= '9';
}
#ifdefined(_AIX) /* AIX does not understand '/proc/self' - it requires the real process ID */ #define FD_DIR aix_fd_dir #define DIR DIR64 #define dirent dirent64 #define opendir opendir64 #define readdir readdir64 #define closedir closedir64 #elifdefined(_ALLBSD_SOURCE) #define FD_DIR "/dev/fd" #else #define FD_DIR "/proc/self/fd" #endif
int
closeDescriptors(void)
{
DIR *dp; struct dirent *dirp; int from_fd = FAIL_FILENO + 1;
/* We're trying to close all file descriptors, but opendir() might *itselfbeimplementedusingafiledescriptor,andwecertainly *don'twanttoclosethatwhileit'sinuse.Weassumethatif *opendir()isimplementedusingafiledescriptor,thenituses *thelowestnumberedfiledescriptor,justlikeopen().Sowe
* close a couple explicitly. */
close(from_fd); /* for possible use by opendir() */
close(from_fd + 1); /* another one for good luck */
#ifdefined(_AIX) /* AIX does not understand '/proc/self' - it requires the real process ID */ char aix_fd_dir[32]; /* the pid has at most 19 digits */
snprintf(aix_fd_dir, 32, "/proc/%d/fd", getpid()); #endif
if ((dp = opendir(FD_DIR)) == NULL) return0;
while ((dirp = readdir(dp)) != NULL) { int fd; if (isAsciiDigit(dirp->d_name[0]) &&
(fd = strtol(dirp->d_name, NULL, 10)) >= from_fd + 2)
close(fd);
}
closedir(dp);
return1;
}
int
moveDescriptor(int fd_from, int fd_to)
{ if (fd_from != fd_to) { if ((restartableDup2(fd_from, fd_to) == -1) ||
(close(fd_from) == -1)) return -1;
} return0;
}
int
magicNumber() { return43110;
}
/* *Readsnbytebytesfromfiledescriptorfdintobuf, *ThereadoperationisretriedincaseofEINTRorpartialreads. * *Returnsnumberofbytesread(normallynbyte,butmaybelessin *caseofEOF).Incaseofreaderrors,returns-1andsetserrno.
*/
ssize_t
readFully(int fd, void *buf, size_t nbyte)
{
ssize_t remaining = nbyte; for (;;) {
ssize_t n = read(fd, buf, remaining); if (n == 0) { return nbyte - remaining;
} elseif (n > 0) {
remaining -= n; if (remaining <= 0) return nbyte; /* We were interrupted in the middle of reading the bytes.
* Unlikely, but possible. */
buf = (void *) (((char *)buf) + n);
} elseif (errno == EINTR) { /* Strange signals like SIGJVM1 are possible at any time.
* See http://www.dreamsongs.com/WorseIsBetter.html */
} else { return -1;
}
}
}
void
initVectorFromBlock(constchar**vector, constchar* block, int count)
{ int i; constchar *p; for (i = 0, p = block; i < count; i++) { /* Invariant: p always points to the start of a C string. */
vector[i] = p; while (*(p++));
}
vector[count] = NULL;
}
/** *ExecFILEasatraditionalBourneshellscript(i.e.onewithout#!). *Ifwecoulddoitoveragain,wewouldprobablynotsupportsuchanancient *misfeature,butcompatibilitywinsoversanity.Theoriginalsupportfor *thiswasimportedaccidentallyfromexecvp().
*/ void
execve_as_traditional_shell_script(constchar *file, constchar *argv[], constchar *const envp[])
{ /* Use the extra word of space provided for us in argv by caller. */ constchar *argv0 = argv[0]; constchar *const *end = argv; while (*end != NULL)
++end;
memmove(argv+2, argv+1, (end-argv) * sizeof(*end));
argv[0] = "/bin/sh";
argv[1] = file;
execve(argv[0], (char **) argv, (char **) envp); /* Can't even exec /bin/sh? Big trouble, but let's soldier on... */
memmove(argv+1, argv+2, (end-argv) * sizeof(*end));
argv[0] = argv0;
}
/** *Likeexecve(2),exceptthatincaseofENOEXEC,FILEisassumedto *beashellscriptandthesystemdefaultshellisinvokedtorunit.
*/ void
execve_with_shell_fallback(int mode, constchar *file, constchar *argv[], constchar *const envp[])
{ if (mode == MODE_CLONE || mode == MODE_VFORK) { /* shared address space; be very careful. */
execve(file, (char **) argv, (char **) envp); if (errno == ENOEXEC)
execve_as_traditional_shell_script(file, argv, envp);
} else { /* unshared address space; we can mutate environ. */
environ = (char **) envp;
execvp(file, (char **) argv);
}
}
if (strchr(file, '/') != NULL) {
execve_with_shell_fallback(mode, file, argv, envp);
} else { /* We must search PATH (parent's, not child's) */ char expanded_file[PATH_MAX]; int filelen = strlen(file); int sticky_errno = 0; constchar * const * dirs; for (dirs = parentPathv; *dirs; dirs++) { constchar * dir = *dirs; int dirlen = strlen(dir); if (filelen + dirlen + 2 >= PATH_MAX) {
errno = ENAMETOOLONG; continue;
}
memcpy(expanded_file, dir, dirlen); if (expanded_file[dirlen - 1] != '/')
expanded_file[dirlen++] = '/';
memcpy(expanded_file + dirlen, file, filelen);
expanded_file[dirlen + filelen] = '\0';
execve_with_shell_fallback(mode, expanded_file, argv, envp); /* There are 3 responses to various classes of errno: *returnimmediately,continue(especiallyforENOENT), *orcontinuewith"sticky"errno. * *Fromexec(3): * *Ifpermissionisdeniedforafile(theattempted *execvereturnedEACCES),thesefunctionswillcontinue *searchingtherestofthesearchpath.Ifnoother *fileisfound,however,theywillreturnwiththe *globalvariableerrnosettoEACCES.
*/ switch (errno) { case EACCES:
sticky_errno = errno; /* FALLTHRU */ case ENOENT: case ENOTDIR: #ifdef ELOOP case ELOOP: #endif #ifdef ESTALE case ESTALE: #endif #ifdef ENODEV case ENODEV: #endif #ifdef ETIMEDOUT case ETIMEDOUT: #endif break; /* Try other directories in PATH */ default: return;
}
} if (sticky_errno != 0)
errno = sticky_errno;
}
}
/** *Childprocessafterasuccessfulfork(). *Thisfunctionmustnotreturn,andmustbepreparedforeitherall *ofitsaddressspacetobesharedwithitsparent,ortobeacopy. *Itmustnotmodifyglobalvariablessuchas"environ".
*/ int
childProcess(void *arg)
{ const ChildStuff* p = (const ChildStuff*) arg; int fail_pipe_fd = p->fail[1];
if (p->sendAlivePing) { /* Child shall signal aliveness to parent at the very first
* moment. */ int code = CHILD_IS_ALIVE;
restartableWrite(fail_pipe_fd, &code, sizeof(code));
}
/* Close the parent sides of the pipes. Closingpipefdshereisredundant,sincecloseDescriptors()
would do it anyways, but a little paranoia is a good thing. */ if ((closeSafely(p->in[1]) == -1) ||
(closeSafely(p->out[0]) == -1) ||
(closeSafely(p->err[0]) == -1) ||
(closeSafely(p->childenv[0]) == -1) ||
(closeSafely(p->childenv[1]) == -1) ||
(closeSafely(p->fail[0]) == -1)) goto WhyCantJohnnyExec;
/* Give the child sides of the pipes the right fileno's. */ /* Note: it is possible for in[0] == 0 */ if ((moveDescriptor(p->in[0] != -1 ? p->in[0] : p->fds[0],
STDIN_FILENO) == -1) ||
(moveDescriptor(p->out[1]!= -1 ? p->out[1] : p->fds[1],
STDOUT_FILENO) == -1)) goto WhyCantJohnnyExec;
if (moveDescriptor(fail_pipe_fd, FAIL_FILENO) == -1) goto WhyCantJohnnyExec;
/* We moved the fail pipe fd */
fail_pipe_fd = FAIL_FILENO;
/* close everything */ if (closeDescriptors() == 0) { /* failed, close the old way */ int max_fd = (int)sysconf(_SC_OPEN_MAX); int fd; for (fd = FAIL_FILENO + 1; fd < max_fd; fd++) if (close(fd) == -1 && errno != EBADF) goto WhyCantJohnnyExec;
}
/* change to the new working directory */ if (p->pdir != NULL && chdir(p->pdir) < 0) goto WhyCantJohnnyExec;
if (fcntl(FAIL_FILENO, F_SETFD, FD_CLOEXEC) == -1) goto WhyCantJohnnyExec;
WhyCantJohnnyExec: /* We used to go to an awful lot of trouble to predict whether the *childwouldfail,butthereisnoreliablewaytopredictthe *successofanoperationwithout*trying*it,andthere'snoway *totryachdirorexecintheparent.Instead,allweneedisa *waytocommunicateanyfailurebacktotheparent.Easy;wejust *sendtheerrnobacktotheparentoverapipeincaseoffailure. *Thetrickythingis,howdowecommunicatethe*success*ofexec? *WeuseFD_CLOEXECtogetherwiththefactthataread()onapipe *yieldsEOFwhenthewriteends(wehavetwoofthem!)areclosed.
*/
{ int errnum = errno;
restartableWrite(fail_pipe_fd, &errnum, sizeof(errnum));
}
close(fail_pipe_fd);
_exit(-1); return0; /* Suppress warning "no return value from function" */
}
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.