36#ifndef BITCOIN_UTIL_SUBPROCESS_H
37#define BITCOIN_UTIL_SUBPROCESS_H
49#include <initializer_list>
73 #include <sys/types.h>
81 #define subprocess_close _close
82 #define subprocess_fileno _fileno
83 #define subprocess_open _open
84 #define subprocess_write _write
86 #define subprocess_close close
87 #define subprocess_fileno fileno
88 #define subprocess_open open
89 #define subprocess_write write
162 OSError(
const std::string& err_msg,
int err_code):
171 inline void quote_argument(
const std::wstring &argument, std::wstring &command_line,
180 if (force ==
false && argument.empty() ==
false &&
181 argument.find_first_of(L
" \t\n\v") == argument.npos) {
182 command_line.append(argument);
185 command_line.push_back(L
'"');
187 for (
auto it = argument.begin();; ++it) {
188 unsigned number_backslashes = 0;
190 while (it != argument.end() && *it == L
'\\') {
192 ++number_backslashes;
195 if (it == argument.end()) {
203 command_line.append(number_backslashes * 2, L
'\\');
206 else if (*it == L
'"') {
213 command_line.append(number_backslashes * 2 + 1, L
'\\');
214 command_line.push_back(*it);
222 command_line.append(number_backslashes, L
'\\');
223 command_line.push_back(*it);
227 command_line.push_back(L
'"');
231 inline std::string get_last_error(DWORD errorMessageID)
233 if (errorMessageID == 0)
234 return std::string();
236 LPSTR messageBuffer =
nullptr;
237 size_t size = FormatMessageA(
238 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
239 FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK,
240 NULL, errorMessageID, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
241 (LPSTR)&messageBuffer, 0, NULL);
243 std::string message(messageBuffer, size);
245 LocalFree(messageBuffer);
250 inline FILE *file_from_handle(HANDLE h,
const char *mode)
254 throw OSError(
"invalid_mode", 0);
257 if (mode[0] ==
'w') {
260 else if (mode[0] ==
'r') {
264 throw OSError(
"file_from_handle", 0);
267 int os_fhandle = _open_osfhandle((intptr_t)h, md);
268 if (os_fhandle == -1) {
270 throw OSError(
"_open_osfhandle", 0);
273 FILE *fp = _fdopen(os_fhandle, mode);
282 inline void configure_pipe(HANDLE* read_handle, HANDLE* write_handle, HANDLE* child_handle)
284 SECURITY_ATTRIBUTES saAttr;
287 saAttr.nLength =
sizeof(SECURITY_ATTRIBUTES);
288 saAttr.bInheritHandle = TRUE;
289 saAttr.lpSecurityDescriptor = NULL;
292 if (!CreatePipe(read_handle, write_handle, &saAttr,0))
293 throw OSError(
"CreatePipe", 0);
296 if (!SetHandleInformation(*child_handle, HANDLE_FLAG_INHERIT, 0))
297 throw OSError(
"SetHandleInformation", 0);
310 static inline std::vector<std::string>
311 split(
const std::string& str,
const std::string& delims=
" \t")
313 std::vector<std::string> res;
317 auto pos = str.find_first_of(delims,
init);
318 if (pos == std::string::npos) {
319 res.emplace_back(str.substr(
init, str.length()));
322 res.emplace_back(str.substr(
init, pos -
init));
344 int flags = fcntl(fd, F_GETFD, 0);
346 throw OSError(
"fcntl F_GETFD failed", errno);
348 if (set)
flags |= FD_CLOEXEC;
349 else flags &= ~FD_CLOEXEC;
350 if (fcntl(fd, F_SETFD,
flags) == -1) {
351 throw OSError(
"fcntl F_SETFD failed", errno);
369 int res = pipe(pipe_fds);
371 throw OSError(
"pipe failure", errno);
377 return std::make_pair(pipe_fds[0], pipe_fds[1]);
394 int write_n(
int fd,
const char* buf,
size_t length)
397 while (nwritten < length) {
399 if (written == -1)
return -1;
424 return (
int)fread(buf, 1, read_upto, fp);
431 int read_bytes = read(fd, buf + rbytes, read_upto - rbytes);
432 if (read_bytes == -1) {
433 if (errno == EINTR) {
434 if (eintr_cnter >= 50)
return -1;
440 if (read_bytes == 0)
return rbytes;
442 rbytes += read_bytes;
462 static inline int read_all(FILE* fp, std::vector<char>& buf)
464 auto buffer = buf.data();
465 int total_bytes_read = 0;
466 int fill_sz = buf.size();
471 if (rd_bytes == -1) {
472 if (total_bytes_read == 0)
return -1;
475 }
else if (rd_bytes == fill_sz) {
476 const auto orig_sz = buf.size();
477 const auto new_sz = orig_sz * 2;
479 fill_sz = new_sz - orig_sz;
483 total_bytes_read += rd_bytes;
484 buffer += total_bytes_read;
487 total_bytes_read += rd_bytes;
492 buf.erase(buf.begin()+total_bytes_read, buf.end());
493 return total_bytes_read;
516 ret = waitpid(pid, &status, 0);
517 if (
ret == -1)
break;
518 if (
ret == 0)
continue;
519 return std::make_pair(
ret, status);
522 return std::make_pair(
ret, status);
556 template <
typename T>
590 explicit input(
const char* filename) {
592 if (fd == -1)
throw OSError(
"File not found: ", errno);
596 assert (typ ==
PIPE &&
"STDOUT/STDERR not allowed");
625 if (fd == -1)
throw OSError(
"File not found: ", errno);
629 assert (typ ==
PIPE &&
"STDOUT/STDERR not allowed");
654 explicit error(
const char* filename) {
656 if (fd == -1)
throw OSError(
"File not found: ", errno);
780 int send(
const char*
msg,
size_t length);
781 int send(
const std::vector<char>&
msg);
783 std::pair<OutBuffer, ErrBuffer>
communicate(
const char*
msg,
size_t length);
792 const char*
msg,
size_t length);
882 HANDLE g_hChildStd_IN_Rd =
nullptr;
883 HANDLE g_hChildStd_IN_Wr =
nullptr;
884 HANDLE g_hChildStd_OUT_Rd =
nullptr;
885 HANDLE g_hChildStd_OUT_Wr =
nullptr;
886 HANDLE g_hChildStd_ERR_Rd =
nullptr;
887 HANDLE g_hChildStd_ERR_Wr =
nullptr;
935 template <
typename... Args>
936 Popen(std::initializer_list<const char*> cmd_args, Args&& ...
args)
938 vargs_.insert(
vargs_.end(), cmd_args.begin(), cmd_args.end());
947 template <
typename... Args>
960 int wait() noexcept(false);
1000 template <
typename F,
typename... Args>
1010 HANDLE process_handle_;
1011 std::future<void> cleanup_future_;
1030template <
typename F,
typename... Args>
1043 cargv_.push_back(
nullptr);
1049 int ret = WaitForSingleObject(process_handle_, INFINITE);
1052 if (
ret != WAIT_OBJECT_0) {
1053 throw OSError(
"Unexpected return code from WaitForSingleObject", 0);
1058 if (FALSE == GetExitCodeProcess(process_handle_, &dretcode_))
1059 throw OSError(
"Failed during call to GetExitCodeProcess", 0);
1061 CloseHandle(process_handle_);
1063 return (
int)dretcode_;
1068 if (errno != ECHILD)
throw OSError(
"waitpid failed", errno);
1071 if (WIFEXITED(status))
return WEXITSTATUS(status);
1072 if (WIFSIGNALED(status))
return WTERMSIG(status);
1083 this->
vargs_.insert(this->
vargs_.begin(), this->exe_name_);
1088 std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
1089 std::wstring argument;
1090 std::wstring command_line;
1091 bool first_arg =
true;
1093 for (
auto arg : this->
vargs_) {
1095 command_line += L
" ";
1099 argument = converter.from_bytes(arg);
1100 util::quote_argument(argument, command_line,
false);
1104 wchar_t *szCmdline =
new wchar_t[command_line.size() + 1];
1105 wcscpy_s(szCmdline, command_line.size() + 1, command_line.c_str());
1106 PROCESS_INFORMATION piProcInfo;
1107 STARTUPINFOW siStartInfo;
1108 BOOL bSuccess = FALSE;
1109 DWORD creation_flags = CREATE_UNICODE_ENVIRONMENT | CREATE_NO_WINDOW;
1112 ZeroMemory(&piProcInfo,
sizeof(PROCESS_INFORMATION));
1117 ZeroMemory(&siStartInfo,
sizeof(STARTUPINFOW));
1118 siStartInfo.cb =
sizeof(STARTUPINFOW);
1120 siStartInfo.hStdError = this->
stream_.g_hChildStd_ERR_Wr;
1121 siStartInfo.hStdOutput = this->
stream_.g_hChildStd_OUT_Wr;
1122 siStartInfo.hStdInput = this->
stream_.g_hChildStd_IN_Rd;
1124 siStartInfo.dwFlags |= STARTF_USESTDHANDLES;
1127 bSuccess = CreateProcessW(NULL,
1140 DWORD errorMessageID = ::GetLastError();
1141 throw CalledProcessError(
"CreateProcess failed: " + util::get_last_error(errorMessageID), errorMessageID);
1144 CloseHandle(piProcInfo.hThread);
1150 this->process_handle_ = piProcInfo.hProcess;
1152 this->cleanup_future_ = std::async(std::launch::async, [
this] {
1153 WaitForSingleObject(this->process_handle_, INFINITE);
1155 CloseHandle(this->
stream_.g_hChildStd_ERR_Wr);
1156 CloseHandle(this->
stream_.g_hChildStd_OUT_Wr);
1157 CloseHandle(this->
stream_.g_hChildStd_IN_Rd);
1169 int err_rd_pipe, err_wr_pipe;
1183 throw OSError(
"fork failed", errno);
1206 FILE* err_fp = fdopen(err_rd_pipe,
"r");
1209 throw OSError(
"fdopen failed", errno);
1214 if (read_bytes || strlen(err_buf)) {
1223 }
catch (std::exception& exp) {
1249 if (err.deferred_) {
1253 throw std::runtime_error(
"Set output before redirecting error to output");
1267 if (stream.write_to_parent_ == 0)
1270 if (stream.err_write_ == 0 || stream.err_write_ == 1)
1271 stream.err_write_ = dup(stream.err_write_);
1275 auto _dup2_ = [](
int fd,
int to_fd) {
1285 }
else if(fd != -1) {
1286 int res = dup2(fd, to_fd);
1287 if (res == -1)
throw OSError(
"dup2 failed", errno);
1292 _dup2_(stream.read_from_parent_, 0);
1293 _dup2_(stream.write_to_parent_, 1);
1294 _dup2_(stream.err_write_, 2);
1297 if (stream.read_from_parent_ != -1 && stream.read_from_parent_ > 2)
1300 if (stream.write_to_parent_ != -1 && stream.write_to_parent_ > 2)
1303 if (stream.err_write_ != -1 && stream.err_write_ > 2)
1309 if (sys_ret == -1)
throw OSError(
"execve failed", errno);
1311 }
catch (
const OSError& exp) {
1314 std::string err_msg(exp.what());
1321 _exit (EXIT_FAILURE);
1329 util::configure_pipe(&this->g_hChildStd_IN_Rd, &this->g_hChildStd_IN_Wr, &this->g_hChildStd_IN_Wr);
1330 this->
input(util::file_from_handle(this->g_hChildStd_IN_Wr,
"w"));
1333 util::configure_pipe(&this->g_hChildStd_OUT_Rd, &this->g_hChildStd_OUT_Wr, &this->g_hChildStd_OUT_Rd);
1334 this->
output(util::file_from_handle(this->g_hChildStd_OUT_Rd,
"r"));
1337 util::configure_pipe(&this->g_hChildStd_ERR_Rd, &this->g_hChildStd_ERR_Wr, &this->g_hChildStd_ERR_Rd);
1338 this->
error(util::file_from_handle(this->g_hChildStd_ERR_Rd,
"r"));
1348 for (
auto& h : handles) {
1349 if (h ==
nullptr)
continue;
1350 setvbuf(h,
nullptr, _IONBF, BUFSIZ);
1366 inline std::pair<OutBuffer, ErrBuffer>
1374 const int len_conv = length;
1381 int wbytes = std::fwrite(
msg,
sizeof(
char), length,
stream_->
input());
1382 if (wbytes < len_conv) {
1383 if (errno != EPIPE && errno != EINVAL) {
1384 throw OSError(
"fwrite error", errno);
1401 throw OSError(
"read to obuf failed", errno);
1418 throw OSError(
"read to ebuf failed", errno);
1425 return std::make_pair(std::move(obuf), std::move(ebuf));
1432 inline std::pair<OutBuffer, ErrBuffer>
1437 std::future<int> out_fut, err_fut;
1438 const int length_conv = length;
1443 out_fut = std::async(std::launch::async,
1451 err_fut = std::async(std::launch::async,
1458 int wbytes = std::fwrite(
msg,
sizeof(
char), length,
stream_->
input());
1459 if (wbytes < length_conv) {
1460 if (errno != EPIPE && errno != EINVAL) {
1461 throw OSError(
"fwrite error", errno);
1468 if (out_fut.valid()) {
1469 int res = out_fut.get();
1470 if (res != -1) obuf.
length = res;
1473 if (err_fut.valid()) {
1474 int res = err_fut.get();
1475 if (res != -1) ebuf.
length = res;
1479 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.