2 * Copyright 2015 Facebook, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
21 #include <folly/Subprocess.h>
24 #include <sys/prctl.h>
33 #include <system_error>
35 #include <boost/container/flat_set.hpp>
36 #include <boost/range/adaptors.hpp>
38 #include <glog/logging.h>
40 #include <folly/Conv.h>
41 #include <folly/Exception.h>
42 #include <folly/ScopeGuard.h>
43 #include <folly/String.h>
44 #include <folly/io/Cursor.h>
46 extern char** environ;
48 constexpr int kExecFailure = 127;
49 constexpr int kChildFailure = 126;
53 ProcessReturnCode::State ProcessReturnCode::state() const {
54 if (rawStatus_ == RV_NOT_STARTED) return NOT_STARTED;
55 if (rawStatus_ == RV_RUNNING) return RUNNING;
56 if (WIFEXITED(rawStatus_)) return EXITED;
57 if (WIFSIGNALED(rawStatus_)) return KILLED;
58 throw std::runtime_error(to<std::string>(
59 "Invalid ProcessReturnCode: ", rawStatus_));
62 void ProcessReturnCode::enforce(State expected) const {
65 throw std::logic_error(to<std::string>(
66 "Bad use of ProcessReturnCode; state is ", s, " expected ", expected
71 int ProcessReturnCode::exitStatus() const {
73 return WEXITSTATUS(rawStatus_);
76 int ProcessReturnCode::killSignal() const {
78 return WTERMSIG(rawStatus_);
81 bool ProcessReturnCode::coreDumped() const {
83 return WCOREDUMP(rawStatus_);
86 std::string ProcessReturnCode::str() const {
93 return to<std::string>("exited with status ", exitStatus());
95 return to<std::string>("killed by signal ", killSignal(),
96 (coreDumped() ? " (core dumped)" : ""));
98 CHECK(false); // unreached
99 return ""; // silence GCC warning
102 CalledProcessError::CalledProcessError(ProcessReturnCode rc)
104 what_(returnCode_.str()) {
107 SubprocessSpawnError::SubprocessSpawnError(const char* executable,
110 : errnoValue_(errnoValue),
111 what_(to<std::string>(errCode == kExecFailure ?
112 "failed to execute " :
113 "error preparing to execute ",
114 executable, ": ", errnoStr(errnoValue))) {
119 // Copy pointers to the given strings in a format suitable for posix_spawn
120 std::unique_ptr<const char*[]> cloneStrings(const std::vector<std::string>& s) {
121 std::unique_ptr<const char*[]> d(new const char*[s.size() + 1]);
122 for (size_t i = 0; i < s.size(); i++) {
125 d[s.size()] = nullptr;
129 // Check a wait() status, throw on non-successful
130 void checkStatus(ProcessReturnCode returnCode) {
131 if (returnCode.state() != ProcessReturnCode::EXITED ||
132 returnCode.exitStatus() != 0) {
133 throw CalledProcessError(returnCode);
139 Subprocess::Options& Subprocess::Options::fd(int fd, int action) {
140 if (action == Subprocess::PIPE) {
142 action = Subprocess::PIPE_IN;
143 } else if (fd == 1 || fd == 2) {
144 action = Subprocess::PIPE_OUT;
146 throw std::invalid_argument(
147 to<std::string>("Only fds 0, 1, 2 are valid for action=PIPE: ", fd));
150 fdActions_[fd] = action;
154 Subprocess::Subprocess(
155 const std::vector<std::string>& argv,
156 const Options& options,
157 const char* executable,
158 const std::vector<std::string>* env)
160 returnCode_(RV_NOT_STARTED) {
162 throw std::invalid_argument("argv must not be empty");
164 if (!executable) executable = argv[0].c_str();
165 spawn(cloneStrings(argv), executable, options, env);
168 Subprocess::Subprocess(
169 const std::string& cmd,
170 const Options& options,
171 const std::vector<std::string>* env)
173 returnCode_(RV_NOT_STARTED) {
174 if (options.usePath_) {
175 throw std::invalid_argument("usePath() not allowed when running in shell");
177 const char* shell = getenv("SHELL");
182 std::unique_ptr<const char*[]> argv(new const char*[4]);
185 argv[2] = cmd.c_str();
187 spawn(std::move(argv), shell, options, env);
190 Subprocess::~Subprocess() {
191 CHECK_NE(returnCode_.state(), ProcessReturnCode::RUNNING)
192 << "Subprocess destroyed without reaping child";
197 struct ChildErrorInfo {
202 FOLLY_NORETURN void childError(int errFd, int errCode, int errnoValue);
203 void childError(int errFd, int errCode, int errnoValue) {
204 ChildErrorInfo info = {errCode, errnoValue};
205 // Write the error information over the pipe to our parent process.
206 // We can't really do anything else if this write call fails.
207 writeNoInt(errFd, &info, sizeof(info));
214 void Subprocess::setAllNonBlocking() {
215 for (auto& p : pipes_) {
216 int fd = p.pipe.fd();
217 int flags = ::fcntl(fd, F_GETFL);
218 checkUnixError(flags, "fcntl");
219 int r = ::fcntl(fd, F_SETFL, flags | O_NONBLOCK);
220 checkUnixError(r, "fcntl");
224 void Subprocess::spawn(
225 std::unique_ptr<const char*[]> argv,
226 const char* executable,
227 const Options& optionsIn,
228 const std::vector<std::string>* env) {
229 if (optionsIn.usePath_ && env) {
230 throw std::invalid_argument(
231 "usePath() not allowed when overriding environment");
234 // Make a copy, we'll mutate options
235 Options options(optionsIn);
237 // On error, close all pipes_ (ignoring errors, but that seems fine here).
238 auto pipesGuard = makeGuard([this] { pipes_.clear(); });
240 // Create a pipe to use to receive error information from the child,
241 // in case it fails before calling exec()
244 checkUnixError(::pipe2(errFds, O_CLOEXEC), "pipe2");
246 checkUnixError(::pipe(errFds), "pipe");
249 CHECK_ERR(::close(errFds[0]));
250 if (errFds[1] >= 0) {
251 CHECK_ERR(::close(errFds[1]));
255 #if !FOLLY_HAVE_PIPE2
256 // Ask the child to close the read end of the error pipe.
257 checkUnixError(fcntl(errFds[0], F_SETFD, FD_CLOEXEC), "set FD_CLOEXEC");
258 // Set the close-on-exec flag on the write side of the pipe.
259 // This way the pipe will be closed automatically in the child if execve()
260 // succeeds. If the exec fails the child can write error information to the
262 checkUnixError(fcntl(errFds[1], F_SETFD, FD_CLOEXEC), "set FD_CLOEXEC");
265 // Perform the actual work of setting up pipes then forking and
266 // executing the child.
267 spawnInternal(std::move(argv), executable, options, env, errFds[1]);
269 // After spawnInternal() returns the child is alive. We have to be very
270 // careful about throwing after this point. We are inside the constructor,
271 // so if we throw the Subprocess object will have never existed, and the
272 // destructor will never be called.
274 // We should only throw if we got an error via the errFd, and we know the
275 // child has exited and can be immediately waited for. In all other cases,
276 // we have no way of cleaning up the child.
278 // Close writable side of the errFd pipe in the parent process
279 CHECK_ERR(::close(errFds[1]));
282 // Read from the errFd pipe, to tell if the child ran into any errors before
284 readChildErrorPipe(errFds[0], executable);
286 // We have fully succeeded now, so release the guard on pipes_
287 pipesGuard.dismiss();
290 void Subprocess::spawnInternal(
291 std::unique_ptr<const char*[]> argv,
292 const char* executable,
294 const std::vector<std::string>* env,
296 // Parent work, pre-fork: create pipes
297 std::vector<int> childFds;
298 // Close all of the childFds as we leave this scope
300 // These are only pipes, closing them shouldn't fail
301 for (int cfd : childFds) {
302 CHECK_ERR(::close(cfd));
307 for (auto& p : options.fdActions_) {
308 if (p.second == PIPE_IN || p.second == PIPE_OUT) {
310 // We're setting both ends of the pipe as close-on-exec. The child
311 // doesn't need to reset the flag on its end, as we always dup2() the fd,
312 // and dup2() fds don't share the close-on-exec flag.
314 // If possible, set close-on-exec atomically. Otherwise, a concurrent
315 // Subprocess invocation can fork() between "pipe" and "fnctl",
316 // causing FDs to leak.
317 r = ::pipe2(fds, O_CLOEXEC);
318 checkUnixError(r, "pipe2");
321 checkUnixError(r, "pipe");
322 r = fcntl(fds[0], F_SETFD, FD_CLOEXEC);
323 checkUnixError(r, "set FD_CLOEXEC");
324 r = fcntl(fds[1], F_SETFD, FD_CLOEXEC);
325 checkUnixError(r, "set FD_CLOEXEC");
327 pipes_.emplace_back();
328 Pipe& pipe = pipes_.back();
329 pipe.direction = p.second;
331 if (p.second == PIPE_IN) {
332 // Child gets reading end
333 pipe.pipe = folly::File(fds[1], /*owns_fd=*/ true);
336 pipe.pipe = folly::File(fds[0], /*owns_fd=*/ true);
339 p.second = cfd; // ensure it gets dup2()ed
340 pipe.childFd = p.first;
341 childFds.push_back(cfd);
345 // This should already be sorted, as options.fdActions_ is
346 DCHECK(std::is_sorted(pipes_.begin(), pipes_.end()));
348 // Note that the const casts below are legit, per
349 // http://pubs.opengroup.org/onlinepubs/009695399/functions/exec.html
351 char** argVec = const_cast<char**>(argv.get());
353 // Set up environment
354 std::unique_ptr<const char*[]> envHolder;
357 envHolder = cloneStrings(*env);
358 envVec = const_cast<char**>(envHolder.get());
363 // Block all signals around vfork; see http://ewontfix.com/7/.
365 // As the child may run in the same address space as the parent until
366 // the actual execve() system call, any (custom) signal handlers that
367 // the parent has might alter parent's memory if invoked in the child,
368 // with undefined results. So we block all signals in the parent before
369 // vfork(), which will cause them to be blocked in the child as well (we
370 // rely on the fact that Linux, just like all sane implementations, only
371 // clones the calling thread). Then, in the child, we reset all signals
372 // to their default dispositions (while still blocked), and unblock them
373 // (so the exec()ed process inherits the parent's signal mask)
375 // The parent also unblocks all signals as soon as vfork() returns.
377 r = sigfillset(&allBlocked);
378 checkUnixError(r, "sigfillset");
381 r = pthread_sigmask(SIG_SETMASK, &allBlocked, &oldSignals);
382 checkPosixError(r, "pthread_sigmask");
384 // Restore signal mask
385 r = pthread_sigmask(SIG_SETMASK, &oldSignals, nullptr);
386 CHECK_EQ(r, 0) << "pthread_sigmask: " << errnoStr(r); // shouldn't fail
389 // Call c_str() here, as it's not necessarily safe after fork.
390 const char* childDir =
391 options.childDir_.empty() ? nullptr : options.childDir_.c_str();
394 int errnoValue = prepareChild(options, &oldSignals, childDir);
395 if (errnoValue != 0) {
396 childError(errFd, kChildFailure, errnoValue);
399 errnoValue = runChild(executable, argVec, envVec, options);
400 // If we get here, exec() failed.
401 childError(errFd, kExecFailure, errnoValue);
403 // In parent. Make sure vfork() succeeded.
404 checkUnixError(pid, errno, "vfork");
406 // Child is alive. We have to be very careful about throwing after this
407 // point. We are inside the constructor, so if we throw the Subprocess
408 // object will have never existed, and the destructor will never be called.
410 // We should only throw if we got an error via the errFd, and we know the
411 // child has exited and can be immediately waited for. In all other cases,
412 // we have no way of cleaning up the child.
414 returnCode_ = ProcessReturnCode(RV_RUNNING);
417 int Subprocess::prepareChild(const Options& options,
418 const sigset_t* sigmask,
419 const char* childDir) const {
420 // While all signals are blocked, we must reset their
421 // dispositions to default.
422 for (int sig = 1; sig < NSIG; ++sig) {
423 ::signal(sig, SIG_DFL);
427 // Unblock signals; restore signal mask.
428 int r = pthread_sigmask(SIG_SETMASK, sigmask, nullptr);
430 return r; // pthread_sigmask() returns an errno value
434 // Change the working directory, if one is given
436 if (::chdir(childDir) == -1) {
441 // We don't have to explicitly close the parent's end of all pipes,
442 // as they all have the FD_CLOEXEC flag set and will be closed at
445 // Close all fds that we're supposed to close.
446 for (auto& p : options.fdActions_) {
447 if (p.second == CLOSE) {
448 if (::close(p.first) == -1) {
451 } else if (p.second != p.first) {
452 if (::dup2(p.second, p.first) == -1) {
458 // If requested, close all other file descriptors. Don't close
459 // any fds in options.fdActions_, and don't touch stdin, stdout, stderr.
461 if (options.closeOtherFds_) {
462 for (int fd = getdtablesize() - 1; fd >= 3; --fd) {
463 if (options.fdActions_.count(fd) == 0) {
470 // Opt to receive signal on parent death, if requested
471 if (options.parentDeathSignal_ != 0) {
472 if (prctl(PR_SET_PDEATHSIG, options.parentDeathSignal_, 0, 0, 0) == -1) {
478 if (options.processGroupLeader_) {
479 if (setpgrp() == -1) {
487 int Subprocess::runChild(const char* executable,
488 char** argv, char** env,
489 const Options& options) const {
490 // Now, finally, exec.
491 if (options.usePath_) {
492 ::execvp(executable, argv);
494 ::execve(executable, argv, env);
499 void Subprocess::readChildErrorPipe(int pfd, const char* executable) {
501 auto rc = readNoInt(pfd, &info, sizeof(info));
503 // No data means the child executed successfully, and the pipe
504 // was closed due to the close-on-exec flag being set.
506 } else if (rc != sizeof(ChildErrorInfo)) {
507 // An error occurred trying to read from the pipe, or we got a partial read.
508 // Neither of these cases should really occur in practice.
510 // We can't get any error data from the child in this case, and we don't
511 // know if it is successfully running or not. All we can do is to return
512 // normally, as if the child executed successfully. If something bad
513 // happened the caller should at least get a non-normal exit status from
515 LOG(ERROR) << "unexpected error trying to read from child error pipe " <<
516 "rc=" << rc << ", errno=" << errno;
520 // We got error data from the child. The child should exit immediately in
521 // this case, so wait on it to clean up.
524 // Throw to signal the error
525 throw SubprocessSpawnError(executable, info.errCode, info.errnoValue);
528 ProcessReturnCode Subprocess::poll() {
529 returnCode_.enforce(ProcessReturnCode::RUNNING);
532 pid_t found = ::waitpid(pid_, &status, WNOHANG);
533 checkUnixError(found, "waitpid");
535 // Though the child process had quit, this call does not close the pipes
536 // since its descendants may still be using them.
537 returnCode_ = ProcessReturnCode(status);
543 bool Subprocess::pollChecked() {
544 if (poll().state() == ProcessReturnCode::RUNNING) {
547 checkStatus(returnCode_);
551 ProcessReturnCode Subprocess::wait() {
552 returnCode_.enforce(ProcessReturnCode::RUNNING);
557 found = ::waitpid(pid_, &status, 0);
558 } while (found == -1 && errno == EINTR);
559 checkUnixError(found, "waitpid");
560 // Though the child process had quit, this call does not close the pipes
561 // since its descendants may still be using them.
562 DCHECK_EQ(found, pid_);
563 returnCode_ = ProcessReturnCode(status);
568 void Subprocess::waitChecked() {
570 checkStatus(returnCode_);
573 void Subprocess::sendSignal(int signal) {
574 returnCode_.enforce(ProcessReturnCode::RUNNING);
575 int r = ::kill(pid_, signal);
576 checkUnixError(r, "kill");
579 pid_t Subprocess::pid() const {
585 std::pair<const uint8_t*, size_t> queueFront(const IOBufQueue& queue) {
586 auto* p = queue.front();
587 if (!p) return std::make_pair(nullptr, 0);
588 return io::Cursor(p).peek();
592 bool handleWrite(int fd, IOBufQueue& queue) {
594 auto p = queueFront(queue);
599 ssize_t n = writeNoInt(fd, p.first, p.second);
600 if (n == -1 && errno == EAGAIN) {
603 checkUnixError(n, "write");
609 bool handleRead(int fd, IOBufQueue& queue) {
611 auto p = queue.preallocate(100, 65000);
612 ssize_t n = readNoInt(fd, p.first, p.second);
613 if (n == -1 && errno == EAGAIN) {
616 checkUnixError(n, "read");
620 queue.postallocate(n);
624 bool discardRead(int fd) {
625 static const size_t bufSize = 65000;
626 // Thread unsafe, but it doesn't matter.
627 static std::unique_ptr<char[]> buf(new char[bufSize]);
630 ssize_t n = readNoInt(fd, buf.get(), bufSize);
631 if (n == -1 && errno == EAGAIN) {
634 checkUnixError(n, "read");
643 std::pair<std::string, std::string> Subprocess::communicate(
645 IOBufQueue inputQueue;
646 inputQueue.wrapBuffer(input.data(), input.size());
648 auto outQueues = communicateIOBuf(std::move(inputQueue));
649 auto outBufs = std::make_pair(outQueues.first.move(),
650 outQueues.second.move());
651 std::pair<std::string, std::string> out;
653 outBufs.first->coalesce();
654 out.first.assign(reinterpret_cast<const char*>(outBufs.first->data()),
655 outBufs.first->length());
657 if (outBufs.second) {
658 outBufs.second->coalesce();
659 out.second.assign(reinterpret_cast<const char*>(outBufs.second->data()),
660 outBufs.second->length());
665 std::pair<IOBufQueue, IOBufQueue> Subprocess::communicateIOBuf(
667 // If the user supplied a non-empty input buffer, make sure
668 // that stdin is a pipe so we can write the data.
669 if (!input.empty()) {
670 // findByChildFd() will throw std::invalid_argument if no pipe for
671 // STDIN_FILENO exists
672 findByChildFd(STDIN_FILENO);
675 std::pair<IOBufQueue, IOBufQueue> out;
677 auto readCallback = [&] (int pfd, int cfd) -> bool {
678 if (cfd == STDOUT_FILENO) {
679 return handleRead(pfd, out.first);
680 } else if (cfd == STDERR_FILENO) {
681 return handleRead(pfd, out.second);
683 // Don't close the file descriptor, the child might not like SIGPIPE,
684 // just read and throw the data away.
685 return discardRead(pfd);
689 auto writeCallback = [&] (int pfd, int cfd) -> bool {
690 if (cfd == STDIN_FILENO) {
691 return handleWrite(pfd, input);
693 // If we don't want to write to this fd, just close it.
698 communicate(std::move(readCallback), std::move(writeCallback));
703 void Subprocess::communicate(FdCallback readCallback,
704 FdCallback writeCallback) {
705 // This serves to prevent wait() followed by communicate(), but if you
706 // legitimately need that, send a patch to delete this line.
707 returnCode_.enforce(ProcessReturnCode::RUNNING);
710 std::vector<pollfd> fds;
711 fds.reserve(pipes_.size());
712 std::vector<size_t> toClose; // indexes into pipes_
713 toClose.reserve(pipes_.size());
715 while (!pipes_.empty()) {
719 for (auto& p : pipes_) {
721 pfd.fd = p.pipe.fd();
722 // Yes, backwards, PIPE_IN / PIPE_OUT are defined from the
723 // child's point of view.
725 // Still keeping fd in watched set so we get notified of POLLHUP /
728 } else if (p.direction == PIPE_IN) {
729 pfd.events = POLLOUT;
738 r = ::poll(fds.data(), fds.size(), -1);
739 } while (r == -1 && errno == EINTR);
740 checkUnixError(r, "poll");
742 for (size_t i = 0; i < pipes_.size(); ++i) {
744 auto parentFd = p.pipe.fd();
745 DCHECK_EQ(fds[i].fd, parentFd);
746 short events = fds[i].revents;
749 if (events & POLLOUT) {
750 DCHECK(!(events & POLLIN));
751 if (writeCallback(parentFd, p.childFd)) {
752 toClose.push_back(i);
757 // Call read callback on POLLHUP, to give it a chance to read (and act
759 if (events & (POLLIN | POLLHUP)) {
760 DCHECK(!(events & POLLOUT));
761 if (readCallback(parentFd, p.childFd)) {
762 toClose.push_back(i);
767 if ((events & (POLLHUP | POLLERR)) && !closed) {
768 toClose.push_back(i);
773 // Close the fds in reverse order so the indexes hold after erase()
774 for (int idx : boost::adaptors::reverse(toClose)) {
775 auto pos = pipes_.begin() + idx;
776 pos->pipe.close(); // Throws on error
782 void Subprocess::enableNotifications(int childFd, bool enabled) {
783 pipes_[findByChildFd(childFd)].enabled = enabled;
786 bool Subprocess::notificationsEnabled(int childFd) const {
787 return pipes_[findByChildFd(childFd)].enabled;
790 size_t Subprocess::findByChildFd(int childFd) const {
791 auto pos = std::lower_bound(
792 pipes_.begin(), pipes_.end(), childFd,
793 [] (const Pipe& pipe, int fd) { return pipe.childFd < fd; });
794 if (pos == pipes_.end() || pos->childFd != childFd) {
795 throw std::invalid_argument(folly::to<std::string>(
796 "child fd not found ", childFd));
798 return pos - pipes_.begin();
801 void Subprocess::closeParentFd(int childFd) {
802 int idx = findByChildFd(childFd);
803 pipes_[idx].pipe.close(); // May throw
804 pipes_.erase(pipes_.begin() + idx);
807 std::vector<Subprocess::ChildPipe> Subprocess::takeOwnershipOfPipes() {
808 std::vector<Subprocess::ChildPipe> pipes;
809 for (auto& p : pipes_) {
810 pipes.emplace_back(ChildPipe{p.childFd, std::move(p.pipe)});
821 // We like EPIPE, thanks.
822 ::signal(SIGPIPE, SIG_IGN);
826 Initializer initializer;