36#ifndef BITCOIN_UTIL_SUBPROCESS_H
37#define BITCOIN_UTIL_SUBPROCESS_H
49#include <initializer_list>
58#if (defined _MSC_VER) || (defined __MINGW32__)
59 #define __USING_WINDOWS__
62#ifdef __USING_WINDOWS__
67#ifdef __USING_WINDOWS__
74 #define fileno _fileno
81 #include <sys/types.h>
154 OSError(
const std::string& err_msg,
int err_code):
162 inline void quote_argument(
const std::wstring &argument, std::wstring &command_line,
171 if (force ==
false && argument.empty() ==
false &&
172 argument.find_first_of(L
" \t\n\v\"") == argument.npos) {
173 command_line.append(argument);
176 command_line.push_back(L
'"');
178 for (
auto it = argument.begin();; ++it) {
179 unsigned number_backslashes = 0;
181 while (it != argument.end() && *it == L
'\\') {
183 ++number_backslashes;
186 if (it == argument.end()) {
194 command_line.append(number_backslashes * 2, L
'\\');
197 else if (*it == L
'"') {
204 command_line.append(number_backslashes * 2 + 1, L
'\\');
205 command_line.push_back(*it);
213 command_line.append(number_backslashes, L
'\\');
214 command_line.push_back(*it);
218 command_line.push_back(L
'"');
222#ifdef __USING_WINDOWS__
223 inline std::string get_last_error(DWORD errorMessageID)
225 if (errorMessageID == 0)
226 return std::string();
228 LPSTR messageBuffer =
nullptr;
229 size_t size = FormatMessageA(
230 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
231 FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK,
232 NULL, errorMessageID, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
233 (LPSTR)&messageBuffer, 0, NULL);
235 std::string message(messageBuffer, size);
237 LocalFree(messageBuffer);
242 inline FILE *file_from_handle(HANDLE h,
const char *mode)
246 throw OSError(
"invalid_mode", 0);
249 if (mode[0] ==
'w') {
252 else if (mode[0] ==
'r') {
256 throw OSError(
"file_from_handle", 0);
259 int os_fhandle = _open_osfhandle((intptr_t)h, md);
260 if (os_fhandle == -1) {
262 throw OSError(
"_open_osfhandle", 0);
265 FILE *fp = _fdopen(os_fhandle, mode);
268 throw OSError(
"_fdopen", 0);
274 inline void configure_pipe(HANDLE* read_handle, HANDLE* write_handle, HANDLE* child_handle)
276 SECURITY_ATTRIBUTES saAttr;
279 saAttr.nLength =
sizeof(SECURITY_ATTRIBUTES);
280 saAttr.bInheritHandle = TRUE;
281 saAttr.lpSecurityDescriptor = NULL;
284 if (!CreatePipe(read_handle, write_handle, &saAttr,0))
285 throw OSError(
"CreatePipe", 0);
288 if (!SetHandleInformation(*child_handle, HANDLE_FLAG_INHERIT, 0))
289 throw OSError(
"SetHandleInformation", 0);
302 static inline std::vector<std::string>
303 split(
const std::string& str,
const std::string& delims=
" \t")
305 std::vector<std::string> res;
309 auto pos = str.find_first_of(delims,
init);
310 if (pos == std::string::npos) {
311 res.emplace_back(str.substr(
init, str.length()));
314 res.emplace_back(str.substr(
init, pos -
init));
323#ifndef __USING_WINDOWS__
336 int flags = fcntl(fd, F_GETFD, 0);
337 if (set)
flags |= FD_CLOEXEC;
338 else flags &= ~FD_CLOEXEC;
340 fcntl(fd, F_SETFD,
flags);
357 int res = pipe(pipe_fds);
359 throw OSError(
"pipe failure", errno);
365 return std::make_pair(pipe_fds[0], pipe_fds[1]);
382 int write_n(
int fd,
const char* buf,
size_t length)
385 while (nwritten < length) {
386 int written = write(fd, buf + nwritten, length - nwritten);
387 if (written == -1)
return -1;
411#ifdef __USING_WINDOWS__
412 return (
int)fread(buf, 1, read_upto, fp);
419 int read_bytes = read(fd, buf + rbytes, read_upto - rbytes);
420 if (read_bytes == -1) {
421 if (errno == EINTR) {
422 if (eintr_cnter >= 50)
return -1;
428 if (read_bytes == 0)
return rbytes;
430 rbytes += read_bytes;
450 static inline int read_all(FILE* fp, std::vector<char>& buf)
452 auto buffer = buf.data();
453 int total_bytes_read = 0;
454 int fill_sz = buf.size();
459 if (rd_bytes == -1) {
460 if (total_bytes_read == 0)
return -1;
463 }
else if (rd_bytes == fill_sz) {
464 const auto orig_sz = buf.size();
465 const auto new_sz = orig_sz * 2;
467 fill_sz = new_sz - orig_sz;
471 total_bytes_read += rd_bytes;
472 buffer += total_bytes_read;
475 total_bytes_read += rd_bytes;
480 buf.erase(buf.begin()+total_bytes_read, buf.end());
481 return total_bytes_read;
484#ifndef __USING_WINDOWS__
504 ret = waitpid(pid, &status, 0);
505 if (
ret == -1)
break;
506 if (
ret == 0)
continue;
507 return std::make_pair(
ret, status);
510 return std::make_pair(
ret, status);
544 template <
typename T>
578 explicit input(
const char* filename) {
579 int fd = open(filename, O_RDONLY);
580 if (fd == -1)
throw OSError(
"File not found: ", errno);
584 assert (typ ==
PIPE &&
"STDOUT/STDERR not allowed");
585#ifndef __USING_WINDOWS__
612 int fd = open(filename, O_APPEND | O_CREAT | O_RDWR, 0640);
613 if (fd == -1)
throw OSError(
"File not found: ", errno);
617 assert (typ ==
PIPE &&
"STDOUT/STDERR not allowed");
618#ifndef __USING_WINDOWS__
642 explicit error(
const char* filename) {
643 int fd = open(filename, O_APPEND | O_CREAT | O_RDWR, 0640);
644 if (fd == -1)
throw OSError(
"File not found: ", errno);
650#ifndef __USING_WINDOWS__
763 int send(
const char*
msg,
size_t length);
764 int send(
const std::vector<char>&
msg);
766 std::pair<OutBuffer, ErrBuffer>
communicate(
const char*
msg,
size_t length);
775 const char*
msg,
size_t length);
861#ifdef __USING_WINDOWS__
862 HANDLE g_hChildStd_IN_Rd =
nullptr;
863 HANDLE g_hChildStd_IN_Wr =
nullptr;
864 HANDLE g_hChildStd_OUT_Rd =
nullptr;
865 HANDLE g_hChildStd_OUT_Wr =
nullptr;
866 HANDLE g_hChildStd_ERR_Rd =
nullptr;
867 HANDLE g_hChildStd_ERR_Wr =
nullptr;
915 template <
typename... Args>
928 template <
typename... Args>
929 Popen(std::initializer_list<const char*> cmd_args, Args&& ...
args)
931 vargs_.insert(
vargs_.end(), cmd_args.begin(), cmd_args.end());
940 template <
typename... Args>
953 int wait() noexcept(false);
993 template <
typename F,
typename... Args>
1002#ifdef __USING_WINDOWS__
1003 HANDLE process_handle_;
1004 std::future<void> cleanup_future_;
1025template <
typename F,
typename... Args>
1038 cargv_.push_back(
nullptr);
1043#ifdef __USING_WINDOWS__
1044 int ret = WaitForSingleObject(process_handle_, INFINITE);
1051 if (errno != ECHILD)
throw OSError(
"waitpid failed", errno);
1054 if (WIFEXITED(status))
return WEXITSTATUS(status);
1055 if (WIFSIGNALED(status))
return WTERMSIG(status);
1064#ifdef __USING_WINDOWS__
1066 this->
vargs_.insert(this->
vargs_.begin(), this->exe_name_);
1071 std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
1072 std::wstring argument;
1073 std::wstring command_line;
1075 for (
auto arg : this->
vargs_) {
1076 argument = converter.from_bytes(arg);
1078 command_line += L
" ";
1082 wchar_t *szCmdline =
new wchar_t[command_line.size() + 1];
1083 wcscpy_s(szCmdline, command_line.size() + 1, command_line.c_str());
1084 PROCESS_INFORMATION piProcInfo;
1085 STARTUPINFOW siStartInfo;
1086 BOOL bSuccess = FALSE;
1087 DWORD creation_flags = CREATE_UNICODE_ENVIRONMENT | CREATE_NO_WINDOW;
1090 ZeroMemory(&piProcInfo,
sizeof(PROCESS_INFORMATION));
1095 ZeroMemory(&siStartInfo,
sizeof(STARTUPINFOW));
1096 siStartInfo.cb =
sizeof(STARTUPINFOW);
1098 siStartInfo.hStdError = this->
stream_.g_hChildStd_ERR_Wr;
1099 siStartInfo.hStdOutput = this->
stream_.g_hChildStd_OUT_Wr;
1100 siStartInfo.hStdInput = this->
stream_.g_hChildStd_IN_Rd;
1102 siStartInfo.dwFlags |= STARTF_USESTDHANDLES;
1105 bSuccess = CreateProcessW(NULL,
1118 DWORD errorMessageID = ::GetLastError();
1119 throw CalledProcessError(
"CreateProcess failed: " + util::get_last_error(errorMessageID), errorMessageID);
1122 CloseHandle(piProcInfo.hThread);
1128 this->process_handle_ = piProcInfo.hProcess;
1130 this->cleanup_future_ = std::async(std::launch::async, [
this] {
1131 WaitForSingleObject(this->process_handle_, INFINITE);
1133 CloseHandle(this->
stream_.g_hChildStd_ERR_Wr);
1134 CloseHandle(this->
stream_.g_hChildStd_OUT_Wr);
1135 CloseHandle(this->
stream_.g_hChildStd_IN_Rd);
1147 int err_rd_pipe, err_wr_pipe;
1161 throw OSError(
"fork failed", errno);
1177 close (err_wr_pipe);
1185 fdopen(err_rd_pipe,
"r"),
1190 if (read_bytes || strlen(err_buf)) {
1199 }
catch (std::exception& exp) {
1225 if (err.deferred_) {
1229 throw std::runtime_error(
"Set output before redirecting error to output");
1238#ifndef __USING_WINDOWS__
1243 if (stream.write_to_parent_ == 0)
1246 if (stream.err_write_ == 0 || stream.err_write_ == 1)
1247 stream.err_write_ = dup(stream.err_write_);
1251 auto _dup2_ = [](
int fd,
int to_fd) {
1261 }
else if(fd != -1) {
1262 int res = dup2(fd, to_fd);
1263 if (res == -1)
throw OSError(
"dup2 failed", errno);
1268 _dup2_(stream.read_from_parent_, 0);
1269 _dup2_(stream.write_to_parent_, 1);
1270 _dup2_(stream.err_write_, 2);
1273 if (stream.read_from_parent_ != -1 && stream.read_from_parent_ > 2)
1274 close(stream.read_from_parent_);
1276 if (stream.write_to_parent_ != -1 && stream.write_to_parent_ > 2)
1277 close(stream.write_to_parent_);
1279 if (stream.err_write_ != -1 && stream.err_write_ > 2)
1280 close(stream.err_write_);
1285 if (sys_ret == -1)
throw OSError(
"execve failed", errno);
1287 }
catch (
const OSError& exp) {
1290 std::string err_msg(exp.what());
1297 _exit (EXIT_FAILURE);
1304#ifdef __USING_WINDOWS__
1305 util::configure_pipe(&this->g_hChildStd_IN_Rd, &this->g_hChildStd_IN_Wr, &this->g_hChildStd_IN_Wr);
1306 this->
input(util::file_from_handle(this->g_hChildStd_IN_Wr,
"w"));
1309 util::configure_pipe(&this->g_hChildStd_OUT_Rd, &this->g_hChildStd_OUT_Wr, &this->g_hChildStd_OUT_Rd);
1310 this->
output(util::file_from_handle(this->g_hChildStd_OUT_Rd,
"r"));
1313 util::configure_pipe(&this->g_hChildStd_ERR_Rd, &this->g_hChildStd_ERR_Wr, &this->g_hChildStd_ERR_Rd);
1314 this->
error(util::file_from_handle(this->g_hChildStd_ERR_Rd,
"r"));
1324 for (
auto& h : handles) {
1325 if (h ==
nullptr)
continue;
1326 setvbuf(h,
nullptr, _IONBF, BUFSIZ);
1342 inline std::pair<OutBuffer, ErrBuffer>
1350 const int len_conv = length;
1357 int wbytes = std::fwrite(
msg,
sizeof(
char), length,
stream_->
input());
1358 if (wbytes < len_conv) {
1359 if (errno != EPIPE && errno != EINVAL) {
1360 throw OSError(
"fwrite error", errno);
1377 throw OSError(
"read to obuf failed", errno);
1394 throw OSError(
"read to ebuf failed", errno);
1401 return std::make_pair(std::move(obuf), std::move(ebuf));
1408 inline std::pair<OutBuffer, ErrBuffer>
1413 std::future<int> out_fut, err_fut;
1414 const int length_conv = length;
1419 out_fut = std::async(std::launch::async,
1427 err_fut = std::async(std::launch::async,
1434 int wbytes = std::fwrite(
msg,
sizeof(
char), length,
stream_->
input());
1435 if (wbytes < length_conv) {
1436 if (errno != EPIPE && errno != EINVAL) {
1437 throw OSError(
"fwrite error", errno);
1444 if (out_fut.valid()) {
1445 int res = out_fut.get();
1446 if (res != -1) obuf.
length = res;
1449 if (err_fut.valid()) {
1450 int res = err_fut.get();
1451 if (res != -1) ebuf.
length = res;
1455 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
Popen(const std::string &cmd_args, Args &&...args)
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)
void operator=(const Communication &)=delete
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)
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()
std::pair< OutBuffer, ErrBuffer > communicate(const char *msg, size_t length)
void set_err_buf_cap(size_t cap)
void operator=(const Streams &)=delete
std::shared_ptr< FILE > output_
std::shared_ptr< FILE > error_
int send(const char *msg, size_t length)
std::shared_ptr< FILE > input_
#define T(expected, seed, data)
static int read_all(FILE *fp, std::vector< char > &buf)
void quote_argument(const std::wstring &argument, std::wstring &command_line, bool force)
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(std::string &&arg)
std::string SysErrorString(int err)
Return system error string from errno value.