LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
platform_win.cpp
Go to the documentation of this file.
1/*
2 * Copyright (c) 2012-2026, QORE Lab, Imperial College London
3 * All rights reserved.
4 */
5
6/**
7 * @file
8 * The Windows (mingw-w64, UCRT) definitions behind include/line/util/platform.h
9 * and the two subprocess runners of include/line/util/subprocess.h.
10 *
11 * Built only on WIN32, as the `line_mp_platform` archive. It is the ONE
12 * translation unit that includes <windows.h> and <winsock2.h>, so their macros
13 * never reach the engine's headers. Each function mirrors the POSIX inline of
14 * the same name; where Windows has no equivalent notion (a uid for
15 * `docker run --user`) the function says so through its return value, exactly
16 * as the header documents.
17 *
18 * Paths are handled in the ANSI code page throughout (the `A` entry points and
19 * the CRT), the same encoding the rest of the engine's narrow strings carry, and
20 * every path this file RETURNS uses '/' separators so call sites that join with
21 * "/" stay consistent.
22 */
23
24#ifndef _WIN32
25#error "platform_win.cpp is built on Windows only"
26#endif
27
28#ifndef _WIN32_WINNT
29#define _WIN32_WINNT 0x0A00
30#endif
31#ifndef WIN32_LEAN_AND_MEAN
32#define WIN32_LEAN_AND_MEAN
33#endif
34#ifndef NOMINMAX
35#define NOMINMAX
36#endif
37
38#include <winsock2.h>
39#include <ws2tcpip.h>
40#include <windows.h>
41
42#include <direct.h>
43#include <fcntl.h>
44#include <io.h>
45#include <sys/stat.h>
46#include <sys/types.h>
47
48#include <cerrno>
49#include <cstdio>
50#include <cstdlib>
51#include <cstring>
52#include <string>
53#include <vector>
54
55#include "line/util/platform.h"
57
58namespace line {
59namespace platform {
60
61namespace {
62
63/** '\\' to '/', in place. */
64std::string forward_slashes(std::string s) {
65 for (std::size_t i = 0; i < s.size(); ++i)
66 if (s[i] == '\\') s[i] = '/';
67 return s;
68}
69
70/** Drop trailing separators, keeping a drive root ("C:/") and "/" intact. */
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;
74 s.pop_back();
75 }
76 return s;
77}
78
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;
83}
84
85/** Winsock is initialised once per process, on first use, and never torn down. */
86void ensure_winsock() {
87 struct Init {
88 Init() {
89 WSADATA data;
90 ::WSAStartup(MAKEWORD(2, 2), &data);
91 }
92 };
93 static Init once;
94 (void)once;
95}
96
97/** The characters a temp-name template's XXXXXX is filled from. */
98const char* temp_alphabet() { return "abcdefghijklmnopqrstuvwxyz0123456789"; }
99
100/**
101 * Fill the trailing XXXXXX of `tmpl` from a per-call generator. The seed mixes
102 * the clock, the process id and the attempt number; uniqueness is enforced by
103 * the exclusive create, not by the name.
104 */
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;
108 name = tmpl;
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];
113 }
114 return true;
115}
116
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);
121}
122
123/**
124 * Connect `s` to `ai` within `millis` (not positive: no bound) with a
125 * non-blocking connect and select(). select() and not WSAPoll: WSAPoll did not
126 * report a refused connect at all before Windows 10 2004.
127 */
128bool connect_within(SOCKET s, const struct addrinfo* ai, int millis, int& err) {
129 u_long nb = 1;
130 ::ioctlsocket(s, FIONBIO, &nb);
131 bool ok = false;
132 err = 0;
133 if (::connect(s, ai->ai_addr, static_cast<int>(ai->ai_addrlen)) == 0) {
134 ok = true;
135 } else {
136 err = ::WSAGetLastError();
137 if (err == WSAEWOULDBLOCK) {
138 fd_set wset, eset;
139 FD_ZERO(&wset);
140 FD_ZERO(&eset);
141 FD_SET(s, &wset);
142 FD_SET(s, &eset);
143 struct timeval tv;
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);
147 if (pr > 0) {
148 int soerr = 0;
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)) {
152 ok = true;
153 err = 0;
154 } else {
155 err = soerr != 0 ? soerr : WSAECONNREFUSED;
156 }
157 } else if (pr == 0) {
158 err = WSAETIMEDOUT;
159 } else {
160 err = ::WSAGetLastError();
161 }
162 }
163 }
164 nb = 0;
165 ::ioctlsocket(s, FIONBIO, &nb);
166 return ok;
167}
168
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));
172}
173
174} // namespace
175
176char path_list_separator() { return ';'; }
177const char* null_device() { return "NUL"; }
178const char* exe_suffix() { return ".exe"; }
179
180std::string temp_root() {
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(".");
187}
188
189std::string home_dir() {
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();
195}
196
197bool is_regular_file(const std::string& p) {
198 struct _stat64 st;
199 return stat64_of(p, st) && (st.st_mode & _S_IFREG) != 0;
200}
201
202bool is_directory(const std::string& p) {
203 struct _stat64 st;
204 return stat64_of(p, st) && (st.st_mode & _S_IFDIR) != 0;
205}
206
207/** Windows has no execute bit: anything that exists may be run (or entered). */
208bool is_executable(const std::string& p) {
209 struct _stat64 st;
210 return stat64_of(p, st);
211}
212
213bool is_writable(const std::string& p) {
214 return !p.empty() && ::_access(strip_trailing_sep(p).c_str(), 2) == 0;
215}
216
217bool stat_file(const std::string& p, FileStat& out) {
218 struct _stat64 st;
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;
224 return true;
225}
226
227/**
228 * The first `dir/name` on PATH that is a regular file, trying `name.exe` too
229 * when `name` carries no extension, as cmd.exe resolves a bare command.
230 */
231std::string find_on_path(const std::string& name) {
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;
237 std::size_t b = 0;
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;
244 if (is_regular_file(base)) return base;
245 if (!has_ext && is_regular_file(base + ".exe")) return base + ".exe";
246 if (e == std::string::npos) break;
247 b = e + 1;
248 }
249 return std::string();
250}
251
252std::string self_exe_path() {
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);
259 }
260 return std::string();
261}
262
263std::string current_dir() {
264 char buf[4096];
265 return ::_getcwd(buf, sizeof(buf)) != nullptr ? forward_slashes(buf) : std::string();
266}
267
268std::string host_sysname() { return "Windows"; }
269
270std::string host_machine() {
271 SYSTEM_INFO si;
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();
278 }
279}
280
281bool make_dir_or_exists(const std::string& path) {
282 return ::_mkdir(path.c_str()) == 0 || errno == EEXIST;
283}
284
285std::string make_temp_dir(const std::string& tmpl) {
286 unsigned long long state = temp_seed();
287 std::string name;
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();
292 }
293 return std::string();
294}
295
296int make_temp_file(std::string& tmpl) {
297 unsigned long long state = temp_seed();
298 std::string name;
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);
303 if (fd >= 0) {
304 tmpl = name;
305 return fd;
306 }
307 if (errno != EEXIST) return -1;
308 }
309 return -1;
310}
311
312int dup_fd(int fd) { return ::_dup(fd); }
313/** POSIX dup2 returns the new descriptor; the CRT's _dup2 returns 0. */
314int dup2_fd(int from, int to) { return ::_dup2(from, to) == 0 ? to : -1; }
315int close_fd(int fd) { return ::_close(fd); }
316
317bool remove_file(const std::string& p) { return ::_unlink(p.c_str()) == 0; }
318
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;
322}
323
324/**
325 * Remove a directory and everything under it. A directory junction or symlink
326 * (a reparse point) is removed as an entry and NOT descended into, the Windows
327 * form of lstat's "do not follow". A read-only file is made writable first,
328 * since DeleteFile refuses it and unlink on POSIX would not care.
329 */
330void remove_tree(const std::string& dir) {
331 WIN32_FIND_DATAA fd;
332 const HANDLE h = ::FindFirstFileA((dir + "/*").c_str(), &fd);
333 if (h != INVALID_HANDLE_VALUE) {
334 do {
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());
342 else
343 remove_tree(child);
344 } else {
345 if ((a & FILE_ATTRIBUTE_READONLY) != 0)
346 ::SetFileAttributesA(child.c_str(), a & ~FILE_ATTRIBUTE_READONLY);
347 ::DeleteFileA(child.c_str());
348 }
349 } while (::FindNextFileA(h, &fd));
350 ::FindClose(h);
351 }
352 ::RemoveDirectoryA(dir.c_str());
353}
354
355long process_id() { return static_cast<long>(::GetCurrentProcessId()); }
356
357long long free_disk_bytes(const std::string& path) {
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;
362}
363
364double available_memory_bytes() {
365 MEMORYSTATUSEX ms;
366 ms.dwLength = sizeof(ms);
367 if (!::GlobalMemoryStatusEx(&ms)) return -1.0;
368 return ms.ullAvailPhys > 0 ? static_cast<double>(ms.ullAvailPhys) : -1.0;
369}
370
371long long monotonic_millis() { return static_cast<long long>(::GetTickCount64()); }
372
373void sleep_millis(long millis) { ::Sleep(millis > 0 ? static_cast<DWORD>(millis) : 0); }
374
375/** Docker Desktop maps the caller itself; there is no uid:gid to pass. */
376bool docker_user_spec(std::string& out) {
377 out.clear();
378 return false;
379}
380
381} // namespace platform
382
383namespace util {
384namespace {
385
386/**
387 * One argument quoted so CommandLineToArgvW and the CRT parse it back intact:
388 * backslashes are literal except before a quote, where they are doubled.
389 */
390void append_quoted(std::string& cmd, const std::string& arg) {
391 if (!arg.empty() && arg.find_first_of(" \t\n\v\"") == std::string::npos) {
392 cmd += arg;
393 return;
394 }
395 cmd += '"';
396 for (std::size_t i = 0;; ++i) {
397 std::size_t backslashes = 0;
398 while (i < arg.size() && arg[i] == '\\') {
399 ++i;
400 ++backslashes;
401 }
402 if (i == arg.size()) {
403 cmd.append(backslashes * 2, '\\');
404 break;
405 }
406 if (arg[i] == '"') {
407 cmd.append(backslashes * 2 + 1, '\\');
408 cmd += '"';
409 } else {
410 cmd.append(backslashes, '\\');
411 cmd += arg[i];
412 }
413 }
414 cmd += '"';
415}
416
417std::string command_line(const std::vector<std::string>& argv) {
418 std::string cmd;
419 for (std::size_t i = 0; i < argv.size(); ++i) {
420 if (i > 0) cmd += ' ';
421 append_quoted(cmd, argv[i]);
422 }
423 return cmd;
424}
425
426/** An inheritable handle on NUL, for a standard stream the child must not have. */
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);
435}
436
437/** An inheritable duplicate of this process's standard handle, or NUL. */
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))
444 return dup;
445 return open_null(write);
446}
447
448/**
449 * CreateProcess with EXACTLY the three standard handles inherited. The explicit
450 * handle list matters when two captures run on different threads: an ordinary
451 * bInheritHandles=TRUE would hand each child the other's pipe write end, and
452 * the first capture would then wait for EOF until the second child exited.
453 */
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) {
459 bool seen = false;
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]);
462 }
463 SIZE_T size = 0;
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;
471 if (ok) {
472 STARTUPINFOEXA si;
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;
487 }
488 ::DeleteProcThreadAttributeList(attrs);
489 return ok;
490}
491
492int exit_code_of(HANDLE process) {
493 DWORD code = 0;
494 if (!::GetExitCodeProcess(process, &code)) return -1;
495 return static_cast<int>(code);
496}
497
498} // namespace
499
500ProcResult capture(const std::vector<std::string>& argv, int timeoutSeconds, bool mergeStderr) {
501 ProcResult r;
502 if (argv.empty()) return r;
503
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);
511
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);
516 ::CloseHandle(wr);
517 if (in != INVALID_HANDLE_VALUE) ::CloseHandle(in);
518 if (!mergeStderr && err != INVALID_HANDLE_VALUE) ::CloseHandle(err);
519 if (!started) {
520 // execvp failing in the POSIX child reports 127; keep the same signal.
521 ::CloseHandle(rd);
522 r.exitCode = 127;
523 return r;
524 }
525 ::CloseHandle(pi.hThread);
526
527 const long long deadline =
528 timeoutSeconds > 0 ? platform::monotonic_millis() + timeoutSeconds * 1000LL : -1;
529 char buf[4096];
530 while (true) {
531 long long left = -1;
532 if (deadline >= 0) {
533 left = deadline - platform::monotonic_millis();
534 if (left <= 0) {
535 r.timedOut = true;
536 break;
537 }
538 }
539 DWORD avail = 0;
540 if (!::PeekNamedPipe(rd, nullptr, 0, nullptr, &avail, nullptr)) break; // every writer gone: EOF
541 if (avail > 0) {
542 DWORD got = 0;
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));
546 continue;
547 }
548 // Nothing buffered: wait a little on the process rather than spin. The
549 // loop still ends on EOF, not on exit, so output a grandchild holding
550 // the pipe writes after the child is gone is read, as on POSIX.
551 const DWORD nap = (left >= 0 && left < 20) ? static_cast<DWORD>(left) : 20;
552 ::WaitForSingleObject(pi.hProcess, nap);
553 }
554 ::CloseHandle(rd);
555
556 if (r.timedOut) {
557 ::TerminateProcess(pi.hProcess, 1);
558 ::WaitForSingleObject(pi.hProcess, INFINITE);
559 ::CloseHandle(pi.hProcess);
560 r.exitCode = -1;
561 return r;
562 }
563 ::WaitForSingleObject(pi.hProcess, INFINITE);
564 r.exitCode = exit_code_of(pi.hProcess);
565 ::CloseHandle(pi.hProcess);
566 return r;
567}
568
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);
584 return code;
585}
586
587} // namespace util
588
589namespace platform {
590
591/**
592 * Start `argv` detached from this console with no standard streams, the
593 * Windows form of the POSIX double fork. Like the POSIX version, success means
594 * the process was started, not that the program it names did what was asked.
595 */
596bool spawn_detached(const std::vector<std::string>& argv) {
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');
601 STARTUPINFOA si;
602 std::memset(&si, 0, sizeof(si));
603 si.cb = 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))
608 return false;
609 ::CloseHandle(pi.hThread);
610 ::CloseHandle(pi.hProcess);
611 return true;
612}
613
614socket_t tcp_connect(const std::string& host, int port, int connectMillis, ConnectFailure& why,
615 std::string& lastError) {
616 ensure_winsock();
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;
627 }
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;
633 int err = 0;
634 if (connect_within(s, ai, connectMillis, err)) break;
635 lastError = err == WSAETIMEDOUT ? std::string("connect timed out") : socket_error_text(err);
636 ::closesocket(s);
637 s = INVALID_SOCKET;
638 }
639 ::freeaddrinfo(res);
640 if (s == INVALID_SOCKET) {
642 return kInvalidSocket;
643 }
644 return static_cast<socket_t>(s);
645}
646
647void set_io_timeout(socket_t s, int millis) {
648 if (millis <= 0) return;
649 set_timeouts_ms(static_cast<SOCKET>(s), static_cast<DWORD>(millis));
650}
651
652/**
653 * The I/O timeouts are set first, as on POSIX. Winsock does NOT bound a
654 * blocking connect by SO_SNDTIMEO the way Linux does, so the connect is made
655 * non-blocking under the same bound instead; zero leaves both unbounded.
656 */
657socket_t tcp_connect_blocking(const std::string& host, const std::string& port, double ioSeconds,
658 ConnectFailure& why) {
659 ensure_winsock();
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;
669 }
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));
676 int err = 0;
677 if (connect_within(s, ai, ms, err)) break;
678 ::closesocket(s);
679 s = INVALID_SOCKET;
680 }
681 ::freeaddrinfo(res);
682 if (s == INVALID_SOCKET) {
684 return kInvalidSocket;
685 }
686 return static_cast<socket_t>(s);
687}
688
689/**
690 * No SO_REUSEADDR here, on purpose: on Windows it lets a second socket STEAL a
691 * port that is in active use, whereas the POSIX meaning (rebind past TIME_WAIT)
692 * is already Winsock's default.
693 */
694socket_t tcp_listen_any(int port, int backlog, std::string& stage) {
695 ensure_winsock();
696 const SOCKET s = ::socket(AF_INET, SOCK_STREAM, 0);
697 if (s == INVALID_SOCKET) {
698 stage = "socket";
699 return kInvalidSocket;
700 }
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) {
707 ::closesocket(s);
708 stage = "bind";
709 return kInvalidSocket;
710 }
711 if (::listen(s, backlog) != 0) {
712 ::closesocket(s);
713 stage = "listen";
714 return kInvalidSocket;
715 }
716 return static_cast<socket_t>(s);
717}
718
719socket_t tcp_accept(socket_t listener) {
720 const SOCKET c = ::accept(static_cast<SOCKET>(listener), nullptr, nullptr);
721 return c == INVALID_SOCKET ? kInvalidSocket : static_cast<socket_t>(c);
722}
723
724int free_loopback_port(std::string& stage) {
725 ensure_winsock();
726 const SOCKET s = ::socket(AF_INET, SOCK_STREAM, 0);
727 if (s == INVALID_SOCKET) {
728 stage = "socket";
729 return -1;
730 }
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);
735 addr.sin_port = 0;
736 if (::bind(s, reinterpret_cast<struct sockaddr*>(&addr), sizeof(addr)) != 0) {
737 ::closesocket(s);
738 stage = "bind";
739 return -1;
740 }
741 int len = sizeof(addr);
742 if (::getsockname(s, reinterpret_cast<struct sockaddr*>(&addr), &len) != 0) {
743 ::closesocket(s);
744 stage = "getsockname";
745 return -1;
746 }
747 const int port = ntohs(addr.sin_port);
748 ::closesocket(s);
749 return port;
750}
751
752/** Winsock raises no SIGPIPE, so a plain send() is the MSG_NOSIGNAL send. */
753long send_some(socket_t s, const char* p, std::size_t n) {
754 const int k = static_cast<int>(n > 0x7fffffff ? 0x7fffffff : n);
755 return static_cast<long>(::send(static_cast<SOCKET>(s), p, k, 0));
756}
757
758long recv_some(socket_t s, char* p, std::size_t n) {
759 const int k = static_cast<int>(n > 0x7fffffff ? 0x7fffffff : n);
760 return static_cast<long>(::recv(static_cast<SOCKET>(s), p, k, 0));
761}
762
763void close_socket(socket_t s) {
764 if (s != kInvalidSocket) ::closesocket(static_cast<SOCKET>(s));
765}
766
767int last_socket_error() { return ::WSAGetLastError(); }
768bool err_interrupted(int e) { return e == WSAEINTR; }
769/** A Winsock receive timeout reports WSAETIMEDOUT where POSIX reports EAGAIN. */
770bool err_timed_out(int e) { return e == WSAETIMEDOUT || e == WSAEWOULDBLOCK; }
771
772std::string socket_error_text(int e) {
773 char* msg = nullptr;
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() == ' ' ||
780 text.back() == '.'))
781 text.pop_back();
782 if (text.empty()) text = "socket error " + std::to_string(e);
783 return text;
784}
785
786} // namespace platform
787} // namespace line
double available_memory_bytes()
Available physical memory in bytes; negative when the host cannot say.
Definition platform.h:277
bool make_dir_or_exists(const std::string &path)
mkdir 0700; an existing entry is success.
Definition platform.h:216
int dup2_fd(int from, int to)
POSIX dup2 returns the new descriptor; the CRT's _dup2 returns 0.
Definition platform.h:238
bool err_interrupted(int e)
Definition platform.h:527
long process_id()
Definition platform.h:265
socket_t tcp_connect_blocking(const std::string &host, const std::string &port, double ioSeconds, ConnectFailure &why)
Connect with the I/O timeouts set BEFORE a blocking connect, so they bound the connect as well (Linux...
Definition platform.h:412
bool is_writable(const std::string &p)
Definition platform.h:159
bool is_regular_file(const std::string &p)
Definition platform.h:143
bool is_directory(const std::string &p)
Definition platform.h:148
bool rename_replace(const std::string &from, const std::string &to)
Definition platform.h:241
int last_socket_error()
Definition platform.h:526
std::intptr_t socket_t
A TCP socket: a POSIX descriptor or a Winsock SOCKET.
Definition platform.h:61
std::string temp_root()
TMPDIR, else /tmp.
Definition platform.h:132
bool is_executable(const std::string &p)
Exists and the caller may execute it (a directory with +x included, as access() says).
Definition platform.h:154
std::string make_temp_dir(const std::string &tmpl)
mkdtemp on a template ending in XXXXXX; empty on failure.
Definition platform.h:221
long send_some(socket_t s, const char *p, std::size_t n)
send() without SIGPIPE; bytes sent or -1.
Definition platform.h:509
char path_list_separator()
Definition platform.h:127
std::string host_machine()
uname -m, or empty.
Definition platform.h:210
bool stat_file(const std::string &p, FileStat &out)
Definition platform.h:163
socket_t tcp_accept(socket_t listener)
Definition platform.h:472
bool docker_user_spec(std::string &out)
"uid:gid" for docker run --user; false where the notion does not apply.
Definition platform.h:302
socket_t tcp_listen_any(int port, int backlog, std::string &stage)
An IPv4 listener on every interface with SO_REUSEADDR.
Definition platform.h:446
std::string self_exe_path()
This executable's path, or empty when it cannot be read.
Definition platform.h:191
int dup_fd(int fd)
Definition platform.h:237
void set_io_timeout(socket_t s, int millis)
Set the receive and send timeouts; not positive leaves them as they are.
Definition platform.h:397
std::string current_dir()
Definition platform.h:198
std::string host_sysname()
uname -s, or empty.
Definition platform.h:204
const char * null_device()
Definition platform.h:128
bool spawn_detached(const std::vector< std::string > &argv)
Start argv detached (own session, std streams on /dev/null, double fork so no zombie).
Definition platform.h:309
int make_temp_file(std::string &tmpl)
mkstemp: replaces the XXXXXX in tmpl and returns an open descriptor, or -1.
Definition platform.h:229
long long free_disk_bytes(const std::string &path)
Bytes available to this user on the filesystem holding path; -1 if unknown.
Definition platform.h:268
void sleep_millis(long millis)
Definition platform.h:294
int close_fd(int fd)
Definition platform.h:239
void remove_tree(const std::string &dir)
Remove a directory and everything under it, not following symlinks.
Definition platform.h:246
bool err_timed_out(int e)
A Winsock receive timeout reports WSAETIMEDOUT where POSIX reports EAGAIN.
Definition platform.h:528
std::string find_on_path(const std::string &name)
The first dir/name on PATH that is a regular executable file, or empty.
Definition platform.h:174
long recv_some(socket_t s, char *p, std::size_t n)
Definition platform.h:518
const char * exe_suffix()
Definition platform.h:129
void close_socket(socket_t s)
Definition platform.h:522
std::string socket_error_text(int e)
Definition platform.h:529
bool remove_file(const std::string &p)
Definition platform.h:240
socket_t tcp_connect(const std::string &host, int port, int connectMillis, ConnectFailure &why, std::string &lastError)
Connect with a deadline on the connect itself: each resolved address is tried non-blocking,...
Definition platform.h:340
int free_loopback_port(std::string &stage)
A loopback port the kernel reports free (bind port 0, read it back), or -1 with the failing step in s...
Definition platform.h:481
std::string home_dir()
HOME, or empty.
Definition platform.h:138
long long monotonic_millis()
Milliseconds on the monotonic clock, for deadlines that survive a clock step.
Definition platform.h:288
ConnectFailure
Why tcp_connect failed, so the caller keeps its own wording.
Definition platform.h:73
int run_inherit(const std::vector< std::string > &argv)
Runs a command with the parent's stdout and stderr, e.g.
Definition subprocess.h:188
ProcResult capture(const std::vector< std::string > &argv, int timeoutSeconds, bool mergeStderr=false)
Runs a command, capturing stdout and discarding stderr.
Definition subprocess.h:100
Conservation laws of a layered queueing network, enumerated from its structure.
Definition aoi_dist2ph.h:51
The operating-system services the engine uses, in one place.
Running an external command and capturing its output, with a deadline.