2 * Copyright 2017 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>
30 #include <system_error>
32 #include <boost/container/flat_set.hpp>
33 #include <boost/range/adaptors.hpp>
35 #include <glog/logging.h>
37 #include <folly/Assume.h>
38 #include <folly/Conv.h>
39 #include <folly/Exception.h>
40 #include <folly/ScopeGuard.h>
41 #include <folly/Shell.h>
42 #include <folly/String.h>
43 #include <folly/io/Cursor.h>
44 #include <folly/portability/Sockets.h>
45 #include <folly/portability/Stdlib.h>
46 #include <folly/portability/SysSyscall.h>
47 #include <folly/portability/Unistd.h>
49 constexpr int kExecFailure = 127;
50 constexpr int kChildFailure = 126;
54 ProcessReturnCode::ProcessReturnCode(ProcessReturnCode&& p) noexcept
55 : rawStatus_(p.rawStatus_) {
56 p.rawStatus_ = ProcessReturnCode::RV_NOT_STARTED;
59 ProcessReturnCode& ProcessReturnCode::operator=(ProcessReturnCode&& p)
61 rawStatus_ = p.rawStatus_;
62 p.rawStatus_ = ProcessReturnCode::RV_NOT_STARTED;
66 ProcessReturnCode::State ProcessReturnCode::state() const {
67 if (rawStatus_ == RV_NOT_STARTED) return NOT_STARTED;
68 if (rawStatus_ == RV_RUNNING) return RUNNING;
69 if (WIFEXITED(rawStatus_)) return EXITED;
70 if (WIFSIGNALED(rawStatus_)) return KILLED;
71 throw std::runtime_error(to<std::string>(
72 "Invalid ProcessReturnCode: ", rawStatus_));
75 void ProcessReturnCode::enforce(State expected) const {
78 throw std::logic_error(to<std::string>(
79 "Bad use of ProcessReturnCode; state is ", s, " expected ", expected
84 int ProcessReturnCode::exitStatus() const {
86 return WEXITSTATUS(rawStatus_);
89 int ProcessReturnCode::killSignal() const {
91 return WTERMSIG(rawStatus_);
94 bool ProcessReturnCode::coreDumped() const {
96 return WCOREDUMP(rawStatus_);
99 std::string ProcessReturnCode::str() const {
102 return "not started";
106 return to<std::string>("exited with status ", exitStatus());
108 return to<std::string>("killed by signal ", killSignal(),
109 (coreDumped() ? " (core dumped)" : ""));
111 assume_unreachable();
114 CalledProcessError::CalledProcessError(ProcessReturnCode rc)
115 : SubprocessError(rc.str()), returnCode_(rc) {}
117 static inline std::string toSubprocessSpawnErrorMessage(
118 char const* executable,
121 auto prefix = errCode == kExecFailure ? "failed to execute "
122 : "error preparing to execute ";
123 return to<std::string>(prefix, executable, ": ", errnoStr(errnoValue));
126 SubprocessSpawnError::SubprocessSpawnError(
127 const char* executable,
131 toSubprocessSpawnErrorMessage(executable, errCode, errnoValue)),
132 errnoValue_(errnoValue) {}
136 // Copy pointers to the given strings in a format suitable for posix_spawn
137 std::unique_ptr<const char*[]> cloneStrings(const std::vector<std::string>& s) {
138 std::unique_ptr<const char*[]> d(new const char*[s.size() + 1]);
139 for (size_t i = 0; i < s.size(); i++) {
142 d[s.size()] = nullptr;
146 // Check a wait() status, throw on non-successful
147 void checkStatus(ProcessReturnCode returnCode) {
148 if (returnCode.state() != ProcessReturnCode::EXITED ||
149 returnCode.exitStatus() != 0) {
150 throw CalledProcessError(returnCode);
156 Subprocess::Options& Subprocess::Options::fd(int fd, int action) {
157 if (action == Subprocess::PIPE) {
159 action = Subprocess::PIPE_IN;
160 } else if (fd == 1 || fd == 2) {
161 action = Subprocess::PIPE_OUT;
163 throw std::invalid_argument(
164 to<std::string>("Only fds 0, 1, 2 are valid for action=PIPE: ", fd));
167 fdActions_[fd] = action;
171 Subprocess::Subprocess() {}
173 Subprocess::Subprocess(
174 const std::vector<std::string>& argv,
175 const Options& options,
176 const char* executable,
177 const std::vector<std::string>* env) {
179 throw std::invalid_argument("argv must not be empty");
181 if (!executable) executable = argv[0].c_str();
182 spawn(cloneStrings(argv), executable, options, env);
185 Subprocess::Subprocess(
186 const std::string& cmd,
187 const Options& options,
188 const std::vector<std::string>* env) {
189 if (options.usePath_) {
190 throw std::invalid_argument("usePath() not allowed when running in shell");
193 std::vector<std::string> argv = {"/bin/sh", "-c", cmd};
194 spawn(cloneStrings(argv), argv[0].c_str(), options, env);
197 Subprocess::~Subprocess() {
198 CHECK_NE(returnCode_.state(), ProcessReturnCode::RUNNING)
199 << "Subprocess destroyed without reaping child";
204 struct ChildErrorInfo {
209 [[noreturn]] void childError(int errFd, int errCode, int errnoValue) {
210 ChildErrorInfo info = {errCode, errnoValue};
211 // Write the error information over the pipe to our parent process.
212 // We can't really do anything else if this write call fails.
213 writeNoInt(errFd, &info, sizeof(info));
220 void Subprocess::setAllNonBlocking() {
221 for (auto& p : pipes_) {
222 int fd = p.pipe.fd();
223 int flags = ::fcntl(fd, F_GETFL);
224 checkUnixError(flags, "fcntl");
225 int r = ::fcntl(fd, F_SETFL, flags | O_NONBLOCK);
226 checkUnixError(r, "fcntl");
230 void Subprocess::spawn(
231 std::unique_ptr<const char*[]> argv,
232 const char* executable,
233 const Options& optionsIn,
234 const std::vector<std::string>* env) {
235 if (optionsIn.usePath_ && env) {
236 throw std::invalid_argument(
237 "usePath() not allowed when overriding environment");
240 // Make a copy, we'll mutate options
241 Options options(optionsIn);
243 // On error, close all pipes_ (ignoring errors, but that seems fine here).
244 auto pipesGuard = makeGuard([this] { pipes_.clear(); });
246 // Create a pipe to use to receive error information from the child,
247 // in case it fails before calling exec()
250 checkUnixError(::pipe2(errFds, O_CLOEXEC), "pipe2");
252 checkUnixError(::pipe(errFds), "pipe");
255 CHECK_ERR(::close(errFds[0]));
256 if (errFds[1] >= 0) {
257 CHECK_ERR(::close(errFds[1]));
261 #if !FOLLY_HAVE_PIPE2
262 // Ask the child to close the read end of the error pipe.
263 checkUnixError(fcntl(errFds[0], F_SETFD, FD_CLOEXEC), "set FD_CLOEXEC");
264 // Set the close-on-exec flag on the write side of the pipe.
265 // This way the pipe will be closed automatically in the child if execve()
266 // succeeds. If the exec fails the child can write error information to the
268 checkUnixError(fcntl(errFds[1], F_SETFD, FD_CLOEXEC), "set FD_CLOEXEC");
271 // Perform the actual work of setting up pipes then forking and
272 // executing the child.
273 spawnInternal(std::move(argv), executable, options, env, errFds[1]);
275 // After spawnInternal() returns the child is alive. We have to be very
276 // careful about throwing after this point. We are inside the constructor,
277 // so if we throw the Subprocess object will have never existed, and the
278 // destructor will never be called.
280 // We should only throw if we got an error via the errFd, and we know the
281 // child has exited and can be immediately waited for. In all other cases,
282 // we have no way of cleaning up the child.
284 // Close writable side of the errFd pipe in the parent process
285 CHECK_ERR(::close(errFds[1]));
288 // Read from the errFd pipe, to tell if the child ran into any errors before
290 readChildErrorPipe(errFds[0], executable);
292 // We have fully succeeded now, so release the guard on pipes_
293 pipesGuard.dismiss();
296 void Subprocess::spawnInternal(
297 std::unique_ptr<const char*[]> argv,
298 const char* executable,
300 const std::vector<std::string>* env,
302 // Parent work, pre-fork: create pipes
303 std::vector<int> childFds;
304 // Close all of the childFds as we leave this scope
306 // These are only pipes, closing them shouldn't fail
307 for (int cfd : childFds) {
308 CHECK_ERR(::close(cfd));
313 for (auto& p : options.fdActions_) {
314 if (p.second == PIPE_IN || p.second == PIPE_OUT) {
316 // We're setting both ends of the pipe as close-on-exec. The child
317 // doesn't need to reset the flag on its end, as we always dup2() the fd,
318 // and dup2() fds don't share the close-on-exec flag.
320 // If possible, set close-on-exec atomically. Otherwise, a concurrent
321 // Subprocess invocation can fork() between "pipe" and "fnctl",
322 // causing FDs to leak.
323 r = ::pipe2(fds, O_CLOEXEC);
324 checkUnixError(r, "pipe2");
327 checkUnixError(r, "pipe");
328 r = fcntl(fds[0], F_SETFD, FD_CLOEXEC);
329 checkUnixError(r, "set FD_CLOEXEC");
330 r = fcntl(fds[1], F_SETFD, FD_CLOEXEC);
331 checkUnixError(r, "set FD_CLOEXEC");
333 pipes_.emplace_back();
334 Pipe& pipe = pipes_.back();
335 pipe.direction = p.second;
337 if (p.second == PIPE_IN) {
338 // Child gets reading end
339 pipe.pipe = folly::File(fds[1], /*owns_fd=*/ true);
342 pipe.pipe = folly::File(fds[0], /*owns_fd=*/ true);
345 p.second = cfd; // ensure it gets dup2()ed
346 pipe.childFd = p.first;
347 childFds.push_back(cfd);
351 // This should already be sorted, as options.fdActions_ is
352 DCHECK(std::is_sorted(pipes_.begin(), pipes_.end()));
354 // Note that the const casts below are legit, per
355 // http://pubs.opengroup.org/onlinepubs/009695399/functions/exec.html
357 char** argVec = const_cast<char**>(argv.get());
359 // Set up environment
360 std::unique_ptr<const char*[]> envHolder;
363 envHolder = cloneStrings(*env);
364 envVec = const_cast<char**>(envHolder.get());
369 // Block all signals around vfork; see http://ewontfix.com/7/.
371 // As the child may run in the same address space as the parent until
372 // the actual execve() system call, any (custom) signal handlers that
373 // the parent has might alter parent's memory if invoked in the child,
374 // with undefined results. So we block all signals in the parent before
375 // vfork(), which will cause them to be blocked in the child as well (we
376 // rely on the fact that Linux, just like all sane implementations, only
377 // clones the calling thread). Then, in the child, we reset all signals
378 // to their default dispositions (while still blocked), and unblock them
379 // (so the exec()ed process inherits the parent's signal mask)
381 // The parent also unblocks all signals as soon as vfork() returns.
383 r = sigfillset(&allBlocked);
384 checkUnixError(r, "sigfillset");
387 r = pthread_sigmask(SIG_SETMASK, &allBlocked, &oldSignals);
388 checkPosixError(r, "pthread_sigmask");
390 // Restore signal mask
391 r = pthread_sigmask(SIG_SETMASK, &oldSignals, nullptr);
392 CHECK_EQ(r, 0) << "pthread_sigmask: " << errnoStr(r); // shouldn't fail
395 // Call c_str() here, as it's not necessarily safe after fork.
396 const char* childDir =
397 options.childDir_.empty() ? nullptr : options.childDir_.c_str();
401 if (options.cloneFlags_) {
402 pid = syscall(SYS_clone, *options.cloneFlags_, 0, nullptr, nullptr);
403 checkUnixError(pid, errno, "clone");
407 checkUnixError(pid, errno, "vfork");
412 int errnoValue = prepareChild(options, &oldSignals, childDir);
413 if (errnoValue != 0) {
414 childError(errFd, kChildFailure, errnoValue);
417 errnoValue = runChild(executable, argVec, envVec, options);
418 // If we get here, exec() failed.
419 childError(errFd, kExecFailure, errnoValue);
422 // Child is alive. We have to be very careful about throwing after this
423 // point. We are inside the constructor, so if we throw the Subprocess
424 // object will have never existed, and the destructor will never be called.
426 // We should only throw if we got an error via the errFd, and we know the
427 // child has exited and can be immediately waited for. In all other cases,
428 // we have no way of cleaning up the child.
430 returnCode_ = ProcessReturnCode(RV_RUNNING);
433 int Subprocess::prepareChild(const Options& options,
434 const sigset_t* sigmask,
435 const char* childDir) const {
436 // While all signals are blocked, we must reset their
437 // dispositions to default.
438 for (int sig = 1; sig < NSIG; ++sig) {
439 ::signal(sig, SIG_DFL);
443 // Unblock signals; restore signal mask.
444 int r = pthread_sigmask(SIG_SETMASK, sigmask, nullptr);
446 return r; // pthread_sigmask() returns an errno value
450 // Change the working directory, if one is given
452 if (::chdir(childDir) == -1) {
457 // We don't have to explicitly close the parent's end of all pipes,
458 // as they all have the FD_CLOEXEC flag set and will be closed at
461 // Close all fds that we're supposed to close.
462 for (auto& p : options.fdActions_) {
463 if (p.second == CLOSE) {
464 if (::close(p.first) == -1) {
467 } else if (p.second != p.first) {
468 if (::dup2(p.second, p.first) == -1) {
474 // If requested, close all other file descriptors. Don't close
475 // any fds in options.fdActions_, and don't touch stdin, stdout, stderr.
477 if (options.closeOtherFds_) {
478 for (int fd = getdtablesize() - 1; fd >= 3; --fd) {
479 if (options.fdActions_.count(fd) == 0) {
486 // Opt to receive signal on parent death, if requested
487 if (options.parentDeathSignal_ != 0) {
488 const auto parentDeathSignal =
489 static_cast<unsigned long>(options.parentDeathSignal_);
490 if (prctl(PR_SET_PDEATHSIG, parentDeathSignal, 0, 0, 0) == -1) {
496 if (options.processGroupLeader_) {
497 if (setpgrp() == -1) {
502 // The user callback comes last, so that the child is otherwise all set up.
503 if (options.dangerousPostForkPreExecCallback_) {
504 if (int error = (*options.dangerousPostForkPreExecCallback_)()) {
512 int Subprocess::runChild(const char* executable,
513 char** argv, char** env,
514 const Options& options) const {
515 // Now, finally, exec.
516 if (options.usePath_) {
517 ::execvp(executable, argv);
519 ::execve(executable, argv, env);
524 void Subprocess::readChildErrorPipe(int pfd, const char* executable) {
526 auto rc = readNoInt(pfd, &info, sizeof(info));
528 // No data means the child executed successfully, and the pipe
529 // was closed due to the close-on-exec flag being set.
531 } else if (rc != sizeof(ChildErrorInfo)) {
532 // An error occurred trying to read from the pipe, or we got a partial read.
533 // Neither of these cases should really occur in practice.
535 // We can't get any error data from the child in this case, and we don't
536 // know if it is successfully running or not. All we can do is to return
537 // normally, as if the child executed successfully. If something bad
538 // happened the caller should at least get a non-normal exit status from
540 LOG(ERROR) << "unexpected error trying to read from child error pipe " <<
541 "rc=" << rc << ", errno=" << errno;
545 // We got error data from the child. The child should exit immediately in
546 // this case, so wait on it to clean up.
549 // Throw to signal the error
550 throw SubprocessSpawnError(executable, info.errCode, info.errnoValue);
553 ProcessReturnCode Subprocess::poll(struct rusage* ru) {
554 returnCode_.enforce(ProcessReturnCode::RUNNING);
557 pid_t found = ::wait4(pid_, &status, WNOHANG, ru);
558 // The spec guarantees that EINTR does not occur with WNOHANG, so the only
559 // two remaining errors are ECHILD (other code reaped the child?), or
560 // EINVAL (cosmic rays?), both of which merit an abort:
561 PCHECK(found != -1) << "waitpid(" << pid_ << ", &status, WNOHANG)";
563 // Though the child process had quit, this call does not close the pipes
564 // since its descendants may still be using them.
565 returnCode_ = ProcessReturnCode(status);
571 bool Subprocess::pollChecked() {
572 if (poll().state() == ProcessReturnCode::RUNNING) {
575 checkStatus(returnCode_);
579 ProcessReturnCode Subprocess::wait() {
580 returnCode_.enforce(ProcessReturnCode::RUNNING);
585 found = ::waitpid(pid_, &status, 0);
586 } while (found == -1 && errno == EINTR);
587 // The only two remaining errors are ECHILD (other code reaped the
588 // child?), or EINVAL (cosmic rays?), and both merit an abort:
589 PCHECK(found != -1) << "waitpid(" << pid_ << ", &status, WNOHANG)";
590 // Though the child process had quit, this call does not close the pipes
591 // since its descendants may still be using them.
592 DCHECK_EQ(found, pid_);
593 returnCode_ = ProcessReturnCode(status);
598 void Subprocess::waitChecked() {
600 checkStatus(returnCode_);
603 void Subprocess::sendSignal(int signal) {
604 returnCode_.enforce(ProcessReturnCode::RUNNING);
605 int r = ::kill(pid_, signal);
606 checkUnixError(r, "kill");
609 pid_t Subprocess::pid() const {
615 ByteRange queueFront(const IOBufQueue& queue) {
616 auto* p = queue.front();
620 return io::Cursor(p).peekBytes();
624 bool handleWrite(int fd, IOBufQueue& queue) {
626 auto b = queueFront(queue);
631 ssize_t n = writeNoInt(fd, b.data(), b.size());
632 if (n == -1 && errno == EAGAIN) {
635 checkUnixError(n, "write");
641 bool handleRead(int fd, IOBufQueue& queue) {
643 auto p = queue.preallocate(100, 65000);
644 ssize_t n = readNoInt(fd, p.first, p.second);
645 if (n == -1 && errno == EAGAIN) {
648 checkUnixError(n, "read");
652 queue.postallocate(n);
656 bool discardRead(int fd) {
657 static const size_t bufSize = 65000;
658 // Thread unsafe, but it doesn't matter.
659 static std::unique_ptr<char[]> buf(new char[bufSize]);
662 ssize_t n = readNoInt(fd, buf.get(), bufSize);
663 if (n == -1 && errno == EAGAIN) {
666 checkUnixError(n, "read");
675 std::pair<std::string, std::string> Subprocess::communicate(
677 IOBufQueue inputQueue;
678 inputQueue.wrapBuffer(input.data(), input.size());
680 auto outQueues = communicateIOBuf(std::move(inputQueue));
681 auto outBufs = std::make_pair(outQueues.first.move(),
682 outQueues.second.move());
683 std::pair<std::string, std::string> out;
685 outBufs.first->coalesce();
686 out.first.assign(reinterpret_cast<const char*>(outBufs.first->data()),
687 outBufs.first->length());
689 if (outBufs.second) {
690 outBufs.second->coalesce();
691 out.second.assign(reinterpret_cast<const char*>(outBufs.second->data()),
692 outBufs.second->length());
697 std::pair<IOBufQueue, IOBufQueue> Subprocess::communicateIOBuf(
699 // If the user supplied a non-empty input buffer, make sure
700 // that stdin is a pipe so we can write the data.
701 if (!input.empty()) {
702 // findByChildFd() will throw std::invalid_argument if no pipe for
703 // STDIN_FILENO exists
704 findByChildFd(STDIN_FILENO);
707 std::pair<IOBufQueue, IOBufQueue> out;
709 auto readCallback = [&] (int pfd, int cfd) -> bool {
710 if (cfd == STDOUT_FILENO) {
711 return handleRead(pfd, out.first);
712 } else if (cfd == STDERR_FILENO) {
713 return handleRead(pfd, out.second);
715 // Don't close the file descriptor, the child might not like SIGPIPE,
716 // just read and throw the data away.
717 return discardRead(pfd);
721 auto writeCallback = [&] (int pfd, int cfd) -> bool {
722 if (cfd == STDIN_FILENO) {
723 return handleWrite(pfd, input);
725 // If we don't want to write to this fd, just close it.
730 communicate(std::move(readCallback), std::move(writeCallback));
735 void Subprocess::communicate(FdCallback readCallback,
736 FdCallback writeCallback) {
737 // This serves to prevent wait() followed by communicate(), but if you
738 // legitimately need that, send a patch to delete this line.
739 returnCode_.enforce(ProcessReturnCode::RUNNING);
742 std::vector<pollfd> fds;
743 fds.reserve(pipes_.size());
744 std::vector<size_t> toClose; // indexes into pipes_
745 toClose.reserve(pipes_.size());
747 while (!pipes_.empty()) {
751 for (auto& p : pipes_) {
753 pfd.fd = p.pipe.fd();
754 // Yes, backwards, PIPE_IN / PIPE_OUT are defined from the
755 // child's point of view.
757 // Still keeping fd in watched set so we get notified of POLLHUP /
760 } else if (p.direction == PIPE_IN) {
761 pfd.events = POLLOUT;
770 r = ::poll(fds.data(), fds.size(), -1);
771 } while (r == -1 && errno == EINTR);
772 checkUnixError(r, "poll");
774 for (size_t i = 0; i < pipes_.size(); ++i) {
776 auto parentFd = p.pipe.fd();
777 DCHECK_EQ(fds[i].fd, parentFd);
778 short events = fds[i].revents;
781 if (events & POLLOUT) {
782 DCHECK(!(events & POLLIN));
783 if (writeCallback(parentFd, p.childFd)) {
784 toClose.push_back(i);
789 // Call read callback on POLLHUP, to give it a chance to read (and act
791 if (events & (POLLIN | POLLHUP)) {
792 DCHECK(!(events & POLLOUT));
793 if (readCallback(parentFd, p.childFd)) {
794 toClose.push_back(i);
799 if ((events & (POLLHUP | POLLERR)) && !closed) {
800 toClose.push_back(i);
805 // Close the fds in reverse order so the indexes hold after erase()
806 for (int idx : boost::adaptors::reverse(toClose)) {
807 auto pos = pipes_.begin() + idx;
808 pos->pipe.close(); // Throws on error
814 void Subprocess::enableNotifications(int childFd, bool enabled) {
815 pipes_[findByChildFd(childFd)].enabled = enabled;
818 bool Subprocess::notificationsEnabled(int childFd) const {
819 return pipes_[findByChildFd(childFd)].enabled;
822 size_t Subprocess::findByChildFd(int childFd) const {
823 auto pos = std::lower_bound(
824 pipes_.begin(), pipes_.end(), childFd,
825 [] (const Pipe& pipe, int fd) { return pipe.childFd < fd; });
826 if (pos == pipes_.end() || pos->childFd != childFd) {
827 throw std::invalid_argument(folly::to<std::string>(
828 "child fd not found ", childFd));
830 return pos - pipes_.begin();
833 void Subprocess::closeParentFd(int childFd) {
834 int idx = findByChildFd(childFd);
835 pipes_[idx].pipe.close(); // May throw
836 pipes_.erase(pipes_.begin() + idx);
839 std::vector<Subprocess::ChildPipe> Subprocess::takeOwnershipOfPipes() {
840 std::vector<Subprocess::ChildPipe> pipes;
841 for (auto& p : pipes_) {
842 pipes.emplace_back(p.childFd, std::move(p.pipe));
845 std::vector<Pipe>().swap(pipes_);
854 // We like EPIPE, thanks.
855 ::signal(SIGPIPE, SIG_IGN);
859 Initializer initializer;