25#error "platform_win.cpp is built on Windows only"
29#define _WIN32_WINNT 0x0A00
31#ifndef WIN32_LEAN_AND_MEAN
32#define WIN32_LEAN_AND_MEAN
64std::string forward_slashes(std::string s) {
65 for (std::size_t i = 0; i < s.size(); ++i)
66 if (s[i] ==
'\\') s[i] =
'/';
71std::string strip_trailing_sep(std::string s) {
72 while (s.size() > 1 && (s.back() ==
'/' || s.back() ==
'\\')) {
73 if (s.size() == 3 && s[1] ==
':')
break;
79bool stat64_of(
const std::string& p,
struct _stat64& st) {
80 if (p.empty())
return false;
81 const std::string q = strip_trailing_sep(p);
82 return ::_stat64(q.c_str(), &st) == 0;
86void ensure_winsock() {
90 ::WSAStartup(MAKEWORD(2, 2), &data);
98const char* temp_alphabet() {
return "abcdefghijklmnopqrstuvwxyz0123456789"; }
105bool fill_template(std::string& name,
const std::string& tmpl,
unsigned long long& state) {
106 const std::size_t n = tmpl.size();
107 if (n < 6 || tmpl.compare(n - 6, 6,
"XXXXXX") != 0)
return false;
109 const char* abc = temp_alphabet();
110 for (std::size_t i = n - 6; i < n; ++i) {
111 state = state * 6364136223846793005ULL + 1442695040888963407ULL;
112 name[i] = abc[(state >> 33) % 36];
117unsigned long long temp_seed() {
118 return (
static_cast<unsigned long long>(::GetTickCount64()) << 16) ^
119 static_cast<unsigned long long>(::GetCurrentProcessId()) ^
120 reinterpret_cast<unsigned long long>(&temp_seed);
128bool connect_within(SOCKET s,
const struct addrinfo* ai,
int millis,
int& err) {
130 ::ioctlsocket(s, FIONBIO, &nb);
133 if (::connect(s, ai->ai_addr,
static_cast<int>(ai->ai_addrlen)) == 0) {
136 err = ::WSAGetLastError();
137 if (err == WSAEWOULDBLOCK) {
144 tv.tv_sec = millis / 1000;
145 tv.tv_usec = (millis % 1000) * 1000;
146 const int pr = ::select(0,
nullptr, &wset, &eset, millis > 0 ? &tv :
nullptr);
149 int len =
sizeof(soerr);
150 ::getsockopt(s, SOL_SOCKET, SO_ERROR,
reinterpret_cast<char*
>(&soerr), &len);
151 if (soerr == 0 && FD_ISSET(s, &wset) && !FD_ISSET(s, &eset)) {
155 err = soerr != 0 ? soerr : WSAECONNREFUSED;
157 }
else if (pr == 0) {
160 err = ::WSAGetLastError();
165 ::ioctlsocket(s, FIONBIO, &nb);
169void set_timeouts_ms(SOCKET s, DWORD ms) {
170 ::setsockopt(s, SOL_SOCKET, SO_RCVTIMEO,
reinterpret_cast<const char*
>(&ms),
sizeof(ms));
171 ::setsockopt(s, SOL_SOCKET, SO_SNDTIMEO,
reinterpret_cast<const char*
>(&ms),
sizeof(ms));
181 const char* base = std::getenv(
"TMPDIR");
182 if (base && *base)
return strip_trailing_sep(forward_slashes(base));
183 char buf[MAX_PATH + 1];
184 const DWORD n = ::GetTempPathA(
sizeof(buf), buf);
185 if (n > 0 && n <
sizeof(buf))
return strip_trailing_sep(forward_slashes(std::string(buf, n)));
186 return std::string(
".");
190 const char* h = std::getenv(
"HOME");
191 if (h !=
nullptr && *h)
return forward_slashes(h);
192 const char* u = std::getenv(
"USERPROFILE");
193 if (u !=
nullptr && *u)
return forward_slashes(u);
194 return std::string();
199 return stat64_of(p, st) && (st.st_mode & _S_IFREG) != 0;
204 return stat64_of(p, st) && (st.st_mode & _S_IFDIR) != 0;
210 return stat64_of(p, st);
214 return !p.empty() && ::_access(strip_trailing_sep(p).c_str(), 2) == 0;
217bool stat_file(
const std::string& p, FileStat& out) {
219 if (!stat64_of(p, st))
return false;
220 out.size =
static_cast<long long>(st.st_size);
221 out.mtime =
static_cast<long long>(st.st_mtime);
222 out.is_dir = (st.st_mode & _S_IFDIR) != 0;
223 out.is_reg = (st.st_mode & _S_IFREG) != 0;
232 const char* raw = std::getenv(
"PATH");
233 if (raw ==
nullptr)
return std::string();
234 const std::string path(raw);
235 const std::size_t slash = name.find_last_of(
"/\\");
236 const bool has_ext = name.find(
'.', slash == std::string::npos ? 0 : slash + 1) != std::string::npos;
238 while (b <= path.size()) {
239 const std::size_t e = path.find(
';', b);
240 std::string dir = path.substr(b, e == std::string::npos ? std::string::npos : e - b);
241 if (dir.size() >= 2 && dir.front() ==
'"' && dir.back() ==
'"')
242 dir = dir.substr(1, dir.size() - 2);
243 const std::string base = forward_slashes(dir.empty() ? std::string(
".") : dir) +
"/" + name;
246 if (e == std::string::npos)
break;
249 return std::string();
253 std::vector<char> buf(MAX_PATH);
254 for (
int tries = 0; tries < 6; ++tries) {
255 const DWORD n = ::GetModuleFileNameA(
nullptr, &buf[0],
static_cast<DWORD
>(buf.size()));
256 if (n == 0)
return std::string();
257 if (n < buf.size())
return forward_slashes(std::string(&buf[0], n));
258 buf.resize(buf.size() * 2);
260 return std::string();
265 return ::_getcwd(buf,
sizeof(buf)) !=
nullptr ? forward_slashes(buf) : std::string();
272 ::GetNativeSystemInfo(&si);
273 switch (si.wProcessorArchitecture) {
274 case PROCESSOR_ARCHITECTURE_AMD64:
return "x86_64";
275 case PROCESSOR_ARCHITECTURE_ARM64:
return "aarch64";
276 case PROCESSOR_ARCHITECTURE_INTEL:
return "i686";
277 default:
return std::string();
282 return ::_mkdir(path.c_str()) == 0 || errno == EEXIST;
286 unsigned long long state = temp_seed();
288 for (
int attempt = 0; attempt < 100; ++attempt) {
289 if (!fill_template(name, tmpl, state))
return std::string();
290 if (::_mkdir(name.c_str()) == 0)
return name;
291 if (errno != EEXIST)
return std::string();
293 return std::string();
297 unsigned long long state = temp_seed();
299 for (
int attempt = 0; attempt < 100; ++attempt) {
300 if (!fill_template(name, tmpl, state))
return -1;
301 const int fd = ::_open(name.c_str(), _O_CREAT | _O_EXCL | _O_RDWR | _O_BINARY,
302 _S_IREAD | _S_IWRITE);
307 if (errno != EEXIST)
return -1;
312int dup_fd(
int fd) { return ::_dup(fd); }
314int dup2_fd(
int from,
int to) { return ::_dup2(from, to) == 0 ? to : -1; }
315int close_fd(
int fd) { return ::_close(fd); }
317bool remove_file(
const std::string& p) { return ::_unlink(p.c_str()) == 0; }
319bool rename_replace(
const std::string& from,
const std::string& to) {
320 return ::MoveFileExA(from.c_str(), to.c_str(),
321 MOVEFILE_REPLACE_EXISTING | MOVEFILE_COPY_ALLOWED) != 0;
332 const HANDLE h = ::FindFirstFileA((dir +
"/*").c_str(), &fd);
333 if (h != INVALID_HANDLE_VALUE) {
335 const std::string n(fd.cFileName);
336 if (n ==
"." || n ==
"..")
continue;
337 const std::string child = dir +
"/" + n;
338 const DWORD a = fd.dwFileAttributes;
339 if ((a & FILE_ATTRIBUTE_DIRECTORY) != 0) {
340 if ((a & FILE_ATTRIBUTE_REPARSE_POINT) != 0)
341 ::RemoveDirectoryA(child.c_str());
345 if ((a & FILE_ATTRIBUTE_READONLY) != 0)
346 ::SetFileAttributesA(child.c_str(), a & ~FILE_ATTRIBUTE_READONLY);
347 ::DeleteFileA(child.c_str());
349 }
while (::FindNextFileA(h, &fd));
352 ::RemoveDirectoryA(dir.c_str());
355long process_id() {
return static_cast<long>(::GetCurrentProcessId()); }
358 ULARGE_INTEGER avail;
359 if (!::GetDiskFreeSpaceExA(path.c_str(), &avail,
nullptr,
nullptr))
return -1;
360 const long long usable =
static_cast<long long>(avail.QuadPart);
361 return usable > 0 ? usable : -1;
366 ms.dwLength =
sizeof(ms);
367 if (!::GlobalMemoryStatusEx(&ms))
return -1.0;
368 return ms.ullAvailPhys > 0 ?
static_cast<double>(ms.ullAvailPhys) : -1.0;
371long long monotonic_millis() {
return static_cast<long long>(::GetTickCount64()); }
373void sleep_millis(
long millis) { ::Sleep(millis > 0 ?
static_cast<DWORD
>(millis) : 0); }
390void append_quoted(std::string& cmd,
const std::string& arg) {
391 if (!arg.empty() && arg.find_first_of(
" \t\n\v\"") == std::string::npos) {
396 for (std::size_t i = 0;; ++i) {
397 std::size_t backslashes = 0;
398 while (i < arg.size() && arg[i] ==
'\\') {
402 if (i == arg.size()) {
403 cmd.append(backslashes * 2,
'\\');
407 cmd.append(backslashes * 2 + 1,
'\\');
410 cmd.append(backslashes,
'\\');
417std::string command_line(
const std::vector<std::string>& argv) {
419 for (std::size_t i = 0; i < argv.size(); ++i) {
420 if (i > 0) cmd +=
' ';
421 append_quoted(cmd, argv[i]);
427HANDLE open_null(
bool write) {
428 SECURITY_ATTRIBUTES sa;
429 sa.nLength =
sizeof(sa);
430 sa.lpSecurityDescriptor =
nullptr;
431 sa.bInheritHandle = TRUE;
432 return ::CreateFileA(
"NUL", write ? GENERIC_WRITE : GENERIC_READ,
433 FILE_SHARE_READ | FILE_SHARE_WRITE, &sa, OPEN_EXISTING,
434 FILE_ATTRIBUTE_NORMAL,
nullptr);
438HANDLE inheritable_std(DWORD which,
bool write) {
439 const HANDLE h = ::GetStdHandle(which);
440 HANDLE dup =
nullptr;
441 if (h !=
nullptr && h != INVALID_HANDLE_VALUE &&
442 ::DuplicateHandle(::GetCurrentProcess(), h, ::GetCurrentProcess(), &dup, 0, TRUE,
443 DUPLICATE_SAME_ACCESS))
445 return open_null(write);
454bool start_child(
const std::vector<std::string>& argv, HANDLE in, HANDLE out, HANDLE err,
455 PROCESS_INFORMATION& pi) {
456 std::vector<HANDLE> list;
457 const HANDLE three[3] = {in, out, err};
458 for (
int i = 0; i < 3; ++i) {
460 for (std::size_t j = 0; j < list.size(); ++j) seen = seen || list[j] == three[i];
461 if (!seen) list.push_back(three[i]);
464 ::InitializeProcThreadAttributeList(
nullptr, 1, 0, &size);
465 std::vector<unsigned char> attrbuf(size);
466 LPPROC_THREAD_ATTRIBUTE_LIST attrs =
467 reinterpret_cast<LPPROC_THREAD_ATTRIBUTE_LIST
>(attrbuf.data());
468 if (!::InitializeProcThreadAttributeList(attrs, 1, 0, &size))
return false;
469 bool ok = ::UpdateProcThreadAttribute(attrs, 0, PROC_THREAD_ATTRIBUTE_HANDLE_LIST, &list[0],
470 list.size() *
sizeof(HANDLE),
nullptr,
nullptr) != 0;
473 std::memset(&si, 0,
sizeof(si));
474 si.StartupInfo.cb =
sizeof(si);
475 si.StartupInfo.dwFlags = STARTF_USESTDHANDLES;
476 si.StartupInfo.hStdInput = in;
477 si.StartupInfo.hStdOutput = out;
478 si.StartupInfo.hStdError = err;
479 si.lpAttributeList = attrs;
480 std::string cmd = command_line(argv);
481 std::vector<char> cmdbuf(cmd.begin(), cmd.end());
482 cmdbuf.push_back(
'\0');
483 std::memset(&pi, 0,
sizeof(pi));
484 ok = ::CreateProcessA(
nullptr, &cmdbuf[0],
nullptr,
nullptr, TRUE,
485 EXTENDED_STARTUPINFO_PRESENT,
nullptr,
nullptr,
486 &si.StartupInfo, &pi) != 0;
488 ::DeleteProcThreadAttributeList(attrs);
492int exit_code_of(HANDLE process) {
494 if (!::GetExitCodeProcess(process, &code))
return -1;
495 return static_cast<int>(code);
500ProcResult
capture(
const std::vector<std::string>& argv,
int timeoutSeconds,
bool mergeStderr) {
502 if (argv.empty())
return r;
504 SECURITY_ATTRIBUTES sa;
505 sa.nLength =
sizeof(sa);
506 sa.lpSecurityDescriptor =
nullptr;
507 sa.bInheritHandle = TRUE;
508 HANDLE rd =
nullptr, wr =
nullptr;
509 if (!::CreatePipe(&rd, &wr, &sa, 0))
return r;
510 ::SetHandleInformation(rd, HANDLE_FLAG_INHERIT, 0);
512 const HANDLE in = open_null(
false);
513 const HANDLE err = mergeStderr ? wr : open_null(
true);
514 PROCESS_INFORMATION pi;
515 const bool started = start_child(argv, in, wr, err, pi);
517 if (in != INVALID_HANDLE_VALUE) ::CloseHandle(in);
518 if (!mergeStderr && err != INVALID_HANDLE_VALUE) ::CloseHandle(err);
525 ::CloseHandle(pi.hThread);
527 const long long deadline =
540 if (!::PeekNamedPipe(rd,
nullptr, 0,
nullptr, &avail,
nullptr))
break;
543 const DWORD want = avail < sizeof(buf) ? avail : static_cast<DWORD>(
sizeof(buf));
544 if (!::ReadFile(rd, buf, want, &got,
nullptr))
break;
545 r.out.append(buf,
static_cast<std::size_t
>(got));
551 const DWORD nap = (left >= 0 && left < 20) ? static_cast<DWORD>(left) : 20;
552 ::WaitForSingleObject(pi.hProcess, nap);
557 ::TerminateProcess(pi.hProcess, 1);
558 ::WaitForSingleObject(pi.hProcess, INFINITE);
559 ::CloseHandle(pi.hProcess);
563 ::WaitForSingleObject(pi.hProcess, INFINITE);
564 r.exitCode = exit_code_of(pi.hProcess);
565 ::CloseHandle(pi.hProcess);
569int run_inherit(
const std::vector<std::string>& argv) {
570 if (argv.empty())
return -1;
571 const HANDLE in = inheritable_std(STD_INPUT_HANDLE,
false);
572 const HANDLE out = inheritable_std(STD_OUTPUT_HANDLE,
true);
573 const HANDLE err = inheritable_std(STD_ERROR_HANDLE,
true);
574 PROCESS_INFORMATION pi;
575 const bool started = start_child(argv, in, out, err, pi);
576 const HANDLE mine[3] = {in, out, err};
577 for (
int i = 0; i < 3; ++i)
578 if (mine[i] !=
nullptr && mine[i] != INVALID_HANDLE_VALUE) ::CloseHandle(mine[i]);
579 if (!started)
return 127;
580 ::CloseHandle(pi.hThread);
581 ::WaitForSingleObject(pi.hProcess, INFINITE);
582 const int code = exit_code_of(pi.hProcess);
583 ::CloseHandle(pi.hProcess);
597 if (argv.empty())
return false;
598 std::string cmd = util::command_line(argv);
599 std::vector<char> cmdbuf(cmd.begin(), cmd.end());
600 cmdbuf.push_back(
'\0');
602 std::memset(&si, 0,
sizeof(si));
604 PROCESS_INFORMATION pi;
605 std::memset(&pi, 0,
sizeof(pi));
606 if (!::CreateProcessA(
nullptr, &cmdbuf[0],
nullptr,
nullptr, FALSE,
607 DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP,
nullptr,
nullptr, &si, &pi))
609 ::CloseHandle(pi.hThread);
610 ::CloseHandle(pi.hProcess);
615 std::string& lastError) {
618 struct addrinfo hints;
619 std::memset(&hints, 0,
sizeof(hints));
620 hints.ai_family = AF_UNSPEC;
621 hints.ai_socktype = SOCK_STREAM;
622 struct addrinfo* res =
nullptr;
623 const std::string portStr = std::to_string(port);
624 if (::getaddrinfo(host.c_str(), portStr.c_str(), &hints, &res) != 0 || res ==
nullptr) {
626 return kInvalidSocket;
628 SOCKET s = INVALID_SOCKET;
629 lastError =
"connection refused";
630 for (
struct addrinfo* ai = res; ai !=
nullptr; ai = ai->ai_next) {
631 s = ::socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
632 if (s == INVALID_SOCKET)
continue;
634 if (connect_within(s, ai, connectMillis, err))
break;
635 lastError = err == WSAETIMEDOUT ? std::string(
"connect timed out") :
socket_error_text(err);
640 if (s == INVALID_SOCKET) {
642 return kInvalidSocket;
648 if (millis <= 0)
return;
649 set_timeouts_ms(
static_cast<SOCKET
>(s),
static_cast<DWORD
>(millis));
661 struct addrinfo hints;
662 std::memset(&hints, 0,
sizeof(hints));
663 hints.ai_family = AF_UNSPEC;
664 hints.ai_socktype = SOCK_STREAM;
665 struct addrinfo* res =
nullptr;
666 if (::getaddrinfo(host.c_str(), port.c_str(), &hints, &res) != 0 || res ==
nullptr) {
668 return kInvalidSocket;
670 const int ms = ioSeconds > 0 ?
static_cast<int>(ioSeconds * 1000.0) : 0;
671 SOCKET s = INVALID_SOCKET;
672 for (
struct addrinfo* ai = res; ai !=
nullptr; ai = ai->ai_next) {
673 s = ::socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
674 if (s == INVALID_SOCKET)
continue;
675 if (ms > 0) set_timeouts_ms(s,
static_cast<DWORD
>(ms));
677 if (connect_within(s, ai, ms, err))
break;
682 if (s == INVALID_SOCKET) {
684 return kInvalidSocket;
696 const SOCKET s = ::socket(AF_INET, SOCK_STREAM, 0);
697 if (s == INVALID_SOCKET) {
699 return kInvalidSocket;
701 struct sockaddr_in addr;
702 std::memset(&addr, 0,
sizeof(addr));
703 addr.sin_family = AF_INET;
704 addr.sin_addr.s_addr = htonl(INADDR_ANY);
705 addr.sin_port = htons(
static_cast<u_short
>(port));
706 if (::bind(s,
reinterpret_cast<struct sockaddr*
>(&addr),
sizeof(addr)) != 0) {
709 return kInvalidSocket;
711 if (::listen(s, backlog) != 0) {
714 return kInvalidSocket;
720 const SOCKET c = ::accept(
static_cast<SOCKET
>(listener),
nullptr,
nullptr);
721 return c == INVALID_SOCKET ? kInvalidSocket :
static_cast<socket_t>(c);
726 const SOCKET s = ::socket(AF_INET, SOCK_STREAM, 0);
727 if (s == INVALID_SOCKET) {
731 struct sockaddr_in addr;
732 std::memset(&addr, 0,
sizeof(addr));
733 addr.sin_family = AF_INET;
734 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
736 if (::bind(s,
reinterpret_cast<struct sockaddr*
>(&addr),
sizeof(addr)) != 0) {
741 int len =
sizeof(addr);
742 if (::getsockname(s,
reinterpret_cast<struct sockaddr*
>(&addr), &len) != 0) {
744 stage =
"getsockname";
747 const int port = ntohs(addr.sin_port);
754 const int k =
static_cast<int>(n > 0x7fffffff ? 0x7fffffff : n);
755 return static_cast<long>(::send(
static_cast<SOCKET
>(s), p, k, 0));
759 const int k =
static_cast<int>(n > 0x7fffffff ? 0x7fffffff : n);
760 return static_cast<long>(::recv(
static_cast<SOCKET
>(s), p, k, 0));
764 if (s != kInvalidSocket) ::closesocket(
static_cast<SOCKET
>(s));
770bool err_timed_out(
int e) {
return e == WSAETIMEDOUT || e == WSAEWOULDBLOCK; }
774 const DWORD n = ::FormatMessageA(
775 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
776 nullptr,
static_cast<DWORD
>(e), 0,
reinterpret_cast<LPSTR
>(&msg), 0,
nullptr);
777 std::string text = (n > 0 && msg !=
nullptr) ? std::string(msg, n) : std::string();
778 if (msg !=
nullptr) ::LocalFree(msg);
779 while (!text.empty() && (text.back() ==
'\r' || text.back() ==
'\n' || text.back() ==
' ' ||
782 if (text.empty()) text =
"socket error " + std::to_string(e);
int run_inherit(const std::vector< std::string > &argv)
Runs a command with the parent's stdout and stderr, e.g.
ProcResult capture(const std::vector< std::string > &argv, int timeoutSeconds, bool mergeStderr=false)
Runs a command, capturing stdout and discarding stderr.
Conservation laws of a layered queueing network, enumerated from its structure.
Running an external command and capturing its output, with a deadline.