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>("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 FOLLY_NORETURN void childError(int errFd, int errCode, int errnoValue);
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 // Change the working directory, if one is given
417 if (!options.childDir_.empty()) {
418 r = ::chdir(options.childDir_.c_str());
424 // Close parent's ends of all pipes
425 for (auto& p : pipes_) {
426 r = ::close(p.parentFd);
432 // Close all fds that we're supposed to close.
433 // Note that we're ignoring errors here, in case some of these
434 // fds were set to close on exec.
435 for (auto& p : options.fdActions_) {
436 if (p.second == CLOSE) {
439 r = ::dup2(p.second, p.first);
446 // If requested, close all other file descriptors. Don't close
447 // any fds in options.fdActions_, and don't touch stdin, stdout, stderr.
449 if (options.closeOtherFds_) {
450 for (int fd = getdtablesize() - 1; fd >= 3; --fd) {
451 if (options.fdActions_.count(fd) == 0) {
458 // Opt to receive signal on parent death, if requested
459 if (options.parentDeathSignal_ != 0) {
460 r = prctl(PR_SET_PDEATHSIG, options.parentDeathSignal_, 0, 0, 0);
470 int Subprocess::runChild(const char* executable,
471 char** argv, char** env,
472 const Options& options) const {
473 // Now, finally, exec.
475 if (options.usePath_) {
476 ::execvp(executable, argv);
478 ::execve(executable, argv, env);
483 void Subprocess::readChildErrorPipe(int pfd, const char* executable) {
485 auto rc = readNoInt(pfd, &info, sizeof(info));
487 // No data means the child executed successfully, and the pipe
488 // was closed due to the close-on-exec flag being set.
490 } else if (rc != sizeof(ChildErrorInfo)) {
491 // An error occurred trying to read from the pipe, or we got a partial read.
492 // Neither of these cases should really occur in practice.
494 // We can't get any error data from the child in this case, and we don't
495 // know if it is successfully running or not. All we can do is to return
496 // normally, as if the child executed successfully. If something bad
497 // happened the caller should at least get a non-normal exit status from
499 LOG(ERROR) << "unexpected error trying to read from child error pipe " <<
500 "rc=" << rc << ", errno=" << errno;
504 // We got error data from the child. The child should exit immediately in
505 // this case, so wait on it to clean up.
508 // Throw to signal the error
509 throw SubprocessSpawnError(executable, info.errCode, info.errnoValue);
512 ProcessReturnCode Subprocess::poll() {
513 returnCode_.enforce(ProcessReturnCode::RUNNING);
516 pid_t found = ::waitpid(pid_, &status, WNOHANG);
517 checkUnixError(found, "waitpid");
519 returnCode_ = ProcessReturnCode(status);
525 bool Subprocess::pollChecked() {
526 if (poll().state() == ProcessReturnCode::RUNNING) {
529 checkStatus(returnCode_);
533 ProcessReturnCode Subprocess::wait() {
534 returnCode_.enforce(ProcessReturnCode::RUNNING);
539 found = ::waitpid(pid_, &status, 0);
540 } while (found == -1 && errno == EINTR);
541 checkUnixError(found, "waitpid");
542 DCHECK_EQ(found, pid_);
543 returnCode_ = ProcessReturnCode(status);
548 void Subprocess::waitChecked() {
550 checkStatus(returnCode_);
553 void Subprocess::sendSignal(int signal) {
554 returnCode_.enforce(ProcessReturnCode::RUNNING);
555 int r = ::kill(pid_, signal);
556 checkUnixError(r, "kill");
559 pid_t Subprocess::pid() const {
565 std::pair<const uint8_t*, size_t> queueFront(const IOBufQueue& queue) {
566 auto* p = queue.front();
567 if (!p) return std::make_pair(nullptr, 0);
568 return io::Cursor(p).peek();
572 bool handleWrite(int fd, IOBufQueue& queue) {
574 auto p = queueFront(queue);
581 n = ::write(fd, p.first, p.second);
582 } while (n == -1 && errno == EINTR);
583 if (n == -1 && errno == EAGAIN) {
586 checkUnixError(n, "write");
592 bool handleRead(int fd, IOBufQueue& queue) {
594 auto p = queue.preallocate(100, 65000);
597 n = ::read(fd, p.first, p.second);
598 } while (n == -1 && errno == EINTR);
599 if (n == -1 && errno == EAGAIN) {
602 checkUnixError(n, "read");
606 queue.postallocate(n);
610 bool discardRead(int fd) {
611 static const size_t bufSize = 65000;
612 // Thread unsafe, but it doesn't matter.
613 static std::unique_ptr<char[]> buf(new char[bufSize]);
618 n = ::read(fd, buf.get(), bufSize);
619 } while (n == -1 && errno == EINTR);
620 if (n == -1 && errno == EAGAIN) {
623 checkUnixError(n, "read");
632 std::pair<std::string, std::string> Subprocess::communicate(
634 IOBufQueue inputQueue;
635 inputQueue.wrapBuffer(input.data(), input.size());
637 auto outQueues = communicateIOBuf(std::move(inputQueue));
638 auto outBufs = std::make_pair(outQueues.first.move(),
639 outQueues.second.move());
640 std::pair<std::string, std::string> out;
642 outBufs.first->coalesce();
643 out.first.assign(reinterpret_cast<const char*>(outBufs.first->data()),
644 outBufs.first->length());
646 if (outBufs.second) {
647 outBufs.second->coalesce();
648 out.second.assign(reinterpret_cast<const char*>(outBufs.second->data()),
649 outBufs.second->length());
654 std::pair<IOBufQueue, IOBufQueue> Subprocess::communicateIOBuf(
656 // If the user supplied a non-empty input buffer, make sure
657 // that stdin is a pipe so we can write the data.
658 if (!input.empty()) {
659 // findByChildFd() will throw std::invalid_argument if no pipe for
660 // STDIN_FILENO exists
661 findByChildFd(STDIN_FILENO);
664 std::pair<IOBufQueue, IOBufQueue> out;
666 auto readCallback = [&] (int pfd, int cfd) -> bool {
667 if (cfd == STDOUT_FILENO) {
668 return handleRead(pfd, out.first);
669 } else if (cfd == STDERR_FILENO) {
670 return handleRead(pfd, out.second);
672 // Don't close the file descriptor, the child might not like SIGPIPE,
673 // just read and throw the data away.
674 return discardRead(pfd);
678 auto writeCallback = [&] (int pfd, int cfd) -> bool {
679 if (cfd == STDIN_FILENO) {
680 return handleWrite(pfd, input);
682 // If we don't want to write to this fd, just close it.
687 communicate(std::move(readCallback), std::move(writeCallback));
692 void Subprocess::communicate(FdCallback readCallback,
693 FdCallback writeCallback) {
694 returnCode_.enforce(ProcessReturnCode::RUNNING);
697 std::vector<pollfd> fds;
698 fds.reserve(pipes_.size());
699 std::vector<int> toClose;
700 toClose.reserve(pipes_.size());
702 while (!pipes_.empty()) {
706 for (auto& p : pipes_) {
709 // Yes, backwards, PIPE_IN / PIPE_OUT are defined from the
710 // child's point of view.
712 // Still keeping fd in watched set so we get notified of POLLHUP /
715 } else if (p.direction == PIPE_IN) {
716 pfd.events = POLLOUT;
725 r = ::poll(fds.data(), fds.size(), -1);
726 } while (r == -1 && errno == EINTR);
727 checkUnixError(r, "poll");
729 for (int i = 0; i < pipes_.size(); ++i) {
731 DCHECK_EQ(fds[i].fd, p.parentFd);
732 short events = fds[i].revents;
735 if (events & POLLOUT) {
736 DCHECK(!(events & POLLIN));
737 if (writeCallback(p.parentFd, p.childFd)) {
738 toClose.push_back(i);
743 if (events & POLLIN) {
744 DCHECK(!(events & POLLOUT));
745 if (readCallback(p.parentFd, p.childFd)) {
746 toClose.push_back(i);
751 if ((events & (POLLHUP | POLLERR)) && !closed) {
752 toClose.push_back(i);
757 // Close the fds in reverse order so the indexes hold after erase()
758 for (int idx : boost::adaptors::reverse(toClose)) {
759 auto pos = pipes_.begin() + idx;
760 closeChecked(pos->parentFd);
766 void Subprocess::enableNotifications(int childFd, bool enabled) {
767 pipes_[findByChildFd(childFd)].enabled = enabled;
770 bool Subprocess::notificationsEnabled(int childFd) const {
771 return pipes_[findByChildFd(childFd)].enabled;
774 int Subprocess::findByChildFd(int childFd) const {
775 auto pos = std::lower_bound(
776 pipes_.begin(), pipes_.end(), childFd,
777 [] (const PipeInfo& info, int fd) { return info.childFd < fd; });
778 if (pos == pipes_.end() || pos->childFd != childFd) {
779 throw std::invalid_argument(folly::to<std::string>(
780 "child fd not found ", childFd));
782 return pos - pipes_.begin();
785 void Subprocess::closeParentFd(int childFd) {
786 int idx = findByChildFd(childFd);
787 closeChecked(pipes_[idx].parentFd);
788 pipes_.erase(pipes_.begin() + idx);
796 // We like EPIPE, thanks.
797 ::signal(SIGPIPE, SIG_IGN);
801 Initializer initializer;