2 * Copyright 2015 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>
33 #include <system_error>
35 #include <boost/container/flat_set.hpp>
36 #include <boost/range/adaptors.hpp>
38 #include <glog/logging.h>
40 #include <folly/Conv.h>
41 #include <folly/Exception.h>
42 #include <folly/ScopeGuard.h>
43 #include <folly/String.h>
44 #include <folly/io/Cursor.h>
46 extern char** environ;
48 constexpr int kExecFailure = 127;
49 constexpr int kChildFailure = 126;
53 ProcessReturnCode::ProcessReturnCode(ProcessReturnCode&& p) noexcept
54 : rawStatus_(p.rawStatus_) {
55 p.rawStatus_ = ProcessReturnCode::RV_NOT_STARTED;
58 ProcessReturnCode& ProcessReturnCode::operator=(ProcessReturnCode&& p)
60 rawStatus_ = p.rawStatus_;
61 p.rawStatus_ = ProcessReturnCode::RV_NOT_STARTED;
65 ProcessReturnCode::State ProcessReturnCode::state() const {
66 if (rawStatus_ == RV_NOT_STARTED) return NOT_STARTED;
67 if (rawStatus_ == RV_RUNNING) return RUNNING;
68 if (WIFEXITED(rawStatus_)) return EXITED;
69 if (WIFSIGNALED(rawStatus_)) return KILLED;
70 throw std::runtime_error(to<std::string>(
71 "Invalid ProcessReturnCode: ", rawStatus_));
74 void ProcessReturnCode::enforce(State expected) const {
77 throw std::logic_error(to<std::string>(
78 "Bad use of ProcessReturnCode; state is ", s, " expected ", expected
83 int ProcessReturnCode::exitStatus() const {
85 return WEXITSTATUS(rawStatus_);
88 int ProcessReturnCode::killSignal() const {
90 return WTERMSIG(rawStatus_);
93 bool ProcessReturnCode::coreDumped() const {
95 return WCOREDUMP(rawStatus_);
98 std::string ProcessReturnCode::str() const {
101 return "not started";
105 return to<std::string>("exited with status ", exitStatus());
107 return to<std::string>("killed by signal ", killSignal(),
108 (coreDumped() ? " (core dumped)" : ""));
110 CHECK(false); // unreached
111 return ""; // silence GCC warning
114 CalledProcessError::CalledProcessError(ProcessReturnCode rc)
116 what_(returnCode_.str()) {
119 SubprocessSpawnError::SubprocessSpawnError(const char* executable,
122 : errnoValue_(errnoValue),
123 what_(to<std::string>(errCode == kExecFailure ?
124 "failed to execute " :
125 "error preparing to execute ",
126 executable, ": ", errnoStr(errnoValue))) {
131 // Copy pointers to the given strings in a format suitable for posix_spawn
132 std::unique_ptr<const char*[]> cloneStrings(const std::vector<std::string>& s) {
133 std::unique_ptr<const char*[]> d(new const char*[s.size() + 1]);
134 for (size_t i = 0; i < s.size(); i++) {
137 d[s.size()] = nullptr;
141 // Check a wait() status, throw on non-successful
142 void checkStatus(ProcessReturnCode returnCode) {
143 if (returnCode.state() != ProcessReturnCode::EXITED ||
144 returnCode.exitStatus() != 0) {
145 throw CalledProcessError(returnCode);
151 Subprocess::Options& Subprocess::Options::fd(int fd, int action) {
152 if (action == Subprocess::PIPE) {
154 action = Subprocess::PIPE_IN;
155 } else if (fd == 1 || fd == 2) {
156 action = Subprocess::PIPE_OUT;
158 throw std::invalid_argument(
159 to<std::string>("Only fds 0, 1, 2 are valid for action=PIPE: ", fd));
162 fdActions_[fd] = action;
166 Subprocess::Subprocess(
167 const std::vector<std::string>& argv,
168 const Options& options,
169 const char* executable,
170 const std::vector<std::string>* env)
172 returnCode_(RV_NOT_STARTED) {
174 throw std::invalid_argument("argv must not be empty");
176 if (!executable) executable = argv[0].c_str();
177 spawn(cloneStrings(argv), executable, options, env);
180 Subprocess::Subprocess(
181 const std::string& cmd,
182 const Options& options,
183 const std::vector<std::string>* env)
185 returnCode_(RV_NOT_STARTED) {
186 if (options.usePath_) {
187 throw std::invalid_argument("usePath() not allowed when running in shell");
189 const char* shell = getenv("SHELL");
194 std::unique_ptr<const char*[]> argv(new const char*[4]);
197 argv[2] = cmd.c_str();
199 spawn(std::move(argv), shell, options, env);
202 Subprocess::~Subprocess() {
203 CHECK_NE(returnCode_.state(), ProcessReturnCode::RUNNING)
204 << "Subprocess destroyed without reaping child";
209 struct ChildErrorInfo {
214 FOLLY_NORETURN void childError(int errFd, int errCode, int errnoValue);
215 void childError(int errFd, int errCode, int errnoValue) {
216 ChildErrorInfo info = {errCode, errnoValue};
217 // Write the error information over the pipe to our parent process.
218 // We can't really do anything else if this write call fails.
219 writeNoInt(errFd, &info, sizeof(info));
226 void Subprocess::setAllNonBlocking() {
227 for (auto& p : pipes_) {
228 int fd = p.pipe.fd();
229 int flags = ::fcntl(fd, F_GETFL);
230 checkUnixError(flags, "fcntl");
231 int r = ::fcntl(fd, F_SETFL, flags | O_NONBLOCK);
232 checkUnixError(r, "fcntl");
236 void Subprocess::spawn(
237 std::unique_ptr<const char*[]> argv,
238 const char* executable,
239 const Options& optionsIn,
240 const std::vector<std::string>* env) {
241 if (optionsIn.usePath_ && env) {
242 throw std::invalid_argument(
243 "usePath() not allowed when overriding environment");
246 // Make a copy, we'll mutate options
247 Options options(optionsIn);
249 // On error, close all pipes_ (ignoring errors, but that seems fine here).
250 auto pipesGuard = makeGuard([this] { pipes_.clear(); });
252 // Create a pipe to use to receive error information from the child,
253 // in case it fails before calling exec()
256 checkUnixError(::pipe2(errFds, O_CLOEXEC), "pipe2");
258 checkUnixError(::pipe(errFds), "pipe");
261 CHECK_ERR(::close(errFds[0]));
262 if (errFds[1] >= 0) {
263 CHECK_ERR(::close(errFds[1]));
267 #if !FOLLY_HAVE_PIPE2
268 // Ask the child to close the read end of the error pipe.
269 checkUnixError(fcntl(errFds[0], F_SETFD, FD_CLOEXEC), "set FD_CLOEXEC");
270 // Set the close-on-exec flag on the write side of the pipe.
271 // This way the pipe will be closed automatically in the child if execve()
272 // succeeds. If the exec fails the child can write error information to the
274 checkUnixError(fcntl(errFds[1], F_SETFD, FD_CLOEXEC), "set FD_CLOEXEC");
277 // Perform the actual work of setting up pipes then forking and
278 // executing the child.
279 spawnInternal(std::move(argv), executable, options, env, errFds[1]);
281 // After spawnInternal() returns the child is alive. We have to be very
282 // careful about throwing after this point. We are inside the constructor,
283 // so if we throw the Subprocess object will have never existed, and the
284 // destructor will never be called.
286 // We should only throw if we got an error via the errFd, and we know the
287 // child has exited and can be immediately waited for. In all other cases,
288 // we have no way of cleaning up the child.
290 // Close writable side of the errFd pipe in the parent process
291 CHECK_ERR(::close(errFds[1]));
294 // Read from the errFd pipe, to tell if the child ran into any errors before
296 readChildErrorPipe(errFds[0], executable);
298 // We have fully succeeded now, so release the guard on pipes_
299 pipesGuard.dismiss();
302 void Subprocess::spawnInternal(
303 std::unique_ptr<const char*[]> argv,
304 const char* executable,
306 const std::vector<std::string>* env,
308 // Parent work, pre-fork: create pipes
309 std::vector<int> childFds;
310 // Close all of the childFds as we leave this scope
312 // These are only pipes, closing them shouldn't fail
313 for (int cfd : childFds) {
314 CHECK_ERR(::close(cfd));
319 for (auto& p : options.fdActions_) {
320 if (p.second == PIPE_IN || p.second == PIPE_OUT) {
322 // We're setting both ends of the pipe as close-on-exec. The child
323 // doesn't need to reset the flag on its end, as we always dup2() the fd,
324 // and dup2() fds don't share the close-on-exec flag.
326 // If possible, set close-on-exec atomically. Otherwise, a concurrent
327 // Subprocess invocation can fork() between "pipe" and "fnctl",
328 // causing FDs to leak.
329 r = ::pipe2(fds, O_CLOEXEC);
330 checkUnixError(r, "pipe2");
333 checkUnixError(r, "pipe");
334 r = fcntl(fds[0], F_SETFD, FD_CLOEXEC);
335 checkUnixError(r, "set FD_CLOEXEC");
336 r = fcntl(fds[1], F_SETFD, FD_CLOEXEC);
337 checkUnixError(r, "set FD_CLOEXEC");
339 pipes_.emplace_back();
340 Pipe& pipe = pipes_.back();
341 pipe.direction = p.second;
343 if (p.second == PIPE_IN) {
344 // Child gets reading end
345 pipe.pipe = folly::File(fds[1], /*owns_fd=*/ true);
348 pipe.pipe = folly::File(fds[0], /*owns_fd=*/ true);
351 p.second = cfd; // ensure it gets dup2()ed
352 pipe.childFd = p.first;
353 childFds.push_back(cfd);
357 // This should already be sorted, as options.fdActions_ is
358 DCHECK(std::is_sorted(pipes_.begin(), pipes_.end()));
360 // Note that the const casts below are legit, per
361 // http://pubs.opengroup.org/onlinepubs/009695399/functions/exec.html
363 char** argVec = const_cast<char**>(argv.get());
365 // Set up environment
366 std::unique_ptr<const char*[]> envHolder;
369 envHolder = cloneStrings(*env);
370 envVec = const_cast<char**>(envHolder.get());
375 // Block all signals around vfork; see http://ewontfix.com/7/.
377 // As the child may run in the same address space as the parent until
378 // the actual execve() system call, any (custom) signal handlers that
379 // the parent has might alter parent's memory if invoked in the child,
380 // with undefined results. So we block all signals in the parent before
381 // vfork(), which will cause them to be blocked in the child as well (we
382 // rely on the fact that Linux, just like all sane implementations, only
383 // clones the calling thread). Then, in the child, we reset all signals
384 // to their default dispositions (while still blocked), and unblock them
385 // (so the exec()ed process inherits the parent's signal mask)
387 // The parent also unblocks all signals as soon as vfork() returns.
389 r = sigfillset(&allBlocked);
390 checkUnixError(r, "sigfillset");
393 r = pthread_sigmask(SIG_SETMASK, &allBlocked, &oldSignals);
394 checkPosixError(r, "pthread_sigmask");
396 // Restore signal mask
397 r = pthread_sigmask(SIG_SETMASK, &oldSignals, nullptr);
398 CHECK_EQ(r, 0) << "pthread_sigmask: " << errnoStr(r); // shouldn't fail
401 // Call c_str() here, as it's not necessarily safe after fork.
402 const char* childDir =
403 options.childDir_.empty() ? nullptr : options.childDir_.c_str();
406 int errnoValue = prepareChild(options, &oldSignals, childDir);
407 if (errnoValue != 0) {
408 childError(errFd, kChildFailure, errnoValue);
411 errnoValue = runChild(executable, argVec, envVec, options);
412 // If we get here, exec() failed.
413 childError(errFd, kExecFailure, errnoValue);
415 // In parent. Make sure vfork() succeeded.
416 checkUnixError(pid, errno, "vfork");
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 if (prctl(PR_SET_PDEATHSIG, options.parentDeathSignal_, 0, 0, 0) == -1) {
490 if (options.processGroupLeader_) {
491 if (setpgrp() == -1) {
499 int Subprocess::runChild(const char* executable,
500 char** argv, char** env,
501 const Options& options) const {
502 // Now, finally, exec.
503 if (options.usePath_) {
504 ::execvp(executable, argv);
506 ::execve(executable, argv, env);
511 void Subprocess::readChildErrorPipe(int pfd, const char* executable) {
513 auto rc = readNoInt(pfd, &info, sizeof(info));
515 // No data means the child executed successfully, and the pipe
516 // was closed due to the close-on-exec flag being set.
518 } else if (rc != sizeof(ChildErrorInfo)) {
519 // An error occurred trying to read from the pipe, or we got a partial read.
520 // Neither of these cases should really occur in practice.
522 // We can't get any error data from the child in this case, and we don't
523 // know if it is successfully running or not. All we can do is to return
524 // normally, as if the child executed successfully. If something bad
525 // happened the caller should at least get a non-normal exit status from
527 LOG(ERROR) << "unexpected error trying to read from child error pipe " <<
528 "rc=" << rc << ", errno=" << errno;
532 // We got error data from the child. The child should exit immediately in
533 // this case, so wait on it to clean up.
536 // Throw to signal the error
537 throw SubprocessSpawnError(executable, info.errCode, info.errnoValue);
540 ProcessReturnCode Subprocess::poll() {
541 returnCode_.enforce(ProcessReturnCode::RUNNING);
544 pid_t found = ::waitpid(pid_, &status, WNOHANG);
545 checkUnixError(found, "waitpid");
547 // Though the child process had quit, this call does not close the pipes
548 // since its descendants may still be using them.
549 returnCode_ = ProcessReturnCode(status);
555 bool Subprocess::pollChecked() {
556 if (poll().state() == ProcessReturnCode::RUNNING) {
559 checkStatus(returnCode_);
563 ProcessReturnCode Subprocess::wait() {
564 returnCode_.enforce(ProcessReturnCode::RUNNING);
569 found = ::waitpid(pid_, &status, 0);
570 } while (found == -1 && errno == EINTR);
571 checkUnixError(found, "waitpid");
572 // Though the child process had quit, this call does not close the pipes
573 // since its descendants may still be using them.
574 DCHECK_EQ(found, pid_);
575 returnCode_ = ProcessReturnCode(status);
580 void Subprocess::waitChecked() {
582 checkStatus(returnCode_);
585 void Subprocess::sendSignal(int signal) {
586 returnCode_.enforce(ProcessReturnCode::RUNNING);
587 int r = ::kill(pid_, signal);
588 checkUnixError(r, "kill");
591 pid_t Subprocess::pid() const {
597 std::pair<const uint8_t*, size_t> queueFront(const IOBufQueue& queue) {
598 auto* p = queue.front();
599 if (!p) return std::make_pair(nullptr, 0);
600 return io::Cursor(p).peek();
604 bool handleWrite(int fd, IOBufQueue& queue) {
606 auto p = queueFront(queue);
611 ssize_t n = writeNoInt(fd, p.first, p.second);
612 if (n == -1 && errno == EAGAIN) {
615 checkUnixError(n, "write");
621 bool handleRead(int fd, IOBufQueue& queue) {
623 auto p = queue.preallocate(100, 65000);
624 ssize_t n = readNoInt(fd, p.first, p.second);
625 if (n == -1 && errno == EAGAIN) {
628 checkUnixError(n, "read");
632 queue.postallocate(n);
636 bool discardRead(int fd) {
637 static const size_t bufSize = 65000;
638 // Thread unsafe, but it doesn't matter.
639 static std::unique_ptr<char[]> buf(new char[bufSize]);
642 ssize_t n = readNoInt(fd, buf.get(), bufSize);
643 if (n == -1 && errno == EAGAIN) {
646 checkUnixError(n, "read");
655 std::pair<std::string, std::string> Subprocess::communicate(
657 IOBufQueue inputQueue;
658 inputQueue.wrapBuffer(input.data(), input.size());
660 auto outQueues = communicateIOBuf(std::move(inputQueue));
661 auto outBufs = std::make_pair(outQueues.first.move(),
662 outQueues.second.move());
663 std::pair<std::string, std::string> out;
665 outBufs.first->coalesce();
666 out.first.assign(reinterpret_cast<const char*>(outBufs.first->data()),
667 outBufs.first->length());
669 if (outBufs.second) {
670 outBufs.second->coalesce();
671 out.second.assign(reinterpret_cast<const char*>(outBufs.second->data()),
672 outBufs.second->length());
677 std::pair<IOBufQueue, IOBufQueue> Subprocess::communicateIOBuf(
679 // If the user supplied a non-empty input buffer, make sure
680 // that stdin is a pipe so we can write the data.
681 if (!input.empty()) {
682 // findByChildFd() will throw std::invalid_argument if no pipe for
683 // STDIN_FILENO exists
684 findByChildFd(STDIN_FILENO);
687 std::pair<IOBufQueue, IOBufQueue> out;
689 auto readCallback = [&] (int pfd, int cfd) -> bool {
690 if (cfd == STDOUT_FILENO) {
691 return handleRead(pfd, out.first);
692 } else if (cfd == STDERR_FILENO) {
693 return handleRead(pfd, out.second);
695 // Don't close the file descriptor, the child might not like SIGPIPE,
696 // just read and throw the data away.
697 return discardRead(pfd);
701 auto writeCallback = [&] (int pfd, int cfd) -> bool {
702 if (cfd == STDIN_FILENO) {
703 return handleWrite(pfd, input);
705 // If we don't want to write to this fd, just close it.
710 communicate(std::move(readCallback), std::move(writeCallback));
715 void Subprocess::communicate(FdCallback readCallback,
716 FdCallback writeCallback) {
717 // This serves to prevent wait() followed by communicate(), but if you
718 // legitimately need that, send a patch to delete this line.
719 returnCode_.enforce(ProcessReturnCode::RUNNING);
722 std::vector<pollfd> fds;
723 fds.reserve(pipes_.size());
724 std::vector<size_t> toClose; // indexes into pipes_
725 toClose.reserve(pipes_.size());
727 while (!pipes_.empty()) {
731 for (auto& p : pipes_) {
733 pfd.fd = p.pipe.fd();
734 // Yes, backwards, PIPE_IN / PIPE_OUT are defined from the
735 // child's point of view.
737 // Still keeping fd in watched set so we get notified of POLLHUP /
740 } else if (p.direction == PIPE_IN) {
741 pfd.events = POLLOUT;
750 r = ::poll(fds.data(), fds.size(), -1);
751 } while (r == -1 && errno == EINTR);
752 checkUnixError(r, "poll");
754 for (size_t i = 0; i < pipes_.size(); ++i) {
756 auto parentFd = p.pipe.fd();
757 DCHECK_EQ(fds[i].fd, parentFd);
758 short events = fds[i].revents;
761 if (events & POLLOUT) {
762 DCHECK(!(events & POLLIN));
763 if (writeCallback(parentFd, p.childFd)) {
764 toClose.push_back(i);
769 // Call read callback on POLLHUP, to give it a chance to read (and act
771 if (events & (POLLIN | POLLHUP)) {
772 DCHECK(!(events & POLLOUT));
773 if (readCallback(parentFd, p.childFd)) {
774 toClose.push_back(i);
779 if ((events & (POLLHUP | POLLERR)) && !closed) {
780 toClose.push_back(i);
785 // Close the fds in reverse order so the indexes hold after erase()
786 for (int idx : boost::adaptors::reverse(toClose)) {
787 auto pos = pipes_.begin() + idx;
788 pos->pipe.close(); // Throws on error
794 void Subprocess::enableNotifications(int childFd, bool enabled) {
795 pipes_[findByChildFd(childFd)].enabled = enabled;
798 bool Subprocess::notificationsEnabled(int childFd) const {
799 return pipes_[findByChildFd(childFd)].enabled;
802 size_t Subprocess::findByChildFd(int childFd) const {
803 auto pos = std::lower_bound(
804 pipes_.begin(), pipes_.end(), childFd,
805 [] (const Pipe& pipe, int fd) { return pipe.childFd < fd; });
806 if (pos == pipes_.end() || pos->childFd != childFd) {
807 throw std::invalid_argument(folly::to<std::string>(
808 "child fd not found ", childFd));
810 return pos - pipes_.begin();
813 void Subprocess::closeParentFd(int childFd) {
814 int idx = findByChildFd(childFd);
815 pipes_[idx].pipe.close(); // May throw
816 pipes_.erase(pipes_.begin() + idx);
819 std::vector<Subprocess::ChildPipe> Subprocess::takeOwnershipOfPipes() {
820 std::vector<Subprocess::ChildPipe> pipes;
821 for (auto& p : pipes_) {
822 pipes.emplace_back(p.childFd, std::move(p.pipe));
833 // We like EPIPE, thanks.
834 ::signal(SIGPIPE, SIG_IGN);
838 Initializer initializer;