2 * Copyright 2014 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.
17 #include "folly/Subprocess.h"
20 #include <sys/prctl.h>
28 #include <system_error>
30 #include <boost/container/flat_set.hpp>
31 #include <boost/range/adaptors.hpp>
33 #include <glog/logging.h>
35 #include "folly/Conv.h"
36 #include "folly/Exception.h"
37 #include "folly/FileUtil.h"
38 #include "folly/ScopeGuard.h"
39 #include "folly/String.h"
40 #include "folly/io/Cursor.h"
42 extern char** environ;
44 constexpr int kExecFailure = 127;
45 constexpr int kChildFailure = 126;
49 ProcessReturnCode::State ProcessReturnCode::state() const {
50 if (rawStatus_ == RV_NOT_STARTED) return NOT_STARTED;
51 if (rawStatus_ == RV_RUNNING) return RUNNING;
52 if (WIFEXITED(rawStatus_)) return EXITED;
53 if (WIFSIGNALED(rawStatus_)) return KILLED;
54 throw std::runtime_error(to<std::string>(
55 "Invalid ProcessReturnCode: ", rawStatus_));
58 void ProcessReturnCode::enforce(State expected) const {
61 throw std::logic_error(to<std::string>(
62 "Bad use of ProcessReturnCode; state is ", s, " expected ", expected
67 int ProcessReturnCode::exitStatus() const {
69 return WEXITSTATUS(rawStatus_);
72 int ProcessReturnCode::killSignal() const {
74 return WTERMSIG(rawStatus_);
77 bool ProcessReturnCode::coreDumped() const {
79 return WCOREDUMP(rawStatus_);
82 std::string ProcessReturnCode::str() const {
89 return to<std::string>("exited with status ", exitStatus());
91 return to<std::string>("killed by signal ", killSignal(),
92 (coreDumped() ? " (core dumped)" : ""));
94 CHECK(false); // unreached
97 CalledProcessError::CalledProcessError(ProcessReturnCode rc)
99 what_(returnCode_.str()) {
102 SubprocessSpawnError::SubprocessSpawnError(const char* executable,
105 : errnoValue_(errnoValue),
106 what_(to<std::string>(errCode == kExecFailure ?
107 "failed to execute " :
108 "error preparing to execute ",
109 executable, ": ", errnoStr(errnoValue))) {
114 // Copy pointers to the given strings in a format suitable for posix_spawn
115 std::unique_ptr<const char*[]> cloneStrings(const std::vector<std::string>& s) {
116 std::unique_ptr<const char*[]> d(new const char*[s.size() + 1]);
117 for (int i = 0; i < s.size(); i++) {
120 d[s.size()] = nullptr;
124 // Check a wait() status, throw on non-successful
125 void checkStatus(ProcessReturnCode returnCode) {
126 if (returnCode.state() != ProcessReturnCode::EXITED ||
127 returnCode.exitStatus() != 0) {
128 throw CalledProcessError(returnCode);
134 Subprocess::Options& Subprocess::Options::fd(int fd, int action) {
135 if (action == Subprocess::PIPE) {
137 action = Subprocess::PIPE_IN;
138 } else if (fd == 1 || fd == 2) {
139 action = Subprocess::PIPE_OUT;
141 throw std::invalid_argument(
142 to<std::string>("Only fds 0, 1, 2 are valid for action=PIPE: ", fd));
145 fdActions_[fd] = action;
149 Subprocess::Subprocess(
150 const std::vector<std::string>& argv,
151 const Options& options,
152 const char* executable,
153 const std::vector<std::string>* env)
155 returnCode_(RV_NOT_STARTED) {
157 throw std::invalid_argument("argv must not be empty");
159 if (!executable) executable = argv[0].c_str();
160 spawn(cloneStrings(argv), executable, options, env);
163 Subprocess::Subprocess(
164 const std::string& cmd,
165 const Options& options,
166 const std::vector<std::string>* env)
168 returnCode_(RV_NOT_STARTED) {
169 if (options.usePath_) {
170 throw std::invalid_argument("usePath() not allowed when running in shell");
172 const char* shell = getenv("SHELL");
177 std::unique_ptr<const char*[]> argv(new const char*[4]);
180 argv[2] = cmd.c_str();
182 spawn(std::move(argv), shell, options, env);
185 Subprocess::~Subprocess() {
186 CHECK_NE(returnCode_.state(), ProcessReturnCode::RUNNING)
187 << "Subprocess destroyed without reaping child";
192 void closeChecked(int fd) {
193 checkUnixError(::close(fd), "close");
196 struct ChildErrorInfo {
201 FOLLY_NORETURN void childError(int errFd, int errCode, int errnoValue);
202 void childError(int errFd, int errCode, int errnoValue) {
203 ChildErrorInfo info = {errCode, errnoValue};
204 // Write the error information over the pipe to our parent process.
205 // We can't really do anything else if this write call fails.
206 writeNoInt(errFd, &info, sizeof(info));
213 void Subprocess::closeAll() {
214 for (auto& p : pipes_) {
215 closeChecked(p.parentFd);
220 void Subprocess::setAllNonBlocking() {
221 for (auto& p : pipes_) {
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 of the pipes_
244 auto pipesGuard = makeGuard([&] {
245 for (auto& p : this->pipes_) {
246 CHECK_ERR(::close(p.parentFd));
250 // Create a pipe to use to receive error information from the child,
251 // in case it fails before calling exec()
253 int r = ::pipe(errFds);
254 checkUnixError(r, "pipe");
256 CHECK_ERR(::close(errFds[0]));
257 if (errFds[1] >= 0) {
258 CHECK_ERR(::close(errFds[1]));
261 // Ask the child to close the read end of the error pipe.
262 options.fdActions_[errFds[0]] = CLOSE;
263 // Set the close-on-exec flag on the write side of the pipe.
264 // This way the pipe will be closed automatically in the child if execve()
265 // succeeds. If the exec fails the child can write error information to the
267 r = fcntl(errFds[1], F_SETFD, FD_CLOEXEC);
268 checkUnixError(r, "set FD_CLOEXEC");
270 // Perform the actual work of setting up pipes then forking and
271 // executing the child.
272 spawnInternal(std::move(argv), executable, options, env, errFds[1]);
274 // After spawnInternal() returns the child is alive. We have to be very
275 // careful about throwing after this point. We are inside the constructor,
276 // so if we throw the Subprocess object will have never existed, and the
277 // destructor will never be called.
279 // We should only throw if we got an error via the errFd, and we know the
280 // child has exited and can be immediately waited for. In all other cases,
281 // we have no way of cleaning up the child.
283 // Close writable side of the errFd pipe in the parent process
284 CHECK_ERR(::close(errFds[1]));
287 // Read from the errFd pipe, to tell if the child ran into any errors before
289 readChildErrorPipe(errFds[0], executable);
291 // We have fully succeeded now, so release the guard on pipes_
292 pipesGuard.dismiss();
295 void Subprocess::spawnInternal(
296 std::unique_ptr<const char*[]> argv,
297 const char* executable,
299 const std::vector<std::string>* env,
301 // Parent work, pre-fork: create pipes
302 std::vector<int> childFds;
303 // Close all of the childFds as we leave this scope
305 // These are only pipes, closing them shouldn't fail
306 for (int cfd : childFds) {
307 CHECK_ERR(::close(cfd));
312 for (auto& p : options.fdActions_) {
313 if (p.second == PIPE_IN || p.second == PIPE_OUT) {
316 checkUnixError(r, "pipe");
318 pinfo.direction = p.second;
320 if (p.second == PIPE_IN) {
321 // Child gets reading end
322 pinfo.parentFd = fds[1];
325 pinfo.parentFd = fds[0];
328 p.second = cfd; // ensure it gets dup2()ed
329 pinfo.childFd = p.first;
330 childFds.push_back(cfd);
331 pipes_.push_back(pinfo);
335 // This should already be sorted, as options.fdActions_ is
336 DCHECK(std::is_sorted(pipes_.begin(), pipes_.end()));
338 // Note that the const casts below are legit, per
339 // http://pubs.opengroup.org/onlinepubs/009695399/functions/exec.html
341 char** argVec = const_cast<char**>(argv.get());
343 // Set up environment
344 std::unique_ptr<const char*[]> envHolder;
347 envHolder = cloneStrings(*env);
348 envVec = const_cast<char**>(envHolder.get());
353 // Block all signals around vfork; see http://ewontfix.com/7/.
355 // As the child may run in the same address space as the parent until
356 // the actual execve() system call, any (custom) signal handlers that
357 // the parent has might alter parent's memory if invoked in the child,
358 // with undefined results. So we block all signals in the parent before
359 // vfork(), which will cause them to be blocked in the child as well (we
360 // rely on the fact that Linux, just like all sane implementations, only
361 // clones the calling thread). Then, in the child, we reset all signals
362 // to their default dispositions (while still blocked), and unblock them
363 // (so the exec()ed process inherits the parent's signal mask)
365 // The parent also unblocks all signals as soon as vfork() returns.
367 r = sigfillset(&allBlocked);
368 checkUnixError(r, "sigfillset");
371 r = pthread_sigmask(SIG_SETMASK, &allBlocked, &oldSignals);
372 checkPosixError(r, "pthread_sigmask");
374 // Restore signal mask
375 r = pthread_sigmask(SIG_SETMASK, &oldSignals, nullptr);
376 CHECK_EQ(r, 0) << "pthread_sigmask: " << errnoStr(r); // shouldn't fail
381 int errnoValue = prepareChild(options, &oldSignals);
382 if (errnoValue != 0) {
383 childError(errFd, kChildFailure, errnoValue);
386 errnoValue = runChild(executable, argVec, envVec, options);
387 // If we get here, exec() failed.
388 childError(errFd, kExecFailure, errnoValue);
390 // In parent. Make sure vfork() succeeded.
391 checkUnixError(pid, errno, "vfork");
393 // Child is alive. We have to be very careful about throwing after this
394 // point. We are inside the constructor, so if we throw the Subprocess
395 // object will have never existed, and the destructor will never be called.
397 // We should only throw if we got an error via the errFd, and we know the
398 // child has exited and can be immediately waited for. In all other cases,
399 // we have no way of cleaning up the child.
401 returnCode_ = ProcessReturnCode(RV_RUNNING);
404 int Subprocess::prepareChild(const Options& options,
405 const sigset_t* sigmask) const {
406 // While all signals are blocked, we must reset their
407 // dispositions to default.
408 for (int sig = 1; sig < NSIG; ++sig) {
409 ::signal(sig, SIG_DFL);
411 // Unblock signals; restore signal mask.
412 int r = pthread_sigmask(SIG_SETMASK, sigmask, nullptr);
414 return r; // pthread_sigmask() returns an errno value
417 // Change the working directory, if one is given
418 if (!options.childDir_.empty()) {
419 r = ::chdir(options.childDir_.c_str());
425 // Close parent's ends of all pipes
426 for (auto& p : pipes_) {
427 r = ::close(p.parentFd);
433 // Close all fds that we're supposed to close.
434 // Note that we're ignoring errors here, in case some of these
435 // fds were set to close on exec.
436 for (auto& p : options.fdActions_) {
437 if (p.second == CLOSE) {
440 r = ::dup2(p.second, p.first);
447 // If requested, close all other file descriptors. Don't close
448 // any fds in options.fdActions_, and don't touch stdin, stdout, stderr.
450 if (options.closeOtherFds_) {
451 for (int fd = getdtablesize() - 1; fd >= 3; --fd) {
452 if (options.fdActions_.count(fd) == 0) {
459 // Opt to receive signal on parent death, if requested
460 if (options.parentDeathSignal_ != 0) {
461 r = prctl(PR_SET_PDEATHSIG, options.parentDeathSignal_, 0, 0, 0);
471 int Subprocess::runChild(const char* executable,
472 char** argv, char** env,
473 const Options& options) const {
474 // Now, finally, exec.
476 if (options.usePath_) {
477 ::execvp(executable, argv);
479 ::execve(executable, argv, env);
484 void Subprocess::readChildErrorPipe(int pfd, const char* executable) {
486 auto rc = readNoInt(pfd, &info, sizeof(info));
488 // No data means the child executed successfully, and the pipe
489 // was closed due to the close-on-exec flag being set.
491 } else if (rc != sizeof(ChildErrorInfo)) {
492 // An error occurred trying to read from the pipe, or we got a partial read.
493 // Neither of these cases should really occur in practice.
495 // We can't get any error data from the child in this case, and we don't
496 // know if it is successfully running or not. All we can do is to return
497 // normally, as if the child executed successfully. If something bad
498 // happened the caller should at least get a non-normal exit status from
500 LOG(ERROR) << "unexpected error trying to read from child error pipe " <<
501 "rc=" << rc << ", errno=" << errno;
505 // We got error data from the child. The child should exit immediately in
506 // this case, so wait on it to clean up.
509 // Throw to signal the error
510 throw SubprocessSpawnError(executable, info.errCode, info.errnoValue);
513 ProcessReturnCode Subprocess::poll() {
514 returnCode_.enforce(ProcessReturnCode::RUNNING);
517 pid_t found = ::waitpid(pid_, &status, WNOHANG);
518 checkUnixError(found, "waitpid");
520 returnCode_ = ProcessReturnCode(status);
526 bool Subprocess::pollChecked() {
527 if (poll().state() == ProcessReturnCode::RUNNING) {
530 checkStatus(returnCode_);
534 ProcessReturnCode Subprocess::wait() {
535 returnCode_.enforce(ProcessReturnCode::RUNNING);
540 found = ::waitpid(pid_, &status, 0);
541 } while (found == -1 && errno == EINTR);
542 checkUnixError(found, "waitpid");
543 DCHECK_EQ(found, pid_);
544 returnCode_ = ProcessReturnCode(status);
549 void Subprocess::waitChecked() {
551 checkStatus(returnCode_);
554 void Subprocess::sendSignal(int signal) {
555 returnCode_.enforce(ProcessReturnCode::RUNNING);
556 int r = ::kill(pid_, signal);
557 checkUnixError(r, "kill");
560 pid_t Subprocess::pid() const {
566 std::pair<const uint8_t*, size_t> queueFront(const IOBufQueue& queue) {
567 auto* p = queue.front();
568 if (!p) return std::make_pair(nullptr, 0);
569 return io::Cursor(p).peek();
573 bool handleWrite(int fd, IOBufQueue& queue) {
575 auto p = queueFront(queue);
580 ssize_t n = writeNoInt(fd, p.first, p.second);
581 if (n == -1 && errno == EAGAIN) {
584 checkUnixError(n, "write");
590 bool handleRead(int fd, IOBufQueue& queue) {
592 auto p = queue.preallocate(100, 65000);
593 ssize_t n = readNoInt(fd, p.first, p.second);
594 if (n == -1 && errno == EAGAIN) {
597 checkUnixError(n, "read");
601 queue.postallocate(n);
605 bool discardRead(int fd) {
606 static const size_t bufSize = 65000;
607 // Thread unsafe, but it doesn't matter.
608 static std::unique_ptr<char[]> buf(new char[bufSize]);
611 ssize_t n = readNoInt(fd, buf.get(), bufSize);
612 if (n == -1 && errno == EAGAIN) {
615 checkUnixError(n, "read");
624 std::pair<std::string, std::string> Subprocess::communicate(
626 IOBufQueue inputQueue;
627 inputQueue.wrapBuffer(input.data(), input.size());
629 auto outQueues = communicateIOBuf(std::move(inputQueue));
630 auto outBufs = std::make_pair(outQueues.first.move(),
631 outQueues.second.move());
632 std::pair<std::string, std::string> out;
634 outBufs.first->coalesce();
635 out.first.assign(reinterpret_cast<const char*>(outBufs.first->data()),
636 outBufs.first->length());
638 if (outBufs.second) {
639 outBufs.second->coalesce();
640 out.second.assign(reinterpret_cast<const char*>(outBufs.second->data()),
641 outBufs.second->length());
646 std::pair<IOBufQueue, IOBufQueue> Subprocess::communicateIOBuf(
648 // If the user supplied a non-empty input buffer, make sure
649 // that stdin is a pipe so we can write the data.
650 if (!input.empty()) {
651 // findByChildFd() will throw std::invalid_argument if no pipe for
652 // STDIN_FILENO exists
653 findByChildFd(STDIN_FILENO);
656 std::pair<IOBufQueue, IOBufQueue> out;
658 auto readCallback = [&] (int pfd, int cfd) -> bool {
659 if (cfd == STDOUT_FILENO) {
660 return handleRead(pfd, out.first);
661 } else if (cfd == STDERR_FILENO) {
662 return handleRead(pfd, out.second);
664 // Don't close the file descriptor, the child might not like SIGPIPE,
665 // just read and throw the data away.
666 return discardRead(pfd);
670 auto writeCallback = [&] (int pfd, int cfd) -> bool {
671 if (cfd == STDIN_FILENO) {
672 return handleWrite(pfd, input);
674 // If we don't want to write to this fd, just close it.
679 communicate(std::move(readCallback), std::move(writeCallback));
684 void Subprocess::communicate(FdCallback readCallback,
685 FdCallback writeCallback) {
686 returnCode_.enforce(ProcessReturnCode::RUNNING);
689 std::vector<pollfd> fds;
690 fds.reserve(pipes_.size());
691 std::vector<int> toClose;
692 toClose.reserve(pipes_.size());
694 while (!pipes_.empty()) {
698 for (auto& p : pipes_) {
701 // Yes, backwards, PIPE_IN / PIPE_OUT are defined from the
702 // child's point of view.
704 // Still keeping fd in watched set so we get notified of POLLHUP /
707 } else if (p.direction == PIPE_IN) {
708 pfd.events = POLLOUT;
717 r = ::poll(fds.data(), fds.size(), -1);
718 } while (r == -1 && errno == EINTR);
719 checkUnixError(r, "poll");
721 for (int i = 0; i < pipes_.size(); ++i) {
723 DCHECK_EQ(fds[i].fd, p.parentFd);
724 short events = fds[i].revents;
727 if (events & POLLOUT) {
728 DCHECK(!(events & POLLIN));
729 if (writeCallback(p.parentFd, p.childFd)) {
730 toClose.push_back(i);
735 // Call read callback on POLLHUP, to give it a chance to read (and act
737 if (events & (POLLIN | POLLHUP)) {
738 DCHECK(!(events & POLLOUT));
739 if (readCallback(p.parentFd, p.childFd)) {
740 toClose.push_back(i);
745 if ((events & (POLLHUP | POLLERR)) && !closed) {
746 toClose.push_back(i);
751 // Close the fds in reverse order so the indexes hold after erase()
752 for (int idx : boost::adaptors::reverse(toClose)) {
753 auto pos = pipes_.begin() + idx;
754 closeChecked(pos->parentFd);
760 void Subprocess::enableNotifications(int childFd, bool enabled) {
761 pipes_[findByChildFd(childFd)].enabled = enabled;
764 bool Subprocess::notificationsEnabled(int childFd) const {
765 return pipes_[findByChildFd(childFd)].enabled;
768 int Subprocess::findByChildFd(int childFd) const {
769 auto pos = std::lower_bound(
770 pipes_.begin(), pipes_.end(), childFd,
771 [] (const PipeInfo& info, int fd) { return info.childFd < fd; });
772 if (pos == pipes_.end() || pos->childFd != childFd) {
773 throw std::invalid_argument(folly::to<std::string>(
774 "child fd not found ", childFd));
776 return pos - pipes_.begin();
779 void Subprocess::closeParentFd(int childFd) {
780 int idx = findByChildFd(childFd);
781 closeChecked(pipes_[idx].parentFd);
782 pipes_.erase(pipes_.begin() + idx);
790 // We like EPIPE, thanks.
791 ::signal(SIGPIPE, SIG_IGN);
795 Initializer initializer;