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>
25 #include <sys/syscall.h>
32 #include <system_error>
34 #include <boost/container/flat_set.hpp>
35 #include <boost/range/adaptors.hpp>
37 #include <glog/logging.h>
39 #include <folly/Assume.h>
40 #include <folly/Conv.h>
41 #include <folly/Exception.h>
42 #include <folly/ScopeGuard.h>
43 #include <folly/Shell.h>
44 #include <folly/String.h>
45 #include <folly/io/Cursor.h>
46 #include <folly/portability/Sockets.h>
47 #include <folly/portability/Stdlib.h>
48 #include <folly/portability/Unistd.h>
50 constexpr int kExecFailure = 127;
51 constexpr int kChildFailure = 126;
55 ProcessReturnCode::ProcessReturnCode(ProcessReturnCode&& p) noexcept
56 : rawStatus_(p.rawStatus_) {
57 p.rawStatus_ = ProcessReturnCode::RV_NOT_STARTED;
60 ProcessReturnCode& ProcessReturnCode::operator=(ProcessReturnCode&& p)
62 rawStatus_ = p.rawStatus_;
63 p.rawStatus_ = ProcessReturnCode::RV_NOT_STARTED;
67 ProcessReturnCode::State ProcessReturnCode::state() const {
68 if (rawStatus_ == RV_NOT_STARTED) return NOT_STARTED;
69 if (rawStatus_ == RV_RUNNING) return RUNNING;
70 if (WIFEXITED(rawStatus_)) return EXITED;
71 if (WIFSIGNALED(rawStatus_)) return KILLED;
72 throw std::runtime_error(to<std::string>(
73 "Invalid ProcessReturnCode: ", rawStatus_));
76 void ProcessReturnCode::enforce(State expected) const {
79 throw std::logic_error(to<std::string>(
80 "Bad use of ProcessReturnCode; state is ", s, " expected ", expected
85 int ProcessReturnCode::exitStatus() const {
87 return WEXITSTATUS(rawStatus_);
90 int ProcessReturnCode::killSignal() const {
92 return WTERMSIG(rawStatus_);
95 bool ProcessReturnCode::coreDumped() const {
97 return WCOREDUMP(rawStatus_);
100 std::string ProcessReturnCode::str() const {
103 return "not started";
107 return to<std::string>("exited with status ", exitStatus());
109 return to<std::string>("killed by signal ", killSignal(),
110 (coreDumped() ? " (core dumped)" : ""));
112 assume_unreachable();
115 CalledProcessError::CalledProcessError(ProcessReturnCode rc)
117 what_(returnCode_.str()) {
120 SubprocessSpawnError::SubprocessSpawnError(const char* executable,
123 : errnoValue_(errnoValue),
124 what_(to<std::string>(errCode == kExecFailure ?
125 "failed to execute " :
126 "error preparing to execute ",
127 executable, ": ", errnoStr(errnoValue))) {
132 // Copy pointers to the given strings in a format suitable for posix_spawn
133 std::unique_ptr<const char*[]> cloneStrings(const std::vector<std::string>& s) {
134 std::unique_ptr<const char*[]> d(new const char*[s.size() + 1]);
135 for (size_t i = 0; i < s.size(); i++) {
138 d[s.size()] = nullptr;
142 // Check a wait() status, throw on non-successful
143 void checkStatus(ProcessReturnCode returnCode) {
144 if (returnCode.state() != ProcessReturnCode::EXITED ||
145 returnCode.exitStatus() != 0) {
146 throw CalledProcessError(returnCode);
152 Subprocess::Options& Subprocess::Options::fd(int fd, int action) {
153 if (action == Subprocess::PIPE) {
155 action = Subprocess::PIPE_IN;
156 } else if (fd == 1 || fd == 2) {
157 action = Subprocess::PIPE_OUT;
159 throw std::invalid_argument(
160 to<std::string>("Only fds 0, 1, 2 are valid for action=PIPE: ", fd));
163 fdActions_[fd] = action;
167 Subprocess::Subprocess() {}
169 Subprocess::Subprocess(
170 const std::vector<std::string>& argv,
171 const Options& options,
172 const char* executable,
173 const std::vector<std::string>* env) {
175 throw std::invalid_argument("argv must not be empty");
177 if (!executable) executable = argv[0].c_str();
178 spawn(cloneStrings(argv), executable, options, env);
181 Subprocess::Subprocess(
182 const std::string& cmd,
183 const Options& options,
184 const std::vector<std::string>* env) {
185 if (options.usePath_) {
186 throw std::invalid_argument("usePath() not allowed when running in shell");
189 std::vector<std::string> argv = {"/bin/sh", "-c", cmd};
190 spawn(cloneStrings(argv), argv[0].c_str(), options, env);
193 Subprocess::~Subprocess() {
194 CHECK_NE(returnCode_.state(), ProcessReturnCode::RUNNING)
195 << "Subprocess destroyed without reaping child";
200 struct ChildErrorInfo {
205 [[noreturn]] void childError(int errFd, int errCode, int errnoValue) {
206 ChildErrorInfo info = {errCode, errnoValue};
207 // Write the error information over the pipe to our parent process.
208 // We can't really do anything else if this write call fails.
209 writeNoInt(errFd, &info, sizeof(info));
216 void Subprocess::setAllNonBlocking() {
217 for (auto& p : pipes_) {
218 int fd = p.pipe.fd();
219 int flags = ::fcntl(fd, F_GETFL);
220 checkUnixError(flags, "fcntl");
221 int r = ::fcntl(fd, F_SETFL, flags | O_NONBLOCK);
222 checkUnixError(r, "fcntl");
226 void Subprocess::spawn(
227 std::unique_ptr<const char*[]> argv,
228 const char* executable,
229 const Options& optionsIn,
230 const std::vector<std::string>* env) {
231 if (optionsIn.usePath_ && env) {
232 throw std::invalid_argument(
233 "usePath() not allowed when overriding environment");
236 // Make a copy, we'll mutate options
237 Options options(optionsIn);
239 // On error, close all pipes_ (ignoring errors, but that seems fine here).
240 auto pipesGuard = makeGuard([this] { pipes_.clear(); });
242 // Create a pipe to use to receive error information from the child,
243 // in case it fails before calling exec()
246 checkUnixError(::pipe2(errFds, O_CLOEXEC), "pipe2");
248 checkUnixError(::pipe(errFds), "pipe");
251 CHECK_ERR(::close(errFds[0]));
252 if (errFds[1] >= 0) {
253 CHECK_ERR(::close(errFds[1]));
257 #if !FOLLY_HAVE_PIPE2
258 // Ask the child to close the read end of the error pipe.
259 checkUnixError(fcntl(errFds[0], F_SETFD, FD_CLOEXEC), "set FD_CLOEXEC");
260 // Set the close-on-exec flag on the write side of the pipe.
261 // This way the pipe will be closed automatically in the child if execve()
262 // succeeds. If the exec fails the child can write error information to the
264 checkUnixError(fcntl(errFds[1], F_SETFD, FD_CLOEXEC), "set FD_CLOEXEC");
267 // Perform the actual work of setting up pipes then forking and
268 // executing the child.
269 spawnInternal(std::move(argv), executable, options, env, errFds[1]);
271 // After spawnInternal() returns the child is alive. We have to be very
272 // careful about throwing after this point. We are inside the constructor,
273 // so if we throw the Subprocess object will have never existed, and the
274 // destructor will never be called.
276 // We should only throw if we got an error via the errFd, and we know the
277 // child has exited and can be immediately waited for. In all other cases,
278 // we have no way of cleaning up the child.
280 // Close writable side of the errFd pipe in the parent process
281 CHECK_ERR(::close(errFds[1]));
284 // Read from the errFd pipe, to tell if the child ran into any errors before
286 readChildErrorPipe(errFds[0], executable);
288 // We have fully succeeded now, so release the guard on pipes_
289 pipesGuard.dismiss();
292 void Subprocess::spawnInternal(
293 std::unique_ptr<const char*[]> argv,
294 const char* executable,
296 const std::vector<std::string>* env,
298 // Parent work, pre-fork: create pipes
299 std::vector<int> childFds;
300 // Close all of the childFds as we leave this scope
302 // These are only pipes, closing them shouldn't fail
303 for (int cfd : childFds) {
304 CHECK_ERR(::close(cfd));
309 for (auto& p : options.fdActions_) {
310 if (p.second == PIPE_IN || p.second == PIPE_OUT) {
312 // We're setting both ends of the pipe as close-on-exec. The child
313 // doesn't need to reset the flag on its end, as we always dup2() the fd,
314 // and dup2() fds don't share the close-on-exec flag.
316 // If possible, set close-on-exec atomically. Otherwise, a concurrent
317 // Subprocess invocation can fork() between "pipe" and "fnctl",
318 // causing FDs to leak.
319 r = ::pipe2(fds, O_CLOEXEC);
320 checkUnixError(r, "pipe2");
323 checkUnixError(r, "pipe");
324 r = fcntl(fds[0], F_SETFD, FD_CLOEXEC);
325 checkUnixError(r, "set FD_CLOEXEC");
326 r = fcntl(fds[1], F_SETFD, FD_CLOEXEC);
327 checkUnixError(r, "set FD_CLOEXEC");
329 pipes_.emplace_back();
330 Pipe& pipe = pipes_.back();
331 pipe.direction = p.second;
333 if (p.second == PIPE_IN) {
334 // Child gets reading end
335 pipe.pipe = folly::File(fds[1], /*owns_fd=*/ true);
338 pipe.pipe = folly::File(fds[0], /*owns_fd=*/ true);
341 p.second = cfd; // ensure it gets dup2()ed
342 pipe.childFd = p.first;
343 childFds.push_back(cfd);
347 // This should already be sorted, as options.fdActions_ is
348 DCHECK(std::is_sorted(pipes_.begin(), pipes_.end()));
350 // Note that the const casts below are legit, per
351 // http://pubs.opengroup.org/onlinepubs/009695399/functions/exec.html
353 char** argVec = const_cast<char**>(argv.get());
355 // Set up environment
356 std::unique_ptr<const char*[]> envHolder;
359 envHolder = cloneStrings(*env);
360 envVec = const_cast<char**>(envHolder.get());
365 // Block all signals around vfork; see http://ewontfix.com/7/.
367 // As the child may run in the same address space as the parent until
368 // the actual execve() system call, any (custom) signal handlers that
369 // the parent has might alter parent's memory if invoked in the child,
370 // with undefined results. So we block all signals in the parent before
371 // vfork(), which will cause them to be blocked in the child as well (we
372 // rely on the fact that Linux, just like all sane implementations, only
373 // clones the calling thread). Then, in the child, we reset all signals
374 // to their default dispositions (while still blocked), and unblock them
375 // (so the exec()ed process inherits the parent's signal mask)
377 // The parent also unblocks all signals as soon as vfork() returns.
379 r = sigfillset(&allBlocked);
380 checkUnixError(r, "sigfillset");
383 r = pthread_sigmask(SIG_SETMASK, &allBlocked, &oldSignals);
384 checkPosixError(r, "pthread_sigmask");
386 // Restore signal mask
387 r = pthread_sigmask(SIG_SETMASK, &oldSignals, nullptr);
388 CHECK_EQ(r, 0) << "pthread_sigmask: " << errnoStr(r); // shouldn't fail
391 // Call c_str() here, as it's not necessarily safe after fork.
392 const char* childDir =
393 options.childDir_.empty() ? nullptr : options.childDir_.c_str();
397 if (options.cloneFlags_) {
398 pid = syscall(SYS_clone, *options.cloneFlags_, 0, nullptr, nullptr);
399 checkUnixError(pid, errno, "clone");
403 checkUnixError(pid, errno, "vfork");
408 int errnoValue = prepareChild(options, &oldSignals, childDir);
409 if (errnoValue != 0) {
410 childError(errFd, kChildFailure, errnoValue);
413 errnoValue = runChild(executable, argVec, envVec, options);
414 // If we get here, exec() failed.
415 childError(errFd, kExecFailure, errnoValue);
418 // Child is alive. We have to be very careful about throwing after this
419 // point. We are inside the constructor, so if we throw the Subprocess
420 // object will have never existed, and the destructor will never be called.
422 // We should only throw if we got an error via the errFd, and we know the
423 // child has exited and can be immediately waited for. In all other cases,
424 // we have no way of cleaning up the child.
426 returnCode_ = ProcessReturnCode(RV_RUNNING);
429 int Subprocess::prepareChild(const Options& options,
430 const sigset_t* sigmask,
431 const char* childDir) const {
432 // While all signals are blocked, we must reset their
433 // dispositions to default.
434 for (int sig = 1; sig < NSIG; ++sig) {
435 ::signal(sig, SIG_DFL);
439 // Unblock signals; restore signal mask.
440 int r = pthread_sigmask(SIG_SETMASK, sigmask, nullptr);
442 return r; // pthread_sigmask() returns an errno value
446 // Change the working directory, if one is given
448 if (::chdir(childDir) == -1) {
453 // We don't have to explicitly close the parent's end of all pipes,
454 // as they all have the FD_CLOEXEC flag set and will be closed at
457 // Close all fds that we're supposed to close.
458 for (auto& p : options.fdActions_) {
459 if (p.second == CLOSE) {
460 if (::close(p.first) == -1) {
463 } else if (p.second != p.first) {
464 if (::dup2(p.second, p.first) == -1) {
470 // If requested, close all other file descriptors. Don't close
471 // any fds in options.fdActions_, and don't touch stdin, stdout, stderr.
473 if (options.closeOtherFds_) {
474 for (int fd = getdtablesize() - 1; fd >= 3; --fd) {
475 if (options.fdActions_.count(fd) == 0) {
482 // Opt to receive signal on parent death, if requested
483 if (options.parentDeathSignal_ != 0) {
484 const auto parentDeathSignal =
485 static_cast<unsigned long>(options.parentDeathSignal_);
486 if (prctl(PR_SET_PDEATHSIG, parentDeathSignal, 0, 0, 0) == -1) {
492 if (options.processGroupLeader_) {
493 if (setpgrp() == -1) {
498 // The user callback comes last, so that the child is otherwise all set up.
499 if (options.dangerousPostForkPreExecCallback_) {
500 if (int error = (*options.dangerousPostForkPreExecCallback_)()) {
508 int Subprocess::runChild(const char* executable,
509 char** argv, char** env,
510 const Options& options) const {
511 // Now, finally, exec.
512 if (options.usePath_) {
513 ::execvp(executable, argv);
515 ::execve(executable, argv, env);
520 void Subprocess::readChildErrorPipe(int pfd, const char* executable) {
522 auto rc = readNoInt(pfd, &info, sizeof(info));
524 // No data means the child executed successfully, and the pipe
525 // was closed due to the close-on-exec flag being set.
527 } else if (rc != sizeof(ChildErrorInfo)) {
528 // An error occurred trying to read from the pipe, or we got a partial read.
529 // Neither of these cases should really occur in practice.
531 // We can't get any error data from the child in this case, and we don't
532 // know if it is successfully running or not. All we can do is to return
533 // normally, as if the child executed successfully. If something bad
534 // happened the caller should at least get a non-normal exit status from
536 LOG(ERROR) << "unexpected error trying to read from child error pipe " <<
537 "rc=" << rc << ", errno=" << errno;
541 // We got error data from the child. The child should exit immediately in
542 // this case, so wait on it to clean up.
545 // Throw to signal the error
546 throw SubprocessSpawnError(executable, info.errCode, info.errnoValue);
549 ProcessReturnCode Subprocess::poll() {
550 returnCode_.enforce(ProcessReturnCode::RUNNING);
553 pid_t found = ::waitpid(pid_, &status, WNOHANG);
554 // The spec guarantees that EINTR does not occur with WNOHANG, so the only
555 // two remaining errors are ECHILD (other code reaped the child?), or
556 // EINVAL (cosmic rays?), both of which merit an abort:
557 PCHECK(found != -1) << "waitpid(" << pid_ << ", &status, WNOHANG)";
559 // Though the child process had quit, this call does not close the pipes
560 // since its descendants may still be using them.
561 returnCode_ = ProcessReturnCode(status);
567 bool Subprocess::pollChecked() {
568 if (poll().state() == ProcessReturnCode::RUNNING) {
571 checkStatus(returnCode_);
575 ProcessReturnCode Subprocess::wait() {
576 returnCode_.enforce(ProcessReturnCode::RUNNING);
581 found = ::waitpid(pid_, &status, 0);
582 } while (found == -1 && errno == EINTR);
583 // The only two remaining errors are ECHILD (other code reaped the
584 // child?), or EINVAL (cosmic rays?), and both merit an abort:
585 PCHECK(found != -1) << "waitpid(" << pid_ << ", &status, WNOHANG)";
586 // Though the child process had quit, this call does not close the pipes
587 // since its descendants may still be using them.
588 DCHECK_EQ(found, pid_);
589 returnCode_ = ProcessReturnCode(status);
594 void Subprocess::waitChecked() {
596 checkStatus(returnCode_);
599 void Subprocess::sendSignal(int signal) {
600 returnCode_.enforce(ProcessReturnCode::RUNNING);
601 int r = ::kill(pid_, signal);
602 checkUnixError(r, "kill");
605 pid_t Subprocess::pid() const {
611 ByteRange queueFront(const IOBufQueue& queue) {
612 auto* p = queue.front();
616 return io::Cursor(p).peekBytes();
620 bool handleWrite(int fd, IOBufQueue& queue) {
622 auto b = queueFront(queue);
627 ssize_t n = writeNoInt(fd, b.data(), b.size());
628 if (n == -1 && errno == EAGAIN) {
631 checkUnixError(n, "write");
637 bool handleRead(int fd, IOBufQueue& queue) {
639 auto p = queue.preallocate(100, 65000);
640 ssize_t n = readNoInt(fd, p.first, p.second);
641 if (n == -1 && errno == EAGAIN) {
644 checkUnixError(n, "read");
648 queue.postallocate(n);
652 bool discardRead(int fd) {
653 static const size_t bufSize = 65000;
654 // Thread unsafe, but it doesn't matter.
655 static std::unique_ptr<char[]> buf(new char[bufSize]);
658 ssize_t n = readNoInt(fd, buf.get(), bufSize);
659 if (n == -1 && errno == EAGAIN) {
662 checkUnixError(n, "read");
671 std::pair<std::string, std::string> Subprocess::communicate(
673 IOBufQueue inputQueue;
674 inputQueue.wrapBuffer(input.data(), input.size());
676 auto outQueues = communicateIOBuf(std::move(inputQueue));
677 auto outBufs = std::make_pair(outQueues.first.move(),
678 outQueues.second.move());
679 std::pair<std::string, std::string> out;
681 outBufs.first->coalesce();
682 out.first.assign(reinterpret_cast<const char*>(outBufs.first->data()),
683 outBufs.first->length());
685 if (outBufs.second) {
686 outBufs.second->coalesce();
687 out.second.assign(reinterpret_cast<const char*>(outBufs.second->data()),
688 outBufs.second->length());
693 std::pair<IOBufQueue, IOBufQueue> Subprocess::communicateIOBuf(
695 // If the user supplied a non-empty input buffer, make sure
696 // that stdin is a pipe so we can write the data.
697 if (!input.empty()) {
698 // findByChildFd() will throw std::invalid_argument if no pipe for
699 // STDIN_FILENO exists
700 findByChildFd(STDIN_FILENO);
703 std::pair<IOBufQueue, IOBufQueue> out;
705 auto readCallback = [&] (int pfd, int cfd) -> bool {
706 if (cfd == STDOUT_FILENO) {
707 return handleRead(pfd, out.first);
708 } else if (cfd == STDERR_FILENO) {
709 return handleRead(pfd, out.second);
711 // Don't close the file descriptor, the child might not like SIGPIPE,
712 // just read and throw the data away.
713 return discardRead(pfd);
717 auto writeCallback = [&] (int pfd, int cfd) -> bool {
718 if (cfd == STDIN_FILENO) {
719 return handleWrite(pfd, input);
721 // If we don't want to write to this fd, just close it.
726 communicate(std::move(readCallback), std::move(writeCallback));
731 void Subprocess::communicate(FdCallback readCallback,
732 FdCallback writeCallback) {
733 // This serves to prevent wait() followed by communicate(), but if you
734 // legitimately need that, send a patch to delete this line.
735 returnCode_.enforce(ProcessReturnCode::RUNNING);
738 std::vector<pollfd> fds;
739 fds.reserve(pipes_.size());
740 std::vector<size_t> toClose; // indexes into pipes_
741 toClose.reserve(pipes_.size());
743 while (!pipes_.empty()) {
747 for (auto& p : pipes_) {
749 pfd.fd = p.pipe.fd();
750 // Yes, backwards, PIPE_IN / PIPE_OUT are defined from the
751 // child's point of view.
753 // Still keeping fd in watched set so we get notified of POLLHUP /
756 } else if (p.direction == PIPE_IN) {
757 pfd.events = POLLOUT;
766 r = ::poll(fds.data(), fds.size(), -1);
767 } while (r == -1 && errno == EINTR);
768 checkUnixError(r, "poll");
770 for (size_t i = 0; i < pipes_.size(); ++i) {
772 auto parentFd = p.pipe.fd();
773 DCHECK_EQ(fds[i].fd, parentFd);
774 short events = fds[i].revents;
777 if (events & POLLOUT) {
778 DCHECK(!(events & POLLIN));
779 if (writeCallback(parentFd, p.childFd)) {
780 toClose.push_back(i);
785 // Call read callback on POLLHUP, to give it a chance to read (and act
787 if (events & (POLLIN | POLLHUP)) {
788 DCHECK(!(events & POLLOUT));
789 if (readCallback(parentFd, p.childFd)) {
790 toClose.push_back(i);
795 if ((events & (POLLHUP | POLLERR)) && !closed) {
796 toClose.push_back(i);
801 // Close the fds in reverse order so the indexes hold after erase()
802 for (int idx : boost::adaptors::reverse(toClose)) {
803 auto pos = pipes_.begin() + idx;
804 pos->pipe.close(); // Throws on error
810 void Subprocess::enableNotifications(int childFd, bool enabled) {
811 pipes_[findByChildFd(childFd)].enabled = enabled;
814 bool Subprocess::notificationsEnabled(int childFd) const {
815 return pipes_[findByChildFd(childFd)].enabled;
818 size_t Subprocess::findByChildFd(int childFd) const {
819 auto pos = std::lower_bound(
820 pipes_.begin(), pipes_.end(), childFd,
821 [] (const Pipe& pipe, int fd) { return pipe.childFd < fd; });
822 if (pos == pipes_.end() || pos->childFd != childFd) {
823 throw std::invalid_argument(folly::to<std::string>(
824 "child fd not found ", childFd));
826 return pos - pipes_.begin();
829 void Subprocess::closeParentFd(int childFd) {
830 int idx = findByChildFd(childFd);
831 pipes_[idx].pipe.close(); // May throw
832 pipes_.erase(pipes_.begin() + idx);
835 std::vector<Subprocess::ChildPipe> Subprocess::takeOwnershipOfPipes() {
836 std::vector<Subprocess::ChildPipe> pipes;
837 for (auto& p : pipes_) {
838 pipes.emplace_back(p.childFd, std::move(p.pipe));
841 std::vector<Pipe>().swap(pipes_);
850 // We like EPIPE, thanks.
851 ::signal(SIGPIPE, SIG_IGN);
855 Initializer initializer;