36#ifndef BITCOIN_UTIL_SUBPROCESS_H
37#define BITCOIN_UTIL_SUBPROCESS_H
49#include <initializer_list>
67 #include <sys/types.h>
75 #define subprocess_close _close
76 #define subprocess_fileno _fileno
77 #define subprocess_open _open
78 #define subprocess_write _write
80 #define subprocess_close close
81 #define subprocess_fileno fileno
82 #define subprocess_open open
83 #define subprocess_write write
156 OSError(
const std::string& err_msg,
int err_code):
165 inline void quote_argument(
const std::string &argument, std::string &command_line,
168 constexpr char quote =
'"';
169 constexpr char backslash =
'\\';
177 if (force ==
false && argument.empty() ==
false &&
178 argument.find_first_of(
" \t\n\v") == argument.npos) {
179 command_line.append(argument);
182 command_line.push_back(quote);
184 for (
auto it = argument.begin();; ++it) {
185 unsigned number_backslashes = 0;
187 while (it != argument.end() && *it == backslash) {
189 ++number_backslashes;
192 if (it == argument.end()) {
200 command_line.append(number_backslashes * 2, backslash);
203 else if (*it == quote) {
210 command_line.append(number_backslashes * 2 + 1, backslash);
211 command_line.push_back(*it);
219 command_line.append(number_backslashes, backslash);
220 command_line.push_back(*it);
224 command_line.push_back(quote);
228 inline std::string get_last_error(DWORD errorMessageID)
230 if (errorMessageID == 0)
231 return std::string();
233 LPSTR messageBuffer =
nullptr;
234 size_t size = FormatMessageA(
235 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
236 FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK,
237 NULL, errorMessageID, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
238 (LPSTR)&messageBuffer, 0, NULL);
240 std::string message(messageBuffer, size);
242 LocalFree(messageBuffer);
247 inline FILE *file_from_handle(HANDLE h,
const char *mode)
251 throw OSError(
"invalid_mode", 0);
254 if (mode[0] ==
'w') {
257 else if (mode[0] ==
'r') {
261 throw OSError(
"file_from_handle", 0);
264 int os_fhandle = _open_osfhandle((intptr_t)h, md);
265 if (os_fhandle == -1) {
267 throw OSError(
"_open_osfhandle", 0);
270 FILE *fp = _fdopen(os_fhandle, mode);
279 inline void configure_pipe(HANDLE* read_handle, HANDLE* write_handle, HANDLE* child_handle)
281 SECURITY_ATTRIBUTES saAttr;
284 saAttr.nLength =
sizeof(SECURITY_ATTRIBUTES);
285 saAttr.bInheritHandle = TRUE;
286 saAttr.lpSecurityDescriptor = NULL;
289 if (!CreatePipe(read_handle, write_handle, &saAttr,0))
290 throw OSError(
"CreatePipe", 0);
293 if (!SetHandleInformation(*child_handle, HANDLE_FLAG_INHERIT, 0))
294 throw OSError(
"SetHandleInformation", 0);
307 static inline std::vector<std::string>
308 split(
const std::string& str,
const std::string& delims=
" \t")
310 std::vector<std::string> res;
314 auto pos = str.find_first_of(delims,
init);
315 if (pos == std::string::npos) {
316 res.emplace_back(str.substr(
init, str.length()));
319 res.emplace_back(str.substr(
init, pos -
init));
341 int flags = fcntl(fd, F_GETFD, 0);
343 throw OSError(
"fcntl F_GETFD failed", errno);
345 if (set)
flags |= FD_CLOEXEC;
346 else flags &= ~FD_CLOEXEC;
347 if (fcntl(fd, F_SETFD,
flags) == -1) {
348 throw OSError(
"fcntl F_SETFD failed", errno);
366 int res = pipe(pipe_fds);
368 throw OSError(
"pipe failure", errno);
374 return std::make_pair(pipe_fds[0], pipe_fds[1]);
391 int write_n(
int fd,
const char* buf,
size_t length)
394 while (nwritten < length) {
396 if (written == -1)
return -1;
421 return (
int)fread(buf, 1, read_upto, fp);
428 int read_bytes = read(fd, buf + rbytes, read_upto - rbytes);
429 if (read_bytes == -1) {
430 if (errno == EINTR) {
431 if (eintr_cnter >= 50)
return -1;
437 if (read_bytes == 0)
return rbytes;
439 rbytes += read_bytes;
459 static inline int read_all(FILE* fp, std::vector<char>& buf)
461 auto buffer = buf.data();
462 int total_bytes_read = 0;
463 int fill_sz = buf.size();
468 if (rd_bytes == -1) {
469 if (total_bytes_read == 0)
return -1;
472 }
else if (rd_bytes == fill_sz) {
473 const auto orig_sz = buf.size();
474 const auto new_sz = orig_sz * 2;
476 fill_sz = new_sz - orig_sz;
480 total_bytes_read += rd_bytes;
481 buffer += total_bytes_read;
484 total_bytes_read += rd_bytes;
489 buf.erase(buf.begin()+total_bytes_read, buf.end());
490 return total_bytes_read;
513 ret = waitpid(pid, &status, 0);
514 if (
ret == -1)
break;
515 if (
ret == 0)
continue;
516 return std::make_pair(
ret, status);
519 return std::make_pair(
ret, status);
553 template <
typename T>
587 explicit input(
const char* filename) {
589 if (fd == -1)
throw OSError(
"File not found: ", errno);
593 assert (typ ==
PIPE &&
"STDOUT/STDERR not allowed");
622 if (fd == -1)
throw OSError(
"File not found: ", errno);
626 assert (typ ==
PIPE &&
"STDOUT/STDERR not allowed");
651 explicit error(
const char* filename) {
653 if (fd == -1)
throw OSError(
"File not found: ", errno);
777 int send(
const char*
msg,
size_t length);
778 int send(
const std::vector<char>&
msg);
780 std::pair<OutBuffer, ErrBuffer>
communicate(
const char*
msg,
size_t length);
789 const char*
msg,
size_t length);
879 HANDLE g_hChildStd_IN_Rd =
nullptr;
880 HANDLE g_hChildStd_IN_Wr =
nullptr;
881 HANDLE g_hChildStd_OUT_Rd =
nullptr;
882 HANDLE g_hChildStd_OUT_Wr =
nullptr;
883 HANDLE g_hChildStd_ERR_Rd =
nullptr;
884 HANDLE g_hChildStd_ERR_Wr =
nullptr;
932 template <
typename... Args>
933 Popen(std::initializer_list<const char*> cmd_args, Args&& ...
args)
935 vargs_.insert(
vargs_.end(), cmd_args.begin(), cmd_args.end());
944 template <
typename... Args>
957 int wait() noexcept(false);
997 template <
typename F,
typename... Args>
1007 HANDLE process_handle_;
1008 std::future<void> cleanup_future_;
1027template <
typename F,
typename... Args>
1040 cargv_.push_back(
nullptr);
1046 int ret = WaitForSingleObject(process_handle_, INFINITE);
1049 if (
ret != WAIT_OBJECT_0) {
1050 throw OSError(
"Unexpected return code from WaitForSingleObject", 0);
1055 if (FALSE == GetExitCodeProcess(process_handle_, &dretcode_))
1056 throw OSError(
"Failed during call to GetExitCodeProcess", 0);
1058 CloseHandle(process_handle_);
1060 return (
int)dretcode_;
1065 if (errno != ECHILD)
throw OSError(
"waitpid failed", errno);
1068 if (WIFEXITED(status))
return WEXITSTATUS(status);
1069 if (WIFSIGNALED(status))
return WTERMSIG(status);
1080 this->
vargs_.insert(this->
vargs_.begin(), this->exe_name_);
1085 std::string argument;
1086 std::string command_line;
1087 bool first_arg =
true;
1089 for (
auto arg : this->
vargs_) {
1091 command_line +=
" ";
1096 util::quote_argument(argument, command_line,
false);
1100 char *szCmdline =
new char[command_line.size() + 1];
1101 strcpy_s(szCmdline, command_line.size() + 1, command_line.c_str());
1102 PROCESS_INFORMATION piProcInfo;
1103 STARTUPINFOA siStartInfo;
1104 BOOL bSuccess = FALSE;
1105 DWORD creation_flags = CREATE_NO_WINDOW;
1108 ZeroMemory(&piProcInfo,
sizeof(PROCESS_INFORMATION));
1113 ZeroMemory(&siStartInfo,
sizeof(STARTUPINFOA));
1114 siStartInfo.cb =
sizeof(STARTUPINFOA);
1116 siStartInfo.hStdError = this->
stream_.g_hChildStd_ERR_Wr;
1117 siStartInfo.hStdOutput = this->
stream_.g_hChildStd_OUT_Wr;
1118 siStartInfo.hStdInput = this->
stream_.g_hChildStd_IN_Rd;
1120 siStartInfo.dwFlags |= STARTF_USESTDHANDLES;
1123 bSuccess = CreateProcessA(NULL,
1136 DWORD errorMessageID = ::GetLastError();
1137 throw CalledProcessError(
"CreateProcess failed: " + util::get_last_error(errorMessageID), errorMessageID);
1140 CloseHandle(piProcInfo.hThread);
1146 this->process_handle_ = piProcInfo.hProcess;
1148 this->cleanup_future_ = std::async(std::launch::async, [
this] {
1149 WaitForSingleObject(this->process_handle_, INFINITE);
1151 CloseHandle(this->
stream_.g_hChildStd_ERR_Wr);
1152 CloseHandle(this->
stream_.g_hChildStd_OUT_Wr);
1153 CloseHandle(this->
stream_.g_hChildStd_IN_Rd);
1165 int err_rd_pipe, err_wr_pipe;
1179 throw OSError(
"fork failed", errno);
1202 FILE* err_fp = fdopen(err_rd_pipe,
"r");
1205 throw OSError(
"fdopen failed", errno);
1210 if (read_bytes || strlen(err_buf)) {
1219 }
catch (std::exception& exp) {
1245 if (err.deferred_) {
1249 throw std::runtime_error(
"Set output before redirecting error to output");
1263 if (stream.write_to_parent_ == 0)
1266 if (stream.err_write_ == 0 || stream.err_write_ == 1)
1267 stream.err_write_ = dup(stream.err_write_);
1271 auto _dup2_ = [](
int fd,
int to_fd) {
1281 }
else if(fd != -1) {
1282 int res = dup2(fd, to_fd);
1283 if (res == -1)
throw OSError(
"dup2 failed", errno);
1288 _dup2_(stream.read_from_parent_, 0);
1289 _dup2_(stream.write_to_parent_, 1);
1290 _dup2_(stream.err_write_, 2);
1293 if (stream.read_from_parent_ != -1 && stream.read_from_parent_ > 2)
1296 if (stream.write_to_parent_ != -1 && stream.write_to_parent_ > 2)
1299 if (stream.err_write_ != -1 && stream.err_write_ > 2)
1305 if (sys_ret == -1)
throw OSError(
"execve failed", errno);
1307 }
catch (
const OSError& exp) {
1310 std::string err_msg(exp.what());
1317 _exit (EXIT_FAILURE);
1325 util::configure_pipe(&this->g_hChildStd_IN_Rd, &this->g_hChildStd_IN_Wr, &this->g_hChildStd_IN_Wr);
1326 this->
input(util::file_from_handle(this->g_hChildStd_IN_Wr,
"w"));
1329 util::configure_pipe(&this->g_hChildStd_OUT_Rd, &this->g_hChildStd_OUT_Wr, &this->g_hChildStd_OUT_Rd);
1330 this->
output(util::file_from_handle(this->g_hChildStd_OUT_Rd,
"r"));
1333 util::configure_pipe(&this->g_hChildStd_ERR_Rd, &this->g_hChildStd_ERR_Wr, &this->g_hChildStd_ERR_Rd);
1334 this->
error(util::file_from_handle(this->g_hChildStd_ERR_Rd,
"r"));
1344 for (
auto& h : handles) {
1345 if (h ==
nullptr)
continue;
1346 setvbuf(h,
nullptr, _IONBF, BUFSIZ);
1362 inline std::pair<OutBuffer, ErrBuffer>
1370 const int len_conv = length;
1377 int wbytes = std::fwrite(
msg,
sizeof(
char), length,
stream_->
input());
1378 if (wbytes < len_conv) {
1379 if (errno != EPIPE && errno != EINVAL) {
1380 throw OSError(
"fwrite error", errno);
1397 throw OSError(
"read to obuf failed", errno);
1414 throw OSError(
"read to ebuf failed", errno);
1421 return std::make_pair(std::move(obuf), std::move(ebuf));
1428 inline std::pair<OutBuffer, ErrBuffer>
1433 std::future<int> out_fut, err_fut;
1434 const int length_conv = length;
1439 out_fut = std::async(std::launch::async,
1447 err_fut = std::async(std::launch::async,
1454 int wbytes = std::fwrite(
msg,
sizeof(
char), length,
stream_->
input());
1455 if (wbytes < length_conv) {
1456 if (errno != EPIPE && errno != EINVAL) {
1457 throw OSError(
"fwrite error", errno);
1464 if (out_fut.valid()) {
1465 int res = out_fut.get();
1466 if (res != -1) obuf.
length = res;
1469 if (err_fut.valid()) {
1470 int res = err_fut.get();
1471 if (res != -1) ebuf.
length = res;
1475 return std::make_pair(std::move(obuf), std::move(ebuf));
CalledProcessError(const std::string &error_msg, int retcode)
OSError(const std::string &err_msg, int err_code)
std::pair< OutBuffer, ErrBuffer > communicate(const char *msg, size_t length)
std::pair< OutBuffer, ErrBuffer > communicate(const std::string &msg)
void set_out_buf_cap(size_t cap)
Popen(std::initializer_list< const char * > cmd_args, Args &&...args)
std::vector< char * > cargv_
Popen(std::vector< std::string > vargs_, Args &&... args)
void execute_process() noexcept(false)
std::vector< std::string > vargs_
int send(const std::vector< char > &msg)
int send(const std::string &msg)
std::pair< OutBuffer, ErrBuffer > communicate()
std::pair< OutBuffer, ErrBuffer > communicate(const std::vector< char > &msg)
int retcode() const noexcept
int wait() noexcept(false)
void set_err_buf_cap(size_t cap)
int send(const char *msg, size_t length)
Child(Popen *p, int err_wr_pipe)
void set_err_buf_cap(size_t cap)
Communication(Streams *stream)
Communication(Communication &&)=default
void set_out_buf_cap(size_t cap)
int send(const char *msg, size_t length)
std::pair< OutBuffer, ErrBuffer > communicate(const char *msg, size_t length)
std::pair< OutBuffer, ErrBuffer > communicate_threaded(const char *msg, size_t length)
Communication & operator=(const Communication &)=delete
Communication(const Communication &)=delete
Communication & operator=(Communication &&)=default
std::pair< OutBuffer, ErrBuffer > communicate(const std::vector< char > &msg)
std::pair< OutBuffer, ErrBuffer > communicate(const std::vector< char > &msg)
int send(const std::vector< char > &msg)
void set_out_buf_cap(size_t cap)
void setup_comm_channels()
Streams(Streams &&)=default
std::pair< OutBuffer, ErrBuffer > communicate(const char *msg, size_t length)
void set_err_buf_cap(size_t cap)
std::shared_ptr< FILE > output_
std::shared_ptr< FILE > error_
Streams & operator=(const Streams &)=delete
int send(const char *msg, size_t length)
Streams(const Streams &)=delete
Streams & operator=(Streams &&)=default
std::shared_ptr< FILE > input_
#define T(expected, seed, data)
static int read_all(FILE *fp, std::vector< char > &buf)
static int read_atmost_n(FILE *fp, char *buf, size_t read_upto)
static void set_clo_on_exec(int fd, bool set=true)
static std::vector< std::string > split(const std::string &str, const std::string &delims=" \t")
static std::pair< int, int > wait_for_child_exit(int pid)
static std::pair< int, int > pipe_cloexec() noexcept(false)
static int write_n(int fd, const char *buf, size_t length)
static const size_t SP_MAX_ERR_BUF_SIZ
static const size_t DEFAULT_BUF_CAP_BYTES
void set_option(executable &&exe)
ArgumentDeducer(Popen *p)
error(const char *filename)
output(const char *filename)
string_arg(const char *arg)
string_arg(std::string &&arg)
string_arg(const std::string &arg)
#define subprocess_fileno
std::string SysErrorString(int err)
Return system error string from errno value.