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"
19 #include <sys/prctl.h>
27 #include <system_error>
29 #include <boost/container/flat_set.hpp>
30 #include <boost/range/adaptors.hpp>
32 #include <glog/logging.h>
34 #include "folly/Conv.h"
35 #include "folly/Exception.h"
36 #include "folly/FileUtil.h"
37 #include "folly/ScopeGuard.h"
38 #include "folly/String.h"
39 #include "folly/io/Cursor.h"
41 extern char** environ;
43 constexpr int kExecFailure = 127;
44 constexpr int kChildFailure = 126;
48 ProcessReturnCode::State ProcessReturnCode::state() const {
49 if (rawStatus_ == RV_NOT_STARTED) return NOT_STARTED;
50 if (rawStatus_ == RV_RUNNING) return RUNNING;
51 if (WIFEXITED(rawStatus_)) return EXITED;
52 if (WIFSIGNALED(rawStatus_)) return KILLED;
53 throw std::runtime_error(to<std::string>(
54 "Invalid ProcessReturnCode: ", rawStatus_));
57 void ProcessReturnCode::enforce(State s) const {
59 throw std::logic_error(to<std::string>("Invalid state ", s));
63 int ProcessReturnCode::exitStatus() const {
65 return WEXITSTATUS(rawStatus_);
68 int ProcessReturnCode::killSignal() const {
70 return WTERMSIG(rawStatus_);
73 bool ProcessReturnCode::coreDumped() const {
75 return WCOREDUMP(rawStatus_);
78 std::string ProcessReturnCode::str() const {
85 return to<std::string>("exited with status ", exitStatus());
87 return to<std::string>("killed by signal ", killSignal(),
88 (coreDumped() ? " (core dumped)" : ""));
90 CHECK(false); // unreached
93 CalledProcessError::CalledProcessError(ProcessReturnCode rc)
95 what_(returnCode_.str()) {
98 SubprocessSpawnError::SubprocessSpawnError(const char* executable,
101 : errnoValue_(errnoValue),
102 what_(to<std::string>(errCode == kExecFailure ?
103 "failed to execute " :
104 "error preparing to execute ",
105 executable, ": ", errnoStr(errnoValue))) {
110 // Copy pointers to the given strings in a format suitable for posix_spawn
111 std::unique_ptr<const char*[]> cloneStrings(const std::vector<std::string>& s) {
112 std::unique_ptr<const char*[]> d(new const char*[s.size() + 1]);
113 for (int i = 0; i < s.size(); i++) {
116 d[s.size()] = nullptr;
120 // Check a wait() status, throw on non-successful
121 void checkStatus(ProcessReturnCode returnCode) {
122 if (returnCode.state() != ProcessReturnCode::EXITED ||
123 returnCode.exitStatus() != 0) {
124 throw CalledProcessError(returnCode);
130 Subprocess::Options& Subprocess::Options::fd(int fd, int action) {
131 if (action == Subprocess::PIPE) {
133 action = Subprocess::PIPE_IN;
134 } else if (fd == 1 || fd == 2) {
135 action = Subprocess::PIPE_OUT;
137 throw std::invalid_argument(
138 to<std::string>("Only fds 0, 1, 2 are valid for action=PIPE: ", fd));
141 fdActions_[fd] = action;
145 Subprocess::Subprocess(
146 const std::vector<std::string>& argv,
147 const Options& options,
148 const char* executable,
149 const std::vector<std::string>* env)
151 returnCode_(RV_NOT_STARTED) {
153 throw std::invalid_argument("argv must not be empty");
155 if (!executable) executable = argv[0].c_str();
156 spawn(cloneStrings(argv), executable, options, env);
159 Subprocess::Subprocess(
160 const std::string& cmd,
161 const Options& options,
162 const std::vector<std::string>* env)
164 returnCode_(RV_NOT_STARTED) {
165 if (options.usePath_) {
166 throw std::invalid_argument("usePath() not allowed when running in shell");
168 const char* shell = getenv("SHELL");
173 std::unique_ptr<const char*[]> argv(new const char*[4]);
176 argv[2] = cmd.c_str();
178 spawn(std::move(argv), shell, options, env);
181 Subprocess::~Subprocess() {
182 CHECK_NE(returnCode_.state(), ProcessReturnCode::RUNNING)
183 << "Subprocess destroyed without reaping child";
188 void closeChecked(int fd) {
189 checkUnixError(::close(fd), "close");
192 struct ChildErrorInfo {
197 void childError(int errFd, int errCode, int errnoValue) FOLLY_NORETURN;
198 void childError(int errFd, int errCode, int errnoValue) {
199 ChildErrorInfo info = {errCode, errnoValue};
200 // Write the error information over the pipe to our parent process.
201 // We can't really do anything else if this write call fails.
202 writeNoInt(errFd, &info, sizeof(info));
209 void Subprocess::closeAll() {
210 for (auto& p : pipes_) {
211 closeChecked(p.parentFd);
216 void Subprocess::setAllNonBlocking() {
217 for (auto& p : pipes_) {
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 of the pipes_
240 auto pipesGuard = makeGuard([&] {
241 for (auto& p : this->pipes_) {
242 CHECK_ERR(::close(p.parentFd));
246 // Create a pipe to use to receive error information from the child,
247 // in case it fails before calling exec()
249 int r = ::pipe(errFds);
250 checkUnixError(r, "pipe");
252 CHECK_ERR(::close(errFds[0]));
253 if (errFds[1] >= 0) {
254 CHECK_ERR(::close(errFds[1]));
257 // Ask the child to close the read end of the error pipe.
258 options.fdActions_[errFds[0]] = CLOSE;
259 // Set the close-on-exec flag on the write side of the pipe.
260 // This way the pipe will be closed automatically in the child if execve()
261 // succeeds. If the exec fails the child can write error information to the
263 r = fcntl(errFds[1], F_SETFD, FD_CLOEXEC);
264 checkUnixError(r, "set FD_CLOEXEC");
266 // Perform the actual work of setting up pipes then forking and
267 // executing the child.
268 spawnInternal(std::move(argv), executable, options, env, errFds[1]);
270 // After spawnInternal() returns the child is alive. We have to be very
271 // careful about throwing after this point. We are inside the constructor,
272 // so if we throw the Subprocess object will have never existed, and the
273 // destructor will never be called.
275 // We should only throw if we got an error via the errFd, and we know the
276 // child has exited and can be immediately waited for. In all other cases,
277 // we have no way of cleaning up the child.
279 // Close writable side of the errFd pipe in the parent process
280 CHECK_ERR(::close(errFds[1]));
283 // Read from the errFd pipe, to tell if the child ran into any errors before
285 readChildErrorPipe(errFds[0], executable);
287 // We have fully succeeded now, so release the guard on pipes_
288 pipesGuard.dismiss();
291 void Subprocess::spawnInternal(
292 std::unique_ptr<const char*[]> argv,
293 const char* executable,
295 const std::vector<std::string>* env,
297 // Parent work, pre-fork: create pipes
298 std::vector<int> childFds;
299 // Close all of the childFds as we leave this scope
301 // These are only pipes, closing them shouldn't fail
302 for (int cfd : childFds) {
303 CHECK_ERR(::close(cfd));
308 for (auto& p : options.fdActions_) {
309 if (p.second == PIPE_IN || p.second == PIPE_OUT) {
312 checkUnixError(r, "pipe");
314 pinfo.direction = p.second;
316 if (p.second == PIPE_IN) {
317 // Child gets reading end
318 pinfo.parentFd = fds[1];
321 pinfo.parentFd = fds[0];
324 p.second = cfd; // ensure it gets dup2()ed
325 pinfo.childFd = p.first;
326 childFds.push_back(cfd);
327 pipes_.push_back(pinfo);
331 // This should already be sorted, as options.fdActions_ is
332 DCHECK(std::is_sorted(pipes_.begin(), pipes_.end()));
334 // Note that the const casts below are legit, per
335 // http://pubs.opengroup.org/onlinepubs/009695399/functions/exec.html
337 char** argVec = const_cast<char**>(argv.get());
339 // Set up environment
340 std::unique_ptr<const char*[]> envHolder;
343 envHolder = cloneStrings(*env);
344 envVec = const_cast<char**>(envHolder.get());
349 // Block all signals around vfork; see http://ewontfix.com/7/.
351 // As the child may run in the same address space as the parent until
352 // the actual execve() system call, any (custom) signal handlers that
353 // the parent has might alter parent's memory if invoked in the child,
354 // with undefined results. So we block all signals in the parent before
355 // vfork(), which will cause them to be blocked in the child as well (we
356 // rely on the fact that Linux, just like all sane implementations, only
357 // clones the calling thread). Then, in the child, we reset all signals
358 // to their default dispositions (while still blocked), and unblock them
359 // (so the exec()ed process inherits the parent's signal mask)
361 // The parent also unblocks all signals as soon as vfork() returns.
363 r = ::sigfillset(&allBlocked);
364 checkUnixError(r, "sigfillset");
367 r = pthread_sigmask(SIG_SETMASK, &allBlocked, &oldSignals);
368 checkPosixError(r, "pthread_sigmask");
370 // Restore signal mask
371 r = pthread_sigmask(SIG_SETMASK, &oldSignals, nullptr);
372 CHECK_EQ(r, 0) << "pthread_sigmask: " << errnoStr(r); // shouldn't fail
377 int errnoValue = prepareChild(options, &oldSignals);
378 if (errnoValue != 0) {
379 childError(errFd, kChildFailure, errnoValue);
382 errnoValue = runChild(executable, argVec, envVec, options);
383 // If we get here, exec() failed.
384 childError(errFd, kExecFailure, errnoValue);
386 // In parent. Make sure vfork() succeeded.
387 checkUnixError(pid, errno, "vfork");
389 // Child is alive. We have to be very careful about throwing after this
390 // point. We are inside the constructor, so if we throw the Subprocess
391 // object will have never existed, and the destructor will never be called.
393 // We should only throw if we got an error via the errFd, and we know the
394 // child has exited and can be immediately waited for. In all other cases,
395 // we have no way of cleaning up the child.
397 returnCode_ = ProcessReturnCode(RV_RUNNING);
400 int Subprocess::prepareChild(const Options& options,
401 const sigset_t* sigmask) const {
402 // While all signals are blocked, we must reset their
403 // dispositions to default.
404 for (int sig = 1; sig < NSIG; ++sig) {
405 ::signal(sig, SIG_DFL);
407 // Unblock signals; restore signal mask.
408 int r = pthread_sigmask(SIG_SETMASK, sigmask, nullptr);
410 return r; // pthread_sigmask() returns an errno value
413 // Close parent's ends of all pipes
414 for (auto& p : pipes_) {
415 r = ::close(p.parentFd);
421 // Close all fds that we're supposed to close.
422 // Note that we're ignoring errors here, in case some of these
423 // fds were set to close on exec.
424 for (auto& p : options.fdActions_) {
425 if (p.second == CLOSE) {
428 r = ::dup2(p.second, p.first);
435 // If requested, close all other file descriptors. Don't close
436 // any fds in options.fdActions_, and don't touch stdin, stdout, stderr.
438 if (options.closeOtherFds_) {
439 for (int fd = getdtablesize() - 1; fd >= 3; --fd) {
440 if (options.fdActions_.count(fd) == 0) {
446 // Opt to receive signal on parent death, if requested
447 if (options.parentDeathSignal_ != 0) {
448 r = prctl(PR_SET_PDEATHSIG, options.parentDeathSignal_, 0, 0, 0);
457 int Subprocess::runChild(const char* executable,
458 char** argv, char** env,
459 const Options& options) const {
460 // Now, finally, exec.
462 if (options.usePath_) {
463 ::execvp(executable, argv);
465 ::execve(executable, argv, env);
470 void Subprocess::readChildErrorPipe(int pfd, const char* executable) {
472 auto rc = readNoInt(pfd, &info, sizeof(info));
474 // No data means the child executed successfully, and the pipe
475 // was closed due to the close-on-exec flag being set.
477 } else if (rc != sizeof(ChildErrorInfo)) {
478 // An error occurred trying to read from the pipe, or we got a partial read.
479 // Neither of these cases should really occur in practice.
481 // We can't get any error data from the child in this case, and we don't
482 // know if it is successfully running or not. All we can do is to return
483 // normally, as if the child executed successfully. If something bad
484 // happened the caller should at least get a non-normal exit status from
486 LOG(ERROR) << "unexpected error trying to read from child error pipe " <<
487 "rc=" << rc << ", errno=" << errno;
491 // We got error data from the child. The child should exit immediately in
492 // this case, so wait on it to clean up.
495 // Throw to signal the error
496 throw SubprocessSpawnError(executable, info.errCode, info.errnoValue);
499 ProcessReturnCode Subprocess::poll() {
500 returnCode_.enforce(ProcessReturnCode::RUNNING);
503 pid_t found = ::waitpid(pid_, &status, WNOHANG);
504 checkUnixError(found, "waitpid");
506 returnCode_ = ProcessReturnCode(status);
512 bool Subprocess::pollChecked() {
513 if (poll().state() == ProcessReturnCode::RUNNING) {
516 checkStatus(returnCode_);
520 ProcessReturnCode Subprocess::wait() {
521 returnCode_.enforce(ProcessReturnCode::RUNNING);
526 found = ::waitpid(pid_, &status, 0);
527 } while (found == -1 && errno == EINTR);
528 checkUnixError(found, "waitpid");
529 DCHECK_EQ(found, pid_);
530 returnCode_ = ProcessReturnCode(status);
535 void Subprocess::waitChecked() {
537 checkStatus(returnCode_);
540 void Subprocess::sendSignal(int signal) {
541 returnCode_.enforce(ProcessReturnCode::RUNNING);
542 int r = ::kill(pid_, signal);
543 checkUnixError(r, "kill");
546 pid_t Subprocess::pid() const {
552 std::pair<const uint8_t*, size_t> queueFront(const IOBufQueue& queue) {
553 auto* p = queue.front();
554 if (!p) return std::make_pair(nullptr, 0);
555 return io::Cursor(p).peek();
559 bool handleWrite(int fd, IOBufQueue& queue) {
561 auto p = queueFront(queue);
568 n = ::write(fd, p.first, p.second);
569 } while (n == -1 && errno == EINTR);
570 if (n == -1 && errno == EAGAIN) {
573 checkUnixError(n, "write");
579 bool handleRead(int fd, IOBufQueue& queue) {
581 auto p = queue.preallocate(100, 65000);
584 n = ::read(fd, p.first, p.second);
585 } while (n == -1 && errno == EINTR);
586 if (n == -1 && errno == EAGAIN) {
589 checkUnixError(n, "read");
593 queue.postallocate(n);
597 bool discardRead(int fd) {
598 static const size_t bufSize = 65000;
599 // Thread unsafe, but it doesn't matter.
600 static std::unique_ptr<char[]> buf(new char[bufSize]);
605 n = ::read(fd, buf.get(), bufSize);
606 } while (n == -1 && errno == EINTR);
607 if (n == -1 && errno == EAGAIN) {
610 checkUnixError(n, "read");
619 std::pair<std::string, std::string> Subprocess::communicate(
621 IOBufQueue inputQueue;
622 inputQueue.wrapBuffer(input.data(), input.size());
624 auto outQueues = communicateIOBuf(std::move(inputQueue));
625 auto outBufs = std::make_pair(outQueues.first.move(),
626 outQueues.second.move());
627 std::pair<std::string, std::string> out;
629 outBufs.first->coalesce();
630 out.first.assign(reinterpret_cast<const char*>(outBufs.first->data()),
631 outBufs.first->length());
633 if (outBufs.second) {
634 outBufs.second->coalesce();
635 out.second.assign(reinterpret_cast<const char*>(outBufs.second->data()),
636 outBufs.second->length());
641 std::pair<IOBufQueue, IOBufQueue> Subprocess::communicateIOBuf(
643 // If the user supplied a non-empty input buffer, make sure
644 // that stdin is a pipe so we can write the data.
645 if (!input.empty()) {
646 // findByChildFd() will throw std::invalid_argument if no pipe for
647 // STDIN_FILENO exists
648 findByChildFd(STDIN_FILENO);
651 std::pair<IOBufQueue, IOBufQueue> out;
653 auto readCallback = [&] (int pfd, int cfd) -> bool {
654 if (cfd == STDOUT_FILENO) {
655 return handleRead(pfd, out.first);
656 } else if (cfd == STDERR_FILENO) {
657 return handleRead(pfd, out.second);
659 // Don't close the file descriptor, the child might not like SIGPIPE,
660 // just read and throw the data away.
661 return discardRead(pfd);
665 auto writeCallback = [&] (int pfd, int cfd) -> bool {
666 if (cfd == STDIN_FILENO) {
667 return handleWrite(pfd, input);
669 // If we don't want to write to this fd, just close it.
674 communicate(std::move(readCallback), std::move(writeCallback));
679 void Subprocess::communicate(FdCallback readCallback,
680 FdCallback writeCallback) {
681 returnCode_.enforce(ProcessReturnCode::RUNNING);
684 std::vector<pollfd> fds;
685 fds.reserve(pipes_.size());
686 std::vector<int> toClose;
687 toClose.reserve(pipes_.size());
689 while (!pipes_.empty()) {
693 for (auto& p : pipes_) {
696 // Yes, backwards, PIPE_IN / PIPE_OUT are defined from the
697 // child's point of view.
698 pfd.events = (p.direction == PIPE_IN ? POLLOUT : POLLIN);
704 r = ::poll(fds.data(), fds.size(), -1);
705 } while (r == -1 && errno == EINTR);
706 checkUnixError(r, "poll");
708 for (int i = 0; i < pipes_.size(); ++i) {
710 DCHECK_EQ(fds[i].fd, p.parentFd);
711 short events = fds[i].revents;
714 if (events & POLLOUT) {
715 DCHECK(!(events & POLLIN));
716 if (writeCallback(p.parentFd, p.childFd)) {
717 toClose.push_back(i);
722 if (events & POLLIN) {
723 DCHECK(!(events & POLLOUT));
724 if (readCallback(p.parentFd, p.childFd)) {
725 toClose.push_back(i);
730 if ((events & (POLLHUP | POLLERR)) && !closed) {
731 toClose.push_back(i);
736 // Close the fds in reverse order so the indexes hold after erase()
737 for (int idx : boost::adaptors::reverse(toClose)) {
738 auto pos = pipes_.begin() + idx;
739 closeChecked(pos->parentFd);
745 int Subprocess::findByChildFd(int childFd) const {
746 auto pos = std::lower_bound(
747 pipes_.begin(), pipes_.end(), childFd,
748 [] (const PipeInfo& info, int fd) { return info.childFd < fd; });
749 if (pos == pipes_.end() || pos->childFd != childFd) {
750 throw std::invalid_argument(folly::to<std::string>(
751 "child fd not found ", childFd));
753 return pos - pipes_.begin();
756 void Subprocess::closeParentFd(int childFd) {
757 int idx = findByChildFd(childFd);
758 closeChecked(pipes_[idx].parentFd);
759 pipes_.erase(pipes_.begin() + idx);
767 // We like EPIPE, thanks.
768 ::signal(SIGPIPE, SIG_IGN);
772 Initializer initializer;