Simplify the dup fix and add better error handling

Original fix might fail if RLIMIT_NOFILE is set to 1024.

PiperOrigin-RevId: 381034115
Change-Id: I39e33a90083533cf85eb04072604665c299b861f
This commit is contained in:
Wiktor Garbacz 2021-06-23 08:13:18 -07:00 committed by Copybara-Service
parent 4a38f59728
commit fe08d724e4

View File

@ -138,18 +138,18 @@ std::unique_ptr<GlobalForkClient> StartGlobalForkServer() {
// The new FD will not be CLOEXEC, which is what we want. // The new FD will not be CLOEXEC, which is what we want.
// If exec_fd == Comms::kSandbox2ClientCommsFD then it would be replaced by // If exec_fd == Comms::kSandbox2ClientCommsFD then it would be replaced by
// the comms fd and result in EACCESS at execveat. // the comms fd and result in EACCESS at execveat.
// So first move exec_fd also making sure it will not clash with sv[0]... // So first move exec_fd to another fd number.
int new_exec_fd = Comms::kSandbox2ClientCommsFD + 1; if (exec_fd == Comms::kSandbox2ClientCommsFD) {
if (sv[0] == new_exec_fd) { exec_fd = dup(exec_fd);
++new_exec_fd; SAPI_RAW_PCHECK(exec_fd != -1, "duping exec fd failed");
fcntl(exec_fd, F_SETFD, FD_CLOEXEC);
} }
dup2(exec_fd, new_exec_fd); SAPI_RAW_PCHECK(dup2(sv[0], Comms::kSandbox2ClientCommsFD) != -1,
fcntl(new_exec_fd, F_SETFD, FD_CLOEXEC); "duping comms fd failed");
dup2(sv[0], Comms::kSandbox2ClientCommsFD);
char* const args[] = {proc_name.data(), nullptr}; char* const args[] = {proc_name.data(), nullptr};
char* const envp[] = {nullptr}; char* const envp[] = {nullptr};
syscall(__NR_execveat, new_exec_fd, "", args, envp, AT_EMPTY_PATH); syscall(__NR_execveat, exec_fd, "", args, envp, AT_EMPTY_PATH);
SAPI_RAW_PLOG(FATAL, "Could not launch forkserver binary"); SAPI_RAW_PLOG(FATAL, "Could not launch forkserver binary");
abort(); abort();
} }