2 * Copyright 2013 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>("Invalid state ", s,
62 " expected ", expected));
66 int ProcessReturnCode::exitStatus() const {
68 return WEXITSTATUS(rawStatus_);
71 int ProcessReturnCode::killSignal() const {
73 return WTERMSIG(rawStatus_);
76 bool ProcessReturnCode::coreDumped() const {
78 return WCOREDUMP(rawStatus_);
81 std::string ProcessReturnCode::str() const {
88 return to<std::string>("exited with status ", exitStatus());
90 return to<std::string>("killed by signal ", killSignal(),
91 (coreDumped() ? " (core dumped)" : ""));
93 CHECK(false); // unreached
96 CalledProcessError::CalledProcessError(ProcessReturnCode rc)
98 what_(returnCode_.str()) {
101 SubprocessSpawnError::SubprocessSpawnError(const char* executable,
104 : errnoValue_(errnoValue),
105 what_(to<std::string>(errCode == kExecFailure ?
106 "failed to execute " :
107 "error preparing to execute ",
108 executable, ": ", errnoStr(errnoValue))) {
113 // Copy pointers to the given strings in a format suitable for posix_spawn
114 std::unique_ptr<const char*[]> cloneStrings(const std::vector<std::string>& s) {
115 std::unique_ptr<const char*[]> d(new const char*[s.size() + 1]);
116 for (int i = 0; i < s.size(); i++) {
119 d[s.size()] = nullptr;
123 // Check a wait() status, throw on non-successful
124 void checkStatus(ProcessReturnCode returnCode) {
125 if (returnCode.state() != ProcessReturnCode::EXITED ||
126 returnCode.exitStatus() != 0) {
127 throw CalledProcessError(returnCode);
133 Subprocess::Options& Subprocess::Options::fd(int fd, int action) {
134 if (action == Subprocess::PIPE) {
136 action = Subprocess::PIPE_IN;
137 } else if (fd == 1 || fd == 2) {
138 action = Subprocess::PIPE_OUT;
140 throw std::invalid_argument(
141 to<std::string>("Only fds 0, 1, 2 are valid for action=PIPE: ", fd));
144 fdActions_[fd] = action;
148 Subprocess::Subprocess(
149 const std::vector<std::string>& argv,
150 const Options& options,
151 const char* executable,
152 const std::vector<std::string>* env)
154 returnCode_(RV_NOT_STARTED) {
156 throw std::invalid_argument("argv must not be empty");
158 if (!executable) executable = argv[0].c_str();
159 spawn(cloneStrings(argv), executable, options, env);
162 Subprocess::Subprocess(
163 const std::string& cmd,
164 const Options& options,
165 const std::vector<std::string>* env)
167 returnCode_(RV_NOT_STARTED) {
168 if (options.usePath_) {
169 throw std::invalid_argument("usePath() not allowed when running in shell");
171 const char* shell = getenv("SHELL");
176 std::unique_ptr<const char*[]> argv(new const char*[4]);
179 argv[2] = cmd.c_str();
181 spawn(std::move(argv), shell, options, env);
184 Subprocess::~Subprocess() {
185 CHECK_NE(returnCode_.state(), ProcessReturnCode::RUNNING)
186 << "Subprocess destroyed without reaping child";
191 void closeChecked(int fd) {
192 checkUnixError(::close(fd), "close");
195 struct ChildErrorInfo {
200 void childError(int errFd, int errCode, int errnoValue) FOLLY_NORETURN;
201 void childError(int errFd, int errCode, int errnoValue) {
202 ChildErrorInfo info = {errCode, errnoValue};
203 // Write the error information over the pipe to our parent process.
204 // We can't really do anything else if this write call fails.
205 writeNoInt(errFd, &info, sizeof(info));
212 void Subprocess::closeAll() {
213 for (auto& p : pipes_) {
214 closeChecked(p.parentFd);
219 void Subprocess::setAllNonBlocking() {
220 for (auto& p : pipes_) {
222 int flags = ::fcntl(fd, F_GETFL);
223 checkUnixError(flags, "fcntl");
224 int r = ::fcntl(fd, F_SETFL, flags | O_NONBLOCK);
225 checkUnixError(r, "fcntl");
229 void Subprocess::spawn(
230 std::unique_ptr<const char*[]> argv,
231 const char* executable,
232 const Options& optionsIn,
233 const std::vector<std::string>* env) {
234 if (optionsIn.usePath_ && env) {
235 throw std::invalid_argument(
236 "usePath() not allowed when overriding environment");
239 // Make a copy, we'll mutate options
240 Options options(optionsIn);
242 // On error, close all of the pipes_
243 auto pipesGuard = makeGuard([&] {
244 for (auto& p : this->pipes_) {
245 CHECK_ERR(::close(p.parentFd));
249 // Create a pipe to use to receive error information from the child,
250 // in case it fails before calling exec()
252 int r = ::pipe(errFds);
253 checkUnixError(r, "pipe");
255 CHECK_ERR(::close(errFds[0]));
256 if (errFds[1] >= 0) {
257 CHECK_ERR(::close(errFds[1]));
260 // Ask the child to close the read end of the error pipe.
261 options.fdActions_[errFds[0]] = CLOSE;
262 // Set the close-on-exec flag on the write side of the pipe.
263 // This way the pipe will be closed automatically in the child if execve()
264 // succeeds. If the exec fails the child can write error information to the
266 r = fcntl(errFds[1], F_SETFD, FD_CLOEXEC);
267 checkUnixError(r, "set FD_CLOEXEC");
269 // Perform the actual work of setting up pipes then forking and
270 // executing the child.
271 spawnInternal(std::move(argv), executable, options, env, errFds[1]);
273 // After spawnInternal() returns the child is alive. We have to be very
274 // careful about throwing after this point. We are inside the constructor,
275 // so if we throw the Subprocess object will have never existed, and the
276 // destructor will never be called.
278 // We should only throw if we got an error via the errFd, and we know the
279 // child has exited and can be immediately waited for. In all other cases,
280 // we have no way of cleaning up the child.
282 // Close writable side of the errFd pipe in the parent process
283 CHECK_ERR(::close(errFds[1]));
286 // Read from the errFd pipe, to tell if the child ran into any errors before
288 readChildErrorPipe(errFds[0], executable);
290 // We have fully succeeded now, so release the guard on pipes_
291 pipesGuard.dismiss();
294 void Subprocess::spawnInternal(
295 std::unique_ptr<const char*[]> argv,
296 const char* executable,
298 const std::vector<std::string>* env,
300 // Parent work, pre-fork: create pipes
301 std::vector<int> childFds;
302 // Close all of the childFds as we leave this scope
304 // These are only pipes, closing them shouldn't fail
305 for (int cfd : childFds) {
306 CHECK_ERR(::close(cfd));
311 for (auto& p : options.fdActions_) {
312 if (p.second == PIPE_IN || p.second == PIPE_OUT) {
315 checkUnixError(r, "pipe");
317 pinfo.direction = p.second;
319 if (p.second == PIPE_IN) {
320 // Child gets reading end
321 pinfo.parentFd = fds[1];
324 pinfo.parentFd = fds[0];
327 p.second = cfd; // ensure it gets dup2()ed
328 pinfo.childFd = p.first;
329 childFds.push_back(cfd);
330 pipes_.push_back(pinfo);
334 // This should already be sorted, as options.fdActions_ is
335 DCHECK(std::is_sorted(pipes_.begin(), pipes_.end()));
337 // Note that the const casts below are legit, per
338 // http://pubs.opengroup.org/onlinepubs/009695399/functions/exec.html
340 char** argVec = const_cast<char**>(argv.get());
342 // Set up environment
343 std::unique_ptr<const char*[]> envHolder;
346 envHolder = cloneStrings(*env);
347 envVec = const_cast<char**>(envHolder.get());
352 // Block all signals around vfork; see http://ewontfix.com/7/.
354 // As the child may run in the same address space as the parent until
355 // the actual execve() system call, any (custom) signal handlers that
356 // the parent has might alter parent's memory if invoked in the child,
357 // with undefined results. So we block all signals in the parent before
358 // vfork(), which will cause them to be blocked in the child as well (we
359 // rely on the fact that Linux, just like all sane implementations, only
360 // clones the calling thread). Then, in the child, we reset all signals
361 // to their default dispositions (while still blocked), and unblock them
362 // (so the exec()ed process inherits the parent's signal mask)
364 // The parent also unblocks all signals as soon as vfork() returns.
366 r = sigfillset(&allBlocked);
367 checkUnixError(r, "sigfillset");
370 r = pthread_sigmask(SIG_SETMASK, &allBlocked, &oldSignals);
371 checkPosixError(r, "pthread_sigmask");
373 // Restore signal mask
374 r = pthread_sigmask(SIG_SETMASK, &oldSignals, nullptr);
375 CHECK_EQ(r, 0) << "pthread_sigmask: " << errnoStr(r); // shouldn't fail
380 int errnoValue = prepareChild(options, &oldSignals);
381 if (errnoValue != 0) {
382 childError(errFd, kChildFailure, errnoValue);
385 errnoValue = runChild(executable, argVec, envVec, options);
386 // If we get here, exec() failed.
387 childError(errFd, kExecFailure, errnoValue);
389 // In parent. Make sure vfork() succeeded.
390 checkUnixError(pid, errno, "vfork");
392 // Child is alive. We have to be very careful about throwing after this
393 // point. We are inside the constructor, so if we throw the Subprocess
394 // object will have never existed, and the destructor will never be called.
396 // We should only throw if we got an error via the errFd, and we know the
397 // child has exited and can be immediately waited for. In all other cases,
398 // we have no way of cleaning up the child.
400 returnCode_ = ProcessReturnCode(RV_RUNNING);
403 int Subprocess::prepareChild(const Options& options,
404 const sigset_t* sigmask) const {
405 // While all signals are blocked, we must reset their
406 // dispositions to default.
407 for (int sig = 1; sig < NSIG; ++sig) {
408 ::signal(sig, SIG_DFL);
410 // Unblock signals; restore signal mask.
411 int r = pthread_sigmask(SIG_SETMASK, sigmask, nullptr);
413 return r; // pthread_sigmask() returns an errno value
416 // Close parent's ends of all pipes
417 for (auto& p : pipes_) {
418 r = ::close(p.parentFd);
424 // Close all fds that we're supposed to close.
425 // Note that we're ignoring errors here, in case some of these
426 // fds were set to close on exec.
427 for (auto& p : options.fdActions_) {
428 if (p.second == CLOSE) {
431 r = ::dup2(p.second, p.first);
438 // If requested, close all other file descriptors. Don't close
439 // any fds in options.fdActions_, and don't touch stdin, stdout, stderr.
441 if (options.closeOtherFds_) {
442 for (int fd = getdtablesize() - 1; fd >= 3; --fd) {
443 if (options.fdActions_.count(fd) == 0) {
450 // Opt to receive signal on parent death, if requested
451 if (options.parentDeathSignal_ != 0) {
452 r = prctl(PR_SET_PDEATHSIG, options.parentDeathSignal_, 0, 0, 0);
462 int Subprocess::runChild(const char* executable,
463 char** argv, char** env,
464 const Options& options) const {
465 // Now, finally, exec.
467 if (options.usePath_) {
468 ::execvp(executable, argv);
470 ::execve(executable, argv, env);
475 void Subprocess::readChildErrorPipe(int pfd, const char* executable) {
477 auto rc = readNoInt(pfd, &info, sizeof(info));
479 // No data means the child executed successfully, and the pipe
480 // was closed due to the close-on-exec flag being set.
482 } else if (rc != sizeof(ChildErrorInfo)) {
483 // An error occurred trying to read from the pipe, or we got a partial read.
484 // Neither of these cases should really occur in practice.
486 // We can't get any error data from the child in this case, and we don't
487 // know if it is successfully running or not. All we can do is to return
488 // normally, as if the child executed successfully. If something bad
489 // happened the caller should at least get a non-normal exit status from
491 LOG(ERROR) << "unexpected error trying to read from child error pipe " <<
492 "rc=" << rc << ", errno=" << errno;
496 // We got error data from the child. The child should exit immediately in
497 // this case, so wait on it to clean up.
500 // Throw to signal the error
501 throw SubprocessSpawnError(executable, info.errCode, info.errnoValue);
504 ProcessReturnCode Subprocess::poll() {
505 returnCode_.enforce(ProcessReturnCode::RUNNING);
508 pid_t found = ::waitpid(pid_, &status, WNOHANG);
509 checkUnixError(found, "waitpid");
511 returnCode_ = ProcessReturnCode(status);
517 bool Subprocess::pollChecked() {
518 if (poll().state() == ProcessReturnCode::RUNNING) {
521 checkStatus(returnCode_);
525 ProcessReturnCode Subprocess::wait() {
526 returnCode_.enforce(ProcessReturnCode::RUNNING);
531 found = ::waitpid(pid_, &status, 0);
532 } while (found == -1 && errno == EINTR);
533 checkUnixError(found, "waitpid");
534 DCHECK_EQ(found, pid_);
535 returnCode_ = ProcessReturnCode(status);
540 void Subprocess::waitChecked() {
542 checkStatus(returnCode_);
545 void Subprocess::sendSignal(int signal) {
546 returnCode_.enforce(ProcessReturnCode::RUNNING);
547 int r = ::kill(pid_, signal);
548 checkUnixError(r, "kill");
551 pid_t Subprocess::pid() const {
557 std::pair<const uint8_t*, size_t> queueFront(const IOBufQueue& queue) {
558 auto* p = queue.front();
559 if (!p) return std::make_pair(nullptr, 0);
560 return io::Cursor(p).peek();
564 bool handleWrite(int fd, IOBufQueue& queue) {
566 auto p = queueFront(queue);
573 n = ::write(fd, p.first, p.second);
574 } while (n == -1 && errno == EINTR);
575 if (n == -1 && errno == EAGAIN) {
578 checkUnixError(n, "write");
584 bool handleRead(int fd, IOBufQueue& queue) {
586 auto p = queue.preallocate(100, 65000);
589 n = ::read(fd, p.first, p.second);
590 } while (n == -1 && errno == EINTR);
591 if (n == -1 && errno == EAGAIN) {
594 checkUnixError(n, "read");
598 queue.postallocate(n);
602 bool discardRead(int fd) {
603 static const size_t bufSize = 65000;
604 // Thread unsafe, but it doesn't matter.
605 static std::unique_ptr<char[]> buf(new char[bufSize]);
610 n = ::read(fd, buf.get(), bufSize);
611 } while (n == -1 && errno == EINTR);
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.
703 pfd.events = (p.direction == PIPE_IN ? POLLOUT : POLLIN);
709 r = ::poll(fds.data(), fds.size(), -1);
710 } while (r == -1 && errno == EINTR);
711 checkUnixError(r, "poll");
713 for (int i = 0; i < pipes_.size(); ++i) {
715 DCHECK_EQ(fds[i].fd, p.parentFd);
716 short events = fds[i].revents;
719 if (events & POLLOUT) {
720 DCHECK(!(events & POLLIN));
721 if (writeCallback(p.parentFd, p.childFd)) {
722 toClose.push_back(i);
727 if (events & POLLIN) {
728 DCHECK(!(events & POLLOUT));
729 if (readCallback(p.parentFd, p.childFd)) {
730 toClose.push_back(i);
735 if ((events & (POLLHUP | POLLERR)) && !closed) {
736 toClose.push_back(i);
741 // Close the fds in reverse order so the indexes hold after erase()
742 for (int idx : boost::adaptors::reverse(toClose)) {
743 auto pos = pipes_.begin() + idx;
744 closeChecked(pos->parentFd);
750 int Subprocess::findByChildFd(int childFd) const {
751 auto pos = std::lower_bound(
752 pipes_.begin(), pipes_.end(), childFd,
753 [] (const PipeInfo& info, int fd) { return info.childFd < fd; });
754 if (pos == pipes_.end() || pos->childFd != childFd) {
755 throw std::invalid_argument(folly::to<std::string>(
756 "child fd not found ", childFd));
758 return pos - pipes_.begin();
761 void Subprocess::closeParentFd(int childFd) {
762 int idx = findByChildFd(childFd);
763 closeChecked(pipes_[idx].parentFd);
764 pipes_.erase(pipes_.begin() + idx);
772 // We like EPIPE, thanks.
773 ::signal(SIGPIPE, SIG_IGN);
777 Initializer initializer;