Commit 9cbe6594 authored by Adam Simpkins's avatar Adam Simpkins Committed by Sara Golemon

Update Subprocess to throw if exec() fails

Summary:
Add a new SubprocessSpawnError, and change the Subprocess constructor to
throw this if the child process encounters an error before calling
execve().  Error information is passed back to the parent process over a
pipe.

Previosly in this case the Subprocess constructor would fail, and
clients would simply get a return code of 126 or 127 when waiting on the
process.  There was no way to distinguish this from a successful
execve() followed by the child process exiting with status 127.

Test Plan:
Added tests to check the exception behavior, and also to check for file
descriptor leaks in the parent process.

Reviewed By: tudorb@fb.com

FB internal diff: D776273
parent 94ddd29d
...@@ -104,7 +104,7 @@ class ScopeGuardImpl : public ScopeGuardImplBase { ...@@ -104,7 +104,7 @@ class ScopeGuardImpl : public ScopeGuardImplBase {
} }
} }
private: private:
void* operator new(size_t) = delete; void* operator new(size_t) = delete;
void execute() noexcept { function_(); } void execute() noexcept { function_(); }
......
This diff is collapsed.
...@@ -144,10 +144,15 @@ class ProcessReturnCode { ...@@ -144,10 +144,15 @@ class ProcessReturnCode {
int rawStatus_; int rawStatus_;
}; };
/**
* Base exception thrown by the Subprocess methods.
*/
class SubprocessError : public std::exception {};
/** /**
* Exception thrown by *Checked methods of Subprocess. * Exception thrown by *Checked methods of Subprocess.
*/ */
class CalledProcessError : public std::exception { class CalledProcessError : public SubprocessError {
public: public:
explicit CalledProcessError(ProcessReturnCode rc); explicit CalledProcessError(ProcessReturnCode rc);
~CalledProcessError() throw() { } ~CalledProcessError() throw() { }
...@@ -158,6 +163,21 @@ class CalledProcessError : public std::exception { ...@@ -158,6 +163,21 @@ class CalledProcessError : public std::exception {
std::string what_; std::string what_;
}; };
/**
* Exception thrown if the subprocess cannot be started.
*/
class SubprocessSpawnError : public SubprocessError {
public:
SubprocessSpawnError(const char* executable, int errCode, int errnoValue);
~SubprocessSpawnError() throw() {}
const char* what() const throw() FOLLY_OVERRIDE { return what_.c_str(); }
int errnoValue() const { return errnoValue_; }
private:
int errnoValue_;
std::string what_;
};
/** /**
* Subprocess. * Subprocess.
*/ */
...@@ -457,16 +477,34 @@ class Subprocess : private boost::noncopyable { ...@@ -457,16 +477,34 @@ class Subprocess : private boost::noncopyable {
static const int RV_RUNNING = ProcessReturnCode::RV_RUNNING; static const int RV_RUNNING = ProcessReturnCode::RV_RUNNING;
static const int RV_NOT_STARTED = ProcessReturnCode::RV_NOT_STARTED; static const int RV_NOT_STARTED = ProcessReturnCode::RV_NOT_STARTED;
// spawn() sets up a pipe to read errors from the child,
// then calls spawnInternal() to do the bulk of the work. Once
// spawnInternal() returns it reads the error pipe to see if the child
// encountered any errors.
void spawn( void spawn(
std::unique_ptr<const char*[]> argv, std::unique_ptr<const char*[]> argv,
const char* executable, const char* executable,
const Options& options, const Options& options,
const std::vector<std::string>* env); const std::vector<std::string>* env);
void spawnInternal(
std::unique_ptr<const char*[]> argv,
const char* executable,
Options& options,
const std::vector<std::string>* env,
int errFd);
// Action to run in child. // Actions to run in child.
// Note that this runs after vfork(), so tread lightly. // Note that this runs after vfork(), so tread lightly.
void runChild(const char* executable, char** argv, char** env, // Returns 0 on success, or an errno value on failure.
const Options& options) const; int prepareChild(const Options& options, const sigset_t* sigmask) const;
int runChild(const char* executable, char** argv, char** env,
const Options& options) const;
/**
* Read from the error pipe, and throw SubprocessSpawnError if the child
* failed before calling exec().
*/
void readChildErrorPipe(int pfd, const char* executable);
/** /**
* Close all file descriptors. * Close all file descriptors.
......
...@@ -17,10 +17,14 @@ ...@@ -17,10 +17,14 @@
#include "folly/Subprocess.h" #include "folly/Subprocess.h"
#include <unistd.h> #include <unistd.h>
#include <sys/types.h>
#include <dirent.h>
#include <boost/container/flat_set.hpp>
#include <glog/logging.h> #include <glog/logging.h>
#include <gtest/gtest.h> #include <gtest/gtest.h>
#include "folly/Exception.h"
#include "folly/Format.h" #include "folly/Format.h"
#include "folly/experimental/Gen.h" #include "folly/experimental/Gen.h"
#include "folly/experimental/FileGen.h" #include "folly/experimental/FileGen.h"
...@@ -49,9 +53,27 @@ TEST(SimpleSubprocessTest, ExitsWithErrorChecked) { ...@@ -49,9 +53,27 @@ TEST(SimpleSubprocessTest, ExitsWithErrorChecked) {
EXPECT_THROW(proc.waitChecked(), CalledProcessError); EXPECT_THROW(proc.waitChecked(), CalledProcessError);
} }
#define EXPECT_SPAWN_ERROR(err, errMsg, cmd, ...) \
do { \
try { \
Subprocess proc(std::vector<std::string>{ (cmd), ## __VA_ARGS__ }); \
ADD_FAILURE() << "expected an error when running " << (cmd); \
} catch (const SubprocessSpawnError& ex) { \
EXPECT_EQ((err), ex.errnoValue()); \
if (StringPiece(ex.what()).find(errMsg) == StringPiece::npos) { \
ADD_FAILURE() << "failed to find \"" << (errMsg) << \
"\" in exception: \"" << ex.what() << "\""; \
} \
} \
} while (0)
TEST(SimpleSubprocessTest, ExecFails) { TEST(SimpleSubprocessTest, ExecFails) {
Subprocess proc(std::vector<std::string>{ "/no/such/file" }); EXPECT_SPAWN_ERROR(ENOENT, "failed to execute /no/such/file:",
EXPECT_EQ(127, proc.wait().exitStatus()); "/no/such/file");
EXPECT_SPAWN_ERROR(EACCES, "failed to execute /etc/passwd:",
"/etc/passwd");
EXPECT_SPAWN_ERROR(ENOTDIR, "failed to execute /etc/passwd/not/a/file:",
"/etc/passwd/not/a/file");
} }
TEST(SimpleSubprocessTest, ShellExitsSuccesssfully) { TEST(SimpleSubprocessTest, ShellExitsSuccesssfully) {
...@@ -64,6 +86,69 @@ TEST(SimpleSubprocessTest, ShellExitsWithError) { ...@@ -64,6 +86,69 @@ TEST(SimpleSubprocessTest, ShellExitsWithError) {
EXPECT_EQ(1, proc.wait().exitStatus()); EXPECT_EQ(1, proc.wait().exitStatus());
} }
namespace {
boost::container::flat_set<int> getOpenFds() {
auto pid = getpid();
auto dirname = to<std::string>("/proc/", pid, "/fd");
boost::container::flat_set<int> fds;
for (fs::directory_iterator it(dirname);
it != fs::directory_iterator();
++it) {
int fd = to<int>(it->path().filename().native());
fds.insert(fd);
}
return fds;
}
template<class Runnable>
void checkFdLeak(const Runnable& r) {
// Get the currently open fds. Check that they are the same both before and
// after calling the specified function. We read the open fds from /proc.
// (If we wanted to work even on systems that don't have /proc, we could
// perhaps create and immediately close a socket both before and after
// running the function, and make sure we got the same fd number both times.)
auto fdsBefore = getOpenFds();
r();
auto fdsAfter = getOpenFds();
EXPECT_EQ(fdsAfter.size(), fdsBefore.size());
}
}
// Make sure Subprocess doesn't leak any file descriptors
TEST(SimpleSubprocessTest, FdLeakTest) {
// Normal execution
checkFdLeak([] {
Subprocess proc("true");
EXPECT_EQ(0, proc.wait().exitStatus());
});
// Normal execution with pipes
checkFdLeak([] {
Subprocess proc("echo foo; echo bar >&2",
Subprocess::pipeStdout() | Subprocess::pipeStderr());
auto p = proc.communicate(Subprocess::readStdout() |
Subprocess::readStderr());
EXPECT_EQ("foo\n", p.first);
EXPECT_EQ("bar\n", p.second);
proc.waitChecked();
});
// Test where the exec call fails()
checkFdLeak([] {
EXPECT_SPAWN_ERROR(ENOENT, "failed to execute", "/no/such/file");
});
// Test where the exec call fails() with pipes
checkFdLeak([] {
try {
Subprocess proc(std::vector<std::string>({"/no/such/file"}),
Subprocess::pipeStdout().stderr(Subprocess::PIPE));
ADD_FAILURE() << "expected an error when running /no/such/file";
} catch (const SubprocessSpawnError& ex) {
EXPECT_EQ(ENOENT, ex.errnoValue());
}
});
}
TEST(ParentDeathSubprocessTest, ParentDeathSignal) { TEST(ParentDeathSubprocessTest, ParentDeathSignal) {
// Find out where we are. // Find out where we are.
static constexpr size_t pathLength = 2048; static constexpr size_t pathLength = 2048;
...@@ -144,4 +229,3 @@ TEST(CommunicateSubprocessTest, Duplex) { ...@@ -144,4 +229,3 @@ TEST(CommunicateSubprocessTest, Duplex) {
EXPECT_EQ(std::string::npos, p.first.find_first_not_of('X')); EXPECT_EQ(std::string::npos, p.first.find_first_not_of('X'));
proc.waitChecked(); proc.waitChecked();
} }
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment