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/ScopeGuard.h"
37 #include "folly/String.h"
38 #include "folly/io/Cursor.h"
40 extern char** environ;
44 ProcessReturnCode::State ProcessReturnCode::state() const {
45 if (rawStatus_ == RV_NOT_STARTED) return NOT_STARTED;
46 if (rawStatus_ == RV_RUNNING) return RUNNING;
47 if (WIFEXITED(rawStatus_)) return EXITED;
48 if (WIFSIGNALED(rawStatus_)) return KILLED;
49 throw std::runtime_error(to<std::string>(
50 "Invalid ProcessReturnCode: ", rawStatus_));
53 void ProcessReturnCode::enforce(State s) const {
55 throw std::logic_error(to<std::string>("Invalid state ", s));
59 int ProcessReturnCode::exitStatus() const {
61 return WEXITSTATUS(rawStatus_);
64 int ProcessReturnCode::killSignal() const {
66 return WTERMSIG(rawStatus_);
69 bool ProcessReturnCode::coreDumped() const {
71 return WCOREDUMP(rawStatus_);
74 std::string ProcessReturnCode::str() const {
81 return to<std::string>("exited with status ", exitStatus());
83 return to<std::string>("killed by signal ", killSignal(),
84 (coreDumped() ? " (core dumped)" : ""));
86 CHECK(false); // unreached
89 CalledProcessError::CalledProcessError(ProcessReturnCode rc)
91 what_(returnCode_.str()) {
96 // Copy pointers to the given strings in a format suitable for posix_spawn
97 std::unique_ptr<const char*[]> cloneStrings(const std::vector<std::string>& s) {
98 std::unique_ptr<const char*[]> d(new const char*[s.size() + 1]);
99 for (int i = 0; i < s.size(); i++) {
102 d[s.size()] = nullptr;
106 // Check a wait() status, throw on non-successful
107 void checkStatus(ProcessReturnCode returnCode) {
108 if (returnCode.state() != ProcessReturnCode::EXITED ||
109 returnCode.exitStatus() != 0) {
110 throw CalledProcessError(returnCode);
116 Subprocess::Options& Subprocess::Options::fd(int fd, int action) {
117 if (action == Subprocess::PIPE) {
119 action = Subprocess::PIPE_IN;
120 } else if (fd == 1 || fd == 2) {
121 action = Subprocess::PIPE_OUT;
123 throw std::invalid_argument(
124 to<std::string>("Only fds 0, 1, 2 are valid for action=PIPE: ", fd));
127 fdActions_[fd] = action;
131 Subprocess::Subprocess(
132 const std::vector<std::string>& argv,
133 const Options& options,
134 const char* executable,
135 const std::vector<std::string>* env)
137 returnCode_(RV_NOT_STARTED) {
139 throw std::invalid_argument("argv must not be empty");
141 if (!executable) executable = argv[0].c_str();
142 spawn(cloneStrings(argv), executable, options, env);
145 Subprocess::Subprocess(
146 const std::string& cmd,
147 const Options& options,
148 const std::vector<std::string>* env)
150 returnCode_(RV_NOT_STARTED) {
151 if (options.usePath_) {
152 throw std::invalid_argument("usePath() not allowed when running in shell");
154 const char* shell = getenv("SHELL");
159 std::unique_ptr<const char*[]> argv(new const char*[4]);
162 argv[2] = cmd.c_str();
164 spawn(std::move(argv), shell, options, env);
167 Subprocess::~Subprocess() {
168 CHECK_NE(returnCode_.state(), ProcessReturnCode::RUNNING)
169 << "Subprocess destroyed without reaping child";
173 void closeChecked(int fd) {
174 checkUnixError(::close(fd), "close");
178 void Subprocess::closeAll() {
179 for (auto& p : pipes_) {
180 closeChecked(p.parentFd);
185 void Subprocess::setAllNonBlocking() {
186 for (auto& p : pipes_) {
188 int flags = ::fcntl(fd, F_GETFL);
189 checkUnixError(flags, "fcntl");
190 int r = ::fcntl(fd, F_SETFL, flags | O_NONBLOCK);
191 checkUnixError(r, "fcntl");
195 void Subprocess::spawn(
196 std::unique_ptr<const char*[]> argv,
197 const char* executable,
198 const Options& optionsIn,
199 const std::vector<std::string>* env) {
200 if (optionsIn.usePath_ && env) {
201 throw std::invalid_argument(
202 "usePath() not allowed when overriding environment");
205 // Make a copy, we'll mutate options
206 Options options(optionsIn);
208 // Parent work, pre-fork: create pipes
209 std::vector<int> childFds;
210 for (auto& p : options.fdActions_) {
211 if (p.second == PIPE_IN || p.second == PIPE_OUT) {
214 checkUnixError(r, "pipe");
216 pinfo.direction = p.second;
218 if (p.second == PIPE_IN) {
219 // Child gets reading end
220 pinfo.parentFd = fds[1];
223 pinfo.parentFd = fds[0];
226 p.second = cfd; // ensure it gets dup2()ed
227 pinfo.childFd = p.first;
228 childFds.push_back(cfd);
229 pipes_.push_back(pinfo);
233 // This should already be sorted, as options.fdActions_ is
234 DCHECK(std::is_sorted(pipes_.begin(), pipes_.end()));
236 // Note that the const casts below are legit, per
237 // http://pubs.opengroup.org/onlinepubs/009695399/functions/exec.html
239 char** argVec = const_cast<char**>(argv.get());
241 // Set up environment
242 std::unique_ptr<const char*[]> envHolder;
245 envHolder = cloneStrings(*env);
246 envVec = const_cast<char**>(envHolder.get());
251 // Block all signals around vfork; see http://ewontfix.com/7/.
253 // As the child may run in the same address space as the parent until
254 // the actual execve() system call, any (custom) signal handlers that
255 // the parent has might alter parent's memory if invoked in the child,
256 // with undefined results. So we block all signals in the parent before
257 // vfork(), which will cause them to be blocked in the child as well (we
258 // rely on the fact that Linux, just like all sane implementations, only
259 // clones the calling thread). Then, in the child, we reset all signals
260 // to their default dispositions (while still blocked), and unblock them
261 // (so the exec()ed process inherits the parent's signal mask)
263 // The parent also unblocks all signals as soon as vfork() returns.
265 int r = ::sigfillset(&allBlocked);
266 checkUnixError(r, "sigfillset");
268 r = pthread_sigmask(SIG_SETMASK, &allBlocked, &oldSignals);
269 checkPosixError(r, "pthread_sigmask");
273 // While all signals are blocked, we must reset their
274 // dispositions to default.
275 for (int sig = 1; sig < NSIG; ++sig) {
276 ::signal(sig, SIG_DFL);
278 // Unblock signals; restore signal mask.
279 int r = pthread_sigmask(SIG_SETMASK, &oldSignals, nullptr);
282 runChild(executable, argVec, envVec, options);
283 // This should never return, but there's nothing else we can do here.
286 // In parent. We want to restore the signal mask even if vfork fails,
287 // so we'll save errno here, restore the signal mask, and only then
289 int savedErrno = errno;
291 // Restore signal mask; do this even if vfork fails!
292 // We only check for errors from pthread_sigmask after we recorded state
293 // that the child is alive, so we know to reap it.
294 r = pthread_sigmask(SIG_SETMASK, &oldSignals, nullptr);
295 checkUnixError(pid, savedErrno, "vfork");
299 returnCode_ = ProcessReturnCode(RV_RUNNING);
301 // Parent work, post-fork: close child's ends of pipes
302 for (int f : childFds) {
306 checkPosixError(r, "pthread_sigmask");
311 // Checked version of close() to use in the child: abort() on error
312 void childClose(int fd) {
314 if (r == -1) abort();
317 // Checked version of dup2() to use in the child: abort() on error
318 void childDup2(int oldfd, int newfd) {
319 int r = ::dup2(oldfd, newfd);
320 if (r == -1) abort();
325 void Subprocess::runChild(const char* executable,
326 char** argv, char** env,
327 const Options& options) const {
328 // Close parent's ends of all pipes
329 for (auto& p : pipes_) {
330 childClose(p.parentFd);
333 // Close all fds that we're supposed to close.
334 // Note that we're ignoring errors here, in case some of these
335 // fds were set to close on exec.
336 for (auto& p : options.fdActions_) {
337 if (p.second == CLOSE) {
340 childDup2(p.second, p.first);
344 // If requested, close all other file descriptors. Don't close
345 // any fds in options.fdActions_, and don't touch stdin, stdout, stderr.
347 if (options.closeOtherFds_) {
348 for (int fd = getdtablesize() - 1; fd >= 3; --fd) {
349 if (options.fdActions_.count(fd) == 0) {
355 // Opt to receive signal on parent death, if requested
356 if (options.parentDeathSignal_ != 0) {
357 int r = prctl(PR_SET_PDEATHSIG, options.parentDeathSignal_, 0, 0, 0);
363 // Now, finally, exec.
365 if (options.usePath_) {
366 ::execvp(executable, argv);
368 ::execve(executable, argv, env);
371 // If we're here, something's wrong.
375 ProcessReturnCode Subprocess::poll() {
376 returnCode_.enforce(ProcessReturnCode::RUNNING);
379 pid_t found = ::waitpid(pid_, &status, WNOHANG);
380 checkUnixError(found, "waitpid");
382 returnCode_ = ProcessReturnCode(status);
388 bool Subprocess::pollChecked() {
389 if (poll().state() == ProcessReturnCode::RUNNING) {
392 checkStatus(returnCode_);
396 ProcessReturnCode Subprocess::wait() {
397 returnCode_.enforce(ProcessReturnCode::RUNNING);
402 found = ::waitpid(pid_, &status, 0);
403 } while (found == -1 && errno == EINTR);
404 checkUnixError(found, "waitpid");
405 DCHECK_EQ(found, pid_);
406 returnCode_ = ProcessReturnCode(status);
411 void Subprocess::waitChecked() {
413 checkStatus(returnCode_);
416 void Subprocess::sendSignal(int signal) {
417 returnCode_.enforce(ProcessReturnCode::RUNNING);
418 int r = ::kill(pid_, signal);
419 checkUnixError(r, "kill");
422 pid_t Subprocess::pid() const {
428 std::pair<const uint8_t*, size_t> queueFront(const IOBufQueue& queue) {
429 auto* p = queue.front();
430 if (!p) return std::make_pair(nullptr, 0);
431 return io::Cursor(p).peek();
435 bool handleWrite(int fd, IOBufQueue& queue) {
437 auto p = queueFront(queue);
444 n = ::write(fd, p.first, p.second);
445 } while (n == -1 && errno == EINTR);
446 if (n == -1 && errno == EAGAIN) {
449 checkUnixError(n, "write");
455 bool handleRead(int fd, IOBufQueue& queue) {
457 auto p = queue.preallocate(100, 65000);
460 n = ::read(fd, p.first, p.second);
461 } while (n == -1 && errno == EINTR);
462 if (n == -1 && errno == EAGAIN) {
465 checkUnixError(n, "read");
469 queue.postallocate(n);
473 bool discardRead(int fd) {
474 static const size_t bufSize = 65000;
475 // Thread unsafe, but it doesn't matter.
476 static std::unique_ptr<char[]> buf(new char[bufSize]);
481 n = ::read(fd, buf.get(), bufSize);
482 } while (n == -1 && errno == EINTR);
483 if (n == -1 && errno == EAGAIN) {
486 checkUnixError(n, "read");
495 std::pair<std::string, std::string> Subprocess::communicate(
496 const CommunicateFlags& flags,
498 IOBufQueue dataQueue;
499 dataQueue.wrapBuffer(data.data(), data.size());
501 auto outQueues = communicateIOBuf(flags, std::move(dataQueue));
502 auto outBufs = std::make_pair(outQueues.first.move(),
503 outQueues.second.move());
504 std::pair<std::string, std::string> out;
506 outBufs.first->coalesce();
507 out.first.assign(reinterpret_cast<const char*>(outBufs.first->data()),
508 outBufs.first->length());
510 if (outBufs.second) {
511 outBufs.second->coalesce();
512 out.second.assign(reinterpret_cast<const char*>(outBufs.second->data()),
513 outBufs.second->length());
518 std::pair<IOBufQueue, IOBufQueue> Subprocess::communicateIOBuf(
519 const CommunicateFlags& flags,
521 std::pair<IOBufQueue, IOBufQueue> out;
523 auto readCallback = [&] (int pfd, int cfd) -> bool {
524 if (cfd == 1 && flags.readStdout_) {
525 return handleRead(pfd, out.first);
526 } else if (cfd == 2 && flags.readStderr_) {
527 return handleRead(pfd, out.second);
529 // Don't close the file descriptor, the child might not like SIGPIPE,
530 // just read and throw the data away.
531 return discardRead(pfd);
535 auto writeCallback = [&] (int pfd, int cfd) -> bool {
536 if (cfd == 0 && flags.writeStdin_) {
537 return handleWrite(pfd, data);
539 // If we don't want to write to this fd, just close it.
544 communicate(std::move(readCallback), std::move(writeCallback));
549 void Subprocess::communicate(FdCallback readCallback,
550 FdCallback writeCallback) {
551 returnCode_.enforce(ProcessReturnCode::RUNNING);
554 std::vector<pollfd> fds;
555 fds.reserve(pipes_.size());
556 std::vector<int> toClose;
557 toClose.reserve(pipes_.size());
559 while (!pipes_.empty()) {
563 for (auto& p : pipes_) {
566 // Yes, backwards, PIPE_IN / PIPE_OUT are defined from the
567 // child's point of view.
568 pfd.events = (p.direction == PIPE_IN ? POLLOUT : POLLIN);
574 r = ::poll(fds.data(), fds.size(), -1);
575 } while (r == -1 && errno == EINTR);
576 checkUnixError(r, "poll");
578 for (int i = 0; i < pipes_.size(); ++i) {
580 DCHECK_EQ(fds[i].fd, p.parentFd);
581 short events = fds[i].revents;
584 if (events & POLLOUT) {
585 DCHECK(!(events & POLLIN));
586 if (writeCallback(p.parentFd, p.childFd)) {
587 toClose.push_back(i);
592 if (events & POLLIN) {
593 DCHECK(!(events & POLLOUT));
594 if (readCallback(p.parentFd, p.childFd)) {
595 toClose.push_back(i);
600 if ((events & (POLLHUP | POLLERR)) && !closed) {
601 toClose.push_back(i);
606 // Close the fds in reverse order so the indexes hold after erase()
607 for (int idx : boost::adaptors::reverse(toClose)) {
608 auto pos = pipes_.begin() + idx;
609 closeChecked(pos->parentFd);
615 int Subprocess::findByChildFd(int childFd) const {
616 auto pos = std::lower_bound(
617 pipes_.begin(), pipes_.end(), childFd,
618 [] (const PipeInfo& info, int fd) { return info.childFd < fd; });
619 if (pos == pipes_.end() || pos->childFd != childFd) {
620 throw std::invalid_argument(folly::to<std::string>(
621 "child fd not found ", childFd));
623 return pos - pipes_.begin();
626 void Subprocess::closeParentFd(int childFd) {
627 int idx = findByChildFd(childFd);
628 closeChecked(pipes_[idx].parentFd);
629 pipes_.erase(pipes_.begin() + idx);
637 // We like EPIPE, thanks.
638 ::signal(SIGPIPE, SIG_IGN);
642 Initializer initializer;