From 2bda940d4b76a913b26141f7efdbc04ec5ce36ee Mon Sep 17 00:00:00 2001 From: sgt57 <198590103+sgt57@users.noreply.github.com> Date: Sat, 7 Nov 2026 18:23:56 +0800 Subject: [PATCH 01/37] refactor(process): introduce shared memory limit policy --- src/core/memorylimiter.h | 62 +++++++++++++++++++++++++++++ tests/CMakeLists.txt | 1 + tests/memory-limiter/CMakeLists.txt | 2 + tests/memory-limiter/main.cpp | 22 ++++++++++ 4 files changed, 87 insertions(+) create mode 100644 src/core/memorylimiter.h create mode 100644 tests/memory-limiter/CMakeLists.txt create mode 100644 tests/memory-limiter/main.cpp diff --git a/src/core/memorylimiter.h b/src/core/memorylimiter.h new file mode 100644 index 00000000..c4d23ffb --- /dev/null +++ b/src/core/memorylimiter.h @@ -0,0 +1,62 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +#pragma once + +#include +#include +#include + +namespace Lemon::Execution { + using Bytes = std::int64_t; + struct MemorySample { + Bytes declared = -1; + Bytes actual = -1; + }; + + inline bool memoryBytes(std::int64_t mib, Bytes &bytes) { + if (mib < 0) { + bytes = -1; + return true; + } + if (mib > std::numeric_limits::max() / (1024 * 1024)) + return false; + bytes = mib * 1024 * 1024; + return true; + } + + class UsageProvider { + public: + virtual ~UsageProvider() = default; + virtual MemorySample sample() = 0; + }; + class Prelimit { + public: + virtual ~Prelimit() = default; + virtual bool apply(Bytes limit) = 0; + }; + class Killer { + public: + virtual ~Killer() = default; + // Must terminate the execution unit and perform bounded reaping. + virtual bool killAndReap() = 0; + }; + + // Pure policy: OS operations and process exit classification belong to adapters. + class Limiter { + public: + explicit Limiter(Bytes limit) : limit(limit) {} + bool observe(MemorySample sample) { + peak.declared = std::max(peak.declared, sample.declared); + peak.actual = std::max(peak.actual, sample.actual); + exceeded = exceeded || (limit >= 0 && usage() > limit); + return exceeded; + } + Bytes usage() const { return std::max(peak.declared, peak.actual); } + MemorySample peaks() const { return peak; } + bool isExceeded() const { return exceeded; } + + private: + Bytes limit; + MemorySample peak; + bool exceeded = false; + }; +} // namespace Lemon::Execution diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 2889d646..8b3c675f 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -7,3 +7,4 @@ if(WIN32) add_subdirectory(windows-sandbox) add_subdirectory(sleep-inhibitor) endif() +add_subdirectory(memory-limiter) diff --git a/tests/memory-limiter/CMakeLists.txt b/tests/memory-limiter/CMakeLists.txt new file mode 100644 index 00000000..4ba061b2 --- /dev/null +++ b/tests/memory-limiter/CMakeLists.txt @@ -0,0 +1,2 @@ +add_executable(memory-limiter-test main.cpp) +add_test(NAME memory-limiter COMMAND memory-limiter-test) diff --git a/tests/memory-limiter/main.cpp b/tests/memory-limiter/main.cpp new file mode 100644 index 00000000..7f493049 --- /dev/null +++ b/tests/memory-limiter/main.cpp @@ -0,0 +1,22 @@ +#include "../../src/core/memorylimiter.h" +#include +using namespace Lemon::Execution; +void check(bool value) { + if (! value) + std::abort(); +} +int main() { + Limiter limited(100); + check(! limited.observe({100, 10})); + check(! limited.observe({20, 90})); + check(limited.peaks().declared == 100 && limited.peaks().actual == 90); + check(limited.observe({-1, 101})); + check(limited.observe({0, 0}) && limited.usage() == 101); + Limiter unlimited(-1); + check(unlimited.usage() == -1); + check(! unlimited.observe({1000, 2000})); + Bytes bytes; + check(memoryBytes(-1, bytes) && bytes == -1); + check(memoryBytes(4096, bytes) && bytes == 4294967296LL); + check(! memoryBytes(std::numeric_limits::max(), bytes)); +} From 0452c5502811b4c99482ba38b1216c19e5c3a234 Mon Sep 17 00:00:00 2001 From: sgt57 <198590103+sgt57@users.noreply.github.com> Date: Sat, 7 Nov 2026 18:29:19 +0800 Subject: [PATCH 02/37] refactor(process): supervise Unix memory through shared limit policy --- src/core/processrunner_unix.cpp | 16 +- unix/memoryusage.h | 6 + unix/test/CMakeLists.txt | 4 + unix/test/memory_cases.cpp | 46 ++++ unix/test/scripts/memory.py | 28 +++ unix/test/scripts/mle_static.py | 5 +- unix/watcher_linux.cpp | 114 ++-------- unix/watcher_macos.mm | 159 ++------------ unix/watcher_unix.cpp | 364 ++++++++++++++++++-------------- 9 files changed, 333 insertions(+), 409 deletions(-) create mode 100644 unix/memoryusage.h create mode 100644 unix/test/memory_cases.cpp create mode 100644 unix/test/scripts/memory.py diff --git a/src/core/processrunner_unix.cpp b/src/core/processrunner_unix.cpp index aec23a2e..419cff55 100644 --- a/src/core/processrunner_unix.cpp +++ b/src/core/processrunner_unix.cpp @@ -167,7 +167,7 @@ ProcessRunnerResult UnixProcessRunner::run() { #endif - if (! runner.waitForStarted(-1)) { + if (! runner.waitForStarted(5000)) { res.score = 0; res.result = CannotStartProgram; res.message = "Start runner failed"; @@ -180,7 +180,7 @@ ProcessRunnerResult UnixProcessRunner::run() { // Using rlimit to limit CPU time can only be accurate to seconds, // so here it is rounded up to an integer second. - long long killTimeLimit = (config.timeLimit + 999) / 1000 * 1000 + extraTime; + long long killTimeLimit = qMax(2000LL, 3LL * config.timeLimit) + 5000LL + extraTime; while (timer.elapsed() <= killTimeLimit) { if (runner.waitForFinished(10)) { isProgramFinishedInExtraTimeLimit = true; @@ -189,7 +189,10 @@ ProcessRunnerResult UnixProcessRunner::run() { if (cancellation.isCanceled()) { runner.terminate(); - runner.waitForFinished(-1); + if (! runner.waitForFinished(2500)) { + runner.kill(); + runner.waitForFinished(2000); + } return res; } @@ -197,7 +200,10 @@ ProcessRunnerResult UnixProcessRunner::run() { if (! isProgramFinishedInExtraTimeLimit) { runner.terminate(); - runner.waitForFinished(-1); + if (! runner.waitForFinished(2500)) { + runner.kill(); + runner.waitForFinished(2000); + } res.score = 0; res.timeUsed = res.memoryUsed = -1; // Watcher usually needs to handle the situation of program timeout and kill it. Therefore, it is @@ -223,7 +229,7 @@ ProcessRunnerResult UnixProcessRunner::run() { RS_MLE = 4, }; - int code = runner.exitCode(); + int code = runner.exitStatus() == QProcess::NormalExit ? runner.exitCode() : -1; switch (code) { case RS_RE: diff --git a/unix/memoryusage.h b/unix/memoryusage.h new file mode 100644 index 00000000..b2dee2a6 --- /dev/null +++ b/unix/memoryusage.h @@ -0,0 +1,6 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +#pragma once +#include "../src/core/memorylimiter.h" +#include +Lemon::Execution::MemorySample sampleMemory(pid_t pid); +Lemon::Execution::Bytes maxRSSBytes(long value); diff --git a/unix/test/CMakeLists.txt b/unix/test/CMakeLists.txt index b3e62a1b..5187189f 100644 --- a/unix/test/CMakeLists.txt +++ b/unix/test/CMakeLists.txt @@ -32,3 +32,7 @@ add_test(NAME watcher_symlink_abs_test COMMAND python3 scripts/symlink_abs.py) add_test(NAME watcher_symlink_rel_test COMMAND python3 scripts/symlink_rel.py) add_test(NAME watcher_redirect_IO_test COMMAND python3 scripts/redirect.py) add_test(NAME watcher_RE_test COMMAND python3 scripts/runtimeerr.py) + +add_executable(memory_cases memory_cases.cpp) +add_test(NAME watcher_memory_policy COMMAND python3 scripts/memory.py) +set_tests_properties(watcher_memory_policy PROPERTIES TIMEOUT 30) diff --git a/unix/test/memory_cases.cpp b/unix/test/memory_cases.cpp new file mode 100644 index 00000000..a0f52a1c --- /dev/null +++ b/unix/test/memory_cases.cpp @@ -0,0 +1,46 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +#include +#include +#include +#include +#include +#include +int main(int argc, char **argv) { + if (argc != 2) + return 1; + if (! strcmp(argv[1], "abort")) + std::abort(); + if (! strcmp(argv[1], "caught") || ! strcmp(argv[1], "uncaught")) { + try { + auto *p = new char[1024ULL * 1024 * 1024 * 1024]; + // Keep the allocation observable even with optimisation enabled. + printf("%p\n", static_cast(p)); + delete[] p; + } catch (const std::bad_alloc &) { + if (! strcmp(argv[1], "uncaught")) + throw; + puts("caught"); + } + return 0; + } + if (! strcmp(argv[1], "resident")) { + auto *p = static_cast(malloc(96 * 1024 * 1024)); + if (! p) + return 7; + for (int i = 0; i < 96 * 1024 * 1024; i += 4096) + p[i] = 1; + usleep(300000); + return 0; + } + if (! strcmp(argv[1], "reserve")) { + void *p = mmap(nullptr, 128 * 1024 * 1024, PROT_NONE, MAP_PRIVATE | MAP_ANON, -1, 0); + puts(p == MAP_FAILED ? "denied" : "reserved"); + usleep(100000); + return 0; + } + if (! strcmp(argv[1], "sleep")) { + sleep(20); + return 0; + } + return 2; +} diff --git a/unix/test/scripts/memory.py b/unix/test/scripts/memory.py new file mode 100644 index 00000000..eae42618 --- /dev/null +++ b/unix/test/scripts/memory.py @@ -0,0 +1,28 @@ +import os +import platform +import subprocess +import tempfile + +with tempfile.TemporaryDirectory() as directory: + def run(mode, limit=64): + output = os.path.join(directory, 'out') + error = os.path.join(directory, 'err') + p = subprocess.run(['./watcher_unix', './memory_cases', mode, '', output, error, + '1000', str(limit), '1000', str(limit), '', ''], + stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=8) + fields = p.stdout.decode().split() + assert len(fields) == 2, (mode, p.stdout, p.stderr) + assert int(fields[1]) >= 0, (mode, p.stdout, p.stderr) + return p.returncode, open(output).read(), int(fields[1]) + + assert run('abort')[0] == 2 + if platform.system() == 'Linux': + assert run('caught')[0:2] == (0, 'caught\n') + assert run('uncaught')[0] == 2 + assert run('reserve')[0:2] == (0, 'denied\n') + # Prelimit refuses the allocation; a nonzero exit is RE, not MLE. + assert run('resident')[0] == 2 + else: + assert run('reserve')[0:2] == (0, 'reserved\n') + assert run('resident')[0] == 4 + assert run('sleep')[0] == 3 diff --git a/unix/test/scripts/mle_static.py b/unix/test/scripts/mle_static.py index f53fedf4..bcd65cda 100644 --- a/unix/test/scripts/mle_static.py +++ b/unix/test/scripts/mle_static.py @@ -1,5 +1,6 @@ import subprocess import os +import platform pid = os.getpid() tmperr = f"_tmperr_{pid}" @@ -8,5 +9,5 @@ stdout, _ = p.communicate() -assert(p.wait() == 4) -assert(stdout[0] == 48) +assert(p.wait() == (2 if platform.system() == 'Linux' else 0)) +assert(len(stdout.split()) == 2) diff --git a/unix/watcher_linux.cpp b/unix/watcher_linux.cpp index cd113c8b..bcce1a23 100644 --- a/unix/watcher_linux.cpp +++ b/unix/watcher_linux.cpp @@ -1,98 +1,24 @@ -/* - * SPDX-FileCopyrightText: 2011-2019 Project Lemon, Zhipeng Jia - * SPDX-FileCopyrightText: 2019-2023 Project LemonLime - * - * SPDX-License-Identifier: GPL-3.0-or-later - * - */ - -#include -#include +// SPDX-License-Identifier: GPL-3.0-or-later +#include "memoryusage.h" #include -#include #include -#include #include -#include -#include -#include -#include -#include -#include - -static auto read_elf_ident(int fd, char *e_ident) -> bool { - if (read(fd, e_ident, EI_NIDENT) != EI_NIDENT) { - return false; - } - if (strncmp(e_ident, "\177ELF", 4) != 0) { - return false; - } - return true; -} - -template static auto calculateStaticMemoryUsage(int fd) -> ssize_t { - ssize_t res = 0; - - Ehdr elf_header; - if (lseek64(fd, 0, SEEK_SET) < 0) { - return -1; - } - if (read(fd, &elf_header, sizeof(Ehdr)) != sizeof(Ehdr)) { - return -1; - } - // gcc with PIE will set executable as ET_DYN - // https://stackoverflow.com/questions/34519521 - if (elf_header.e_type != ET_EXEC && elf_header.e_type != ET_DYN) { - return -1; - } - if (elf_header.e_phoff == 0) { - return -1; // no program header, not executable - } - if (elf_header.e_phentsize != sizeof(Phdr)) { - return -1; - } - - if (lseek64(fd, elf_header.e_phoff, SEEK_SET) < 0) { - return -1; - } - Phdr program_header; - for (int i = 0; i < elf_header.e_phnum; ++i) { - if (read(fd, &program_header, sizeof(Phdr)) != sizeof(Phdr)) { - return -1; - } - if (program_header.p_type == PT_LOAD) { - res += program_header.p_memsz; - } - } - - return res; -} - -void initWatcher() { return; } - -ssize_t calculateStaticMemoryUsage(const std::string &fileName) { - char e_ident[EI_NIDENT]; - ssize_t staticMemoryUsage = 0; - int fd = open(fileName.c_str(), O_RDONLY); - if (fd < 0) { - return -1; - } - - if (read_elf_ident(fd, e_ident) == false) { - return -1; - } - if (e_ident[EI_CLASS] == ELFCLASS32) { - staticMemoryUsage = calculateStaticMemoryUsage(fd); - } else if (e_ident[EI_CLASS] == ELFCLASS64) { - staticMemoryUsage = calculateStaticMemoryUsage(fd); - } else { - staticMemoryUsage = -1; - } - close(fd); - - return staticMemoryUsage; +using namespace Lemon::Execution; +MemorySample sampleMemory(pid_t pid) { + MemorySample result; + auto path = "/proc/" + std::to_string(pid) + "/status"; + FILE *file = fopen(path.c_str(), "r"); + if (! file) + return result; + char line[512]; + while (fgets(line, sizeof(line), file)) { + long long kib = 0; + if (sscanf(line, "VmSize: %lld kB", &kib) == 1 || sscanf(line, "VmPeak: %lld kB", &kib) == 1) + result.declared = std::max(result.declared, Bytes(kib) * 1024); + if (sscanf(line, "VmRSS: %lld kB", &kib) == 1 || sscanf(line, "VmHWM: %lld kB", &kib) == 1) + result.actual = std::max(result.actual, Bytes(kib) * 1024); + } + fclose(file); + return result; } - -ssize_t getMemoryRLimit(ssize_t memoryLimitInMB) { return memoryLimitInMB * 1024 * 1024; } - -size_t getMaxRSSInByte(long ru_maxrss) { return ru_maxrss * 1024; } +Bytes maxRSSBytes(long value) { return Bytes(value) * 1024; } diff --git a/unix/watcher_macos.mm b/unix/watcher_macos.mm index 73fc1be3..aeac1eb0 100644 --- a/unix/watcher_macos.mm +++ b/unix/watcher_macos.mm @@ -1,148 +1,13 @@ -/* - * SPDX-FileCopyrightText: 2011-2019 Project Lemon, Zhipeng Jia - * SPDX-FileCopyrightText: 2019-2023 Project LemonLime - * - * SPDX-License-Identifier: GPL-3.0-or-later - * - */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -template static ssize_t calculateStaticMemoryUsage(int fd, int start_offset = 0) { - ssize_t res = 0; - - header hdr; - if (lseek(fd, start_offset, SEEK_SET) < 0) { - return -1; - } - if (read(fd, &hdr, sizeof(header)) != sizeof(header)) { - return -1; - } - if (hdr.filetype != MH_EXECUTE) { - return -1; - } - - uint32_t ncmds = hdr.ncmds; - while (ncmds--) { - struct load_command command; - struct segment_command seg; - struct segment_command_64 seg64; - - if (read(fd, &command, sizeof(struct load_command)) != sizeof(struct load_command)) { - return -1; - } - if (lseek(fd, -sizeof(struct load_command), SEEK_CUR) < 0) { - return -1; - } - - switch (command.cmd) { - case LC_SEGMENT: - if (read(fd, &seg, sizeof(struct segment_command)) != sizeof(struct segment_command)) { - return -1; - } - if (strcmp(seg.segname, SEG_DATA) == 0 || strcmp(seg.segname, SEG_TEXT) == 0) { - res += seg.vmsize; - } - if (sizeof(struct segment_command) != command.cmdsize) { - if (sizeof(struct segment_command) > command.cmdsize || - lseek(fd, command.cmdsize - sizeof(struct segment_command), SEEK_CUR) < 0) { - return -1; - } - } - break; - case LC_SEGMENT_64: - if (read(fd, &seg64, sizeof(struct segment_command_64)) != - sizeof(struct segment_command_64)) { - return -1; - } - if (strcmp(seg64.segname, SEG_DATA) == 0 || strcmp(seg64.segname, SEG_TEXT) == 0) { - res += seg64.vmsize; - } - if (sizeof(struct segment_command_64) != command.cmdsize) { - if (sizeof(struct segment_command_64) > command.cmdsize || - lseek(fd, command.cmdsize - sizeof(struct segment_command_64), SEEK_CUR) < 0) { - return -1; - } - } - break; - default: - if (lseek(fd, command.cmdsize, SEEK_CUR) < 0) { - return -1; - } - } - } - - return res; +// SPDX-License-Identifier: GPL-3.0-or-later +#include "memoryusage.h" +#include +#include +using namespace Lemon::Execution; +MemorySample sampleMemory(pid_t pid) { + proc_taskinfo info{}; + if (proc_pidinfo(pid, PROC_PIDTASKINFO, 0, &info, sizeof(info)) != sizeof(info)) + return {}; + Bytes rss = static_cast(info.pti_resident_size); + return {rss, rss}; } - -static std::string getCpuBrandString() { - char buf[1024]; - size_t buflen = 1024; - sysctlbyname("machdep.cpu.brand_string", &buf, &buflen, NULL, 0); - return std::string(buf, buflen); -} - -int isAppleSilicon; - -void initWatcher() { isAppleSilicon = getCpuBrandString().contains("Apple"); } - -ssize_t calculateStaticMemoryUsage(const std::string &fileName) { - uint32_t magic; - ssize_t staticMemoryUsage = 0; - int fd = open(fileName.c_str(), O_RDONLY); - if (fd < 0) { - return -1; - } - - int rc = - macho_best_slice_in_fd(fd, [&](const mach_header *slice, uint64_t sliceFileOffset, size_t sliceSize) { - if (slice->magic == MH_MAGIC) { - staticMemoryUsage = calculateStaticMemoryUsage(fd, sliceFileOffset); - } else if (slice->magic == MH_MAGIC_64) { - staticMemoryUsage = calculateStaticMemoryUsage(fd, sliceFileOffset); - } else { - staticMemoryUsage = -1; - } - }); - - if (rc != 0) { - // not a fat file, consider a mach-o file - if (lseek(fd, 0, SEEK_SET) < 0) { - return -1; - } - if (read(fd, &magic, sizeof(magic)) != sizeof(magic)) { - return -1; - } - if (magic == MH_MAGIC) { - staticMemoryUsage = calculateStaticMemoryUsage(fd); - } else if (magic == MH_MAGIC_64) { - staticMemoryUsage = calculateStaticMemoryUsage(fd); - } else { - staticMemoryUsage = -1; - } - } - close(fd); - - return staticMemoryUsage; -} - -ssize_t getMemoryRLimit(ssize_t memoryLimitInMB) { return memoryLimitInMB * 1024 * (isAppleSilicon ? 4 : 1); } - -size_t getMaxRSSInByte(long ru_maxrss) { return ru_maxrss / (isAppleSilicon ? 4 : 1); } +Bytes maxRSSBytes(long value) { return value; } diff --git a/unix/watcher_unix.cpp b/unix/watcher_unix.cpp index 096042e6..00bcdae6 100644 --- a/unix/watcher_unix.cpp +++ b/unix/watcher_unix.cpp @@ -1,189 +1,231 @@ -/* - * SPDX-FileCopyrightText: 2011-2019 Project Lemon, Zhipeng Jia - * SPDX-FileCopyrightText: 2019-2023 Project LemonLime - * - * SPDX-License-Identifier: GPL-3.0-or-later - * - */ - -#include +// SPDX-License-Identifier: GPL-3.0-or-later +#include "memoryusage.h" +#include +#include #include #include #include -#include -#include +#include #include -#include #include -#include -#include #include +#include #include - -int pid; - -void cleanUp(int /*dummy*/) { - kill(pid, SIGKILL); - exit(0); -} - -extern void initWatcher(); -extern ssize_t calculateStaticMemoryUsage(const std::string &); -extern ssize_t getMemoryRLimit(ssize_t memoryLimitInMB); -extern size_t getMaxRSSInByte(long ru_maxrss); - -enum : int { - RS_AC = 0, - RS_FAIL = 1, - RS_RE = 2, - RS_TLE = 3, - RS_MLE = 4, -}; - -/** - * argv[1]: executable file path - * argv[2]: 执行选手程序时,传递的命令行参数,但不包含 argv0 - * argv[3]: 重定向输入文件(如果有) - * argv[4]: 重定向输出文件(如果有) - * argv[5]: 重定向错误流文件(如果有) - * argv[6]: 时间限制(毫秒) - * argv[7]: 空间限制(MiB),若为负数表示无限制 - * argv[8]: 原始(未经语言设置缩放的)时间限制(毫秒) - * argv[9]: 原始(未经语言设置缩放的)空间限制(MiB) - * argv[10]: 选手程序只读的文件 - * argv[11]: 选手程序只写的文件 - */ -auto main(int argc, char *argv[]) -> int { +#ifdef __linux__ +#include +#endif +using namespace Lemon::Execution; +namespace { + enum { RS_AC, RS_FAIL, RS_RE, RS_TLE, RS_MLE }; + volatile sig_atomic_t stopped = 0; + void stop(int) { stopped = 1; } + class UnixPrelimit : public Prelimit { + public: + bool apply(Bytes limit) override { +#ifdef __linux__ + if (limit >= 0) { + rlimit memory{static_cast(limit), static_cast(limit)}; + if (setrlimit(RLIMIT_AS, &memory) != 0) + return false; + } +#else + (void)limit; // macOS intentionally has no memory prelimit. +#endif + return true; + } + }; + class UnixUsage : public UsageProvider { + pid_t pid; + + public: + explicit UnixUsage(pid_t pid) : pid(pid) {} + MemorySample sample() override { return sampleMemory(pid); } + }; + class UnixProcess : public Killer { + public: + pid_t pid; + int status = 0; + rusage usage{}; + bool reaped = false; + explicit UnixProcess(pid_t pid) : pid(pid) {} + // Do not destroy the exit information until all final samples are consumed. + int poll() { + if (reaped) + return 1; + pid_t result = wait4(pid, &status, WNOHANG, &usage); + if (result == pid) { + reaped = true; + return 1; + } + if (result < 0 && errno != EINTR) + return -1; + return 0; + } + bool killAndReap() override { + kill(-pid, SIGKILL); + if (! reaped) + kill(pid, SIGKILL); + auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(2); + while (! reaped && std::chrono::steady_clock::now() < deadline) { + if (poll() < 0) + return false; + if (! reaped) + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + } + return reaped; + } + }; + struct ChildError { + int stage; + int error; + }; +} // namespace +int main(int argc, char **argv) { if (argc != 12) { printf("-1\n-1\n"); - fprintf(stderr, "Expected 11 arguments, found %d\n", argc); return RS_FAIL; } - std::string fileName = argv[1]; - std::string runArgs = argv[2]; - std::string stdinRedirect = argv[3]; - std::string stdoutRedirect = argv[4]; - std::string stderrRedirect = argv[5]; - long long timeLimitMs = std::stoll(argv[6]); - long long memoryLimitMib = std::stoll(argv[7]); - [[maybe_unused]] long long rawTimeLimitMs = std::stoll(argv[8]); - [[maybe_unused]] long long rawMemoryLimitMib = std::stoll(argv[9]); - [[maybe_unused]] std::string readableFile = argv[10]; - [[maybe_unused]] std::string writableFile = argv[11]; - - initWatcher(); - - std::ostringstream ss; - ss << '"'; - ss << fileName; - ss << "\" "; - ss << runArgs; - std::string runCmd = ss.str(); - - if (memoryLimitMib > 0) { - ssize_t staticMemoryUsageByte = calculateStaticMemoryUsage(fileName); - if (staticMemoryUsageByte == -1) { + try { + long long timeLimit = std::stoll(argv[6]); + Bytes limit; + if (! memoryBytes(std::stoll(argv[7]), limit) || timeLimit < 0) { printf("-1\n-1\n"); - fprintf(stderr, "Error in calculating static memory usage\n"); return RS_FAIL; } - if (staticMemoryUsageByte > memoryLimitMib * 1024 * 1024) { - // If static memory usage exceeds the limit, it's an MLE. - printf("0\n%zd\n", staticMemoryUsageByte); - fprintf(stderr, "Static memory usage exceeds the limit\n"); - return RS_MLE; + int errors[2]; + if (pipe(errors) != 0) { + perror("pipe"); + printf("-1\n-1\n"); + return RS_FAIL; } - } - - ssize_t actualMemoryRLimit = getMemoryRLimit(memoryLimitMib); - - pid = fork(); - - if (pid > 0) { - // Parent process - signal(SIGINT, cleanUp); - signal(SIGABRT, cleanUp); - signal(SIGTERM, cleanUp); - struct rusage usage{}; - int status = 0; - - if (wait4(pid, &status, 0, &usage) == -1) { + if (fcntl(errors[1], F_SETFD, FD_CLOEXEC) < 0 || fcntl(errors[0], F_SETFL, O_NONBLOCK) < 0) { + perror("fcntl"); + close(errors[0]); + close(errors[1]); printf("-1\n-1\n"); - perror("wait4"); return RS_FAIL; } - - if (WIFEXITED(status)) { - long long timeUsedMs = - static_cast(usage.ru_utime.tv_sec * 1000 + usage.ru_utime.tv_usec / 1000); - size_t memoryUsed = getMaxRSSInByte(usage.ru_maxrss); - printf("%lld\n%zu\n", timeUsedMs, memoryUsed); - if (WEXITSTATUS(status) != 0) { - // Any non-zero exit status indicates a runtime error. - return RS_RE; + pid_t pid = fork(); + if (pid < 0) { + perror("fork"); + close(errors[0]); + close(errors[1]); + printf("-1\n-1\n"); + return RS_FAIL; + } + if (pid == 0) { + close(errors[0]); + auto fail = [&](int stage) { + ChildError error{stage, errno}; + (void)write(errors[1], &error, sizeof(error)); + _exit(127); + }; + if (setpgid(0, 0) != 0) + fail(1); + const char *modes[] = {"r", "w", "w"}; + FILE *streams[] = {stdin, stdout, stderr}; + for (int i = 0; i < 3; ++i) + if (! freopen(*argv[3 + i] ? argv[3 + i] : "/dev/null", modes[i], streams[i])) + fail(2); +#ifdef __linux__ + // Disable dump generation, including piped core handlers. + if (prctl(PR_SET_DUMPABLE, 0) != 0) + fail(6); +#endif + UnixPrelimit prelimit; + if (! prelimit.apply(limit)) + fail(3); + rlim_t seconds = static_cast((timeLimit + 999) / 1000); + rlimit cpu{seconds, seconds + 1}; + if (setrlimit(RLIMIT_CPU, &cpu) != 0) + fail(4); + // The shell replaces itself, so pid continues to identify the submission. + std::string command = "exec \"" + std::string(argv[1]) + "\" " + argv[2]; + execlp("bash", "bash", "-c", command.c_str(), static_cast(nullptr)); + fail(5); + } + close(errors[1]); + (void)setpgid(pid, pid); + signal(SIGTERM, stop); + signal(SIGINT, stop); + signal(SIGABRT, stop); + UnixProcess process(pid); + UnixUsage provider(pid); + Limiter limiter(limit); + auto deadline = + std::chrono::steady_clock::now() + std::chrono::milliseconds(std::max(2000LL, 3LL * timeLimit)); + int verdict = RS_AC; + int missing = 0; + ChildError childError{}; + bool setupFailed = false; + for (;;) { + auto sample = provider.sample(); + limiter.observe(sample); + if (read(errors[0], &childError, sizeof(childError)) == sizeof(childError)) + setupFailed = true; + int finished = process.poll(); + if (setupFailed || finished < 0) { + verdict = RS_FAIL; + break; } - if (timeUsedMs > timeLimitMs) { - return RS_TLE; + if (limiter.isExceeded()) { + verdict = RS_MLE; + break; } - if (memoryUsed > memoryLimitMib * 1024 * 1024) { - return RS_MLE; + if (finished) + break; + if (std::chrono::steady_clock::now() >= deadline) { + verdict = RS_TLE; + break; } - return RS_AC; - } - - if (WIFSIGNALED(status)) { - long long timeUsedMs = - static_cast(usage.ru_utime.tv_sec * 1000 + usage.ru_utime.tv_usec / 1000); - printf("%lld\n-1\n", timeUsedMs); - if (WTERMSIG(status) == SIGXCPU) { - return RS_TLE; + if (stopped) { + verdict = RS_FAIL; + break; } - if (WTERMSIG(status) == SIGKILL || WTERMSIG(status) == SIGABRT) { - return RS_MLE; + missing = sample.declared < 0 || sample.actual < 0 ? missing + 1 : 0; + if (missing >= 10) { + fprintf(stderr, "Memory statistics unavailable\n"); + verdict = RS_FAIL; + break; } - return RS_RE; - } - } else { - std::string finalStdinRedirect = stdinRedirect.empty() ? "/dev/null" : stdinRedirect; - if (freopen(finalStdinRedirect.c_str(), "r", stdin) == NULL) { - perror("freopen stdin"); - exit(RS_FAIL); + std::this_thread::sleep_for(std::chrono::milliseconds(10)); } - std::string finalStdoutRedirect = stdoutRedirect.empty() ? "/dev/null" : stdoutRedirect; - if (freopen(finalStdoutRedirect.c_str(), "w", stdout) == NULL) { - perror("freopen stdout"); - exit(RS_FAIL); + // Catch setup errors delivered concurrently with the final wait. + if (read(errors[0], &childError, sizeof(childError)) == sizeof(childError)) + setupFailed = true; + close(errors[0]); + if (! process.killAndReap()) + fprintf(stderr, "Process reaping deadline exceeded\n"); + if (setupFailed) { + fprintf(stderr, "Child setup stage %d failed: errno %d\n", childError.stage, childError.error); + verdict = RS_FAIL; } - std::string finalStderrRedirect = stderrRedirect.empty() ? "/dev/null" : stderrRedirect; - if (freopen(finalStderrRedirect.c_str(), "w", stderr) == NULL) { - perror("freopen stderr"); - exit(RS_FAIL); - } - - rlimit memlim{}, stalim{}, timlim{}; - - if (memoryLimitMib > 0) { - memlim = (rlimit){(rlim_t)actualMemoryRLimit, (rlim_t)actualMemoryRLimit}; - stalim = (rlimit){(rlim_t)actualMemoryRLimit, (rlim_t)actualMemoryRLimit}; - } else { - // No memory limit specified, set to infinity - memlim = (rlimit){RLIM_INFINITY, RLIM_INFINITY}; - stalim = (rlimit){(rlim_t)2147483647LL, (rlim_t)2147483647LL}; - } - - // Calculate time limit in seconds, rounding up - rlim_t soft_time_limit_sec = (timeLimitMs + 999) / 1000; - timlim = (rlimit){soft_time_limit_sec, soft_time_limit_sec + 1}; // Soft limit + 1 for hard limit - - setrlimit(RLIMIT_AS, &memlim); - setrlimit(RLIMIT_STACK, &stalim); - setrlimit(RLIMIT_CPU, &timlim); - - if (execlp("bash", "bash", "-c", runCmd.c_str(), NULL) == -1) { - perror("execlp"); - exit(RS_FAIL); + if (process.reaped) { + Bytes rss = maxRSSBytes(process.usage.ru_maxrss); +#ifdef __APPLE__ + limiter.observe({rss, rss}); +#else + limiter.observe({-1, rss}); +#endif + if (verdict == RS_AC) { + if (limiter.isExceeded()) + verdict = RS_MLE; + else if (WIFSIGNALED(process.status)) + verdict = WTERMSIG(process.status) == SIGXCPU ? RS_TLE : RS_RE; + else if (! WIFEXITED(process.status) || WEXITSTATUS(process.status) != 0) + verdict = RS_RE; + } } + long long elapsed = + process.reaped ? process.usage.ru_utime.tv_sec * 1000LL + process.usage.ru_utime.tv_usec / 1000 + : -1; + if (verdict == RS_AC && elapsed > timeLimit) + verdict = RS_TLE; + printf("%lld\n%lld\n", elapsed, static_cast(limiter.usage())); + return verdict; + } catch (...) { + printf("-1\n-1\n"); + fprintf(stderr, "Invalid watcher arguments\n"); + return RS_FAIL; } - - return 0; } From 86ab3f9f980b8cbe211ff8abade21eae1e3e6052 Mon Sep 17 00:00:00 2001 From: sgt57 <198590103+sgt57@users.noreply.github.com> Date: Sat, 7 Nov 2026 18:30:10 +0800 Subject: [PATCH 03/37] refactor(process): enforce Windows memory limits with execution jobs --- src/core/processrunner_win.cpp | 111 ++++++++++++++++----------------- src/core/windowsmemory.h | 74 ++++++++++++++++++++++ src/core/windowssandbox.cpp | 27 +++----- src/core/windowssandbox.h | 2 +- 4 files changed, 137 insertions(+), 77 deletions(-) create mode 100644 src/core/windowsmemory.h diff --git a/src/core/processrunner_win.cpp b/src/core/processrunner_win.cpp index fa6fd7e7..204369d2 100644 --- a/src/core/processrunner_win.cpp +++ b/src/core/processrunner_win.cpp @@ -11,6 +11,7 @@ #include "processrunner_win.h" #include "base/LemonLog.hpp" +#include "windowsmemory.h" #include "windowsprocessutils.h" #include "windowssandbox.h" @@ -75,14 +76,14 @@ ProcessRunnerResult WinProcessRunner::run() { if (config.standardOutputCheck) { siex.StartupInfo.hStdOutput = CreateFileW((const WCHAR *)((config.workingDirectory + "_tmpout").utf16()), GENERIC_WRITE, - FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, &sa, CREATE_ALWAYS, - FILE_ATTRIBUTE_NORMAL, NULL); + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, &sa, CREATE_ALWAYS, + FILE_ATTRIBUTE_NORMAL, NULL); } siex.StartupInfo.hStdError = CreateFileW((const WCHAR *)((config.workingDirectory + "_tmperr").utf16()), GENERIC_WRITE, - FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, &sa, CREATE_ALWAYS, - FILE_ATTRIBUTE_NORMAL, NULL); + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, &sa, CREATE_ALWAYS, + FILE_ATTRIBUTE_NORMAL, NULL); auto closeStdIO = qScopeGuard([&] { if (config.standardInputCheck) @@ -94,7 +95,15 @@ ProcessRunnerResult WinProcessRunner::run() { CloseHandle(siex.StartupInfo.hStdError); }); - if (sandbox && ! sandbox->prepareProcess(siex, res.message)) { + Lemon::Execution::Bytes memoryLimit; + ExecutionJob job; + if (! Lemon::Execution::memoryBytes(config.memoryLimit, memoryLimit) || ! job.apply(memoryLimit) || + (sandbox && ! job.restrictToOneProcess())) { + res.result = CannotStartProgram; + res.message = "Cannot configure memory prelimit"; + return res; + } + if (sandbox && ! sandbox->prepareProcess(siex, job.get(), res.message)) { res.result = CannotStartProgram; return res; } @@ -106,8 +115,8 @@ ProcessRunnerResult WinProcessRunner::run() { QString commandLine = QString(R"("%1" %2)").arg(config.executableFile).arg(config.arguments); if (! CreateProcessW(nullptr, reinterpret_cast(commandLine.data()), nullptr, &sa, TRUE, - HIGH_PRIORITY_CLASS | EXTENDED_STARTUPINFO_PRESENT | DETACHED_PROCESS | - CREATE_UNICODE_ENVIRONMENT, + CREATE_SUSPENDED | HIGH_PRIORITY_CLASS | EXTENDED_STARTUPINFO_PRESENT | + DETACHED_PROCESS | CREATE_UNICODE_ENVIRONMENT, (LPVOID)(environmentValues.utf16()), (const WCHAR *)(config.workingDirectory.utf16()), (STARTUPINFO *)(&siex), &pi)) { const DWORD code = GetLastError(); @@ -126,64 +135,56 @@ ProcessRunnerResult WinProcessRunner::run() { CloseHandle(pi.hThread); }); - PROCESS_MEMORY_COUNTERS_EX memoryInfo; - ZeroMemory(&memoryInfo, sizeof(memoryInfo)); - memoryInfo.cb = sizeof(memoryInfo); - - if (config.memoryLimit != -1) { - GetProcessMemoryInfo(pi.hProcess, (PROCESS_MEMORY_COUNTERS *)&memoryInfo, sizeof(memoryInfo)); - - if (qMax(memoryInfo.PrivateUsage, memoryInfo.PeakWorkingSetSize) > - 1ll * config.memoryLimit * 1024 * 1024) { - TerminateProcess(pi.hProcess, 0); - - res.score = 0; - res.result = MemoryLimitExceeded; - res.memoryUsed = res.timeUsed = -1; - return res; - } + ProcessKiller killer(pi.hProcess, job.get()); + auto reap = qScopeGuard([&] { + if (! killer.killAndReap()) + WARN("Process reaping deadline exceeded"); + }); + if ((! sandbox && ! AssignProcessToJobObject(job.get(), pi.hProcess)) || + ResumeThread(pi.hThread) == DWORD(-1)) { + TerminateProcess(pi.hProcess, 1); + res.result = CannotStartProgram; + res.message = "Cannot attach or resume process"; + return res; } - - bool isProgramFinishedInExtraTimeLimit = false; + ProcessUsage provider(pi.hProcess, job); + Lemon::Execution::Limiter limiter(memoryLimit); QElapsedTimer timer; timer.start(); - - while (timer.elapsed() <= config.timeLimit + extraTime) { - if (WaitForSingleObject(pi.hProcess, 0) == WAIT_OBJECT_0) { - isProgramFinishedInExtraTimeLimit = true; - break; + int missing = 0; + for (;;) { + auto sample = provider.sample(); + limiter.observe(sample); + res.memoryUsed = limiter.usage(); + if (limiter.isExceeded()) { + res.result = MemoryLimitExceeded; + return res; } - - if (config.memoryLimit != -1) { - GetProcessMemoryInfo(pi.hProcess, (PROCESS_MEMORY_COUNTERS *)&memoryInfo, sizeof(memoryInfo)); - - if (qMax(memoryInfo.PrivateUsage, memoryInfo.PeakWorkingSetSize) > - 1ll * config.memoryLimit * 1024 * 1024) { - TerminateProcess(pi.hProcess, 0); - res.score = 0; + DWORD state = WaitForSingleObject(pi.hProcess, 0); + if (state == WAIT_OBJECT_0) { + limiter.observe({job.peakCommit(), -1}); + res.memoryUsed = limiter.usage(); + if (limiter.isExceeded()) { res.result = MemoryLimitExceeded; - res.memoryUsed = res.timeUsed = -1; return res; } + break; } - - if (cancellation.isCanceled()) { - TerminateProcess(pi.hProcess, 0); + missing = sample.declared < 0 || sample.actual < 0 ? missing + 1 : 0; + if (state == WAIT_FAILED || missing >= 10) { + res.result = CannotStartProgram; + res.message = "Process statistics unavailable"; + return res; + } + if (cancellation.isCanceled()) + return res; + if (timer.elapsed() > config.timeLimit + extraTime) { + res.result = TimeLimitExceeded; + res.timeUsed = -1; return res; } - QThread::msleep(10); } - - if (! isProgramFinishedInExtraTimeLimit) { - TerminateProcess(pi.hProcess, 0); - - res.score = 0; - res.result = TimeLimitExceeded; - res.timeUsed = -1; - return res; - } - unsigned long exitCode; GetExitCodeProcess(pi.hProcess, &exitCode); @@ -199,7 +200,7 @@ ProcessRunnerResult WinProcessRunner::run() { file.close(); } - res.memoryUsed = res.timeUsed = -1; + res.timeUsed = -1; LOG(config.executableFile, "Unexpectedly exited."); LOG("Exit code", exitCode); return res; @@ -214,8 +215,6 @@ ProcessRunnerResult WinProcessRunner::run() { realUserTime.wMinute * 60 * 1000 + realUserTime.wHour * 60 * 60 * 1000; int kernelTimeUsed = realKernelTime.wMilliseconds + realKernelTime.wSecond * 1000 + realKernelTime.wMinute * 60 * 1000 + realKernelTime.wHour * 60 * 60 * 1000; - GetProcessMemoryInfo(pi.hProcess, (PROCESS_MEMORY_COUNTERS *)&memoryInfo, sizeof(memoryInfo)); - res.memoryUsed = memoryInfo.PeakWorkingSetSize; if (sandbox) { const QDir work(config.workingDirectory); const auto outputPath = diff --git a/src/core/windowsmemory.h b/src/core/windowsmemory.h new file mode 100644 index 00000000..20065bfb --- /dev/null +++ b/src/core/windowsmemory.h @@ -0,0 +1,74 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +#pragma once +#include "memorylimiter.h" +#include "windowsprocessutils.h" +#ifdef Q_OS_WIN +#include +namespace Lemon::Windows { + class ExecutionJob : public Execution::Prelimit { + Handle handle{CreateJobObjectW(nullptr, nullptr)}; + + public: + HANDLE get() const { return handle.get(); } + bool apply(Execution::Bytes limit) override { + if (! handle) + return false; + JOBOBJECT_EXTENDED_LIMIT_INFORMATION info{}; + info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; + if (limit >= 0) { + if (static_cast(limit) > SIZE_MAX) { + SetLastError(ERROR_INVALID_PARAMETER); + return false; + } + info.BasicLimitInformation.LimitFlags |= JOB_OBJECT_LIMIT_PROCESS_MEMORY; + info.ProcessMemoryLimit = static_cast(limit); + } + return SetInformationJobObject(get(), JobObjectExtendedLimitInformation, &info, sizeof(info)); + } + bool restrictToOneProcess() { + JOBOBJECT_EXTENDED_LIMIT_INFORMATION info{}; + if (! QueryInformationJobObject(get(), JobObjectExtendedLimitInformation, &info, sizeof(info), + nullptr)) + return false; + info.BasicLimitInformation.LimitFlags |= JOB_OBJECT_LIMIT_ACTIVE_PROCESS; + info.BasicLimitInformation.ActiveProcessLimit = 1; + return SetInformationJobObject(get(), JobObjectExtendedLimitInformation, &info, sizeof(info)); + } + Execution::Bytes peakCommit() const { + JOBOBJECT_EXTENDED_LIMIT_INFORMATION info{}; + if (! QueryInformationJobObject(get(), JobObjectExtendedLimitInformation, &info, sizeof(info), + nullptr)) + return -1; + return static_cast(info.PeakProcessMemoryUsed); + } + }; + class ProcessUsage : public Execution::UsageProvider { + HANDLE process; + const ExecutionJob &job; + + public: + ProcessUsage(HANDLE process, const ExecutionJob &job) : process(process), job(job) {} + Execution::MemorySample sample() override { + PROCESS_MEMORY_COUNTERS_EX info{}; + info.cb = sizeof(info); + if (! GetProcessMemoryInfo(process, reinterpret_cast(&info), + sizeof(info))) + return {}; + return {std::max(static_cast(info.PrivateUsage), job.peakCommit()), + static_cast(std::max(info.WorkingSetSize, info.PeakWorkingSetSize))}; + } + }; + class ProcessKiller : public Execution::Killer { + HANDLE process; + HANDLE job; + + public: + ProcessKiller(HANDLE process, HANDLE job) : process(process), job(job) {} + bool killAndReap() override { + if (! TerminateJobObject(job, 1) && WaitForSingleObject(process, 0) != WAIT_OBJECT_0) + return false; + return WaitForSingleObject(process, 2000) == WAIT_OBJECT_0; + } + }; +} // namespace Lemon::Windows +#endif diff --git a/src/core/windowssandbox.cpp b/src/core/windowssandbox.cpp index f6d4c590..0f2b2892 100644 --- a/src/core/windowssandbox.cpp +++ b/src/core/windowssandbox.cpp @@ -98,7 +98,7 @@ namespace { } HANDLE file = CreateFileW(wide(nativePath), access, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, - nullptr, OPEN_EXISTING, flags, nullptr); + nullptr, OPEN_EXISTING, flags, nullptr); if (file == INVALID_HANDLE_VALUE && ! directory && ! privateFile && GetLastError() == ERROR_ACCESS_DENIED) { file = CreateFileW(wide(nativePath), READ_CONTROL | FILE_READ_ATTRIBUTES, @@ -232,7 +232,7 @@ struct WindowsSandbox::Data { std::vector capabilityList; std::vector> capabilitySids; - Handle job; + std::vector attributeBuffer; LPPROC_THREAD_ATTRIBUTE_LIST attributeList = nullptr; SECURITY_CAPABILITIES processCapabilities{}; @@ -248,7 +248,6 @@ struct WindowsSandbox::Data { session(config.sandboxSession ? config.sandboxSession : WindowsSandbox::createSession()) {} ~Data() { - job.reset(); if (! workingDirectory.isEmpty()) { QMutexLocker lock(&permissionsMutex); @@ -295,7 +294,7 @@ struct WindowsSandbox::Data { return false; } - bool prepareProcess(STARTUPINFOEXW &startup) { + bool prepareProcess(STARTUPINFOEXW &startup, HANDLE job) { DWORD handleCount = 0; for (HANDLE handle : {startup.StartupInfo.hStdInput, startup.StartupInfo.hStdOutput, startup.StartupInfo.hStdError}) { @@ -305,24 +304,12 @@ struct WindowsSandbox::Data { for (DWORD i = 0; i < handleCount; ++i) if (! inheritedHandles[i] || inheritedHandles[i] == INVALID_HANDLE_VALUE) return processFailure("Cannot open sandbox standard streams.", ERROR_INVALID_HANDLE); - - job.reset(CreateJobObjectW(nullptr, nullptr)); - if (! job) - return processFailure("Cannot create sandbox job."); - JOBOBJECT_EXTENDED_LIMIT_INFORMATION limits{}; - limits.BasicLimitInformation.LimitFlags = - JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE | JOB_OBJECT_LIMIT_ACTIVE_PROCESS; - // Use the job limit because the child-process creation - // attribute can fail AppContainer DLL initialization on Windows. - limits.BasicLimitInformation.ActiveProcessLimit = 1; - if (! SetInformationJobObject(job.get(), JobObjectExtendedLimitInformation, &limits, sizeof(limits))) - return processFailure("Cannot set sandbox process limits."); JOBOBJECT_BASIC_UI_RESTRICTIONS uiLimits{}; uiLimits.UIRestrictionsClass = JOB_OBJECT_UILIMIT_DESKTOP | JOB_OBJECT_UILIMIT_DISPLAYSETTINGS | JOB_OBJECT_UILIMIT_EXITWINDOWS | JOB_OBJECT_UILIMIT_GLOBALATOMS | JOB_OBJECT_UILIMIT_HANDLES | JOB_OBJECT_UILIMIT_READCLIPBOARD | JOB_OBJECT_UILIMIT_SYSTEMPARAMETERS | JOB_OBJECT_UILIMIT_WRITECLIPBOARD; - if (! SetInformationJobObject(job.get(), JobObjectBasicUIRestrictions, &uiLimits, sizeof(uiLimits))) + if (! SetInformationJobObject(job, JobObjectBasicUIRestrictions, &uiLimits, sizeof(uiLimits))) return processFailure("Cannot restrict sandbox desktop access."); SIZE_T attributeSize = 0; InitializeProcThreadAttributeList(nullptr, 3, 0, &attributeSize); @@ -333,7 +320,7 @@ struct WindowsSandbox::Data { attributeList = list; startup.lpAttributeList = attributeList; processCapabilities = {packageSid, capabilityList.data(), DWORD(capabilityList.size()), 0}; - jobs[0] = job.get(); + jobs[0] = job; if (! UpdateProcThreadAttribute(attributeList, 0, PROC_THREAD_ATTRIBUTE_SECURITY_CAPABILITIES, &processCapabilities, sizeof(processCapabilities), nullptr, nullptr) || @@ -686,8 +673,8 @@ bool WindowsSandbox::prepare(QString &error) { return result; } -bool WindowsSandbox::prepareProcess(STARTUPINFOEXW &startup, QString &error) { - const bool result = data->prepareProcess(startup); +bool WindowsSandbox::prepareProcess(STARTUPINFOEXW &startup, HANDLE job, QString &error) { + const bool result = data->prepareProcess(startup, job); error = data->error; return result; } diff --git a/src/core/windowssandbox.h b/src/core/windowssandbox.h index df5ac5c1..c733a705 100644 --- a/src/core/windowssandbox.h +++ b/src/core/windowssandbox.h @@ -19,7 +19,7 @@ class WindowsSandbox { WindowsSandbox(const WindowsSandbox &) = delete; WindowsSandbox &operator=(const WindowsSandbox &) = delete; bool prepare(QString &error); - bool prepareProcess(STARTUPINFOEXW &startup, QString &error); + bool prepareProcess(STARTUPINFOEXW &startup, HANDLE job, QString &error); const QProcessEnvironment &environment() const; int aclUpdates() const; bool cacheHit() const; From 32f9f516335213ec124e148e417644615091db22 Mon Sep 17 00:00:00 2001 From: sgt57 <198590103+sgt57@users.noreply.github.com> Date: Sat, 7 Nov 2026 18:39:51 +0800 Subject: [PATCH 04/37] refactor(process): centralize exit outcomes and bound process cleanup --- src/core/memorylimiter.h | 20 +++++++++++++++ src/core/processrunner_unix.cpp | 4 +-- src/core/processrunner_win.cpp | 7 +++--- tests/memory-limiter/main.cpp | 5 ++++ unix/watcher_unix.cpp | 44 ++++++++++++++++++++++++++++----- 5 files changed, 69 insertions(+), 11 deletions(-) diff --git a/src/core/memorylimiter.h b/src/core/memorylimiter.h index c4d23ffb..d52ba3b0 100644 --- a/src/core/memorylimiter.h +++ b/src/core/memorylimiter.h @@ -40,6 +40,14 @@ namespace Lemon::Execution { virtual bool killAndReap() = 0; }; + enum class ExitKind { Normal, RuntimeError, TimeLimit, StartError }; + enum class RunReason { Accepted, RuntimeError, TimeLimit, MemoryLimit, InternalError }; + struct RunOutcome { + RunReason reason; + MemorySample peaks; + Bytes usage; + }; + // Pure policy: OS operations and process exit classification belong to adapters. class Limiter { public: @@ -50,6 +58,18 @@ namespace Lemon::Execution { exceeded = exceeded || (limit >= 0 && usage() > limit); return exceeded; } + RunOutcome finish(ExitKind exit) const { + RunReason reason = RunReason::Accepted; + if (exit == ExitKind::StartError) + reason = RunReason::InternalError; + else if (exceeded) + reason = RunReason::MemoryLimit; + else if (exit == ExitKind::TimeLimit) + reason = RunReason::TimeLimit; + else if (exit == ExitKind::RuntimeError) + reason = RunReason::RuntimeError; + return {reason, peak, usage()}; + } Bytes usage() const { return std::max(peak.declared, peak.actual); } MemorySample peaks() const { return peak; } bool isExceeded() const { return exceeded; } diff --git a/src/core/processrunner_unix.cpp b/src/core/processrunner_unix.cpp index 419cff55..9aa6de44 100644 --- a/src/core/processrunner_unix.cpp +++ b/src/core/processrunner_unix.cpp @@ -178,8 +178,8 @@ ProcessRunnerResult UnixProcessRunner::run() { QElapsedTimer timer; timer.start(); - // Using rlimit to limit CPU time can only be accurate to seconds, - // so here it is rounded up to an integer second. + // Leave room for the watcher's explicit wall deadline and bounded reaping. + // Custom watchers retain the same outer watchdog protection. long long killTimeLimit = qMax(2000LL, 3LL * config.timeLimit) + 5000LL + extraTime; while (timer.elapsed() <= killTimeLimit) { if (runner.waitForFinished(10)) { diff --git a/src/core/processrunner_win.cpp b/src/core/processrunner_win.cpp index 204369d2..0a93cad3 100644 --- a/src/core/processrunner_win.cpp +++ b/src/core/processrunner_win.cpp @@ -129,8 +129,6 @@ ProcessRunnerResult WinProcessRunner::run() { } auto closeProcessHandle = qScopeGuard([&] { - if (sandbox) - WaitForSingleObject(pi.hProcess, 5000); CloseHandle(pi.hProcess); CloseHandle(pi.hThread); }); @@ -188,7 +186,10 @@ ProcessRunnerResult WinProcessRunner::run() { unsigned long exitCode; GetExitCodeProcess(pi.hProcess, &exitCode); - if (exitCode != 0) { + if (limiter + .finish(exitCode == 0 ? Lemon::Execution::ExitKind::Normal + : Lemon::Execution::ExitKind::RuntimeError) + .reason == Lemon::Execution::RunReason::RuntimeError) { res.score = 0; res.result = RunTimeError; diff --git a/tests/memory-limiter/main.cpp b/tests/memory-limiter/main.cpp index 7f493049..f4938e63 100644 --- a/tests/memory-limiter/main.cpp +++ b/tests/memory-limiter/main.cpp @@ -12,7 +12,12 @@ int main() { check(limited.peaks().declared == 100 && limited.peaks().actual == 90); check(limited.observe({-1, 101})); check(limited.observe({0, 0}) && limited.usage() == 101); + check(limited.finish(ExitKind::RuntimeError).reason == RunReason::MemoryLimit); + check(limited.finish(ExitKind::StartError).reason == RunReason::InternalError); Limiter unlimited(-1); + check(unlimited.finish(ExitKind::RuntimeError).reason == RunReason::RuntimeError); + check(unlimited.finish(ExitKind::Normal).reason == RunReason::Accepted); + check(unlimited.finish(ExitKind::TimeLimit).reason == RunReason::TimeLimit); check(unlimited.usage() == -1); check(! unlimited.observe({1000, 2000})); Bytes bytes; diff --git a/unix/watcher_unix.cpp b/unix/watcher_unix.cpp index 00bcdae6..01bcb0cc 100644 --- a/unix/watcher_unix.cpp +++ b/unix/watcher_unix.cpp @@ -27,6 +27,12 @@ namespace { rlimit memory{static_cast(limit), static_cast(limit)}; if (setrlimit(RLIMIT_AS, &memory) != 0) return false; + rlimit stack{}; + if (getrlimit(RLIMIT_STACK, &stack) != 0) + return false; + stack.rlim_cur = std::min(stack.rlim_max, static_cast(limit)); + if (setrlimit(RLIMIT_STACK, &stack) != 0) + return false; } #else (void)limit; // macOS intentionally has no memory prelimit. @@ -47,7 +53,12 @@ namespace { int status = 0; rusage usage{}; bool reaped = false; + bool cleaned = false; explicit UnixProcess(pid_t pid) : pid(pid) {} + ~UnixProcess() override { + if (! cleaned) + killAndReap(); + } // Do not destroy the exit information until all final samples are consumed. int poll() { if (reaped) @@ -62,6 +73,9 @@ namespace { return 0; } bool killAndReap() override { + if (cleaned) + return reaped; + cleaned = true; kill(-pid, SIGKILL); if (! reaped) kill(pid, SIGKILL); @@ -88,7 +102,7 @@ int main(int argc, char **argv) { try { long long timeLimit = std::stoll(argv[6]); Bytes limit; - if (! memoryBytes(std::stoll(argv[7]), limit) || timeLimit < 0) { + if (! memoryBytes(std::stoll(argv[7]), limit) || timeLimit < 0 || timeLimit > 86400000LL) { printf("-1\n-1\n"); return RS_FAIL; } @@ -132,6 +146,9 @@ int main(int argc, char **argv) { if (prctl(PR_SET_DUMPABLE, 0) != 0) fail(6); #endif + rlimit core{0, 0}; + if (setrlimit(RLIMIT_CORE, &core) != 0) + fail(7); UnixPrelimit prelimit; if (! prelimit.apply(limit)) fail(3); @@ -208,12 +225,27 @@ int main(int argc, char **argv) { limiter.observe({-1, rss}); #endif if (verdict == RS_AC) { - if (limiter.isExceeded()) - verdict = RS_MLE; - else if (WIFSIGNALED(process.status)) - verdict = WTERMSIG(process.status) == SIGXCPU ? RS_TLE : RS_RE; + ExitKind exit = ExitKind::Normal; + if (WIFSIGNALED(process.status)) + exit = WTERMSIG(process.status) == SIGXCPU ? ExitKind::TimeLimit : ExitKind::RuntimeError; else if (! WIFEXITED(process.status) || WEXITSTATUS(process.status) != 0) - verdict = RS_RE; + exit = ExitKind::RuntimeError; + switch (limiter.finish(exit).reason) { + case RunReason::MemoryLimit: + verdict = RS_MLE; + break; + case RunReason::TimeLimit: + verdict = RS_TLE; + break; + case RunReason::RuntimeError: + verdict = RS_RE; + break; + case RunReason::InternalError: + verdict = RS_FAIL; + break; + case RunReason::Accepted: + break; + } } } long long elapsed = From 52963a12c5feff9a3bbe72a7deb01d9348ca0836 Mon Sep 17 00:00:00 2001 From: sgt57 <198590103+sgt57@users.noreply.github.com> Date: Sat, 7 Nov 2026 18:43:29 +0800 Subject: [PATCH 05/37] test(process): cover memory accounting and prelimit failures --- .github/workflows/watcher_linux.yml | 4 +-- .github/workflows/watcher_macos.yml | 4 +-- tests/integrated-test/main.cpp | 33 ++++++++++++----------- tests/windows-sandbox/helper.cpp | 17 ++++++++++++ tests/windows-sandbox/main.cpp | 42 ++++++++++++++++++++--------- unix/test/CMakeLists.txt | 3 +++ 6 files changed, 71 insertions(+), 32 deletions(-) diff --git a/.github/workflows/watcher_linux.yml b/.github/workflows/watcher_linux.yml index 0967e6ca..3d967636 100644 --- a/.github/workflows/watcher_linux.yml +++ b/.github/workflows/watcher_linux.yml @@ -3,10 +3,10 @@ name: Watcher for Linux Test on: push: branches: ["master"] - paths: ["unix/**"] + paths: ["unix/**", "src/core/memorylimiter.h", "tests/memory-limiter/**"] pull_request: branches: ["master"] - paths: ["unix/**"] + paths: ["unix/**", "src/core/memorylimiter.h", "tests/memory-limiter/**"] workflow_dispatch: env: diff --git a/.github/workflows/watcher_macos.yml b/.github/workflows/watcher_macos.yml index d8e26fef..6386f634 100644 --- a/.github/workflows/watcher_macos.yml +++ b/.github/workflows/watcher_macos.yml @@ -3,10 +3,10 @@ name: Watcher for MacOS Test on: push: branches: ["master"] - paths: ["unix/**"] + paths: ["unix/**", "src/core/memorylimiter.h", "tests/memory-limiter/**"] pull_request: branches: ["master"] - paths: ["unix/**"] + paths: ["unix/**", "src/core/memorylimiter.h", "tests/memory-limiter/**"] workflow_dispatch: env: diff --git a/tests/integrated-test/main.cpp b/tests/integrated-test/main.cpp index 21be5d14..44d1097f 100644 --- a/tests/integrated-test/main.cpp +++ b/tests/integrated-test/main.cpp @@ -201,17 +201,23 @@ class IntegratedTest : public QObject { CompileState compilation; QList verdicts; }; + // Hard-prelimit platforms reject the allocation before resident usage grows. +#ifdef Q_OS_MACOS + const ResultState allocationVerdict = MemoryLimitExceeded; +#else + const ResultState allocationVerdict = RunTimeError; +#endif const QList expected = { {"user1", 0, CompileSuccessfully, {CorrectAnswer}}, {"user2", 0, NoValidSourceFile, {}}, {"user1", - 1, - CompileSuccessfully, - {CorrectAnswer, TimeLimitExceeded, MemoryLimitExceeded, WrongAnswer, RunTimeError, WrongAnswer}}, + 1, + CompileSuccessfully, + {CorrectAnswer, TimeLimitExceeded, allocationVerdict, WrongAnswer, RunTimeError, WrongAnswer}}, {"user2", - 1, - CompileSuccessfully, - {CorrectAnswer, CorrectAnswer, CorrectAnswer, CorrectAnswer, CorrectAnswer, CorrectAnswer}}, + 1, + CompileSuccessfully, + {CorrectAnswer, CorrectAnswer, CorrectAnswer, CorrectAnswer, CorrectAnswer, CorrectAnswer}}, }; for (const Expected &row : expected) { const Contestant *contestant = contest.getContestant(row.contestant); @@ -224,15 +230,12 @@ class IntegratedTest : public QObject { QCOMPARE(results[i].size(), 1); const ResultState actual = results[i][0]; const ResultState wanted = row.verdicts[i]; - // Allocation failures may be reported as MLE or RE depending on the platform. - const bool allocationFailure = wanted == MemoryLimitExceeded && actual == RunTimeError; - QVERIFY2(actual == wanted || allocationFailure, - qPrintable(QString("%1 task %2 case %3: expected %4, got %5") - .arg(row.contestant) - .arg(row.task) - .arg(i) - .arg(wanted) - .arg(actual))); + QVERIFY2(actual == wanted, qPrintable(QString("%1 task %2 case %3: expected %4, got %5") + .arg(row.contestant) + .arg(row.task) + .arg(i) + .arg(wanted) + .arg(actual))); } } } diff --git a/tests/windows-sandbox/helper.cpp b/tests/windows-sandbox/helper.cpp index 4f3fe5a9..5b94dd38 100644 --- a/tests/windows-sandbox/helper.cpp +++ b/tests/windows-sandbox/helper.cpp @@ -12,6 +12,10 @@ #include static bool readsSecret(HANDLE handle) { + // Parent handle values can be invalid or reused for a different object in the child. + DWORD flags = 0; + if (! GetHandleInformation(handle, &flags) || GetFileType(handle) != FILE_TYPE_DISK) + return false; #ifdef _MSC_VER __try { #endif @@ -288,6 +292,19 @@ int wmain(int argc, wchar_t **argv) { return int(code); } + if (mode == L"reserve" || mode == L"commit-caught" || mode == L"commit-rejected") { + const bool reserve = mode == L"reserve"; + void *p = VirtualAlloc(nullptr, 128 * 1024 * 1024, reserve ? MEM_RESERVE : (MEM_RESERVE | MEM_COMMIT), + PAGE_READWRITE); + if ((p != nullptr) != reserve) + return 37; + puts("expected"); + fflush(stdout); + Sleep(100); + if (p) + VirtualFree(p, 0, MEM_RELEASE); + return mode == L"commit-rejected" ? 12 : 0; + } if (mode == L"memory") { for (int i = 0; i < 256; ++i) { auto *memory = static_cast( diff --git a/tests/windows-sandbox/main.cpp b/tests/windows-sandbox/main.cpp index 403ebfa4..d2539da5 100644 --- a/tests/windows-sandbox/main.cpp +++ b/tests/windows-sandbox/main.cpp @@ -763,8 +763,23 @@ class WindowsSandboxTests : public QObject { PROCESS_MEMORY_COUNTERS memory{}; memory.cb = sizeof(memory); QVERIFY(GetProcessMemoryInfo(primary.get(), &memory, sizeof(memory))); - QCOMPARE(result.memoryUsed, qint64(memory.PeakWorkingSetSize)); - QVERIFY(result.memoryUsed < 64ll * 1024 * 1024); + QVERIFY(result.memoryUsed >= qint64(memory.PeakWorkingSetSize)); + QVERIFY(result.memoryUsed >= 64ll * 1024 * 1024); + } + + void memoryPrelimit_data() { primaryProcessAccounting_data(); } + void memoryPrelimit() { + QFETCH(bool, enabled); + for (const auto &mode : {"reserve", "commit-caught", "commit-rejected"}) { + auto cfg = config(mode); + cfg.sandboxSettings.enabled = enabled; + cfg.memoryLimit = 32; + auto result = run(cfg); + QCOMPARE(result.result, QString(mode) == "commit-rejected" ? RunTimeError : CorrectAnswer); + QVERIFY(result.memoryUsed > 0); + QVERIFY(result.memoryUsed <= 32ll * 1024 * 1024); + QVERIFY(read(cfg.workingDirectory + "_tmpout").contains("expected")); + } } void runtimeErrorDetails_data() { primaryProcessAccounting_data(); } @@ -776,7 +791,7 @@ class WindowsSandboxTests : public QObject { const auto result = run(cfg); QCOMPARE(result.result, RunTimeError); QCOMPARE(result.timeUsed, -1); - QCOMPARE(result.memoryUsed, -1); + QVERIFY(result.memoryUsed > 0); QCOMPARE(result.message, QString(1020, 'a') + "tail"); } @@ -784,9 +799,10 @@ class WindowsSandboxTests : public QObject { auto cpu = config("burn 3000"); cpu.timeLimit = 100; QCOMPARE(run(cpu).result, TimeLimitExceeded); - auto memory = config("memory"); + auto memory = config("commit-rejected"); memory.memoryLimit = 24; - QCOMPARE(run(memory).result, MemoryLimitExceeded); + // The Job refuses the next commit; helper exits nonzero without exceeding the limit. + QCOMPARE(run(memory).result, RunTimeError); } void cancellation() { @@ -821,7 +837,7 @@ class WindowsSandboxTests : public QObject { QVERIFY(! permissions(cfg.workingDirectory).contains("S-1-15-2-")); QCOMPARE(result.result, CorrectAnswer); QCOMPARE(result.timeUsed, -1); - QCOMPARE(result.memoryUsed, -1); + QVERIFY(result.memoryUsed > 0); } void runtimeDirectoryWithInput() { @@ -926,7 +942,7 @@ class WindowsSandboxTests : public QObject { source, extension == "c" ? "#include \nint main(void){int a,b;scanf(\"%d%d\",&a,&b);printf(\"%d\\n\",a+b);}" - : "#include \nint main(){int a,b;std::cin>>a>>b;std::cout<\nint main(){int a,b;std::cin>>a>>b;std::cout< Date: Sat, 7 Nov 2026 10:45:06 +0000 Subject: [PATCH 06/37] style: format codes --- src/core/processrunner_win.cpp | 8 ++++---- src/core/windowssandbox.cpp | 2 +- tests/integrated-test/main.cpp | 12 ++++++------ tests/windows-sandbox/main.cpp | 14 +++++++------- unix/watcher_unix.cpp | 2 +- 5 files changed, 19 insertions(+), 19 deletions(-) diff --git a/src/core/processrunner_win.cpp b/src/core/processrunner_win.cpp index 0a93cad3..70c886bf 100644 --- a/src/core/processrunner_win.cpp +++ b/src/core/processrunner_win.cpp @@ -76,14 +76,14 @@ ProcessRunnerResult WinProcessRunner::run() { if (config.standardOutputCheck) { siex.StartupInfo.hStdOutput = CreateFileW((const WCHAR *)((config.workingDirectory + "_tmpout").utf16()), GENERIC_WRITE, - FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, &sa, CREATE_ALWAYS, - FILE_ATTRIBUTE_NORMAL, NULL); + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, &sa, CREATE_ALWAYS, + FILE_ATTRIBUTE_NORMAL, NULL); } siex.StartupInfo.hStdError = CreateFileW((const WCHAR *)((config.workingDirectory + "_tmperr").utf16()), GENERIC_WRITE, - FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, &sa, CREATE_ALWAYS, - FILE_ATTRIBUTE_NORMAL, NULL); + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, &sa, CREATE_ALWAYS, + FILE_ATTRIBUTE_NORMAL, NULL); auto closeStdIO = qScopeGuard([&] { if (config.standardInputCheck) diff --git a/src/core/windowssandbox.cpp b/src/core/windowssandbox.cpp index 0f2b2892..006ab3c1 100644 --- a/src/core/windowssandbox.cpp +++ b/src/core/windowssandbox.cpp @@ -98,7 +98,7 @@ namespace { } HANDLE file = CreateFileW(wide(nativePath), access, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, - nullptr, OPEN_EXISTING, flags, nullptr); + nullptr, OPEN_EXISTING, flags, nullptr); if (file == INVALID_HANDLE_VALUE && ! directory && ! privateFile && GetLastError() == ERROR_ACCESS_DENIED) { file = CreateFileW(wide(nativePath), READ_CONTROL | FILE_READ_ATTRIBUTES, diff --git a/tests/integrated-test/main.cpp b/tests/integrated-test/main.cpp index 44d1097f..58b55ca5 100644 --- a/tests/integrated-test/main.cpp +++ b/tests/integrated-test/main.cpp @@ -211,13 +211,13 @@ class IntegratedTest : public QObject { {"user1", 0, CompileSuccessfully, {CorrectAnswer}}, {"user2", 0, NoValidSourceFile, {}}, {"user1", - 1, - CompileSuccessfully, - {CorrectAnswer, TimeLimitExceeded, allocationVerdict, WrongAnswer, RunTimeError, WrongAnswer}}, + 1, + CompileSuccessfully, + {CorrectAnswer, TimeLimitExceeded, allocationVerdict, WrongAnswer, RunTimeError, WrongAnswer}}, {"user2", - 1, - CompileSuccessfully, - {CorrectAnswer, CorrectAnswer, CorrectAnswer, CorrectAnswer, CorrectAnswer, CorrectAnswer}}, + 1, + CompileSuccessfully, + {CorrectAnswer, CorrectAnswer, CorrectAnswer, CorrectAnswer, CorrectAnswer, CorrectAnswer}}, }; for (const Expected &row : expected) { const Contestant *contestant = contest.getContestant(row.contestant); diff --git a/tests/windows-sandbox/main.cpp b/tests/windows-sandbox/main.cpp index d2539da5..2f910c60 100644 --- a/tests/windows-sandbox/main.cpp +++ b/tests/windows-sandbox/main.cpp @@ -942,7 +942,7 @@ class WindowsSandboxTests : public QObject { source, extension == "c" ? "#include \nint main(void){int a,b;scanf(\"%d%d\",&a,&b);printf(\"%d\\n\",a+b);}" - : "#include \nint main(){int a,b;std::cin>>a>>b;std::cout<\nint main(){int a,b;std::cin>>a>>b;std::cout< timeLimit) verdict = RS_TLE; printf("%lld\n%lld\n", elapsed, static_cast(limiter.usage())); From c5178a66272d948af2d662835b46f12c114a6ac7 Mon Sep 17 00:00:00 2001 From: sgt57 <198590103+sgt57@users.noreply.github.com> Date: Sat, 7 Nov 2026 18:54:00 +0800 Subject: [PATCH 07/37] fix(process): protect memory accounting from Windows max macro --- src/core/memorylimiter.h | 8 ++++---- src/core/windowsmemory.h | 4 ++-- tests/memory-limiter/CMakeLists.txt | 4 ++++ tests/memory-limiter/main.cpp | 6 ++++++ tests/memory-limiter/windows_macros.cpp | 14 ++++++++++++++ 5 files changed, 30 insertions(+), 6 deletions(-) create mode 100644 tests/memory-limiter/windows_macros.cpp diff --git a/src/core/memorylimiter.h b/src/core/memorylimiter.h index d52ba3b0..833a1258 100644 --- a/src/core/memorylimiter.h +++ b/src/core/memorylimiter.h @@ -17,7 +17,7 @@ namespace Lemon::Execution { bytes = -1; return true; } - if (mib > std::numeric_limits::max() / (1024 * 1024)) + if (mib > (std::numeric_limits::max)() / (1024 * 1024)) return false; bytes = mib * 1024 * 1024; return true; @@ -53,8 +53,8 @@ namespace Lemon::Execution { public: explicit Limiter(Bytes limit) : limit(limit) {} bool observe(MemorySample sample) { - peak.declared = std::max(peak.declared, sample.declared); - peak.actual = std::max(peak.actual, sample.actual); + peak.declared = (std::max)(peak.declared, sample.declared); + peak.actual = (std::max)(peak.actual, sample.actual); exceeded = exceeded || (limit >= 0 && usage() > limit); return exceeded; } @@ -70,7 +70,7 @@ namespace Lemon::Execution { reason = RunReason::RuntimeError; return {reason, peak, usage()}; } - Bytes usage() const { return std::max(peak.declared, peak.actual); } + Bytes usage() const { return (std::max)(peak.declared, peak.actual); } MemorySample peaks() const { return peak; } bool isExceeded() const { return exceeded; } diff --git a/src/core/windowsmemory.h b/src/core/windowsmemory.h index 20065bfb..96c0fa7b 100644 --- a/src/core/windowsmemory.h +++ b/src/core/windowsmemory.h @@ -54,8 +54,8 @@ namespace Lemon::Windows { if (! GetProcessMemoryInfo(process, reinterpret_cast(&info), sizeof(info))) return {}; - return {std::max(static_cast(info.PrivateUsage), job.peakCommit()), - static_cast(std::max(info.WorkingSetSize, info.PeakWorkingSetSize))}; + return {(std::max)(static_cast(info.PrivateUsage), job.peakCommit()), + static_cast((std::max)(info.WorkingSetSize, info.PeakWorkingSetSize))}; } }; class ProcessKiller : public Execution::Killer { diff --git a/tests/memory-limiter/CMakeLists.txt b/tests/memory-limiter/CMakeLists.txt index 4ba061b2..00f4f7dc 100644 --- a/tests/memory-limiter/CMakeLists.txt +++ b/tests/memory-limiter/CMakeLists.txt @@ -1,2 +1,6 @@ add_executable(memory-limiter-test main.cpp) +if(WIN32) + target_sources(memory-limiter-test PRIVATE windows_macros.cpp) + target_link_libraries(memory-limiter-test PRIVATE ${LEMON_QT_LIBNAME}::Core) +endif() add_test(NAME memory-limiter COMMAND memory-limiter-test) diff --git a/tests/memory-limiter/main.cpp b/tests/memory-limiter/main.cpp index f4938e63..b8e3b74c 100644 --- a/tests/memory-limiter/main.cpp +++ b/tests/memory-limiter/main.cpp @@ -1,4 +1,10 @@ +#include +#include +#include +// Reproduce the Windows SDK function-like macro, including with a PCH. +#define max(a, b) windows_max_macro_must_not_expand(a, b) #include "../../src/core/memorylimiter.h" +#undef max #include using namespace Lemon::Execution; void check(bool value) { diff --git a/tests/memory-limiter/windows_macros.cpp b/tests/memory-limiter/windows_macros.cpp new file mode 100644 index 00000000..14506b31 --- /dev/null +++ b/tests/memory-limiter/windows_macros.cpp @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +#include "../../src/core/windowsprocessutils.h" +#include +#include +#include +#include + +// Define after dependency headers so their macro cleanup cannot hide the regression. +#ifdef max +#undef max +#endif +#define max(a, b) windows_max_macro_must_not_expand(a, b) +#include "../../src/core/windowsmemory.h" +#undef max From 85d0d8ccd203a9a6e76e3b7800bc1834b97f3005 Mon Sep 17 00:00:00 2001 From: "GitHub Action (clang-format)" Date: Sat, 7 Nov 2026 10:56:06 +0000 Subject: [PATCH 08/37] style: format codes --- tests/memory-limiter/windows_macros.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/memory-limiter/windows_macros.cpp b/tests/memory-limiter/windows_macros.cpp index 14506b31..e9fd7311 100644 --- a/tests/memory-limiter/windows_macros.cpp +++ b/tests/memory-limiter/windows_macros.cpp @@ -1,9 +1,9 @@ // SPDX-License-Identifier: GPL-3.0-or-later #include "../../src/core/windowsprocessutils.h" -#include #include #include #include +#include // Define after dependency headers so their macro cleanup cannot hide the regression. #ifdef max From d5fdeba0d09ae666ac1dddbfee77ef1a880d0094 Mon Sep 17 00:00:00 2001 From: sgt57 <198590103+sgt57@users.noreply.github.com> Date: Sat, 7 Nov 2026 19:00:19 +0800 Subject: [PATCH 09/37] fix(ci): skip Qt deployment for memory limiter test --- .github/workflows/windows-qt6.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/windows-qt6.yml b/.github/workflows/windows-qt6.yml index 3f0ff731..af6a232c 100644 --- a/.github/workflows/windows-qt6.yml +++ b/.github/workflows/windows-qt6.yml @@ -91,8 +91,9 @@ jobs: - name: Deploy Qt for tests shell: pwsh run: | + # These helpers do not import Qt at runtime. Get-ChildItem tests -Recurse -Filter *.exe | - Where-Object { $_.Name -ne 'sandbox-helper.exe' } | + Where-Object { $_.Name -notin @('sandbox-helper.exe', 'memory-limiter-test.exe') } | ForEach-Object { windeployqt $_.FullName if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } From 24956a1caf1b320a4943924257fb18d44b8fb964 Mon Sep 17 00:00:00 2001 From: sgt57 <198590103+sgt57@users.noreply.github.com> Date: Sat, 7 Nov 2026 13:19:48 +0800 Subject: [PATCH 10/37] fix(tests): statically link MinGW sandbox helper runtime --- tests/windows-sandbox/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/windows-sandbox/CMakeLists.txt b/tests/windows-sandbox/CMakeLists.txt index 522ab307..1786699e 100644 --- a/tests/windows-sandbox/CMakeLists.txt +++ b/tests/windows-sandbox/CMakeLists.txt @@ -5,7 +5,7 @@ if(MSVC) set_property(TARGET sandbox-helper PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") endif() if(MINGW) - target_link_options(sandbox-helper PRIVATE -municode) + target_link_options(sandbox-helper PRIVATE -municode -static) endif() target_link_libraries(sandbox-helper PRIVATE advapi32 ws2_32) From b4fc9c1aaade879b5813643de9030fc7b5e1e8e6 Mon Sep 17 00:00:00 2001 From: sgt57 <198590103+sgt57@users.noreply.github.com> Date: Sat, 7 Nov 2026 20:07:49 +0800 Subject: [PATCH 11/37] fix(tests): guard sandbox handle queries with SEH --- tests/windows-sandbox/CMakeLists.txt | 3 +++ tests/windows-sandbox/helper.cpp | 12 ++++++------ 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/tests/windows-sandbox/CMakeLists.txt b/tests/windows-sandbox/CMakeLists.txt index 1786699e..f98f41a1 100644 --- a/tests/windows-sandbox/CMakeLists.txt +++ b/tests/windows-sandbox/CMakeLists.txt @@ -6,6 +6,9 @@ if(MSVC) endif() if(MINGW) target_link_options(sandbox-helper PRIVATE -municode -static) + if(CMAKE_CXX_COMPILER_ID MATCHES "Clang") + target_compile_options(sandbox-helper PRIVATE -fms-extensions) + endif() endif() target_link_libraries(sandbox-helper PRIVATE advapi32 ws2_32) diff --git a/tests/windows-sandbox/helper.cpp b/tests/windows-sandbox/helper.cpp index 5b94dd38..8061b4c3 100644 --- a/tests/windows-sandbox/helper.cpp +++ b/tests/windows-sandbox/helper.cpp @@ -12,18 +12,18 @@ #include static bool readsSecret(HANDLE handle) { - // Parent handle values can be invalid or reused for a different object in the child. - DWORD flags = 0; - if (! GetHandleInformation(handle, &flags) || GetFileType(handle) != FILE_TYPE_DISK) - return false; -#ifdef _MSC_VER +#if defined(_MSC_VER) || defined(__clang__) __try { #endif + // Queries on a missing parent handle can raise STATUS_INVALID_HANDLE too. + DWORD flags = 0; + if (! GetHandleInformation(handle, &flags) || GetFileType(handle) != FILE_TYPE_DISK) + return false; char buffer[64]{}; DWORD length = 0; return ReadFile(handle, buffer, sizeof(buffer), &length, nullptr) && length >= 6 && memcmp(buffer, "secret", 6) == 0; -#ifdef _MSC_VER +#if defined(_MSC_VER) || defined(__clang__) } __except (EXCEPTION_EXECUTE_HANDLER) { return false; } From 99756a4a1f8a2dfc576294cbf8cdbdf731133a9c Mon Sep 17 00:00:00 2001 From: sgt57 <198590103+sgt57@users.noreply.github.com> Date: Sat, 7 Nov 2026 21:42:08 +0800 Subject: [PATCH 12/37] fix(tests): address Codacy memory supervision findings --- tests/windows-sandbox/main.cpp | 54 +++++++++++++++++----------------- unix/test/memory_cases.cpp | 9 +++--- unix/test/scripts/memory.py | 6 ++-- unix/watcher_unix.cpp | 4 +++ 4 files changed, 40 insertions(+), 33 deletions(-) diff --git a/tests/windows-sandbox/main.cpp b/tests/windows-sandbox/main.cpp index 2f910c60..679ab4dc 100644 --- a/tests/windows-sandbox/main.cpp +++ b/tests/windows-sandbox/main.cpp @@ -100,7 +100,7 @@ class WindowsSandboxTests : public QObject { return file.open(QIODevice::WriteOnly) && file.write(bytes) == bytes.size(); } - static QByteArray read(const QString &path) { + static QByteArray readFile(const QString &path) { QFile file(path); if (! file.open(QIODevice::ReadOnly)) return {}; @@ -215,7 +215,7 @@ class WindowsSandboxTests : public QObject { const auto result = run(cfg); QVERIFY2(result.result == CorrectAnswer, qPrintable(result.message)); - QCOMPARE(read(cfg.workingDirectory + "_tmpout").trimmed(), QByteArray("host")); + QCOMPARE(readFile(cfg.workingDirectory + "_tmpout").trimmed(), QByteArray("host")); QCOMPARE(result.preparationTime, 0); QCOMPARE(result.runtimeAclUpdates, 0); QVERIFY(! cfg.sandboxSession); @@ -230,7 +230,7 @@ class WindowsSandboxTests : public QObject { const auto result = run(cfg); QVERIFY2(result.result == CorrectAnswer, qPrintable(result.message)); - QCOMPARE(read(cfg.workingDirectory + "_tmpout").trimmed(), QByteArray("42")); + QCOMPARE(readFile(cfg.workingDirectory + "_tmpout").trimmed(), QByteArray("42")); QVERIFY(result.memoryUsed > 0); } @@ -317,7 +317,7 @@ class WindowsSandboxTests : public QObject { const QDir workingDirectory(error.mid(prefix.size())); QVERIFY(workingDirectory.exists("program.dummy")); QVERIFY(! workingDirectory.exists("created")); - QCOMPARE(read(workingDirectory.filePath("../_2.0/created/nested/data.txt")), QByteArray("created")); + QCOMPARE(readFile(workingDirectory.filePath("../_2.0/created/nested/data.txt")), QByteArray("created")); } void commandLineArguments_data() { @@ -345,7 +345,7 @@ class WindowsSandboxTests : public QObject { const auto result = run(cfg); QVERIFY2(result.result == CorrectAnswer, qPrintable(result.message)); - QCOMPARE(read(cfg.workingDirectory + "_tmpout").replace("\r\n", "\n"), + QCOMPARE(readFile(cfg.workingDirectory + "_tmpout").replace("\r\n", "\n"), arguments.join('\n').toUtf8() + '\n'); } @@ -419,7 +419,7 @@ class WindowsSandboxTests : public QObject { const auto result = run(cfg); QVERIFY2(result.result == CorrectAnswer, qPrintable(result.message)); const auto output = cfg.standardOutputCheck ? QString("_tmpout") : cfg.outputFileName; - QCOMPARE(read(cfg.workingDirectory + output).trimmed(), QByteArray("42")); + QCOMPARE(readFile(cfg.workingDirectory + output).trimmed(), QByteArray("42")); } void isolationAndHandles() { @@ -432,7 +432,7 @@ class WindowsSandboxTests : public QObject { const auto result = run(cfg); QVERIFY2(result.result == CorrectAnswer, qPrintable(result.message)); - QCOMPARE(read(cfg.workingDirectory + "_tmpout").trimmed(), QByteArray("isolated")); + QCOMPARE(readFile(cfg.workingDirectory + "_tmpout").trimmed(), QByteArray("isolated")); QVERIFY(QFileInfo::exists(cfg.workingDirectory + "own.txt")); } @@ -528,7 +528,7 @@ class WindowsSandboxTests : public QObject { QVERIFY2(result.result == CorrectAnswer, qPrintable(result.message)); for (int i = 0; i < existing.size(); ++i) QCOMPARE(permissions(existing[i]), before[i]); - QCOMPARE(read(cfg.workingDirectory + "created/nested/data.txt"), QByteArray("created")); + QCOMPARE(readFile(cfg.workingDirectory + "created/nested/data.txt"), QByteArray("created")); for (const auto &name : {"created", "created/nested", "created/nested/data.txt", "_tmpout", "_tmperr"}) { const auto acl = permissions(cfg.workingDirectory + name); @@ -560,7 +560,7 @@ class WindowsSandboxTests : public QObject { QVERIFY2(result.result == CorrectAnswer, qPrintable(result.message)); QVERIFY(result.runtimeCacheHit); QCOMPARE(result.runtimeAclUpdates, 0); - QCOMPARE(read(second.workingDirectory + "_tmpout").trimmed(), QByteArray("readonly")); + QCOMPARE(readFile(second.workingDirectory + "_tmpout").trimmed(), QByteArray("readonly")); two.reset(); first.sandboxSession.reset(); second.sandboxSession.reset(); @@ -722,7 +722,7 @@ class WindowsSandboxTests : public QObject { const auto result = run(cfg); QVERIFY2(result.result == CorrectAnswer, qPrintable(result.message)); - QVERIFY(read(cfg.workingDirectory + "_tmpout").startsWith("child-denied=")); + QVERIFY(readFile(cfg.workingDirectory + "_tmpout").startsWith("child-denied=")); } void primaryProcessAccounting_data() { @@ -742,7 +742,7 @@ class WindowsSandboxTests : public QObject { timer.start(); while (! primary && timer.elapsed() < 5000) { const auto match = QRegularExpression("process=(\\d+)") - .match(QString::fromUtf8(read(cfg.workingDirectory + "_tmpout"))); + .match(QString::fromUtf8(readFile(cfg.workingDirectory + "_tmpout"))); if (match.hasMatch()) { primary.reset(OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ | SYNCHRONIZE, FALSE, match.captured(1).toULong())); @@ -778,7 +778,7 @@ class WindowsSandboxTests : public QObject { QCOMPARE(result.result, QString(mode) == "commit-rejected" ? RunTimeError : CorrectAnswer); QVERIFY(result.memoryUsed > 0); QVERIFY(result.memoryUsed <= 32ll * 1024 * 1024); - QVERIFY(read(cfg.workingDirectory + "_tmpout").contains("expected")); + QVERIFY(readFile(cfg.workingDirectory + "_tmpout").contains("expected")); } } @@ -821,7 +821,7 @@ class WindowsSandboxTests : public QObject { timer.start(); while (! primary && timer.elapsed() < 5000) { const auto match = QRegularExpression("process=(\\d+)") - .match(QString::fromUtf8(read(cfg.workingDirectory + "_tmpout"))); + .match(QString::fromUtf8(readFile(cfg.workingDirectory + "_tmpout"))); if (match.hasMatch()) primary.reset(OpenProcess(SYNCHRONIZE, FALSE, match.captured(1).toULong())); if (! primary) @@ -848,7 +848,7 @@ class WindowsSandboxTests : public QObject { cfg.inputFile = directory + "/input.txt"; cfg.sandboxSettings.readOnlyDirectories = {directory}; QCOMPARE(run(cfg).result, CorrectAnswer); - QCOMPARE(read(cfg.workingDirectory + "_tmpout").trimmed(), QByteArray("42")); + QCOMPARE(readFile(cfg.workingDirectory + "_tmpout").trimmed(), QByteArray("42")); } void rejectHardLinkedWorkFile() { @@ -860,7 +860,7 @@ class WindowsSandboxTests : public QObject { const auto result = run(cfg); QCOMPARE(result.result, CannotStartProgram); - QCOMPARE(read(target), QByteArray("secret answer\n")); + QCOMPARE(readFile(target), QByteArray("secret answer\n")); QCOMPARE(permissions(cfg.workingDirectory), beforeDirectory); QCOMPARE(permissions(cfg.executableFile), beforeExecutable); } @@ -885,7 +885,7 @@ class WindowsSandboxTests : public QObject { QElapsedTimer timer; timer.start(); while (! probeId && timer.elapsed() < 5000) { - probeId = read(marker).trimmed().toULong(); + probeId = readFile(marker).trimmed().toULong(); if (! probeId) QThread::msleep(10); } @@ -917,8 +917,8 @@ class WindowsSandboxTests : public QObject { worker.join(); QVERIFY2(one.result == CorrectAnswer, qPrintable(one.message)); QVERIFY2(two.result == CorrectAnswer, qPrintable(two.message)); - QCOMPARE(read(first.workingDirectory + "_tmpout").trimmed(), QByteArray("isolated")); - QCOMPARE(read(second.workingDirectory + "_tmpout").trimmed(), QByteArray("isolated")); + QCOMPARE(readFile(first.workingDirectory + "_tmpout").trimmed(), QByteArray("isolated")); + QCOMPARE(readFile(second.workingDirectory + "_tmpout").trimmed(), QByteArray("isolated")); } void nativeCompiler_data() { @@ -950,7 +950,7 @@ class WindowsSandboxTests : public QObject { const auto result = run(cfg); QVERIFY2(result.result == CorrectAnswer, qPrintable(result.message)); - QCOMPARE(read(cfg.workingDirectory + "_tmpout").trimmed(), QByteArray("42")); + QCOMPARE(readFile(cfg.workingDirectory + "_tmpout").trimmed(), QByteArray("42")); } void settingsRoundTrip() { @@ -996,7 +996,7 @@ class WindowsSandboxTests : public QObject { const auto first = run(cfg); QVERIFY2(first.result == CorrectAnswer, qPrintable(first.message)); - QCOMPARE(read(cfg.workingDirectory + "_tmpout"), QByteArray("42 \xe9")); + QCOMPARE(readFile(cfg.workingDirectory + "_tmpout"), QByteArray("42 \xe9")); const auto second = run(cfg); QVERIFY2(second.result == CorrectAnswer, qPrintable(second.message)); @@ -1026,12 +1026,12 @@ class WindowsSandboxTests : public QObject { const auto ordinary = run(cfg); QVERIFY2(ordinary.result == CorrectAnswer, qPrintable(ordinary.message)); - QCOMPARE(read(cfg.workingDirectory + "_tmpout").trimmed(), QByteArray("allowed")); + QCOMPARE(readFile(cfg.workingDirectory + "_tmpout").trimmed(), QByteArray("allowed")); cfg.sandboxSettings.enabled = true; const auto restricted = run(cfg); QVERIFY2(restricted.result == CorrectAnswer, qPrintable(restricted.message)); - QCOMPARE(read(cfg.workingDirectory + "_tmpout").trimmed(), QByteArray("denied")); + QCOMPARE(readFile(cfg.workingDirectory + "_tmpout").trimmed(), QByteArray("denied")); } void pythonVenv() { @@ -1051,14 +1051,14 @@ class WindowsSandboxTests : public QObject { const auto ordinary = run(cfg); QVERIFY2(ordinary.result == CorrectAnswer, qPrintable(ordinary.message)); - QCOMPARE(read(cfg.workingDirectory + "_tmpout").trimmed(), QByteArray("42")); + QCOMPARE(readFile(cfg.workingDirectory + "_tmpout").trimmed(), QByteArray("42")); cfg.sandboxSettings.enabled = true; const auto restricted = run(cfg); QCOMPARE(restricted.result, RunTimeError); QVERIFY2(restricted.message.contains("Unable to create process", Qt::CaseInsensitive), qPrintable(restricted.message)); - QVERIFY(read(cfg.workingDirectory + "_tmpout").isEmpty()); + QVERIFY(readFile(cfg.workingDirectory + "_tmpout").isEmpty()); } void javaRuntime() { @@ -1080,7 +1080,7 @@ class WindowsSandboxTests : public QObject { const auto first = run(cfg); QVERIFY2(first.result == CorrectAnswer, qPrintable(first.message)); - QCOMPARE(read(cfg.workingDirectory + "_tmpout").trimmed(), QByteArray("42")); + QCOMPARE(readFile(cfg.workingDirectory + "_tmpout").trimmed(), QByteArray("42")); const auto second = run(cfg); QVERIFY2(second.result == CorrectAnswer, qPrintable(second.message)); @@ -1111,12 +1111,12 @@ class WindowsSandboxTests : public QObject { const auto ordinary = run(cfg); QVERIFY2(ordinary.result == CorrectAnswer, qPrintable(ordinary.message)); - QCOMPARE(read(cfg.workingDirectory + "_tmpout").trimmed(), QByteArray("allowed")); + QCOMPARE(readFile(cfg.workingDirectory + "_tmpout").trimmed(), QByteArray("allowed")); cfg.sandboxSettings.enabled = true; const auto restricted = run(cfg); QVERIFY2(restricted.result == CorrectAnswer, qPrintable(restricted.message)); - QCOMPARE(read(cfg.workingDirectory + "_tmpout").trimmed(), QByteArray("denied")); + QCOMPARE(readFile(cfg.workingDirectory + "_tmpout").trimmed(), QByteArray("denied")); } }; diff --git a/unix/test/memory_cases.cpp b/unix/test/memory_cases.cpp index a0f52a1c..158a9aae 100644 --- a/unix/test/memory_cases.cpp +++ b/unix/test/memory_cases.cpp @@ -1,10 +1,11 @@ // SPDX-License-Identifier: GPL-3.0-or-later +#include #include #include #include #include #include -#include +#include int main(int argc, char **argv) { if (argc != 2) return 1; @@ -29,17 +30,17 @@ int main(int argc, char **argv) { return 7; for (int i = 0; i < 96 * 1024 * 1024; i += 4096) p[i] = 1; - usleep(300000); + std::this_thread::sleep_for(std::chrono::milliseconds(300)); return 0; } if (! strcmp(argv[1], "reserve")) { void *p = mmap(nullptr, 128 * 1024 * 1024, PROT_NONE, MAP_PRIVATE | MAP_ANON, -1, 0); puts(p == MAP_FAILED ? "denied" : "reserved"); - usleep(100000); + std::this_thread::sleep_for(std::chrono::milliseconds(100)); return 0; } if (! strcmp(argv[1], "sleep")) { - sleep(20); + std::this_thread::sleep_for(std::chrono::seconds(20)); return 0; } return 2; diff --git a/unix/test/scripts/memory.py b/unix/test/scripts/memory.py index eae42618..c4a04a9b 100644 --- a/unix/test/scripts/memory.py +++ b/unix/test/scripts/memory.py @@ -1,13 +1,15 @@ import os import platform -import subprocess +# subprocess is required to run the local regression-test fixtures. +import subprocess # nosec B404 import tempfile with tempfile.TemporaryDirectory() as directory: def run(mode, limit=64): output = os.path.join(directory, 'out') error = os.path.join(directory, 'err') - p = subprocess.run(['./watcher_unix', './memory_cases', mode, '', output, error, + # Fixed local binaries and test-controlled arguments; no shell is involved. + p = subprocess.run(['./watcher_unix', './memory_cases', mode, '', output, error, # nosec B603 '1000', str(limit), '1000', str(limit), '', ''], stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=8) fields = p.stdout.decode().split() diff --git a/unix/watcher_unix.cpp b/unix/watcher_unix.cpp index c978c8f3..b262ccb7 100644 --- a/unix/watcher_unix.cpp +++ b/unix/watcher_unix.cpp @@ -178,6 +178,8 @@ int main(int argc, char **argv) { for (;;) { auto sample = provider.sample(); limiter.observe(sample); + // The fixed-size read is bounded by the destination object on every iteration. + /* Flawfinder: ignore */ if (read(errors[0], &childError, sizeof(childError)) == sizeof(childError)) setupFailed = true; int finished = process.poll(); @@ -208,6 +210,8 @@ int main(int argc, char **argv) { std::this_thread::sleep_for(std::chrono::milliseconds(10)); } // Catch setup errors delivered concurrently with the final wait. + // The final read uses the same destination-size bound. + /* Flawfinder: ignore */ if (read(errors[0], &childError, sizeof(childError)) == sizeof(childError)) setupFailed = true; close(errors[0]); From 414b7c07d73acf2900d8acb86c49a252e1134600 Mon Sep 17 00:00:00 2001 From: "GitHub Action (clang-format)" Date: Sat, 7 Nov 2026 13:43:07 +0000 Subject: [PATCH 13/37] style: format codes --- tests/windows-sandbox/main.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/windows-sandbox/main.cpp b/tests/windows-sandbox/main.cpp index 679ab4dc..6d5d90bc 100644 --- a/tests/windows-sandbox/main.cpp +++ b/tests/windows-sandbox/main.cpp @@ -317,7 +317,8 @@ class WindowsSandboxTests : public QObject { const QDir workingDirectory(error.mid(prefix.size())); QVERIFY(workingDirectory.exists("program.dummy")); QVERIFY(! workingDirectory.exists("created")); - QCOMPARE(readFile(workingDirectory.filePath("../_2.0/created/nested/data.txt")), QByteArray("created")); + QCOMPARE(readFile(workingDirectory.filePath("../_2.0/created/nested/data.txt")), + QByteArray("created")); } void commandLineArguments_data() { From ed2aea71285dc8d95afb0109d5aa8091fac97784 Mon Sep 17 00:00:00 2001 From: sgt57 <198590103+sgt57@users.noreply.github.com> Date: Sat, 7 Nov 2026 22:11:42 +0800 Subject: [PATCH 14/37] refactor(process): account memory by declared usage only --- src/core/memorylimiter.h | 20 +++++++------------- src/core/processrunner_win.cpp | 6 +++--- src/core/windowsmemory.h | 18 +++++------------- tests/memory-limiter/main.cpp | 14 ++++++++------ unix/memoryusage.h | 4 +++- unix/watcher_linux.cpp | 9 +++------ unix/watcher_macos.mm | 6 +++--- unix/watcher_unix.cpp | 10 ++++------ 8 files changed, 36 insertions(+), 51 deletions(-) diff --git a/src/core/memorylimiter.h b/src/core/memorylimiter.h index 833a1258..e8df2257 100644 --- a/src/core/memorylimiter.h +++ b/src/core/memorylimiter.h @@ -7,10 +7,6 @@ namespace Lemon::Execution { using Bytes = std::int64_t; - struct MemorySample { - Bytes declared = -1; - Bytes actual = -1; - }; inline bool memoryBytes(std::int64_t mib, Bytes &bytes) { if (mib < 0) { @@ -26,7 +22,8 @@ namespace Lemon::Execution { class UsageProvider { public: virtual ~UsageProvider() = default; - virtual MemorySample sample() = 0; + // DeclaredUsage in bytes; negative means unavailable. + virtual Bytes sample() = 0; }; class Prelimit { public: @@ -44,7 +41,6 @@ namespace Lemon::Execution { enum class RunReason { Accepted, RuntimeError, TimeLimit, MemoryLimit, InternalError }; struct RunOutcome { RunReason reason; - MemorySample peaks; Bytes usage; }; @@ -52,9 +48,8 @@ namespace Lemon::Execution { class Limiter { public: explicit Limiter(Bytes limit) : limit(limit) {} - bool observe(MemorySample sample) { - peak.declared = (std::max)(peak.declared, sample.declared); - peak.actual = (std::max)(peak.actual, sample.actual); + bool observe(Bytes declaredUsage) { + peak = (std::max)(peak, declaredUsage); exceeded = exceeded || (limit >= 0 && usage() > limit); return exceeded; } @@ -68,15 +63,14 @@ namespace Lemon::Execution { reason = RunReason::TimeLimit; else if (exit == ExitKind::RuntimeError) reason = RunReason::RuntimeError; - return {reason, peak, usage()}; + return {reason, usage()}; } - Bytes usage() const { return (std::max)(peak.declared, peak.actual); } - MemorySample peaks() const { return peak; } + Bytes usage() const { return peak; } bool isExceeded() const { return exceeded; } private: Bytes limit; - MemorySample peak; + Bytes peak = -1; bool exceeded = false; }; } // namespace Lemon::Execution diff --git a/src/core/processrunner_win.cpp b/src/core/processrunner_win.cpp index 70c886bf..0af4f8a4 100644 --- a/src/core/processrunner_win.cpp +++ b/src/core/processrunner_win.cpp @@ -145,7 +145,7 @@ ProcessRunnerResult WinProcessRunner::run() { res.message = "Cannot attach or resume process"; return res; } - ProcessUsage provider(pi.hProcess, job); + ProcessUsage provider(pi.hProcess); Lemon::Execution::Limiter limiter(memoryLimit); QElapsedTimer timer; timer.start(); @@ -160,7 +160,7 @@ ProcessRunnerResult WinProcessRunner::run() { } DWORD state = WaitForSingleObject(pi.hProcess, 0); if (state == WAIT_OBJECT_0) { - limiter.observe({job.peakCommit(), -1}); + limiter.observe(provider.sample()); res.memoryUsed = limiter.usage(); if (limiter.isExceeded()) { res.result = MemoryLimitExceeded; @@ -168,7 +168,7 @@ ProcessRunnerResult WinProcessRunner::run() { } break; } - missing = sample.declared < 0 || sample.actual < 0 ? missing + 1 : 0; + missing = sample < 0 ? missing + 1 : 0; if (state == WAIT_FAILED || missing >= 10) { res.result = CannotStartProgram; res.message = "Process statistics unavailable"; diff --git a/src/core/windowsmemory.h b/src/core/windowsmemory.h index 96c0fa7b..c5609d04 100644 --- a/src/core/windowsmemory.h +++ b/src/core/windowsmemory.h @@ -34,28 +34,20 @@ namespace Lemon::Windows { info.BasicLimitInformation.ActiveProcessLimit = 1; return SetInformationJobObject(get(), JobObjectExtendedLimitInformation, &info, sizeof(info)); } - Execution::Bytes peakCommit() const { - JOBOBJECT_EXTENDED_LIMIT_INFORMATION info{}; - if (! QueryInformationJobObject(get(), JobObjectExtendedLimitInformation, &info, sizeof(info), - nullptr)) - return -1; - return static_cast(info.PeakProcessMemoryUsed); - } }; class ProcessUsage : public Execution::UsageProvider { HANDLE process; - const ExecutionJob &job; public: - ProcessUsage(HANDLE process, const ExecutionJob &job) : process(process), job(job) {} - Execution::MemorySample sample() override { + explicit ProcessUsage(HANDLE process) : process(process) {} + Execution::Bytes sample() override { PROCESS_MEMORY_COUNTERS_EX info{}; info.cb = sizeof(info); if (! GetProcessMemoryInfo(process, reinterpret_cast(&info), sizeof(info))) - return {}; - return {(std::max)(static_cast(info.PrivateUsage), job.peakCommit()), - static_cast((std::max)(info.WorkingSetSize, info.PeakWorkingSetSize))}; + return -1; + // PeakPagefileUsage is the process lifetime peak of private committed memory. + return static_cast(info.PeakPagefileUsage); } }; class ProcessKiller : public Execution::Killer { diff --git a/tests/memory-limiter/main.cpp b/tests/memory-limiter/main.cpp index b8e3b74c..38288db0 100644 --- a/tests/memory-limiter/main.cpp +++ b/tests/memory-limiter/main.cpp @@ -13,11 +13,12 @@ void check(bool value) { } int main() { Limiter limited(100); - check(! limited.observe({100, 10})); - check(! limited.observe({20, 90})); - check(limited.peaks().declared == 100 && limited.peaks().actual == 90); - check(limited.observe({-1, 101})); - check(limited.observe({0, 0}) && limited.usage() == 101); + check(! limited.observe(100)); + check(! limited.observe(20)); + check(limited.usage() == 100); + check(! limited.observe(-1) && limited.usage() == 100); + check(limited.observe(101)); + check(limited.observe(0) && limited.usage() == 101); check(limited.finish(ExitKind::RuntimeError).reason == RunReason::MemoryLimit); check(limited.finish(ExitKind::StartError).reason == RunReason::InternalError); Limiter unlimited(-1); @@ -25,7 +26,8 @@ int main() { check(unlimited.finish(ExitKind::Normal).reason == RunReason::Accepted); check(unlimited.finish(ExitKind::TimeLimit).reason == RunReason::TimeLimit); check(unlimited.usage() == -1); - check(! unlimited.observe({1000, 2000})); + check(! unlimited.observe(1000)); + check(unlimited.finish(ExitKind::Normal).usage == 1000); Bytes bytes; check(memoryBytes(-1, bytes) && bytes == -1); check(memoryBytes(4096, bytes) && bytes == 4294967296LL); diff --git a/unix/memoryusage.h b/unix/memoryusage.h index b2dee2a6..6393b413 100644 --- a/unix/memoryusage.h +++ b/unix/memoryusage.h @@ -2,5 +2,7 @@ #pragma once #include "../src/core/memorylimiter.h" #include -Lemon::Execution::MemorySample sampleMemory(pid_t pid); +Lemon::Execution::Bytes sampleMemory(pid_t pid); +#ifdef __APPLE__ Lemon::Execution::Bytes maxRSSBytes(long value); +#endif diff --git a/unix/watcher_linux.cpp b/unix/watcher_linux.cpp index bcce1a23..2b9ad44d 100644 --- a/unix/watcher_linux.cpp +++ b/unix/watcher_linux.cpp @@ -4,8 +4,8 @@ #include #include using namespace Lemon::Execution; -MemorySample sampleMemory(pid_t pid) { - MemorySample result; +Bytes sampleMemory(pid_t pid) { + Bytes result = -1; auto path = "/proc/" + std::to_string(pid) + "/status"; FILE *file = fopen(path.c_str(), "r"); if (! file) @@ -14,11 +14,8 @@ MemorySample sampleMemory(pid_t pid) { while (fgets(line, sizeof(line), file)) { long long kib = 0; if (sscanf(line, "VmSize: %lld kB", &kib) == 1 || sscanf(line, "VmPeak: %lld kB", &kib) == 1) - result.declared = std::max(result.declared, Bytes(kib) * 1024); - if (sscanf(line, "VmRSS: %lld kB", &kib) == 1 || sscanf(line, "VmHWM: %lld kB", &kib) == 1) - result.actual = std::max(result.actual, Bytes(kib) * 1024); + result = std::max(result, Bytes(kib) * 1024); } fclose(file); return result; } -Bytes maxRSSBytes(long value) { return Bytes(value) * 1024; } diff --git a/unix/watcher_macos.mm b/unix/watcher_macos.mm index aeac1eb0..177d9501 100644 --- a/unix/watcher_macos.mm +++ b/unix/watcher_macos.mm @@ -3,11 +3,11 @@ #include #include using namespace Lemon::Execution; -MemorySample sampleMemory(pid_t pid) { +Bytes sampleMemory(pid_t pid) { proc_taskinfo info{}; if (proc_pidinfo(pid, PROC_PIDTASKINFO, 0, &info, sizeof(info)) != sizeof(info)) - return {}; + return -1; Bytes rss = static_cast(info.pti_resident_size); - return {rss, rss}; + return rss; } Bytes maxRSSBytes(long value) { return value; } diff --git a/unix/watcher_unix.cpp b/unix/watcher_unix.cpp index b262ccb7..4f63903b 100644 --- a/unix/watcher_unix.cpp +++ b/unix/watcher_unix.cpp @@ -45,7 +45,7 @@ namespace { public: explicit UnixUsage(pid_t pid) : pid(pid) {} - MemorySample sample() override { return sampleMemory(pid); } + Bytes sample() override { return sampleMemory(pid); } }; class UnixProcess : public Killer { public: @@ -201,7 +201,7 @@ int main(int argc, char **argv) { verdict = RS_FAIL; break; } - missing = sample.declared < 0 || sample.actual < 0 ? missing + 1 : 0; + missing = sample < 0 ? missing + 1 : 0; if (missing >= 10) { fprintf(stderr, "Memory statistics unavailable\n"); verdict = RS_FAIL; @@ -222,11 +222,9 @@ int main(int argc, char **argv) { verdict = RS_FAIL; } if (process.reaped) { - Bytes rss = maxRSSBytes(process.usage.ru_maxrss); #ifdef __APPLE__ - limiter.observe({rss, rss}); -#else - limiter.observe({-1, rss}); + // Only macOS defines DeclaredUsage as RSS. Linux must not use RSS as a VSS fallback. + limiter.observe(maxRSSBytes(process.usage.ru_maxrss)); #endif if (verdict == RS_AC) { ExitKind exit = ExitKind::Normal; From a7a52b46b587c96924268b25b2ad0f87d67281ff Mon Sep 17 00:00:00 2001 From: sgt57 <198590103+sgt57@users.noreply.github.com> Date: Sat, 7 Nov 2026 22:11:43 +0800 Subject: [PATCH 15/37] test(process): distinguish private commit from working set --- tests/windows-sandbox/CMakeLists.txt | 2 +- tests/windows-sandbox/helper.cpp | 38 ++++++++++++++++++++++++++++ tests/windows-sandbox/main.cpp | 22 +++++++++++++--- 3 files changed, 58 insertions(+), 4 deletions(-) diff --git a/tests/windows-sandbox/CMakeLists.txt b/tests/windows-sandbox/CMakeLists.txt index f98f41a1..a3fecb2a 100644 --- a/tests/windows-sandbox/CMakeLists.txt +++ b/tests/windows-sandbox/CMakeLists.txt @@ -10,7 +10,7 @@ if(MINGW) target_compile_options(sandbox-helper PRIVATE -fms-extensions) endif() endif() -target_link_libraries(sandbox-helper PRIVATE advapi32 ws2_32) +target_link_libraries(sandbox-helper PRIVATE advapi32 ws2_32 psapi) add_executable(windows-sandbox-tests main.cpp) target_compile_definitions(windows-sandbox-tests PRIVATE WIN32_LEAN_AND_MEAN) diff --git a/tests/windows-sandbox/helper.cpp b/tests/windows-sandbox/helper.cpp index 8061b4c3..f9116a30 100644 --- a/tests/windows-sandbox/helper.cpp +++ b/tests/windows-sandbox/helper.cpp @@ -10,6 +10,8 @@ #include #include #include +// psapi.h requires Windows types to be declared first. +#include static bool readsSecret(HANDLE handle) { #if defined(_MSC_VER) || defined(__clang__) @@ -305,6 +307,42 @@ int wmain(int argc, wchar_t **argv) { VirtualFree(p, 0, MEM_RELEASE); return mode == L"commit-rejected" ? 12 : 0; } + if (mode == L"mapped-working-set") { + // Read-only file-backed pages grow the working set without private commitment. + HANDLE file = CreateFileW(L"mapped.dat", GENERIC_READ | GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, + FILE_ATTRIBUTE_NORMAL, nullptr); + if (file == INVALID_HANDLE_VALUE) + return 38; + LARGE_INTEGER size{}; + size.QuadPart = 64 * 1024 * 1024; + if (! SetFilePointerEx(file, size, nullptr, FILE_BEGIN) || ! SetEndOfFile(file)) { + CloseHandle(file); + return 39; + } + HANDLE mapping = CreateFileMappingW(file, nullptr, PAGE_READONLY, 0, 0, nullptr); + CloseHandle(file); + if (! mapping) + return 40; + auto *pages = static_cast(MapViewOfFile(mapping, FILE_MAP_READ, 0, 0, 0)); + if (! pages) { + CloseHandle(mapping); + return 41; + } + unsigned int sum = 0; + for (int i = 0; i < size.QuadPart; i += 4096) + sum += pages[i]; + PROCESS_MEMORY_COUNTERS_EX counters{}; + counters.cb = sizeof(counters); + const bool measured = GetProcessMemoryInfo( + GetCurrentProcess(), reinterpret_cast(&counters), sizeof(counters)); + printf("working-set-peak=%llu sum=%u\n", static_cast(counters.PeakWorkingSetSize), + sum); + fflush(stdout); + Sleep(200); + UnmapViewOfFile(const_cast(pages)); + CloseHandle(mapping); + return measured ? 0 : 42; + } if (mode == L"memory") { for (int i = 0; i < 256; ++i) { auto *memory = static_cast( diff --git a/tests/windows-sandbox/main.cpp b/tests/windows-sandbox/main.cpp index 6d5d90bc..7e003d84 100644 --- a/tests/windows-sandbox/main.cpp +++ b/tests/windows-sandbox/main.cpp @@ -761,13 +761,29 @@ class WindowsSandboxTests : public QObject { QVERIFY(userTicks > 0); QVERIFY(kernelTicks > 0); QCOMPARE(result.timeUsed, int(userTicks / 10000)); - PROCESS_MEMORY_COUNTERS memory{}; + PROCESS_MEMORY_COUNTERS_EX memory{}; memory.cb = sizeof(memory); - QVERIFY(GetProcessMemoryInfo(primary.get(), &memory, sizeof(memory))); - QVERIFY(result.memoryUsed >= qint64(memory.PeakWorkingSetSize)); + QVERIFY(GetProcessMemoryInfo(primary.get(), reinterpret_cast(&memory), + sizeof(memory))); + QCOMPARE(result.memoryUsed, qint64(memory.PeakPagefileUsage)); QVERIFY(result.memoryUsed >= 64ll * 1024 * 1024); } + void workingSetDoesNotLimitPrivateCommit_data() { primaryProcessAccounting_data(); } + void workingSetDoesNotLimitPrivateCommit() { + QFETCH(bool, enabled); + auto cfg = config("mapped-working-set"); + cfg.sandboxSettings.enabled = enabled; + cfg.memoryLimit = 32; + auto result = run(cfg); + QVERIFY2(result.result == CorrectAnswer, qPrintable(result.message)); + QVERIFY(result.memoryUsed > 0 && result.memoryUsed <= 32ll * 1024 * 1024); + auto output = QString::fromUtf8(readFile(cfg.workingDirectory + "_tmpout")); + auto match = QRegularExpression("working-set-peak=(\\d+)").match(output); + QVERIFY(match.hasMatch()); + QVERIFY(match.captured(1).toLongLong() > 32ll * 1024 * 1024); + } + void memoryPrelimit_data() { primaryProcessAccounting_data(); } void memoryPrelimit() { QFETCH(bool, enabled); From 1886ec1b38a33f6d92a43d5f426510a8b6a83544 Mon Sep 17 00:00:00 2001 From: sgt57 <198590103+sgt57@users.noreply.github.com> Date: Sun, 8 Nov 2026 16:23:24 +0800 Subject: [PATCH 16/37] refactor(process): remove redundant execution outcome types --- src/core/memorylimiter.h | 19 ------------------- src/core/processrunner_win.cpp | 5 +---- tests/memory-limiter/main.cpp | 7 +------ unix/watcher_unix.cpp | 25 +++++-------------------- 4 files changed, 7 insertions(+), 49 deletions(-) diff --git a/src/core/memorylimiter.h b/src/core/memorylimiter.h index e8df2257..ff2282e7 100644 --- a/src/core/memorylimiter.h +++ b/src/core/memorylimiter.h @@ -37,13 +37,6 @@ namespace Lemon::Execution { virtual bool killAndReap() = 0; }; - enum class ExitKind { Normal, RuntimeError, TimeLimit, StartError }; - enum class RunReason { Accepted, RuntimeError, TimeLimit, MemoryLimit, InternalError }; - struct RunOutcome { - RunReason reason; - Bytes usage; - }; - // Pure policy: OS operations and process exit classification belong to adapters. class Limiter { public: @@ -53,18 +46,6 @@ namespace Lemon::Execution { exceeded = exceeded || (limit >= 0 && usage() > limit); return exceeded; } - RunOutcome finish(ExitKind exit) const { - RunReason reason = RunReason::Accepted; - if (exit == ExitKind::StartError) - reason = RunReason::InternalError; - else if (exceeded) - reason = RunReason::MemoryLimit; - else if (exit == ExitKind::TimeLimit) - reason = RunReason::TimeLimit; - else if (exit == ExitKind::RuntimeError) - reason = RunReason::RuntimeError; - return {reason, usage()}; - } Bytes usage() const { return peak; } bool isExceeded() const { return exceeded; } diff --git a/src/core/processrunner_win.cpp b/src/core/processrunner_win.cpp index 0af4f8a4..0e0fd4c9 100644 --- a/src/core/processrunner_win.cpp +++ b/src/core/processrunner_win.cpp @@ -186,10 +186,7 @@ ProcessRunnerResult WinProcessRunner::run() { unsigned long exitCode; GetExitCodeProcess(pi.hProcess, &exitCode); - if (limiter - .finish(exitCode == 0 ? Lemon::Execution::ExitKind::Normal - : Lemon::Execution::ExitKind::RuntimeError) - .reason == Lemon::Execution::RunReason::RuntimeError) { + if (exitCode != 0) { res.score = 0; res.result = RunTimeError; diff --git a/tests/memory-limiter/main.cpp b/tests/memory-limiter/main.cpp index 38288db0..deda8d4a 100644 --- a/tests/memory-limiter/main.cpp +++ b/tests/memory-limiter/main.cpp @@ -19,15 +19,10 @@ int main() { check(! limited.observe(-1) && limited.usage() == 100); check(limited.observe(101)); check(limited.observe(0) && limited.usage() == 101); - check(limited.finish(ExitKind::RuntimeError).reason == RunReason::MemoryLimit); - check(limited.finish(ExitKind::StartError).reason == RunReason::InternalError); Limiter unlimited(-1); - check(unlimited.finish(ExitKind::RuntimeError).reason == RunReason::RuntimeError); - check(unlimited.finish(ExitKind::Normal).reason == RunReason::Accepted); - check(unlimited.finish(ExitKind::TimeLimit).reason == RunReason::TimeLimit); check(unlimited.usage() == -1); check(! unlimited.observe(1000)); - check(unlimited.finish(ExitKind::Normal).usage == 1000); + check(unlimited.usage() == 1000); Bytes bytes; check(memoryBytes(-1, bytes) && bytes == -1); check(memoryBytes(4096, bytes) && bytes == 4294967296LL); diff --git a/unix/watcher_unix.cpp b/unix/watcher_unix.cpp index 4f63903b..62e84989 100644 --- a/unix/watcher_unix.cpp +++ b/unix/watcher_unix.cpp @@ -227,27 +227,12 @@ int main(int argc, char **argv) { limiter.observe(maxRSSBytes(process.usage.ru_maxrss)); #endif if (verdict == RS_AC) { - ExitKind exit = ExitKind::Normal; - if (WIFSIGNALED(process.status)) - exit = WTERMSIG(process.status) == SIGXCPU ? ExitKind::TimeLimit : ExitKind::RuntimeError; + if (limiter.isExceeded()) + verdict = RS_MLE; + else if (WIFSIGNALED(process.status)) + verdict = WTERMSIG(process.status) == SIGXCPU ? RS_TLE : RS_RE; else if (! WIFEXITED(process.status) || WEXITSTATUS(process.status) != 0) - exit = ExitKind::RuntimeError; - switch (limiter.finish(exit).reason) { - case RunReason::MemoryLimit: - verdict = RS_MLE; - break; - case RunReason::TimeLimit: - verdict = RS_TLE; - break; - case RunReason::RuntimeError: - verdict = RS_RE; - break; - case RunReason::InternalError: - verdict = RS_FAIL; - break; - case RunReason::Accepted: - break; - } + verdict = RS_RE; } } long long elapsed = From 921e716ffdb678575abbcc5e0e60bf90f06b2d86 Mon Sep 17 00:00:00 2001 From: sgt57 <198590103+sgt57@users.noreply.github.com> Date: Sun, 8 Nov 2026 16:28:14 +0800 Subject: [PATCH 17/37] refactor(process): replace unused interfaces with platform functions --- src/core/memorylimiter.h | 26 +++----------------- src/core/processrunner_win.cpp | 8 +++---- src/core/windowsmemory.h | 44 +++++++++++++--------------------- unix/memoryusage.h | 4 +--- unix/watcher_linux.cpp | 14 +++++++++++ unix/watcher_macos.mm | 6 ++--- unix/watcher_unix.cpp | 42 +++++--------------------------- 7 files changed, 46 insertions(+), 98 deletions(-) diff --git a/src/core/memorylimiter.h b/src/core/memorylimiter.h index ff2282e7..d6291c08 100644 --- a/src/core/memorylimiter.h +++ b/src/core/memorylimiter.h @@ -19,39 +19,19 @@ namespace Lemon::Execution { return true; } - class UsageProvider { - public: - virtual ~UsageProvider() = default; - // DeclaredUsage in bytes; negative means unavailable. - virtual Bytes sample() = 0; - }; - class Prelimit { - public: - virtual ~Prelimit() = default; - virtual bool apply(Bytes limit) = 0; - }; - class Killer { - public: - virtual ~Killer() = default; - // Must terminate the execution unit and perform bounded reaping. - virtual bool killAndReap() = 0; - }; - - // Pure policy: OS operations and process exit classification belong to adapters. + // Tracks memory usage only; platform code owns process operations and exit statuses. class Limiter { public: explicit Limiter(Bytes limit) : limit(limit) {} bool observe(Bytes declaredUsage) { peak = (std::max)(peak, declaredUsage); - exceeded = exceeded || (limit >= 0 && usage() > limit); - return exceeded; + return isExceeded(); } Bytes usage() const { return peak; } - bool isExceeded() const { return exceeded; } + bool isExceeded() const { return limit >= 0 && peak > limit; } private: Bytes limit; Bytes peak = -1; - bool exceeded = false; }; } // namespace Lemon::Execution diff --git a/src/core/processrunner_win.cpp b/src/core/processrunner_win.cpp index 0e0fd4c9..830bb3d3 100644 --- a/src/core/processrunner_win.cpp +++ b/src/core/processrunner_win.cpp @@ -133,9 +133,8 @@ ProcessRunnerResult WinProcessRunner::run() { CloseHandle(pi.hThread); }); - ProcessKiller killer(pi.hProcess, job.get()); auto reap = qScopeGuard([&] { - if (! killer.killAndReap()) + if (! killAndReap(pi.hProcess, job.get())) WARN("Process reaping deadline exceeded"); }); if ((! sandbox && ! AssignProcessToJobObject(job.get(), pi.hProcess)) || @@ -145,13 +144,12 @@ ProcessRunnerResult WinProcessRunner::run() { res.message = "Cannot attach or resume process"; return res; } - ProcessUsage provider(pi.hProcess); Lemon::Execution::Limiter limiter(memoryLimit); QElapsedTimer timer; timer.start(); int missing = 0; for (;;) { - auto sample = provider.sample(); + auto sample = sampleMemory(pi.hProcess); limiter.observe(sample); res.memoryUsed = limiter.usage(); if (limiter.isExceeded()) { @@ -160,7 +158,7 @@ ProcessRunnerResult WinProcessRunner::run() { } DWORD state = WaitForSingleObject(pi.hProcess, 0); if (state == WAIT_OBJECT_0) { - limiter.observe(provider.sample()); + limiter.observe(sampleMemory(pi.hProcess)); res.memoryUsed = limiter.usage(); if (limiter.isExceeded()) { res.result = MemoryLimitExceeded; diff --git a/src/core/windowsmemory.h b/src/core/windowsmemory.h index c5609d04..d3398f74 100644 --- a/src/core/windowsmemory.h +++ b/src/core/windowsmemory.h @@ -5,12 +5,12 @@ #ifdef Q_OS_WIN #include namespace Lemon::Windows { - class ExecutionJob : public Execution::Prelimit { + class ExecutionJob { Handle handle{CreateJobObjectW(nullptr, nullptr)}; public: HANDLE get() const { return handle.get(); } - bool apply(Execution::Bytes limit) override { + bool apply(Execution::Bytes limit) { if (! handle) return false; JOBOBJECT_EXTENDED_LIMIT_INFORMATION info{}; @@ -35,32 +35,20 @@ namespace Lemon::Windows { return SetInformationJobObject(get(), JobObjectExtendedLimitInformation, &info, sizeof(info)); } }; - class ProcessUsage : public Execution::UsageProvider { - HANDLE process; + // Platform operations stay separate from the shared memory-limit policy. + inline Execution::Bytes sampleMemory(HANDLE process) { + PROCESS_MEMORY_COUNTERS_EX info{}; + info.cb = sizeof(info); + if (! GetProcessMemoryInfo(process, reinterpret_cast(&info), sizeof(info))) + return -1; + // PeakPagefileUsage is the process lifetime peak of private committed memory. + return static_cast(info.PeakPagefileUsage); + } - public: - explicit ProcessUsage(HANDLE process) : process(process) {} - Execution::Bytes sample() override { - PROCESS_MEMORY_COUNTERS_EX info{}; - info.cb = sizeof(info); - if (! GetProcessMemoryInfo(process, reinterpret_cast(&info), - sizeof(info))) - return -1; - // PeakPagefileUsage is the process lifetime peak of private committed memory. - return static_cast(info.PeakPagefileUsage); - } - }; - class ProcessKiller : public Execution::Killer { - HANDLE process; - HANDLE job; - - public: - ProcessKiller(HANDLE process, HANDLE job) : process(process), job(job) {} - bool killAndReap() override { - if (! TerminateJobObject(job, 1) && WaitForSingleObject(process, 0) != WAIT_OBJECT_0) - return false; - return WaitForSingleObject(process, 2000) == WAIT_OBJECT_0; - } - }; + inline bool killAndReap(HANDLE process, HANDLE job) { + if (! TerminateJobObject(job, 1) && WaitForSingleObject(process, 0) != WAIT_OBJECT_0) + return false; + return WaitForSingleObject(process, 2000) == WAIT_OBJECT_0; + } } // namespace Lemon::Windows #endif diff --git a/unix/memoryusage.h b/unix/memoryusage.h index 6393b413..23913d07 100644 --- a/unix/memoryusage.h +++ b/unix/memoryusage.h @@ -3,6 +3,4 @@ #include "../src/core/memorylimiter.h" #include Lemon::Execution::Bytes sampleMemory(pid_t pid); -#ifdef __APPLE__ -Lemon::Execution::Bytes maxRSSBytes(long value); -#endif +bool applyMemoryLimit(Lemon::Execution::Bytes limit); diff --git a/unix/watcher_linux.cpp b/unix/watcher_linux.cpp index 2b9ad44d..d4da2cbf 100644 --- a/unix/watcher_linux.cpp +++ b/unix/watcher_linux.cpp @@ -3,6 +3,7 @@ #include #include #include +#include using namespace Lemon::Execution; Bytes sampleMemory(pid_t pid) { Bytes result = -1; @@ -19,3 +20,16 @@ Bytes sampleMemory(pid_t pid) { fclose(file); return result; } + +bool applyMemoryLimit(Bytes limit) { + if (limit < 0) + return true; + rlimit memory{static_cast(limit), static_cast(limit)}; + if (setrlimit(RLIMIT_AS, &memory) != 0) + return false; + rlimit stack{}; + if (getrlimit(RLIMIT_STACK, &stack) != 0) + return false; + stack.rlim_cur = std::min(stack.rlim_max, static_cast(limit)); + return setrlimit(RLIMIT_STACK, &stack) == 0; +} diff --git a/unix/watcher_macos.mm b/unix/watcher_macos.mm index 177d9501..dc6246f3 100644 --- a/unix/watcher_macos.mm +++ b/unix/watcher_macos.mm @@ -7,7 +7,7 @@ Bytes sampleMemory(pid_t pid) { proc_taskinfo info{}; if (proc_pidinfo(pid, PROC_PIDTASKINFO, 0, &info, sizeof(info)) != sizeof(info)) return -1; - Bytes rss = static_cast(info.pti_resident_size); - return rss; + return static_cast(info.pti_resident_size); } -Bytes maxRSSBytes(long value) { return value; } +// macOS intentionally has no memory prelimit. +bool applyMemoryLimit(Bytes) { return true; } diff --git a/unix/watcher_unix.cpp b/unix/watcher_unix.cpp index 62e84989..435d2ab0 100644 --- a/unix/watcher_unix.cpp +++ b/unix/watcher_unix.cpp @@ -19,35 +19,7 @@ namespace { enum { RS_AC, RS_FAIL, RS_RE, RS_TLE, RS_MLE }; volatile sig_atomic_t stopped = 0; void stop(int) { stopped = 1; } - class UnixPrelimit : public Prelimit { - public: - bool apply(Bytes limit) override { -#ifdef __linux__ - if (limit >= 0) { - rlimit memory{static_cast(limit), static_cast(limit)}; - if (setrlimit(RLIMIT_AS, &memory) != 0) - return false; - rlimit stack{}; - if (getrlimit(RLIMIT_STACK, &stack) != 0) - return false; - stack.rlim_cur = std::min(stack.rlim_max, static_cast(limit)); - if (setrlimit(RLIMIT_STACK, &stack) != 0) - return false; - } -#else - (void)limit; // macOS intentionally has no memory prelimit. -#endif - return true; - } - }; - class UnixUsage : public UsageProvider { - pid_t pid; - - public: - explicit UnixUsage(pid_t pid) : pid(pid) {} - Bytes sample() override { return sampleMemory(pid); } - }; - class UnixProcess : public Killer { + class UnixProcess { public: pid_t pid; int status = 0; @@ -55,7 +27,7 @@ namespace { bool reaped = false; bool cleaned = false; explicit UnixProcess(pid_t pid) : pid(pid) {} - ~UnixProcess() override { + ~UnixProcess() { if (! cleaned) killAndReap(); } @@ -72,7 +44,7 @@ namespace { return -1; return 0; } - bool killAndReap() override { + bool killAndReap() { if (cleaned) return reaped; cleaned = true; @@ -149,8 +121,7 @@ int main(int argc, char **argv) { rlimit core{0, 0}; if (setrlimit(RLIMIT_CORE, &core) != 0) fail(7); - UnixPrelimit prelimit; - if (! prelimit.apply(limit)) + if (! applyMemoryLimit(limit)) fail(3); rlim_t seconds = static_cast((timeLimit + 999) / 1000); rlimit cpu{seconds, seconds + 1}; @@ -167,7 +138,6 @@ int main(int argc, char **argv) { signal(SIGINT, stop); signal(SIGABRT, stop); UnixProcess process(pid); - UnixUsage provider(pid); Limiter limiter(limit); auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(std::max(2000LL, 3LL * timeLimit)); @@ -176,7 +146,7 @@ int main(int argc, char **argv) { ChildError childError{}; bool setupFailed = false; for (;;) { - auto sample = provider.sample(); + auto sample = sampleMemory(pid); limiter.observe(sample); // The fixed-size read is bounded by the destination object on every iteration. /* Flawfinder: ignore */ @@ -224,7 +194,7 @@ int main(int argc, char **argv) { if (process.reaped) { #ifdef __APPLE__ // Only macOS defines DeclaredUsage as RSS. Linux must not use RSS as a VSS fallback. - limiter.observe(maxRSSBytes(process.usage.ru_maxrss)); + limiter.observe(static_cast(process.usage.ru_maxrss)); #endif if (verdict == RS_AC) { if (limiter.isExceeded()) From 0592d8ed59f2e343e3240bea73517321fe450c2f Mon Sep 17 00:00:00 2001 From: sgt57 <198590103+sgt57@users.noreply.github.com> Date: Sun, 8 Nov 2026 16:42:49 +0800 Subject: [PATCH 18/37] test(process): compare Unix memory reports with native counters --- unix/test/CMakeLists.txt | 2 ++ unix/test/memory_cases.cpp | 49 +++++++++++++++++++++++++++- unix/test/scripts/memory_accuracy.py | 31 ++++++++++++++++++ 3 files changed, 81 insertions(+), 1 deletion(-) create mode 100644 unix/test/scripts/memory_accuracy.py diff --git a/unix/test/CMakeLists.txt b/unix/test/CMakeLists.txt index 574f5a11..4cceb9f7 100644 --- a/unix/test/CMakeLists.txt +++ b/unix/test/CMakeLists.txt @@ -36,6 +36,8 @@ add_test(NAME watcher_RE_test COMMAND python3 scripts/runtimeerr.py) add_executable(memory_cases memory_cases.cpp) add_test(NAME watcher_memory_policy COMMAND python3 scripts/memory.py) set_tests_properties(watcher_memory_policy PROPERTIES TIMEOUT 30) +add_test(NAME watcher_memory_accuracy COMMAND python3 scripts/memory_accuracy.py) +set_tests_properties(watcher_memory_accuracy PROPERTIES TIMEOUT 30) add_executable(memory-limiter-test ../../tests/memory-limiter/main.cpp) add_test(NAME memory-limiter COMMAND memory-limiter-test) diff --git a/unix/test/memory_cases.cpp b/unix/test/memory_cases.cpp index 158a9aae..d5f157ef 100644 --- a/unix/test/memory_cases.cpp +++ b/unix/test/memory_cases.cpp @@ -6,9 +6,56 @@ #include #include #include +#ifdef __APPLE__ +#include +#else +#include +#include +#endif int main(int argc, char **argv) { - if (argc != 2) + const bool accuracy = argc == 3 && ! strcmp(argv[1], "accuracy"); + if (argc != 2 && ! accuracy) return 1; + if (accuracy) { + const auto mib = std::strtoul(argv[2], nullptr, 10); + if (mib != 16 && mib != 64) + return 20; + const size_t bytes = mib * 1024 * 1024; + void *mapping = mmap(nullptr, bytes, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0); + if (mapping == MAP_FAILED) + return 21; +#ifdef __APPLE__ + auto *pages = static_cast(mapping); + // macOS uses RSS, so fault in every page. Linux leaves the mapping untouched + // to ensure that an accidental RSS measurement cannot pass the VSS comparison. + for (size_t offset = 0; offset < bytes; offset += 4096) + pages[offset] = 1; +#endif + unsigned long long reference = 0; +#ifdef __APPLE__ + // Independent of the watcher's proc_pidinfo implementation. + mach_task_basic_info_data_t info{}; + mach_msg_type_number_t count = MACH_TASK_BASIC_INFO_COUNT; + if (task_info(mach_task_self(), MACH_TASK_BASIC_INFO, reinterpret_cast(&info), &count) != + KERN_SUCCESS) + return 22; + reference = info.resident_size; +#else + // statm reports current VSS in pages; the watcher reads VmPeak from status. + std::ifstream statm("/proc/self/statm"); + const auto pageSize = sysconf(_SC_PAGESIZE); + if (! (statm >> reference) || pageSize <= 0) + return 22; + reference *= static_cast(pageSize); +#endif + printf("reference-bytes=%llu allocation-bytes=%llu\n", reference, + static_cast(bytes)); + fflush(stdout); + // Leave the allocation visible across many watcher sampling intervals. + std::this_thread::sleep_for(std::chrono::milliseconds(500)); + munmap(mapping, bytes); + return 0; + } if (! strcmp(argv[1], "abort")) std::abort(); if (! strcmp(argv[1], "caught") || ! strcmp(argv[1], "uncaught")) { diff --git a/unix/test/scripts/memory_accuracy.py b/unix/test/scripts/memory_accuracy.py new file mode 100644 index 00000000..7c2366e8 --- /dev/null +++ b/unix/test/scripts/memory_accuracy.py @@ -0,0 +1,31 @@ +import pathlib +import sys +# Only local test executables and fixed arguments are launched below. +import subprocess # nosec B404 +import tempfile + +metric = "RSS" if sys.platform == "darwin" else "VSS" + +with tempfile.TemporaryDirectory() as directory: + for mib in (16, 64): + output = pathlib.Path(directory) / f"accuracy-{mib}.out" + error = pathlib.Path(directory) / f"accuracy-{mib}.err" + result = subprocess.run( # nosec B603 + ["./watcher_unix", "./memory_cases", f"accuracy {mib}", "", str(output), str(error), + "2000", "512", "2000", "512", "", ""], + stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=10, + ) + assert result.returncode == 0, (mib, result.returncode, result.stderr, + error.read_text() if error.exists() else "") + fields = result.stdout.decode().split() + assert len(fields) == 2, result.stdout + usage = int(fields[1]) + measurements = dict(field.split("=") for field in output.read_text().split()) + reference = int(measurements["reference-bytes"]) + allocation = mib * 1024 * 1024 + assert int(measurements["allocation-bytes"]) == allocation + assert reference >= allocation, (mib, reference) + # Kernel snapshots and lifetime peaks can differ slightly during final I/O. + tolerance = max(1024 * 1024, reference // 100) + print(f"metric={metric} allocation={allocation} reference={reference} usage={usage} tolerance={tolerance}") + assert abs(usage - reference) <= tolerance, (mib, reference, usage, tolerance) From b11229ce497bfd28ae2ec55672d3e606154b642c Mon Sep 17 00:00:00 2001 From: sgt57 <198590103+sgt57@users.noreply.github.com> Date: Sun, 8 Nov 2026 16:42:49 +0800 Subject: [PATCH 19/37] test(process): verify reported private commit at multiple sizes --- tests/windows-sandbox/helper.cpp | 24 ++++++++++++++++++++++++ tests/windows-sandbox/main.cpp | 28 ++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+) diff --git a/tests/windows-sandbox/helper.cpp b/tests/windows-sandbox/helper.cpp index f9116a30..4dcd76d6 100644 --- a/tests/windows-sandbox/helper.cpp +++ b/tests/windows-sandbox/helper.cpp @@ -307,6 +307,30 @@ int wmain(int argc, wchar_t **argv) { VirtualFree(p, 0, MEM_RELEASE); return mode == L"commit-rejected" ? 12 : 0; } + if (mode == L"memory-accuracy") { + const auto mib = argc == 3 ? _wtoi(argv[2]) : 0; + if (mib != 16 && mib != 64) + return 43; + const SIZE_T bytes = SIZE_T(mib) * 1024 * 1024; + void *allocation = VirtualAlloc(nullptr, bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + if (! allocation) + return 44; + PROCESS_MEMORY_COUNTERS_EX counters{}; + counters.cb = sizeof(counters); + if (! GetProcessMemoryInfo(GetCurrentProcess(), + reinterpret_cast(&counters), + sizeof(counters))) { + VirtualFree(allocation, 0, MEM_RELEASE); + return 45; + } + printf("reference-bytes=%llu allocation-bytes=%llu\n", + static_cast(counters.PeakPagefileUsage), + static_cast(bytes)); + fflush(stdout); + Sleep(500); + VirtualFree(allocation, 0, MEM_RELEASE); + return 0; + } if (mode == L"mapped-working-set") { // Read-only file-backed pages grow the working set without private commitment. HANDLE file = CreateFileW(L"mapped.dat", GENERIC_READ | GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, diff --git a/tests/windows-sandbox/main.cpp b/tests/windows-sandbox/main.cpp index 7e003d84..d68315bb 100644 --- a/tests/windows-sandbox/main.cpp +++ b/tests/windows-sandbox/main.cpp @@ -769,6 +769,34 @@ class WindowsSandboxTests : public QObject { QVERIFY(result.memoryUsed >= 64ll * 1024 * 1024); } + void memoryUsageAccuracy_data() { + QTest::addColumn("enabled"); + QTest::addColumn("mib"); + QTest::newRow("ordinary-16MiB") << false << 16; + QTest::newRow("ordinary-64MiB") << false << 64; + QTest::newRow("sandbox-16MiB") << true << 16; + QTest::newRow("sandbox-64MiB") << true << 64; + } + void memoryUsageAccuracy() { + QFETCH(bool, enabled); + QFETCH(int, mib); + auto cfg = config(QString("memory-accuracy %1").arg(mib)); + cfg.sandboxSettings.enabled = enabled; + auto result = run(cfg); + QVERIFY2(result.result == CorrectAnswer, qPrintable(result.message)); + const auto output = QString::fromUtf8(readFile(cfg.workingDirectory + "_tmpout")); + const auto match = QRegularExpression("reference-bytes=(\\d+) allocation-bytes=(\\d+)").match(output); + QVERIFY2(match.hasMatch(), qPrintable(output)); + const qint64 reference = match.captured(1).toLongLong(); + const qint64 allocation = qint64(mib) * 1024 * 1024; + QCOMPARE(match.captured(2).toLongLong(), allocation); + QVERIFY(reference >= allocation); + const qint64 tolerance = qMax(qint64(1024 * 1024), reference / 100); + qInfo() << "Private commit accuracy: allocation" << allocation << "reference" << reference << "usage" + << result.memoryUsed << "tolerance" << tolerance; + QVERIFY(qAbs(result.memoryUsed - reference) <= tolerance); + } + void workingSetDoesNotLimitPrivateCommit_data() { primaryProcessAccounting_data(); } void workingSetDoesNotLimitPrivateCommit() { QFETCH(bool, enabled); From e2883c846d327a1a1d1ad818060c3ada56fd4899 Mon Sep 17 00:00:00 2001 From: sgt57 <198590103+sgt57@users.noreply.github.com> Date: Sun, 8 Nov 2026 17:08:18 +0800 Subject: [PATCH 20/37] ci: fix macos ci --- .github/workflows/macos-qt6.yml | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/.github/workflows/macos-qt6.yml b/.github/workflows/macos-qt6.yml index da0ece58..a871f90c 100644 --- a/.github/workflows/macos-qt6.yml +++ b/.github/workflows/macos-qt6.yml @@ -19,11 +19,14 @@ jobs: strategy: fail-fast: false matrix: - os: [macos-latest] build_type: [Release, RelWithDebInfo, Debug] arch: [x86_64, arm64] qt_ver: [6.12.0] - qt_arch: [clang_64] + include: + - arch: x86_64 + os: macos-26-intel + - arch: arm64 + os: macos-latest env: targetName: lemon steps: @@ -54,18 +57,12 @@ jobs: -DCMAKE_OSX_ARCHITECTURES="${{ matrix.arch }}" cmake --build . --parallel $(sysctl -n hw.logicalcpu) - name: Run tests - if: ${{ false }} run: | ctest --test-dir . --output-on-failure --timeout 120 # tag 打包 - name: package - env: - Qt6_DIR: ../Qt/${{matrix.qt_ver}}/${{matrix.qt_arch}} run: | - # 拷贝依赖 - #mv ${targetName} ${targetName}.app - export PATH=$Qt6_DIR/bin:$PATH - macdeployqt ${targetName}.app -qmldir=. -verbose=1 -dmg + macdeployqt "${targetName}.app" -qmldir=. -verbose=1 -dmg mv "${targetName}.dmg" "${{ steps.artifact_name.outputs.name }}.dmg" - name: Upload artifact uses: actions/upload-artifact@v7 From 586aa2034e10dd8b0abc5704e3bb3e887b70ba86 Mon Sep 17 00:00:00 2001 From: sgt57 <198590103+sgt57@users.noreply.github.com> Date: Mon, 9 Nov 2026 00:22:27 +0800 Subject: [PATCH 21/37] refactor(process): use event-driven monitoring on Linux and macOS --- unix/watcher_unix.cpp | 211 +++++++++++++++++++++++++++++++++++++----- 1 file changed, 190 insertions(+), 21 deletions(-) diff --git a/unix/watcher_unix.cpp b/unix/watcher_unix.cpp index 435d2ab0..ea7b6a71 100644 --- a/unix/watcher_unix.cpp +++ b/unix/watcher_unix.cpp @@ -1,7 +1,6 @@ // SPDX-License-Identifier: GPL-3.0-or-later #include "memoryusage.h" #include -#include #include #include #include @@ -9,16 +8,152 @@ #include #include #include -#include #include #ifdef __linux__ +#include #include +#include +#include +#elif defined(__APPLE__) +#include #endif using namespace Lemon::Execution; namespace { enum { RS_AC, RS_FAIL, RS_RE, RS_TLE, RS_MLE }; - volatile sig_atomic_t stopped = 0; - void stop(int) { stopped = 1; } + class Events { + int signals[4] = {SIGCHLD, SIGTERM, SIGINT, SIGABRT}; + sigset_t previous{}; + bool masked = false; +#ifdef __linux__ + int descriptors[3] = {-1, -1, -1}; +#else + int queue = -1; + struct sigaction actions[4]{}; + int installed = 0; + static void ignore(int) {} +#endif + public: + enum { Sample = 1, Deadline = 2, Child = 4, Stop = 8 }; + Events() = default; + Events(const Events &) = delete; + Events &operator=(const Events &) = delete; + ~Events() { restore(); } + void restore() { +#ifdef __linux__ + for (int &fd : descriptors) { + if (fd >= 0) + close(fd); + fd = -1; + } +#else + if (queue >= 0) + close(queue); + queue = -1; + while (installed) { + --installed; + sigaction(signals[installed], &actions[installed], nullptr); + } +#endif + if (masked) + sigprocmask(SIG_SETMASK, &previous, nullptr); + masked = false; + } + bool initialize() { + sigset_t mask; + sigemptyset(&mask); + for (int signal : signals) + sigaddset(&mask, signal); + if (sigprocmask(SIG_BLOCK, &mask, &previous) != 0) + return false; + masked = true; +#ifdef __linux__ + descriptors[0] = timerfd_create(CLOCK_MONOTONIC, TFD_CLOEXEC | TFD_NONBLOCK); + descriptors[1] = timerfd_create(CLOCK_MONOTONIC, TFD_CLOEXEC | TFD_NONBLOCK); + descriptors[2] = signalfd(-1, &mask, SFD_CLOEXEC | SFD_NONBLOCK); + return descriptors[0] >= 0 && descriptors[1] >= 0 && descriptors[2] >= 0; +#else + queue = kqueue(); + if (queue < 0 || fcntl(queue, F_SETFD, FD_CLOEXEC) < 0) + return false; + for (int signal : signals) { + struct sigaction action{}; + action.sa_handler = ignore; + sigemptyset(&action.sa_mask); + if (sigaction(signal, &action, &actions[installed]) != 0) + return false; + ++installed; + struct kevent event{}; + EV_SET(&event, signal, EVFILT_SIGNAL, EV_ADD, 0, 0, nullptr); + if (kevent(queue, &event, 1, nullptr, 0, nullptr) < 0) + return false; + } + return sigprocmask(SIG_SETMASK, &previous, nullptr) == 0; +#endif + } + bool arm(long long milliseconds, bool sampling) { +#ifdef __linux__ + for (int i = 0; i < 2; ++i) { + long long delay = i == 0 ? milliseconds : (sampling ? 10 : 0); + itimerspec spec{}; + spec.it_value = {delay / 1000, (delay % 1000) * 1000000}; + if (i == 1) + spec.it_interval = spec.it_value; + if (timerfd_settime(descriptors[i], 0, &spec, nullptr) < 0) + return false; + } + return true; +#else + struct kevent changes[2]{}; + EV_SET(&changes[0], Deadline, EVFILT_TIMER, EV_ADD | EV_ONESHOT, 0, milliseconds, nullptr); + EV_SET(&changes[1], Sample, EVFILT_TIMER, EV_ADD | (sampling ? EV_ENABLE : EV_DISABLE), 0, 10, + nullptr); + return kevent(queue, changes, 2, nullptr, 0, nullptr) == 0; +#endif + } + int wait() { + int events = 0; +#ifdef __linux__ + pollfd ready[3] = { + {descriptors[0], POLLIN, 0}, {descriptors[1], POLLIN, 0}, {descriptors[2], POLLIN, 0}}; + if (::poll(ready, 3, -1) < 0) + return errno == EINTR ? 0 : -1; + for (int i = 0; i < 3; ++i) { + if (ready[i].revents & (POLLERR | POLLHUP | POLLNVAL)) { + errno = EIO; + return -1; + } + if (! (ready[i].revents & POLLIN)) + continue; + if (i < 2) { + uint64_t count; + if (read(descriptors[i], &count, sizeof(count)) != sizeof(count)) + return -1; + events |= i == 0 ? Deadline : Sample; + } else { + signalfd_siginfo info; + while (read(descriptors[2], &info, sizeof(info)) == sizeof(info)) + events |= info.ssi_signo == SIGCHLD ? Child : Stop; + if (errno != EAGAIN && errno != EINTR) + return -1; + } + } +#else + struct kevent ready[6]{}; + int count = kevent(queue, nullptr, 0, ready, 6, nullptr); + if (count < 0) + return errno == EINTR ? 0 : -1; + for (int i = 0; i < count; ++i) { + if (ready[i].flags & EV_ERROR) { + errno = ready[i].data; + return -1; + } + events |= ready[i].filter == EVFILT_TIMER ? ready[i].ident + : (ready[i].ident == SIGCHLD ? Child : Stop); + } +#endif + return events; + } + }; class UnixProcess { public: pid_t pid; @@ -26,7 +161,8 @@ namespace { rusage usage{}; bool reaped = false; bool cleaned = false; - explicit UnixProcess(pid_t pid) : pid(pid) {} + Events &events; + explicit UnixProcess(pid_t pid, Events &events) : pid(pid), events(events) {} ~UnixProcess() { if (! cleaned) killAndReap(); @@ -51,12 +187,27 @@ namespace { kill(-pid, SIGKILL); if (! reaped) kill(pid, SIGKILL); - auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(2); - while (! reaped && std::chrono::steady_clock::now() < deadline) { + if (reaped) + return true; + if (! events.arm(2000, false)) { + perror("reaping events"); + return false; + } + for (;;) { if (poll() < 0) return false; - if (! reaped) - std::this_thread::sleep_for(std::chrono::milliseconds(10)); + if (reaped) + break; + int event = events.wait(); + if (event < 0) { + perror("reaping wait"); + return false; + } + if (event & Events::Deadline) { + if (poll() < 0) + return false; + break; + } } return reaped; } @@ -91,6 +242,14 @@ int main(int argc, char **argv) { printf("-1\n-1\n"); return RS_FAIL; } + Events events; + if (! events.initialize()) { + perror("events"); + close(errors[0]); + close(errors[1]); + printf("-1\n-1\n"); + return RS_FAIL; + } pid_t pid = fork(); if (pid < 0) { perror("fork"); @@ -100,6 +259,7 @@ int main(int argc, char **argv) { return RS_FAIL; } if (pid == 0) { + events.restore(); close(errors[0]); auto fail = [&](int stage) { ChildError error{stage, errno}; @@ -134,19 +294,22 @@ int main(int argc, char **argv) { } close(errors[1]); (void)setpgid(pid, pid); - signal(SIGTERM, stop); - signal(SIGINT, stop); - signal(SIGABRT, stop); - UnixProcess process(pid); + UnixProcess process(pid, events); Limiter limiter(limit); - auto deadline = - std::chrono::steady_clock::now() + std::chrono::milliseconds(std::max(2000LL, 3LL * timeLimit)); + bool ready = events.arm(std::max(2000LL, 3LL * timeLimit), true); + if (! ready) + perror("events arm"); + int event = Events::Sample; int verdict = RS_AC; int missing = 0; ChildError childError{}; bool setupFailed = false; for (;;) { - auto sample = sampleMemory(pid); + if (! ready) { + verdict = RS_FAIL; + break; + } + auto sample = event & Events::Sample ? sampleMemory(pid) : Bytes(-1); limiter.observe(sample); // The fixed-size read is bounded by the destination object on every iteration. /* Flawfinder: ignore */ @@ -163,21 +326,27 @@ int main(int argc, char **argv) { } if (finished) break; - if (std::chrono::steady_clock::now() >= deadline) { + if (event & Events::Deadline) { verdict = RS_TLE; break; } - if (stopped) { + if (event & Events::Stop) { verdict = RS_FAIL; break; } - missing = sample < 0 ? missing + 1 : 0; + if (event & Events::Sample) + missing = sample < 0 ? missing + 1 : 0; if (missing >= 10) { fprintf(stderr, "Memory statistics unavailable\n"); verdict = RS_FAIL; break; } - std::this_thread::sleep_for(std::chrono::milliseconds(10)); + event = events.wait(); + if (event < 0) { + perror("events wait"); + verdict = RS_FAIL; + break; + } } // Catch setup errors delivered concurrently with the final wait. // The final read uses the same destination-size bound. @@ -207,7 +376,7 @@ int main(int argc, char **argv) { } long long elapsed = process.reaped ? process.usage.ru_utime.tv_sec * 1000LL + process.usage.ru_utime.tv_usec / 1000 - : -1; + : -1; if (verdict == RS_AC && elapsed > timeLimit) verdict = RS_TLE; printf("%lld\n%lld\n", elapsed, static_cast(limiter.usage())); From dfbef219719d57632e136fc3af4390cd1e3f2b09 Mon Sep 17 00:00:00 2001 From: "GitHub Action (clang-format)" Date: Sun, 8 Nov 2026 16:22:44 +0000 Subject: [PATCH 22/37] style: format codes --- unix/watcher_unix.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/unix/watcher_unix.cpp b/unix/watcher_unix.cpp index ea7b6a71..557e3ce6 100644 --- a/unix/watcher_unix.cpp +++ b/unix/watcher_unix.cpp @@ -376,7 +376,7 @@ int main(int argc, char **argv) { } long long elapsed = process.reaped ? process.usage.ru_utime.tv_sec * 1000LL + process.usage.ru_utime.tv_usec / 1000 - : -1; + : -1; if (verdict == RS_AC && elapsed > timeLimit) verdict = RS_TLE; printf("%lld\n%lld\n", elapsed, static_cast(limiter.usage())); From adc09f0b1ff2500a9dc070e1ae29a487f0513499 Mon Sep 17 00:00:00 2001 From: sgt57 <198590103+sgt57@users.noreply.github.com> Date: Mon, 9 Nov 2026 00:29:45 +0800 Subject: [PATCH 23/37] refactor(process): use event-driven waits on Windows --- src/core/processrunner_win.cpp | 49 ++++++++++++++++++++++------------ 1 file changed, 32 insertions(+), 17 deletions(-) diff --git a/src/core/processrunner_win.cpp b/src/core/processrunner_win.cpp index 830bb3d3..290bbb09 100644 --- a/src/core/processrunner_win.cpp +++ b/src/core/processrunner_win.cpp @@ -19,7 +19,6 @@ #include #include #include -#include #include #include @@ -76,14 +75,14 @@ ProcessRunnerResult WinProcessRunner::run() { if (config.standardOutputCheck) { siex.StartupInfo.hStdOutput = CreateFileW((const WCHAR *)((config.workingDirectory + "_tmpout").utf16()), GENERIC_WRITE, - FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, &sa, CREATE_ALWAYS, - FILE_ATTRIBUTE_NORMAL, NULL); + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, &sa, CREATE_ALWAYS, + FILE_ATTRIBUTE_NORMAL, NULL); } siex.StartupInfo.hStdError = CreateFileW((const WCHAR *)((config.workingDirectory + "_tmperr").utf16()), GENERIC_WRITE, - FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, &sa, CREATE_ALWAYS, - FILE_ATTRIBUTE_NORMAL, NULL); + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, &sa, CREATE_ALWAYS, + FILE_ATTRIBUTE_NORMAL, NULL); auto closeStdIO = qScopeGuard([&] { if (config.standardInputCheck) @@ -145,8 +144,24 @@ ProcessRunnerResult WinProcessRunner::run() { return res; } Lemon::Execution::Limiter limiter(memoryLimit); - QElapsedTimer timer; - timer.start(); + Handle deadline(CreateWaitableTimerW(nullptr, TRUE, nullptr)); + Handle sampling(CreateWaitableTimerW(nullptr, FALSE, nullptr)); + LARGE_INTEGER due{}; + // Negative values specify a relative interval in 100 ns units. + due.QuadPart = -qMax(1LL, (static_cast(config.timeLimit) + extraTime) * 10000LL); + LARGE_INTEGER sampleDue{}; + sampleDue.QuadPart = -100000; + if (! deadline || ! sampling || ! SetWaitableTimer(deadline.get(), &due, 0, nullptr, nullptr, FALSE) || + ! SetWaitableTimer(sampling.get(), &sampleDue, 10, nullptr, nullptr, FALSE)) { + const DWORD code = GetLastError(); + res.result = CannotStartProgram; + res.message = "Cannot configure execution timers"; + WARN("Last Error code:", code); + return res; + } + HANDLE handles[] = {pi.hProcess, deadline.get(), sampling.get()}; + // Take the initial sample before entering the blocking event wait. + DWORD state = WAIT_OBJECT_0 + 2; int missing = 0; for (;;) { auto sample = sampleMemory(pi.hProcess); @@ -156,30 +171,30 @@ ProcessRunnerResult WinProcessRunner::run() { res.result = MemoryLimitExceeded; return res; } - DWORD state = WaitForSingleObject(pi.hProcess, 0); if (state == WAIT_OBJECT_0) { - limiter.observe(sampleMemory(pi.hProcess)); - res.memoryUsed = limiter.usage(); - if (limiter.isExceeded()) { - res.result = MemoryLimitExceeded; - return res; - } break; } missing = sample < 0 ? missing + 1 : 0; - if (state == WAIT_FAILED || missing >= 10) { + if (missing >= 10) { res.result = CannotStartProgram; res.message = "Process statistics unavailable"; return res; } if (cancellation.isCanceled()) return res; - if (timer.elapsed() > config.timeLimit + extraTime) { + if (state == WAIT_OBJECT_0 + 1) { res.result = TimeLimitExceeded; res.timeUsed = -1; return res; } - QThread::msleep(10); + state = WaitForMultipleObjects(3, handles, FALSE, INFINITE); + if (state == WAIT_FAILED) { + const DWORD code = GetLastError(); + res.result = CannotStartProgram; + res.message = "Cannot wait for process events"; + WARN("Last Error code:", code); + return res; + } } unsigned long exitCode; GetExitCodeProcess(pi.hProcess, &exitCode); From 4eadf75f05ccf7aca1b76127196de0d3b416edc7 Mon Sep 17 00:00:00 2001 From: sgt57 <198590103+sgt57@users.noreply.github.com> Date: Mon, 9 Nov 2026 00:56:48 +0800 Subject: [PATCH 24/37] refactor(process): remove periodic sampling on Linux and Windows --- src/core/casejudger.cpp | 1 + src/core/casejudger.h | 1 + src/core/judgingcontroller.cpp | 4 +- src/core/processrunner.h | 2 + src/core/processrunner_win.cpp | 85 +++++++------- src/core/taskjudger.cpp | 7 +- src/core/taskjudger.h | 3 + tests/windows-sandbox/main.cpp | 20 ++-- unix/watcher_unix.cpp | 195 ++++++++++++++++++++++++++++----- 9 files changed, 238 insertions(+), 80 deletions(-) diff --git a/src/core/casejudger.cpp b/src/core/casejudger.cpp index 31ead802..5eb1379e 100644 --- a/src/core/casejudger.cpp +++ b/src/core/casejudger.cpp @@ -774,6 +774,7 @@ void CaseJudger::judgeTraditionalTask() { }); ProcessRunnerConfig cfg{ + .stopToken = stopToken, .executableFile = executableFile, .arguments = arguments, .workingDirectory = workingDirectory, diff --git a/src/core/casejudger.h b/src/core/casejudger.h index c37c1d7f..8b497f7a 100644 --- a/src/core/casejudger.h +++ b/src/core/casejudger.h @@ -23,6 +23,7 @@ class CaseJudger { public: CaseJudger(); void setCancellation(QFuture); + std::stop_token stopToken; void setExtraTimeRatio(double); void setEnvironment(const QProcessEnvironment &); void setWorkingDirectory(const QString &); diff --git a/src/core/judgingcontroller.cpp b/src/core/judgingcontroller.cpp index 492e76cd..fe166384 100644 --- a/src/core/judgingcontroller.cpp +++ b/src/core/judgingcontroller.cpp @@ -77,7 +77,9 @@ void JudgingController::stop() { delete queuingTasks.dequeue().judger; for (auto *watcher : runningTasks.keys()) { // Preserve results that finished before the stop request reached the GUI. - if (! watcher->isFinished()) + if (! watcher->isFinished()) { watcher->cancel(); + runningTasks.value(watcher).judger->requestStop(); + } } } diff --git a/src/core/processrunner.h b/src/core/processrunner.h index 236254f0..a14dfcb8 100644 --- a/src/core/processrunner.h +++ b/src/core/processrunner.h @@ -14,10 +14,12 @@ #include #include #include +#include class WindowsSandboxSession; struct ProcessRunnerConfig { + std::stop_token stopToken; QString executableFile; QString arguments; QString workingDirectory; diff --git a/src/core/processrunner_win.cpp b/src/core/processrunner_win.cpp index 290bbb09..79ee1bd7 100644 --- a/src/core/processrunner_win.cpp +++ b/src/core/processrunner_win.cpp @@ -136,65 +136,68 @@ ProcessRunnerResult WinProcessRunner::run() { if (! killAndReap(pi.hProcess, job.get())) WARN("Process reaping deadline exceeded"); }); + std::stop_callback stopCallback(config.stopToken, [&] { + TerminateJobObject(job.get(), 1); + // Also cover cancellation before the suspended process joins the Job. + TerminateProcess(pi.hProcess, 1); + }); + if (config.stopToken.stop_requested() || cancellation.isCanceled()) + return res; if ((! sandbox && ! AssignProcessToJobObject(job.get(), pi.hProcess)) || ResumeThread(pi.hThread) == DWORD(-1)) { TerminateProcess(pi.hProcess, 1); res.result = CannotStartProgram; res.message = "Cannot attach or resume process"; + if (config.stopToken.stop_requested()) { + res.result = CorrectAnswer; + res.message.clear(); + } return res; } Lemon::Execution::Limiter limiter(memoryLimit); Handle deadline(CreateWaitableTimerW(nullptr, TRUE, nullptr)); - Handle sampling(CreateWaitableTimerW(nullptr, FALSE, nullptr)); LARGE_INTEGER due{}; // Negative values specify a relative interval in 100 ns units. due.QuadPart = -qMax(1LL, (static_cast(config.timeLimit) + extraTime) * 10000LL); - LARGE_INTEGER sampleDue{}; - sampleDue.QuadPart = -100000; - if (! deadline || ! sampling || ! SetWaitableTimer(deadline.get(), &due, 0, nullptr, nullptr, FALSE) || - ! SetWaitableTimer(sampling.get(), &sampleDue, 10, nullptr, nullptr, FALSE)) { + if (! deadline || ! SetWaitableTimer(deadline.get(), &due, 0, nullptr, nullptr, FALSE)) { const DWORD code = GetLastError(); res.result = CannotStartProgram; res.message = "Cannot configure execution timers"; WARN("Last Error code:", code); return res; } - HANDLE handles[] = {pi.hProcess, deadline.get(), sampling.get()}; - // Take the initial sample before entering the blocking event wait. - DWORD state = WAIT_OBJECT_0 + 2; - int missing = 0; - for (;;) { - auto sample = sampleMemory(pi.hProcess); - limiter.observe(sample); - res.memoryUsed = limiter.usage(); - if (limiter.isExceeded()) { - res.result = MemoryLimitExceeded; - return res; - } - if (state == WAIT_OBJECT_0) { - break; - } - missing = sample < 0 ? missing + 1 : 0; - if (missing >= 10) { - res.result = CannotStartProgram; - res.message = "Process statistics unavailable"; - return res; - } - if (cancellation.isCanceled()) - return res; - if (state == WAIT_OBJECT_0 + 1) { - res.result = TimeLimitExceeded; - res.timeUsed = -1; - return res; - } - state = WaitForMultipleObjects(3, handles, FALSE, INFINITE); - if (state == WAIT_FAILED) { - const DWORD code = GetLastError(); - res.result = CannotStartProgram; - res.message = "Cannot wait for process events"; - WARN("Last Error code:", code); - return res; - } + HANDLE handles[] = {pi.hProcess, deadline.get()}; + DWORD state = WaitForMultipleObjects(2, handles, FALSE, INFINITE); + if (config.stopToken.stop_requested() || cancellation.isCanceled()) { + if (! killAndReap(pi.hProcess, job.get())) + WARN("Process reaping deadline exceeded"); + res.memoryUsed = sampleMemory(pi.hProcess); + return res; + } + if (state == WAIT_FAILED) { + WARN("Last Error code:", GetLastError()); + res.result = CannotStartProgram; + res.message = "Cannot wait for process events"; + return res; + } + if (state == WAIT_OBJECT_0 + 1) { + if (! killAndReap(pi.hProcess, job.get())) + WARN("Process reaping deadline exceeded"); + res.result = TimeLimitExceeded; + } + auto sample = sampleMemory(pi.hProcess); + limiter.observe(sample); + res.memoryUsed = limiter.usage(); + if (res.result == TimeLimitExceeded) + return res; + if (sample < 0) { + res.result = CannotStartProgram; + res.message = "Process statistics unavailable"; + return res; + } + if (limiter.isExceeded()) { + res.result = MemoryLimitExceeded; + return res; } unsigned long exitCode; GetExitCodeProcess(pi.hProcess, &exitCode); diff --git a/src/core/taskjudger.cpp b/src/core/taskjudger.cpp index 78fc2a38..50789e0c 100644 --- a/src/core/taskjudger.cpp +++ b/src/core/taskjudger.cpp @@ -433,8 +433,8 @@ int TaskJudger::judge() { QString workingDirectory = QDir::toNativeSeparators(QDir(QDir::toNativeSeparators(temporaryDir.path()) + - QDir::separator() + QString("_%1.%2").arg(i).arg(j)) - .absolutePath()) + + QDir::separator() + QString("_%1.%2").arg(i).arg(j)) + .absolutePath()) + QDir::separator(); if (! QDir(temporaryDir.path()).mkdir(QString("_%1.%2").arg(i).arg(j))) { result[i][j] = FileError; @@ -447,6 +447,7 @@ int TaskJudger::judge() { } auto caseJudger = std::make_unique(); caseJudger->setCancellation(cancellation); + caseJudger->stopToken = stopSource.get_token(); caseJudger->setExtraTimeRatio(settings->getDefaultExtraTimeRatio()); caseJudger->setWorkingDirectory(workingDirectory); caseJudger->setSandboxConfiguration(sandboxSettings, runtimeExecutable, runtimeEnvironment, @@ -528,7 +529,7 @@ int TaskJudger::judge() { result[i][j] = caseJudger->getResult(); overallStatus[i] = qMin(overallStatus[i], stateToStatus(caseJudger->getResult(), caseJudger->getScore(), - caseJudger->getFullScore())); + caseJudger->getFullScore())); message[i][j] = caseJudger->getMessage(); caseJudger.reset(); int nowScore = score[i][j]; diff --git a/src/core/taskjudger.h b/src/core/taskjudger.h index af69d014..1d019645 100644 --- a/src/core/taskjudger.h +++ b/src/core/taskjudger.h @@ -20,6 +20,7 @@ #include #include #include +#include class Settings; class Task; @@ -45,6 +46,7 @@ class TaskJudger : public QObject { const Task *task{}; QString contestantName; QFuture cancellation; + std::stop_source stopSource; CompileState compileState; QString compileMessage; QString sourceFile; @@ -78,6 +80,7 @@ class TaskJudger : public QObject { public: TaskResult judgeIt(QPromise &promise); + void requestStop() { stopSource.request_stop(); } signals: void judgingStarted(QString); void dialogAlert(QString); diff --git a/tests/windows-sandbox/main.cpp b/tests/windows-sandbox/main.cpp index d68315bb..4c10feeb 100644 --- a/tests/windows-sandbox/main.cpp +++ b/tests/windows-sandbox/main.cpp @@ -861,6 +861,8 @@ class WindowsSandboxTests : public QObject { QPromise promise; promise.start(); Handle primary; + std::stop_source stopSource; + cfg.stopToken = stopSource.get_token(); std::thread cancel([&] { QElapsedTimer timer; timer.start(); @@ -873,6 +875,7 @@ class WindowsSandboxTests : public QObject { QThread::msleep(10); } promise.future().cancel(); + stopSource.request_stop(); }); const auto result = ProcessRunner::create(cfg, promise.future())->run(); cancel.join(); @@ -926,6 +929,8 @@ class WindowsSandboxTests : public QObject { promise.start(); cfg.sandboxSettings.preparationTimeLimit = 1000; DWORD probeId = 0; + std::stop_source stopSource; + cfg.stopToken = stopSource.get_token(); std::thread cancel([&] { QElapsedTimer timer; timer.start(); @@ -935,6 +940,7 @@ class WindowsSandboxTests : public QObject { QThread::msleep(10); } promise.future().cancel(); + stopSource.request_stop(); }); const auto limitedWithStop = ProcessRunner::create(cfg, promise.future())->run(); cancel.join(); @@ -987,7 +993,7 @@ class WindowsSandboxTests : public QObject { source, extension == "c" ? "#include \nint main(void){int a,b;scanf(\"%d%d\",&a,&b);printf(\"%d\\n\",a+b);}" - : "#include \nint main(){int a,b;std::cin>>a>>b;std::cout<\nint main(){int a,b;std::cin>>a>>b;std::cout< #ifdef __linux__ #include +#include #include +#include #include #include #elif defined(__APPLE__) @@ -25,7 +27,7 @@ namespace { sigset_t previous{}; bool masked = false; #ifdef __linux__ - int descriptors[3] = {-1, -1, -1}; + int descriptors[2] = {-1, -1}; #else int queue = -1; struct sigaction actions[4]{}; @@ -68,9 +70,8 @@ namespace { masked = true; #ifdef __linux__ descriptors[0] = timerfd_create(CLOCK_MONOTONIC, TFD_CLOEXEC | TFD_NONBLOCK); - descriptors[1] = timerfd_create(CLOCK_MONOTONIC, TFD_CLOEXEC | TFD_NONBLOCK); - descriptors[2] = signalfd(-1, &mask, SFD_CLOEXEC | SFD_NONBLOCK); - return descriptors[0] >= 0 && descriptors[1] >= 0 && descriptors[2] >= 0; + descriptors[1] = signalfd(-1, &mask, SFD_CLOEXEC | SFD_NONBLOCK); + return descriptors[0] >= 0 && descriptors[1] >= 0; #else queue = kqueue(); if (queue < 0 || fcntl(queue, F_SETFD, FD_CLOEXEC) < 0) @@ -92,16 +93,10 @@ namespace { } bool arm(long long milliseconds, bool sampling) { #ifdef __linux__ - for (int i = 0; i < 2; ++i) { - long long delay = i == 0 ? milliseconds : (sampling ? 10 : 0); - itimerspec spec{}; - spec.it_value = {delay / 1000, (delay % 1000) * 1000000}; - if (i == 1) - spec.it_interval = spec.it_value; - if (timerfd_settime(descriptors[i], 0, &spec, nullptr) < 0) - return false; - } - return true; + (void)sampling; + itimerspec spec{}; + spec.it_value = {milliseconds / 1000, (milliseconds % 1000) * 1000000}; + return timerfd_settime(descriptors[0], 0, &spec, nullptr) == 0; #else struct kevent changes[2]{}; EV_SET(&changes[0], Deadline, EVFILT_TIMER, EV_ADD | EV_ONESHOT, 0, milliseconds, nullptr); @@ -113,25 +108,24 @@ namespace { int wait() { int events = 0; #ifdef __linux__ - pollfd ready[3] = { - {descriptors[0], POLLIN, 0}, {descriptors[1], POLLIN, 0}, {descriptors[2], POLLIN, 0}}; - if (::poll(ready, 3, -1) < 0) + pollfd ready[2] = {{descriptors[0], POLLIN, 0}, {descriptors[1], POLLIN, 0}}; + if (::poll(ready, 2, -1) < 0) return errno == EINTR ? 0 : -1; - for (int i = 0; i < 3; ++i) { + for (int i = 0; i < 2; ++i) { if (ready[i].revents & (POLLERR | POLLHUP | POLLNVAL)) { errno = EIO; return -1; } if (! (ready[i].revents & POLLIN)) continue; - if (i < 2) { + if (i == 0) { uint64_t count; if (read(descriptors[i], &count, sizeof(count)) != sizeof(count)) return -1; - events |= i == 0 ? Deadline : Sample; + events |= Deadline; } else { signalfd_siginfo info; - while (read(descriptors[2], &info, sizeof(info)) == sizeof(info)) + while (read(descriptors[1], &info, sizeof(info)) == sizeof(info)) events |= info.ssi_signo == SIGCHLD ? Child : Stop; if (errno != EAGAIN && errno != EINTR) return -1; @@ -162,15 +156,124 @@ namespace { bool reaped = false; bool cleaned = false; Events &events; - explicit UnixProcess(pid_t pid, Events &events) : pid(pid), events(events) {} + Bytes peak = -1; +#ifdef __linux__ + std::set traced; + std::set newborn; + bool initialized = false; +#endif + explicit UnixProcess(pid_t pid, Events &events) : pid(pid), events(events) { +#ifdef __linux__ + traced.insert(pid); +#endif + } ~UnixProcess() { if (! cleaned) killAndReap(); } // Do not destroy the exit information until all final samples are consumed. int poll() { - if (reaped) + if (reaped +#ifdef __linux__ + && traced.empty() +#endif + ) return 1; +#ifdef __linux__ + for (;;) { + bool progress = false; + for (auto it = traced.begin(); it != traced.end();) { + pid_t tid = *it; + int state = 0; + rusage sample{}; + pid_t result = wait4(tid, &state, WNOHANG | __WALL, &sample); + if (result < 0) { + if (errno == EINTR) + return 0; + return -1; + } + if (result == 0) { + ++it; + continue; + } + progress = true; + if (WIFEXITED(state) || WIFSIGNALED(state)) { + if (tid == pid) { + status = state; + usage = sample; + reaped = true; + } + it = traced.erase(it); + continue; + } + unsigned event = static_cast(state) >> 16; + int signal = WSTOPSIG(state); + if (! initialized && tid == pid) { + if (signal != SIGSTOP || ptrace(PTRACE_SETOPTIONS, pid, nullptr, + PTRACE_O_TRACEEXIT | PTRACE_O_TRACEEXEC | + PTRACE_O_TRACECLONE | PTRACE_O_EXITKILL) < 0) + return -1; + initialized = true; + signal = 0; + } else if (event == PTRACE_EVENT_EXIT) { + auto memory = sampleMemory(tid); + if (memory < 0) + return -1; + peak = std::max(peak, memory); + signal = 0; + } else if (event == PTRACE_EVENT_CLONE) { + unsigned long child = 0; + if (ptrace(PTRACE_GETEVENTMSG, tid, nullptr, &child) < 0) + return -1; + traced.insert(static_cast(child)); + newborn.insert(static_cast(child)); + signal = 0; + } else if (event == PTRACE_EVENT_EXEC) { + unsigned long oldTid = 0; + if (ptrace(PTRACE_GETEVENTMSG, tid, nullptr, &oldTid) < 0) + return -1; + if (static_cast(oldTid) != tid) + traced.erase(static_cast(oldTid)); + signal = 0; + } else if (newborn.erase(tid)) { + int group = -1; + auto path = "/proc/" + std::to_string(tid) + "/status"; + FILE *file = fopen(path.c_str(), "r"); + if (! file) + return -1; + char line[512]; + while (fgets(line, sizeof(line), file)) + if (sscanf(line, "Tgid: %d", &group) == 1) + break; + fclose(file); + if (group < 0) + return -1; + if (group != pid) { + if (ptrace(PTRACE_DETACH, tid, nullptr, nullptr) < 0) + return -1; + it = traced.erase(it); + continue; + } + signal = 0; + } else if (! event) { + siginfo_t info{}; + if (ptrace(PTRACE_GETSIGINFO, tid, nullptr, &info) < 0) { + if (errno != EINVAL) + return -1; + // A group stop remains stopped until SIGCONT or cleanup. + ++it; + continue; + } + } else + signal = 0; + if (ptrace(PTRACE_CONT, tid, nullptr, signal) < 0 && errno != ESRCH) + return -1; + ++it; + } + if (! progress) + return reaped && traced.empty() ? 1 : 0; + } +#else pid_t result = wait4(pid, &status, WNOHANG, &usage); if (result == pid) { reaped = true; @@ -179,15 +282,24 @@ namespace { if (result < 0 && errno != EINTR) return -1; return 0; +#endif } bool killAndReap() { if (cleaned) - return reaped; + return reaped +#ifdef __linux__ + && traced.empty() +#endif + ; cleaned = true; kill(-pid, SIGKILL); if (! reaped) kill(pid, SIGKILL); - if (reaped) + if (reaped +#ifdef __linux__ + && traced.empty() +#endif + ) return true; if (! events.arm(2000, false)) { perror("reaping events"); @@ -196,7 +308,11 @@ namespace { for (;;) { if (poll() < 0) return false; - if (reaped) + if (reaped +#ifdef __linux__ + && traced.empty() +#endif + ) break; int event = events.wait(); if (event < 0) { @@ -209,7 +325,11 @@ namespace { break; } } - return reaped; + return reaped +#ifdef __linux__ + && traced.empty() +#endif + ; } }; struct ChildError { @@ -274,6 +394,10 @@ int main(int argc, char **argv) { if (! freopen(*argv[3 + i] ? argv[3 + i] : "/dev/null", modes[i], streams[i])) fail(2); #ifdef __linux__ + if (ptrace(PTRACE_TRACEME, 0, nullptr, nullptr) < 0) + fail(8); + if (raise(SIGSTOP) != 0) + fail(8); // Disable dump generation, including piped core handlers. if (prctl(PR_SET_DUMPABLE, 0) != 0) fail(6); @@ -301,7 +425,10 @@ int main(int argc, char **argv) { perror("events arm"); int event = Events::Sample; int verdict = RS_AC; + +#ifdef __APPLE__ int missing = 0; +#endif ChildError childError{}; bool setupFailed = false; for (;;) { @@ -309,13 +436,20 @@ int main(int argc, char **argv) { verdict = RS_FAIL; break; } +#ifdef __linux__ + auto sample = Bytes(-1); +#else auto sample = event & Events::Sample ? sampleMemory(pid) : Bytes(-1); +#endif limiter.observe(sample); // The fixed-size read is bounded by the destination object on every iteration. /* Flawfinder: ignore */ if (read(errors[0], &childError, sizeof(childError)) == sizeof(childError)) setupFailed = true; int finished = process.poll(); +#ifdef __linux__ + limiter.observe(process.peak); +#endif if (setupFailed || finished < 0) { verdict = RS_FAIL; break; @@ -334,6 +468,7 @@ int main(int argc, char **argv) { verdict = RS_FAIL; break; } +#ifdef __APPLE__ if (event & Events::Sample) missing = sample < 0 ? missing + 1 : 0; if (missing >= 10) { @@ -341,6 +476,7 @@ int main(int argc, char **argv) { verdict = RS_FAIL; break; } +#endif event = events.wait(); if (event < 0) { perror("events wait"); @@ -356,6 +492,9 @@ int main(int argc, char **argv) { close(errors[0]); if (! process.killAndReap()) fprintf(stderr, "Process reaping deadline exceeded\n"); +#ifdef __linux__ + limiter.observe(process.peak); +#endif if (setupFailed) { fprintf(stderr, "Child setup stage %d failed: errno %d\n", childError.stage, childError.error); verdict = RS_FAIL; @@ -376,7 +515,7 @@ int main(int argc, char **argv) { } long long elapsed = process.reaped ? process.usage.ru_utime.tv_sec * 1000LL + process.usage.ru_utime.tv_usec / 1000 - : -1; + : -1; if (verdict == RS_AC && elapsed > timeLimit) verdict = RS_TLE; printf("%lld\n%lld\n", elapsed, static_cast(limiter.usage())); From 6ae31aadd84867ce30472c663a8b1ce193a5c1ce Mon Sep 17 00:00:00 2001 From: "GitHub Action (clang-format)" Date: Sun, 8 Nov 2026 16:59:45 +0000 Subject: [PATCH 25/37] style: format codes --- src/core/processrunner_win.cpp | 8 ++++---- src/core/taskjudger.cpp | 6 +++--- tests/windows-sandbox/main.cpp | 14 +++++++------- unix/watcher_unix.cpp | 2 +- 4 files changed, 15 insertions(+), 15 deletions(-) diff --git a/src/core/processrunner_win.cpp b/src/core/processrunner_win.cpp index 79ee1bd7..c336aa32 100644 --- a/src/core/processrunner_win.cpp +++ b/src/core/processrunner_win.cpp @@ -75,14 +75,14 @@ ProcessRunnerResult WinProcessRunner::run() { if (config.standardOutputCheck) { siex.StartupInfo.hStdOutput = CreateFileW((const WCHAR *)((config.workingDirectory + "_tmpout").utf16()), GENERIC_WRITE, - FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, &sa, CREATE_ALWAYS, - FILE_ATTRIBUTE_NORMAL, NULL); + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, &sa, CREATE_ALWAYS, + FILE_ATTRIBUTE_NORMAL, NULL); } siex.StartupInfo.hStdError = CreateFileW((const WCHAR *)((config.workingDirectory + "_tmperr").utf16()), GENERIC_WRITE, - FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, &sa, CREATE_ALWAYS, - FILE_ATTRIBUTE_NORMAL, NULL); + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, &sa, CREATE_ALWAYS, + FILE_ATTRIBUTE_NORMAL, NULL); auto closeStdIO = qScopeGuard([&] { if (config.standardInputCheck) diff --git a/src/core/taskjudger.cpp b/src/core/taskjudger.cpp index 50789e0c..98d72acb 100644 --- a/src/core/taskjudger.cpp +++ b/src/core/taskjudger.cpp @@ -433,8 +433,8 @@ int TaskJudger::judge() { QString workingDirectory = QDir::toNativeSeparators(QDir(QDir::toNativeSeparators(temporaryDir.path()) + - QDir::separator() + QString("_%1.%2").arg(i).arg(j)) - .absolutePath()) + + QDir::separator() + QString("_%1.%2").arg(i).arg(j)) + .absolutePath()) + QDir::separator(); if (! QDir(temporaryDir.path()).mkdir(QString("_%1.%2").arg(i).arg(j))) { result[i][j] = FileError; @@ -529,7 +529,7 @@ int TaskJudger::judge() { result[i][j] = caseJudger->getResult(); overallStatus[i] = qMin(overallStatus[i], stateToStatus(caseJudger->getResult(), caseJudger->getScore(), - caseJudger->getFullScore())); + caseJudger->getFullScore())); message[i][j] = caseJudger->getMessage(); caseJudger.reset(); int nowScore = score[i][j]; diff --git a/tests/windows-sandbox/main.cpp b/tests/windows-sandbox/main.cpp index 4c10feeb..91b30afd 100644 --- a/tests/windows-sandbox/main.cpp +++ b/tests/windows-sandbox/main.cpp @@ -993,7 +993,7 @@ class WindowsSandboxTests : public QObject { source, extension == "c" ? "#include \nint main(void){int a,b;scanf(\"%d%d\",&a,&b);printf(\"%d\\n\",a+b);}" - : "#include \nint main(){int a,b;std::cin>>a>>b;std::cout<\nint main(){int a,b;std::cin>>a>>b;std::cout< timeLimit) verdict = RS_TLE; printf("%lld\n%lld\n", elapsed, static_cast(limiter.usage())); From c2dcfecb5e684411b59ddce1fb679e050a620244 Mon Sep 17 00:00:00 2001 From: sgt57 <198590103+sgt57@users.noreply.github.com> Date: Mon, 9 Nov 2026 01:02:06 +0800 Subject: [PATCH 26/37] test(process): remove sampling delays from memory fixtures --- tests/windows-sandbox/helper.cpp | 4 ---- unix/test/memory_cases.cpp | 4 ---- 2 files changed, 8 deletions(-) diff --git a/tests/windows-sandbox/helper.cpp b/tests/windows-sandbox/helper.cpp index 4dcd76d6..1cd96f80 100644 --- a/tests/windows-sandbox/helper.cpp +++ b/tests/windows-sandbox/helper.cpp @@ -302,7 +302,6 @@ int wmain(int argc, wchar_t **argv) { return 37; puts("expected"); fflush(stdout); - Sleep(100); if (p) VirtualFree(p, 0, MEM_RELEASE); return mode == L"commit-rejected" ? 12 : 0; @@ -327,7 +326,6 @@ int wmain(int argc, wchar_t **argv) { static_cast(counters.PeakPagefileUsage), static_cast(bytes)); fflush(stdout); - Sleep(500); VirtualFree(allocation, 0, MEM_RELEASE); return 0; } @@ -362,7 +360,6 @@ int wmain(int argc, wchar_t **argv) { printf("working-set-peak=%llu sum=%u\n", static_cast(counters.PeakWorkingSetSize), sum); fflush(stdout); - Sleep(200); UnmapViewOfFile(const_cast(pages)); CloseHandle(mapping); return measured ? 0 : 42; @@ -372,7 +369,6 @@ int wmain(int argc, wchar_t **argv) { auto *memory = static_cast( VirtualAlloc(nullptr, 1024 * 1024, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE)); if (! memory) { - Sleep(100); return 12; } for (int j = 0; j < 1024 * 1024; j += 4096) diff --git a/unix/test/memory_cases.cpp b/unix/test/memory_cases.cpp index d5f157ef..d3f0f32c 100644 --- a/unix/test/memory_cases.cpp +++ b/unix/test/memory_cases.cpp @@ -51,8 +51,6 @@ int main(int argc, char **argv) { printf("reference-bytes=%llu allocation-bytes=%llu\n", reference, static_cast(bytes)); fflush(stdout); - // Leave the allocation visible across many watcher sampling intervals. - std::this_thread::sleep_for(std::chrono::milliseconds(500)); munmap(mapping, bytes); return 0; } @@ -77,13 +75,11 @@ int main(int argc, char **argv) { return 7; for (int i = 0; i < 96 * 1024 * 1024; i += 4096) p[i] = 1; - std::this_thread::sleep_for(std::chrono::milliseconds(300)); return 0; } if (! strcmp(argv[1], "reserve")) { void *p = mmap(nullptr, 128 * 1024 * 1024, PROT_NONE, MAP_PRIVATE | MAP_ANON, -1, 0); puts(p == MAP_FAILED ? "denied" : "reserved"); - std::this_thread::sleep_for(std::chrono::milliseconds(100)); return 0; } if (! strcmp(argv[1], "sleep")) { From bf3a0c4f12498cc7eb51000a65dc3aee09dc7594 Mon Sep 17 00:00:00 2001 From: sgt57 <198590103+sgt57@users.noreply.github.com> Date: Mon, 9 Nov 2026 01:21:42 +0800 Subject: [PATCH 27/37] fix(process): expand stack on Linux when there is no memory limit --- unix/watcher_linux.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/unix/watcher_linux.cpp b/unix/watcher_linux.cpp index d4da2cbf..d9ff908c 100644 --- a/unix/watcher_linux.cpp +++ b/unix/watcher_linux.cpp @@ -22,14 +22,14 @@ Bytes sampleMemory(pid_t pid) { } bool applyMemoryLimit(Bytes limit) { - if (limit < 0) - return true; - rlimit memory{static_cast(limit), static_cast(limit)}; - if (setrlimit(RLIMIT_AS, &memory) != 0) - return false; + if (limit >= 0) { + rlimit memory{static_cast(limit), static_cast(limit)}; + if (setrlimit(RLIMIT_AS, &memory) != 0) + return false; + } rlimit stack{}; if (getrlimit(RLIMIT_STACK, &stack) != 0) return false; - stack.rlim_cur = std::min(stack.rlim_max, static_cast(limit)); + stack.rlim_cur = std::min(stack.rlim_max, static_cast(limit < 0 ? 2147483647LL : limit)); return setrlimit(RLIMIT_STACK, &stack) == 0; } From b7de2d5a3a6cd09afbed2bdd492ba3752eb87266 Mon Sep 17 00:00:00 2001 From: sgt57 <198590103+sgt57@users.noreply.github.com> Date: Mon, 9 Nov 2026 01:42:59 +0800 Subject: [PATCH 28/37] refactor(process): inline memory limit checks and localize Windows helpers --- .github/workflows/watcher_linux.yml | 4 +- .github/workflows/watcher_macos.yml | 4 +- .github/workflows/windows-qt6.yml | 4 +- src/core/memorylimiter.h | 37 ----------------- src/core/memoryunits.h | 22 ++++++++++ src/core/processrunner_win.cpp | 55 ++++++++++++++++++++++--- src/core/windowsmemory.h | 54 ------------------------ tests/CMakeLists.txt | 1 - tests/memory-limiter/CMakeLists.txt | 6 --- tests/memory-limiter/main.cpp | 30 -------------- tests/memory-limiter/windows_macros.cpp | 14 ------- unix/memoryusage.h | 2 +- unix/test/CMakeLists.txt | 3 -- unix/watcher_linux.cpp | 15 +++++-- unix/watcher_macos.mm | 10 ++++- unix/watcher_unix.cpp | 27 +++++++----- 16 files changed, 115 insertions(+), 173 deletions(-) delete mode 100644 src/core/memorylimiter.h create mode 100644 src/core/memoryunits.h delete mode 100644 src/core/windowsmemory.h delete mode 100644 tests/memory-limiter/CMakeLists.txt delete mode 100644 tests/memory-limiter/main.cpp delete mode 100644 tests/memory-limiter/windows_macros.cpp diff --git a/.github/workflows/watcher_linux.yml b/.github/workflows/watcher_linux.yml index 3d967636..ff05ffd6 100644 --- a/.github/workflows/watcher_linux.yml +++ b/.github/workflows/watcher_linux.yml @@ -3,10 +3,10 @@ name: Watcher for Linux Test on: push: branches: ["master"] - paths: ["unix/**", "src/core/memorylimiter.h", "tests/memory-limiter/**"] + paths: ["unix/**", "src/core/memoryunits.h"] pull_request: branches: ["master"] - paths: ["unix/**", "src/core/memorylimiter.h", "tests/memory-limiter/**"] + paths: ["unix/**", "src/core/memoryunits.h"] workflow_dispatch: env: diff --git a/.github/workflows/watcher_macos.yml b/.github/workflows/watcher_macos.yml index 6386f634..d2daf200 100644 --- a/.github/workflows/watcher_macos.yml +++ b/.github/workflows/watcher_macos.yml @@ -3,10 +3,10 @@ name: Watcher for MacOS Test on: push: branches: ["master"] - paths: ["unix/**", "src/core/memorylimiter.h", "tests/memory-limiter/**"] + paths: ["unix/**", "src/core/memoryunits.h"] pull_request: branches: ["master"] - paths: ["unix/**", "src/core/memorylimiter.h", "tests/memory-limiter/**"] + paths: ["unix/**", "src/core/memoryunits.h"] workflow_dispatch: env: diff --git a/.github/workflows/windows-qt6.yml b/.github/workflows/windows-qt6.yml index af6a232c..6308c411 100644 --- a/.github/workflows/windows-qt6.yml +++ b/.github/workflows/windows-qt6.yml @@ -91,9 +91,9 @@ jobs: - name: Deploy Qt for tests shell: pwsh run: | - # These helpers do not import Qt at runtime. + # This helper does not import Qt at runtime. Get-ChildItem tests -Recurse -Filter *.exe | - Where-Object { $_.Name -notin @('sandbox-helper.exe', 'memory-limiter-test.exe') } | + Where-Object { $_.Name -ne 'sandbox-helper.exe' } | ForEach-Object { windeployqt $_.FullName if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } diff --git a/src/core/memorylimiter.h b/src/core/memorylimiter.h deleted file mode 100644 index d6291c08..00000000 --- a/src/core/memorylimiter.h +++ /dev/null @@ -1,37 +0,0 @@ -// SPDX-License-Identifier: GPL-3.0-or-later -#pragma once - -#include -#include -#include - -namespace Lemon::Execution { - using Bytes = std::int64_t; - - inline bool memoryBytes(std::int64_t mib, Bytes &bytes) { - if (mib < 0) { - bytes = -1; - return true; - } - if (mib > (std::numeric_limits::max)() / (1024 * 1024)) - return false; - bytes = mib * 1024 * 1024; - return true; - } - - // Tracks memory usage only; platform code owns process operations and exit statuses. - class Limiter { - public: - explicit Limiter(Bytes limit) : limit(limit) {} - bool observe(Bytes declaredUsage) { - peak = (std::max)(peak, declaredUsage); - return isExceeded(); - } - Bytes usage() const { return peak; } - bool isExceeded() const { return limit >= 0 && peak > limit; } - - private: - Bytes limit; - Bytes peak = -1; - }; -} // namespace Lemon::Execution diff --git a/src/core/memoryunits.h b/src/core/memoryunits.h new file mode 100644 index 00000000..2c9a56b8 --- /dev/null +++ b/src/core/memoryunits.h @@ -0,0 +1,22 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +#pragma once + +#include +#include + +namespace Lemon::Execution { + using Bytes = std::int64_t; + inline constexpr Bytes KiB = 1024; + inline constexpr Bytes MiB = KiB * 1024; + + inline bool memoryBytes(std::int64_t mib, Bytes &bytes) { + if (mib < 0) { + bytes = -1; + return true; + } + if (mib > (std::numeric_limits::max)() / MiB) + return false; + bytes = mib * MiB; + return true; + } +} // namespace Lemon::Execution diff --git a/src/core/processrunner_win.cpp b/src/core/processrunner_win.cpp index c336aa32..56789fdc 100644 --- a/src/core/processrunner_win.cpp +++ b/src/core/processrunner_win.cpp @@ -11,7 +11,7 @@ #include "processrunner_win.h" #include "base/LemonLog.hpp" -#include "windowsmemory.h" +#include "memoryunits.h" #include "windowsprocessutils.h" #include "windowssandbox.h" @@ -30,6 +30,53 @@ using namespace Lemon::Windows; +namespace { + class ExecutionJob { + Handle handle{CreateJobObjectW(nullptr, nullptr)}; + + public: + HANDLE get() const { return handle.get(); } + bool apply(Lemon::Execution::Bytes limit) { + if (! handle) + return false; + JOBOBJECT_EXTENDED_LIMIT_INFORMATION info{}; + info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; + if (limit >= 0) { + if (static_cast(limit) > SIZE_MAX) { + SetLastError(ERROR_INVALID_PARAMETER); + return false; + } + info.BasicLimitInformation.LimitFlags |= JOB_OBJECT_LIMIT_PROCESS_MEMORY; + info.ProcessMemoryLimit = static_cast(limit); + } + return SetInformationJobObject(get(), JobObjectExtendedLimitInformation, &info, sizeof(info)); + } + bool restrictToOneProcess() { + JOBOBJECT_EXTENDED_LIMIT_INFORMATION info{}; + if (! QueryInformationJobObject(get(), JobObjectExtendedLimitInformation, &info, sizeof(info), + nullptr)) + return false; + info.BasicLimitInformation.LimitFlags |= JOB_OBJECT_LIMIT_ACTIVE_PROCESS; + info.BasicLimitInformation.ActiveProcessLimit = 1; + return SetInformationJobObject(get(), JobObjectExtendedLimitInformation, &info, sizeof(info)); + } + }; + Lemon::Execution::Bytes sampleMemory(HANDLE process) { + PROCESS_MEMORY_COUNTERS_EX info{}; + info.cb = sizeof(info); + if (! GetProcessMemoryInfo(process, reinterpret_cast(&info), sizeof(info))) + return -1; + // PeakPagefileUsage is the process lifetime peak of private committed memory. + return static_cast(info.PeakPagefileUsage); + } + + bool killAndReap(HANDLE process, HANDLE job) { + if (! TerminateJobObject(job, 1) && WaitForSingleObject(process, 0) != WAIT_OBJECT_0) + return false; + return WaitForSingleObject(process, 2000) == WAIT_OBJECT_0; + } +} // namespace + ProcessRunnerResult WinProcessRunner::run() { ProcessRunnerResult res; res.result = CorrectAnswer; @@ -154,7 +201,6 @@ ProcessRunnerResult WinProcessRunner::run() { } return res; } - Lemon::Execution::Limiter limiter(memoryLimit); Handle deadline(CreateWaitableTimerW(nullptr, TRUE, nullptr)); LARGE_INTEGER due{}; // Negative values specify a relative interval in 100 ns units. @@ -186,8 +232,7 @@ ProcessRunnerResult WinProcessRunner::run() { res.result = TimeLimitExceeded; } auto sample = sampleMemory(pi.hProcess); - limiter.observe(sample); - res.memoryUsed = limiter.usage(); + res.memoryUsed = sample; if (res.result == TimeLimitExceeded) return res; if (sample < 0) { @@ -195,7 +240,7 @@ ProcessRunnerResult WinProcessRunner::run() { res.message = "Process statistics unavailable"; return res; } - if (limiter.isExceeded()) { + if (memoryLimit >= 0 && res.memoryUsed > memoryLimit) { res.result = MemoryLimitExceeded; return res; } diff --git a/src/core/windowsmemory.h b/src/core/windowsmemory.h deleted file mode 100644 index d3398f74..00000000 --- a/src/core/windowsmemory.h +++ /dev/null @@ -1,54 +0,0 @@ -// SPDX-License-Identifier: GPL-3.0-or-later -#pragma once -#include "memorylimiter.h" -#include "windowsprocessutils.h" -#ifdef Q_OS_WIN -#include -namespace Lemon::Windows { - class ExecutionJob { - Handle handle{CreateJobObjectW(nullptr, nullptr)}; - - public: - HANDLE get() const { return handle.get(); } - bool apply(Execution::Bytes limit) { - if (! handle) - return false; - JOBOBJECT_EXTENDED_LIMIT_INFORMATION info{}; - info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; - if (limit >= 0) { - if (static_cast(limit) > SIZE_MAX) { - SetLastError(ERROR_INVALID_PARAMETER); - return false; - } - info.BasicLimitInformation.LimitFlags |= JOB_OBJECT_LIMIT_PROCESS_MEMORY; - info.ProcessMemoryLimit = static_cast(limit); - } - return SetInformationJobObject(get(), JobObjectExtendedLimitInformation, &info, sizeof(info)); - } - bool restrictToOneProcess() { - JOBOBJECT_EXTENDED_LIMIT_INFORMATION info{}; - if (! QueryInformationJobObject(get(), JobObjectExtendedLimitInformation, &info, sizeof(info), - nullptr)) - return false; - info.BasicLimitInformation.LimitFlags |= JOB_OBJECT_LIMIT_ACTIVE_PROCESS; - info.BasicLimitInformation.ActiveProcessLimit = 1; - return SetInformationJobObject(get(), JobObjectExtendedLimitInformation, &info, sizeof(info)); - } - }; - // Platform operations stay separate from the shared memory-limit policy. - inline Execution::Bytes sampleMemory(HANDLE process) { - PROCESS_MEMORY_COUNTERS_EX info{}; - info.cb = sizeof(info); - if (! GetProcessMemoryInfo(process, reinterpret_cast(&info), sizeof(info))) - return -1; - // PeakPagefileUsage is the process lifetime peak of private committed memory. - return static_cast(info.PeakPagefileUsage); - } - - inline bool killAndReap(HANDLE process, HANDLE job) { - if (! TerminateJobObject(job, 1) && WaitForSingleObject(process, 0) != WAIT_OBJECT_0) - return false; - return WaitForSingleObject(process, 2000) == WAIT_OBJECT_0; - } -} // namespace Lemon::Windows -#endif diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 8b3c675f..2889d646 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -7,4 +7,3 @@ if(WIN32) add_subdirectory(windows-sandbox) add_subdirectory(sleep-inhibitor) endif() -add_subdirectory(memory-limiter) diff --git a/tests/memory-limiter/CMakeLists.txt b/tests/memory-limiter/CMakeLists.txt deleted file mode 100644 index 00f4f7dc..00000000 --- a/tests/memory-limiter/CMakeLists.txt +++ /dev/null @@ -1,6 +0,0 @@ -add_executable(memory-limiter-test main.cpp) -if(WIN32) - target_sources(memory-limiter-test PRIVATE windows_macros.cpp) - target_link_libraries(memory-limiter-test PRIVATE ${LEMON_QT_LIBNAME}::Core) -endif() -add_test(NAME memory-limiter COMMAND memory-limiter-test) diff --git a/tests/memory-limiter/main.cpp b/tests/memory-limiter/main.cpp deleted file mode 100644 index deda8d4a..00000000 --- a/tests/memory-limiter/main.cpp +++ /dev/null @@ -1,30 +0,0 @@ -#include -#include -#include -// Reproduce the Windows SDK function-like macro, including with a PCH. -#define max(a, b) windows_max_macro_must_not_expand(a, b) -#include "../../src/core/memorylimiter.h" -#undef max -#include -using namespace Lemon::Execution; -void check(bool value) { - if (! value) - std::abort(); -} -int main() { - Limiter limited(100); - check(! limited.observe(100)); - check(! limited.observe(20)); - check(limited.usage() == 100); - check(! limited.observe(-1) && limited.usage() == 100); - check(limited.observe(101)); - check(limited.observe(0) && limited.usage() == 101); - Limiter unlimited(-1); - check(unlimited.usage() == -1); - check(! unlimited.observe(1000)); - check(unlimited.usage() == 1000); - Bytes bytes; - check(memoryBytes(-1, bytes) && bytes == -1); - check(memoryBytes(4096, bytes) && bytes == 4294967296LL); - check(! memoryBytes(std::numeric_limits::max(), bytes)); -} diff --git a/tests/memory-limiter/windows_macros.cpp b/tests/memory-limiter/windows_macros.cpp deleted file mode 100644 index e9fd7311..00000000 --- a/tests/memory-limiter/windows_macros.cpp +++ /dev/null @@ -1,14 +0,0 @@ -// SPDX-License-Identifier: GPL-3.0-or-later -#include "../../src/core/windowsprocessutils.h" -#include -#include -#include -#include - -// Define after dependency headers so their macro cleanup cannot hide the regression. -#ifdef max -#undef max -#endif -#define max(a, b) windows_max_macro_must_not_expand(a, b) -#include "../../src/core/windowsmemory.h" -#undef max diff --git a/unix/memoryusage.h b/unix/memoryusage.h index 23913d07..8ad16b15 100644 --- a/unix/memoryusage.h +++ b/unix/memoryusage.h @@ -1,6 +1,6 @@ // SPDX-License-Identifier: GPL-3.0-or-later #pragma once -#include "../src/core/memorylimiter.h" +#include "../src/core/memoryunits.h" #include Lemon::Execution::Bytes sampleMemory(pid_t pid); bool applyMemoryLimit(Lemon::Execution::Bytes limit); diff --git a/unix/test/CMakeLists.txt b/unix/test/CMakeLists.txt index 4cceb9f7..d1b3ab15 100644 --- a/unix/test/CMakeLists.txt +++ b/unix/test/CMakeLists.txt @@ -38,6 +38,3 @@ add_test(NAME watcher_memory_policy COMMAND python3 scripts/memory.py) set_tests_properties(watcher_memory_policy PROPERTIES TIMEOUT 30) add_test(NAME watcher_memory_accuracy COMMAND python3 scripts/memory_accuracy.py) set_tests_properties(watcher_memory_accuracy PROPERTIES TIMEOUT 30) - -add_executable(memory-limiter-test ../../tests/memory-limiter/main.cpp) -add_test(NAME memory-limiter COMMAND memory-limiter-test) diff --git a/unix/watcher_linux.cpp b/unix/watcher_linux.cpp index d9ff908c..a4725dbf 100644 --- a/unix/watcher_linux.cpp +++ b/unix/watcher_linux.cpp @@ -1,5 +1,12 @@ -// SPDX-License-Identifier: GPL-3.0-or-later +/* + * SPDX-FileCopyrightText: 2011-2019 Project Lemon, Zhipeng Jia + * SPDX-FileCopyrightText: 2019-2023 Project LemonLime + * + * SPDX-License-Identifier: GPL-3.0-or-later + * + */ #include "memoryusage.h" +#include #include #include #include @@ -15,7 +22,7 @@ Bytes sampleMemory(pid_t pid) { while (fgets(line, sizeof(line), file)) { long long kib = 0; if (sscanf(line, "VmSize: %lld kB", &kib) == 1 || sscanf(line, "VmPeak: %lld kB", &kib) == 1) - result = std::max(result, Bytes(kib) * 1024); + result = std::max(result, Bytes(kib) * KiB); } fclose(file); return result; @@ -25,11 +32,11 @@ bool applyMemoryLimit(Bytes limit) { if (limit >= 0) { rlimit memory{static_cast(limit), static_cast(limit)}; if (setrlimit(RLIMIT_AS, &memory) != 0) - return false; + return false; } rlimit stack{}; if (getrlimit(RLIMIT_STACK, &stack) != 0) return false; stack.rlim_cur = std::min(stack.rlim_max, static_cast(limit < 0 ? 2147483647LL : limit)); return setrlimit(RLIMIT_STACK, &stack) == 0; -} + } diff --git a/unix/watcher_macos.mm b/unix/watcher_macos.mm index dc6246f3..0e25a798 100644 --- a/unix/watcher_macos.mm +++ b/unix/watcher_macos.mm @@ -1,4 +1,10 @@ -// SPDX-License-Identifier: GPL-3.0-or-later +/* + * SPDX-FileCopyrightText: 2011-2019 Project Lemon, Zhipeng Jia + * SPDX-FileCopyrightText: 2019-2023 Project LemonLime + * + * SPDX-License-Identifier: GPL-3.0-or-later + * + */ #include "memoryusage.h" #include #include @@ -8,6 +14,6 @@ Bytes sampleMemory(pid_t pid) { if (proc_pidinfo(pid, PROC_PIDTASKINFO, 0, &info, sizeof(info)) != sizeof(info)) return -1; return static_cast(info.pti_resident_size); -} + } // macOS intentionally has no memory prelimit. bool applyMemoryLimit(Bytes) { return true; } diff --git a/unix/watcher_unix.cpp b/unix/watcher_unix.cpp index 6ddfd414..30b982b6 100644 --- a/unix/watcher_unix.cpp +++ b/unix/watcher_unix.cpp @@ -1,5 +1,12 @@ -// SPDX-License-Identifier: GPL-3.0-or-later +/* + * SPDX-FileCopyrightText: 2011-2019 Project Lemon, Zhipeng Jia + * SPDX-FileCopyrightText: 2019-2023 Project LemonLime + * + * SPDX-License-Identifier: GPL-3.0-or-later + * + */ #include "memoryusage.h" +#include #include #include #include @@ -419,7 +426,7 @@ int main(int argc, char **argv) { close(errors[1]); (void)setpgid(pid, pid); UnixProcess process(pid, events); - Limiter limiter(limit); + Bytes peak = -1; bool ready = events.arm(std::max(2000LL, 3LL * timeLimit), true); if (! ready) perror("events arm"); @@ -441,20 +448,20 @@ int main(int argc, char **argv) { #else auto sample = event & Events::Sample ? sampleMemory(pid) : Bytes(-1); #endif - limiter.observe(sample); + peak = std::max(peak, sample); // The fixed-size read is bounded by the destination object on every iteration. /* Flawfinder: ignore */ if (read(errors[0], &childError, sizeof(childError)) == sizeof(childError)) setupFailed = true; int finished = process.poll(); #ifdef __linux__ - limiter.observe(process.peak); + peak = std::max(peak, process.peak); #endif if (setupFailed || finished < 0) { verdict = RS_FAIL; break; } - if (limiter.isExceeded()) { + if (limit >= 0 && peak > limit) { verdict = RS_MLE; break; } @@ -482,7 +489,7 @@ int main(int argc, char **argv) { perror("events wait"); verdict = RS_FAIL; break; - } + } } // Catch setup errors delivered concurrently with the final wait. // The final read uses the same destination-size bound. @@ -493,7 +500,7 @@ int main(int argc, char **argv) { if (! process.killAndReap()) fprintf(stderr, "Process reaping deadline exceeded\n"); #ifdef __linux__ - limiter.observe(process.peak); + peak = std::max(peak, process.peak); #endif if (setupFailed) { fprintf(stderr, "Child setup stage %d failed: errno %d\n", childError.stage, childError.error); @@ -502,10 +509,10 @@ int main(int argc, char **argv) { if (process.reaped) { #ifdef __APPLE__ // Only macOS defines DeclaredUsage as RSS. Linux must not use RSS as a VSS fallback. - limiter.observe(static_cast(process.usage.ru_maxrss)); + peak = std::max(peak, static_cast(process.usage.ru_maxrss)); #endif if (verdict == RS_AC) { - if (limiter.isExceeded()) + if (limit >= 0 && peak > limit) verdict = RS_MLE; else if (WIFSIGNALED(process.status)) verdict = WTERMSIG(process.status) == SIGXCPU ? RS_TLE : RS_RE; @@ -518,7 +525,7 @@ int main(int argc, char **argv) { : -1; if (verdict == RS_AC && elapsed > timeLimit) verdict = RS_TLE; - printf("%lld\n%lld\n", elapsed, static_cast(limiter.usage())); + printf("%lld\n%lld\n", elapsed, static_cast(peak)); return verdict; } catch (...) { printf("-1\n-1\n"); From ffaa181af39c15c9e3ac1078440033a404942441 Mon Sep 17 00:00:00 2001 From: "GitHub Action (clang-format)" Date: Sun, 8 Nov 2026 17:44:51 +0000 Subject: [PATCH 29/37] style: format codes --- unix/watcher_linux.cpp | 4 ++-- unix/watcher_unix.cpp | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/unix/watcher_linux.cpp b/unix/watcher_linux.cpp index a4725dbf..7779f7cb 100644 --- a/unix/watcher_linux.cpp +++ b/unix/watcher_linux.cpp @@ -32,11 +32,11 @@ bool applyMemoryLimit(Bytes limit) { if (limit >= 0) { rlimit memory{static_cast(limit), static_cast(limit)}; if (setrlimit(RLIMIT_AS, &memory) != 0) - return false; + return false; } rlimit stack{}; if (getrlimit(RLIMIT_STACK, &stack) != 0) return false; stack.rlim_cur = std::min(stack.rlim_max, static_cast(limit < 0 ? 2147483647LL : limit)); return setrlimit(RLIMIT_STACK, &stack) == 0; - } +} diff --git a/unix/watcher_unix.cpp b/unix/watcher_unix.cpp index 30b982b6..e6167c2c 100644 --- a/unix/watcher_unix.cpp +++ b/unix/watcher_unix.cpp @@ -489,7 +489,7 @@ int main(int argc, char **argv) { perror("events wait"); verdict = RS_FAIL; break; - } + } } // Catch setup errors delivered concurrently with the final wait. // The final read uses the same destination-size bound. From 29218695bcc9268e6a837cbdf82c1188c088c897 Mon Sep 17 00:00:00 2001 From: sgt57 <198590103+sgt57@users.noreply.github.com> Date: Mon, 9 Nov 2026 01:48:30 +0800 Subject: [PATCH 30/37] fix(process): wait for watcher exit after forced termination --- src/core/processrunner_unix.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/core/processrunner_unix.cpp b/src/core/processrunner_unix.cpp index 9aa6de44..7aa59733 100644 --- a/src/core/processrunner_unix.cpp +++ b/src/core/processrunner_unix.cpp @@ -191,9 +191,8 @@ ProcessRunnerResult UnixProcessRunner::run() { runner.terminate(); if (! runner.waitForFinished(2500)) { runner.kill(); - runner.waitForFinished(2000); + runner.waitForFinished(-1); } - return res; } } From 4ad15830afb343c48a534d095bd07eda44044f05 Mon Sep 17 00:00:00 2001 From: sgt57 <198590103+sgt57@users.noreply.github.com> Date: Mon, 9 Nov 2026 05:04:40 +0800 Subject: [PATCH 31/37] refactor: simplify code --- .github/workflows/windows-qt6.yml | 1 - src/core/processrunner_win.cpp | 53 +++++++++++--------------- src/core/windowssandbox.cpp | 1 - tests/windows-sandbox/helper.cpp | 12 ------ tests/windows-sandbox/main.cpp | 63 ++++++++++++++----------------- unix/watcher_linux.cpp | 1 - unix/watcher_macos.mm | 2 +- unix/watcher_unix.cpp | 63 +++++++++---------------------- 8 files changed, 71 insertions(+), 125 deletions(-) diff --git a/.github/workflows/windows-qt6.yml b/.github/workflows/windows-qt6.yml index 6308c411..3f0ff731 100644 --- a/.github/workflows/windows-qt6.yml +++ b/.github/workflows/windows-qt6.yml @@ -91,7 +91,6 @@ jobs: - name: Deploy Qt for tests shell: pwsh run: | - # This helper does not import Qt at runtime. Get-ChildItem tests -Recurse -Filter *.exe | Where-Object { $_.Name -ne 'sandbox-helper.exe' } | ForEach-Object { diff --git a/src/core/processrunner_win.cpp b/src/core/processrunner_win.cpp index 56789fdc..51efc55b 100644 --- a/src/core/processrunner_win.cpp +++ b/src/core/processrunner_win.cpp @@ -31,36 +31,29 @@ using namespace Lemon::Windows; namespace { - class ExecutionJob { - Handle handle{CreateJobObjectW(nullptr, nullptr)}; - - public: - HANDLE get() const { return handle.get(); } - bool apply(Lemon::Execution::Bytes limit) { - if (! handle) + bool configureJob(HANDLE job, Lemon::Execution::Bytes limit) { + if (! job) + return false; + JOBOBJECT_EXTENDED_LIMIT_INFORMATION info{}; + info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; + if (limit >= 0) { + if (static_cast(limit) > SIZE_MAX) { + SetLastError(ERROR_INVALID_PARAMETER); return false; - JOBOBJECT_EXTENDED_LIMIT_INFORMATION info{}; - info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; - if (limit >= 0) { - if (static_cast(limit) > SIZE_MAX) { - SetLastError(ERROR_INVALID_PARAMETER); - return false; - } - info.BasicLimitInformation.LimitFlags |= JOB_OBJECT_LIMIT_PROCESS_MEMORY; - info.ProcessMemoryLimit = static_cast(limit); } - return SetInformationJobObject(get(), JobObjectExtendedLimitInformation, &info, sizeof(info)); - } - bool restrictToOneProcess() { - JOBOBJECT_EXTENDED_LIMIT_INFORMATION info{}; - if (! QueryInformationJobObject(get(), JobObjectExtendedLimitInformation, &info, sizeof(info), - nullptr)) - return false; - info.BasicLimitInformation.LimitFlags |= JOB_OBJECT_LIMIT_ACTIVE_PROCESS; - info.BasicLimitInformation.ActiveProcessLimit = 1; - return SetInformationJobObject(get(), JobObjectExtendedLimitInformation, &info, sizeof(info)); + info.BasicLimitInformation.LimitFlags |= JOB_OBJECT_LIMIT_PROCESS_MEMORY; + info.ProcessMemoryLimit = static_cast(limit); } - }; + return SetInformationJobObject(job, JobObjectExtendedLimitInformation, &info, sizeof(info)); + } + bool restrictToOneProcess(HANDLE job) { + JOBOBJECT_EXTENDED_LIMIT_INFORMATION info{}; + if (! QueryInformationJobObject(job, JobObjectExtendedLimitInformation, &info, sizeof(info), nullptr)) + return false; + info.BasicLimitInformation.LimitFlags |= JOB_OBJECT_LIMIT_ACTIVE_PROCESS; + info.BasicLimitInformation.ActiveProcessLimit = 1; + return SetInformationJobObject(job, JobObjectExtendedLimitInformation, &info, sizeof(info)); + } Lemon::Execution::Bytes sampleMemory(HANDLE process) { PROCESS_MEMORY_COUNTERS_EX info{}; info.cb = sizeof(info); @@ -142,9 +135,9 @@ ProcessRunnerResult WinProcessRunner::run() { }); Lemon::Execution::Bytes memoryLimit; - ExecutionJob job; - if (! Lemon::Execution::memoryBytes(config.memoryLimit, memoryLimit) || ! job.apply(memoryLimit) || - (sandbox && ! job.restrictToOneProcess())) { + Handle job(CreateJobObjectW(nullptr, nullptr)); + if (! Lemon::Execution::memoryBytes(config.memoryLimit, memoryLimit) || + ! configureJob(job.get(), memoryLimit) || (sandbox && ! restrictToOneProcess(job.get()))) { res.result = CannotStartProgram; res.message = "Cannot configure memory prelimit"; return res; diff --git a/src/core/windowssandbox.cpp b/src/core/windowssandbox.cpp index 006ab3c1..73d50b7c 100644 --- a/src/core/windowssandbox.cpp +++ b/src/core/windowssandbox.cpp @@ -248,7 +248,6 @@ struct WindowsSandbox::Data { session(config.sandboxSession ? config.sandboxSession : WindowsSandbox::createSession()) {} ~Data() { - if (! workingDirectory.isEmpty()) { QMutexLocker lock(&permissionsMutex); revokeSid(workingDirectory, packageSid, true); diff --git a/tests/windows-sandbox/helper.cpp b/tests/windows-sandbox/helper.cpp index 1cd96f80..74889c3e 100644 --- a/tests/windows-sandbox/helper.cpp +++ b/tests/windows-sandbox/helper.cpp @@ -364,17 +364,5 @@ int wmain(int argc, wchar_t **argv) { CloseHandle(mapping); return measured ? 0 : 42; } - if (mode == L"memory") { - for (int i = 0; i < 256; ++i) { - auto *memory = static_cast( - VirtualAlloc(nullptr, 1024 * 1024, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE)); - if (! memory) { - return 12; - } - for (int j = 0; j < 1024 * 1024; j += 4096) - memory[j] = 1; - } - return 13; - } return 14; } diff --git a/tests/windows-sandbox/main.cpp b/tests/windows-sandbox/main.cpp index 91b30afd..10d62f3a 100644 --- a/tests/windows-sandbox/main.cpp +++ b/tests/windows-sandbox/main.cpp @@ -100,7 +100,7 @@ class WindowsSandboxTests : public QObject { return file.open(QIODevice::WriteOnly) && file.write(bytes) == bytes.size(); } - static QByteArray readFile(const QString &path) { + static QByteArray read(const QString &path) { QFile file(path); if (! file.open(QIODevice::ReadOnly)) return {}; @@ -215,7 +215,7 @@ class WindowsSandboxTests : public QObject { const auto result = run(cfg); QVERIFY2(result.result == CorrectAnswer, qPrintable(result.message)); - QCOMPARE(readFile(cfg.workingDirectory + "_tmpout").trimmed(), QByteArray("host")); + QCOMPARE(read(cfg.workingDirectory + "_tmpout").trimmed(), QByteArray("host")); QCOMPARE(result.preparationTime, 0); QCOMPARE(result.runtimeAclUpdates, 0); QVERIFY(! cfg.sandboxSession); @@ -230,7 +230,7 @@ class WindowsSandboxTests : public QObject { const auto result = run(cfg); QVERIFY2(result.result == CorrectAnswer, qPrintable(result.message)); - QCOMPARE(readFile(cfg.workingDirectory + "_tmpout").trimmed(), QByteArray("42")); + QCOMPARE(read(cfg.workingDirectory + "_tmpout").trimmed(), QByteArray("42")); QVERIFY(result.memoryUsed > 0); } @@ -317,8 +317,7 @@ class WindowsSandboxTests : public QObject { const QDir workingDirectory(error.mid(prefix.size())); QVERIFY(workingDirectory.exists("program.dummy")); QVERIFY(! workingDirectory.exists("created")); - QCOMPARE(readFile(workingDirectory.filePath("../_2.0/created/nested/data.txt")), - QByteArray("created")); + QCOMPARE(read(workingDirectory.filePath("../_2.0/created/nested/data.txt")), QByteArray("created")); } void commandLineArguments_data() { @@ -346,7 +345,7 @@ class WindowsSandboxTests : public QObject { const auto result = run(cfg); QVERIFY2(result.result == CorrectAnswer, qPrintable(result.message)); - QCOMPARE(readFile(cfg.workingDirectory + "_tmpout").replace("\r\n", "\n"), + QCOMPARE(read(cfg.workingDirectory + "_tmpout").replace("\r\n", "\n"), arguments.join('\n').toUtf8() + '\n'); } @@ -420,7 +419,7 @@ class WindowsSandboxTests : public QObject { const auto result = run(cfg); QVERIFY2(result.result == CorrectAnswer, qPrintable(result.message)); const auto output = cfg.standardOutputCheck ? QString("_tmpout") : cfg.outputFileName; - QCOMPARE(readFile(cfg.workingDirectory + output).trimmed(), QByteArray("42")); + QCOMPARE(read(cfg.workingDirectory + output).trimmed(), QByteArray("42")); } void isolationAndHandles() { @@ -433,7 +432,7 @@ class WindowsSandboxTests : public QObject { const auto result = run(cfg); QVERIFY2(result.result == CorrectAnswer, qPrintable(result.message)); - QCOMPARE(readFile(cfg.workingDirectory + "_tmpout").trimmed(), QByteArray("isolated")); + QCOMPARE(read(cfg.workingDirectory + "_tmpout").trimmed(), QByteArray("isolated")); QVERIFY(QFileInfo::exists(cfg.workingDirectory + "own.txt")); } @@ -529,7 +528,7 @@ class WindowsSandboxTests : public QObject { QVERIFY2(result.result == CorrectAnswer, qPrintable(result.message)); for (int i = 0; i < existing.size(); ++i) QCOMPARE(permissions(existing[i]), before[i]); - QCOMPARE(readFile(cfg.workingDirectory + "created/nested/data.txt"), QByteArray("created")); + QCOMPARE(read(cfg.workingDirectory + "created/nested/data.txt"), QByteArray("created")); for (const auto &name : {"created", "created/nested", "created/nested/data.txt", "_tmpout", "_tmperr"}) { const auto acl = permissions(cfg.workingDirectory + name); @@ -561,7 +560,7 @@ class WindowsSandboxTests : public QObject { QVERIFY2(result.result == CorrectAnswer, qPrintable(result.message)); QVERIFY(result.runtimeCacheHit); QCOMPARE(result.runtimeAclUpdates, 0); - QCOMPARE(readFile(second.workingDirectory + "_tmpout").trimmed(), QByteArray("readonly")); + QCOMPARE(read(second.workingDirectory + "_tmpout").trimmed(), QByteArray("readonly")); two.reset(); first.sandboxSession.reset(); second.sandboxSession.reset(); @@ -723,7 +722,7 @@ class WindowsSandboxTests : public QObject { const auto result = run(cfg); QVERIFY2(result.result == CorrectAnswer, qPrintable(result.message)); - QVERIFY(readFile(cfg.workingDirectory + "_tmpout").startsWith("child-denied=")); + QVERIFY(read(cfg.workingDirectory + "_tmpout").startsWith("child-denied=")); } void primaryProcessAccounting_data() { @@ -743,7 +742,7 @@ class WindowsSandboxTests : public QObject { timer.start(); while (! primary && timer.elapsed() < 5000) { const auto match = QRegularExpression("process=(\\d+)") - .match(QString::fromUtf8(readFile(cfg.workingDirectory + "_tmpout"))); + .match(QString::fromUtf8(read(cfg.workingDirectory + "_tmpout"))); if (match.hasMatch()) { primary.reset(OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ | SYNCHRONIZE, FALSE, match.captured(1).toULong())); @@ -784,7 +783,7 @@ class WindowsSandboxTests : public QObject { cfg.sandboxSettings.enabled = enabled; auto result = run(cfg); QVERIFY2(result.result == CorrectAnswer, qPrintable(result.message)); - const auto output = QString::fromUtf8(readFile(cfg.workingDirectory + "_tmpout")); + const auto output = QString::fromUtf8(read(cfg.workingDirectory + "_tmpout")); const auto match = QRegularExpression("reference-bytes=(\\d+) allocation-bytes=(\\d+)").match(output); QVERIFY2(match.hasMatch(), qPrintable(output)); const qint64 reference = match.captured(1).toLongLong(); @@ -806,7 +805,7 @@ class WindowsSandboxTests : public QObject { auto result = run(cfg); QVERIFY2(result.result == CorrectAnswer, qPrintable(result.message)); QVERIFY(result.memoryUsed > 0 && result.memoryUsed <= 32ll * 1024 * 1024); - auto output = QString::fromUtf8(readFile(cfg.workingDirectory + "_tmpout")); + auto output = QString::fromUtf8(read(cfg.workingDirectory + "_tmpout")); auto match = QRegularExpression("working-set-peak=(\\d+)").match(output); QVERIFY(match.hasMatch()); QVERIFY(match.captured(1).toLongLong() > 32ll * 1024 * 1024); @@ -823,7 +822,7 @@ class WindowsSandboxTests : public QObject { QCOMPARE(result.result, QString(mode) == "commit-rejected" ? RunTimeError : CorrectAnswer); QVERIFY(result.memoryUsed > 0); QVERIFY(result.memoryUsed <= 32ll * 1024 * 1024); - QVERIFY(readFile(cfg.workingDirectory + "_tmpout").contains("expected")); + QVERIFY(read(cfg.workingDirectory + "_tmpout").contains("expected")); } } @@ -844,10 +843,6 @@ class WindowsSandboxTests : public QObject { auto cpu = config("burn 3000"); cpu.timeLimit = 100; QCOMPARE(run(cpu).result, TimeLimitExceeded); - auto memory = config("commit-rejected"); - memory.memoryLimit = 24; - // The Job refuses the next commit; helper exits nonzero without exceeding the limit. - QCOMPARE(run(memory).result, RunTimeError); } void cancellation() { @@ -868,7 +863,7 @@ class WindowsSandboxTests : public QObject { timer.start(); while (! primary && timer.elapsed() < 5000) { const auto match = QRegularExpression("process=(\\d+)") - .match(QString::fromUtf8(readFile(cfg.workingDirectory + "_tmpout"))); + .match(QString::fromUtf8(read(cfg.workingDirectory + "_tmpout"))); if (match.hasMatch()) primary.reset(OpenProcess(SYNCHRONIZE, FALSE, match.captured(1).toULong())); if (! primary) @@ -896,7 +891,7 @@ class WindowsSandboxTests : public QObject { cfg.inputFile = directory + "/input.txt"; cfg.sandboxSettings.readOnlyDirectories = {directory}; QCOMPARE(run(cfg).result, CorrectAnswer); - QCOMPARE(readFile(cfg.workingDirectory + "_tmpout").trimmed(), QByteArray("42")); + QCOMPARE(read(cfg.workingDirectory + "_tmpout").trimmed(), QByteArray("42")); } void rejectHardLinkedWorkFile() { @@ -908,7 +903,7 @@ class WindowsSandboxTests : public QObject { const auto result = run(cfg); QCOMPARE(result.result, CannotStartProgram); - QCOMPARE(readFile(target), QByteArray("secret answer\n")); + QCOMPARE(read(target), QByteArray("secret answer\n")); QCOMPARE(permissions(cfg.workingDirectory), beforeDirectory); QCOMPARE(permissions(cfg.executableFile), beforeExecutable); } @@ -935,7 +930,7 @@ class WindowsSandboxTests : public QObject { QElapsedTimer timer; timer.start(); while (! probeId && timer.elapsed() < 5000) { - probeId = readFile(marker).trimmed().toULong(); + probeId = read(marker).trimmed().toULong(); if (! probeId) QThread::msleep(10); } @@ -968,8 +963,8 @@ class WindowsSandboxTests : public QObject { worker.join(); QVERIFY2(one.result == CorrectAnswer, qPrintable(one.message)); QVERIFY2(two.result == CorrectAnswer, qPrintable(two.message)); - QCOMPARE(readFile(first.workingDirectory + "_tmpout").trimmed(), QByteArray("isolated")); - QCOMPARE(readFile(second.workingDirectory + "_tmpout").trimmed(), QByteArray("isolated")); + QCOMPARE(read(first.workingDirectory + "_tmpout").trimmed(), QByteArray("isolated")); + QCOMPARE(read(second.workingDirectory + "_tmpout").trimmed(), QByteArray("isolated")); } void nativeCompiler_data() { @@ -1001,7 +996,7 @@ class WindowsSandboxTests : public QObject { const auto result = run(cfg); QVERIFY2(result.result == CorrectAnswer, qPrintable(result.message)); - QCOMPARE(readFile(cfg.workingDirectory + "_tmpout").trimmed(), QByteArray("42")); + QCOMPARE(read(cfg.workingDirectory + "_tmpout").trimmed(), QByteArray("42")); } void settingsRoundTrip() { @@ -1047,7 +1042,7 @@ class WindowsSandboxTests : public QObject { const auto first = run(cfg); QVERIFY2(first.result == CorrectAnswer, qPrintable(first.message)); - QCOMPARE(readFile(cfg.workingDirectory + "_tmpout"), QByteArray("42 \xe9")); + QCOMPARE(read(cfg.workingDirectory + "_tmpout"), QByteArray("42 \xe9")); const auto second = run(cfg); QVERIFY2(second.result == CorrectAnswer, qPrintable(second.message)); @@ -1077,12 +1072,12 @@ class WindowsSandboxTests : public QObject { const auto ordinary = run(cfg); QVERIFY2(ordinary.result == CorrectAnswer, qPrintable(ordinary.message)); - QCOMPARE(readFile(cfg.workingDirectory + "_tmpout").trimmed(), QByteArray("allowed")); + QCOMPARE(read(cfg.workingDirectory + "_tmpout").trimmed(), QByteArray("allowed")); cfg.sandboxSettings.enabled = true; const auto restricted = run(cfg); QVERIFY2(restricted.result == CorrectAnswer, qPrintable(restricted.message)); - QCOMPARE(readFile(cfg.workingDirectory + "_tmpout").trimmed(), QByteArray("denied")); + QCOMPARE(read(cfg.workingDirectory + "_tmpout").trimmed(), QByteArray("denied")); } void pythonVenv() { @@ -1102,14 +1097,14 @@ class WindowsSandboxTests : public QObject { const auto ordinary = run(cfg); QVERIFY2(ordinary.result == CorrectAnswer, qPrintable(ordinary.message)); - QCOMPARE(readFile(cfg.workingDirectory + "_tmpout").trimmed(), QByteArray("42")); + QCOMPARE(read(cfg.workingDirectory + "_tmpout").trimmed(), QByteArray("42")); cfg.sandboxSettings.enabled = true; const auto restricted = run(cfg); QCOMPARE(restricted.result, RunTimeError); QVERIFY2(restricted.message.contains("Unable to create process", Qt::CaseInsensitive), qPrintable(restricted.message)); - QVERIFY(readFile(cfg.workingDirectory + "_tmpout").isEmpty()); + QVERIFY(read(cfg.workingDirectory + "_tmpout").isEmpty()); } void javaRuntime() { @@ -1131,7 +1126,7 @@ class WindowsSandboxTests : public QObject { const auto first = run(cfg); QVERIFY2(first.result == CorrectAnswer, qPrintable(first.message)); - QCOMPARE(readFile(cfg.workingDirectory + "_tmpout").trimmed(), QByteArray("42")); + QCOMPARE(read(cfg.workingDirectory + "_tmpout").trimmed(), QByteArray("42")); const auto second = run(cfg); QVERIFY2(second.result == CorrectAnswer, qPrintable(second.message)); @@ -1162,12 +1157,12 @@ class WindowsSandboxTests : public QObject { const auto ordinary = run(cfg); QVERIFY2(ordinary.result == CorrectAnswer, qPrintable(ordinary.message)); - QCOMPARE(readFile(cfg.workingDirectory + "_tmpout").trimmed(), QByteArray("allowed")); + QCOMPARE(read(cfg.workingDirectory + "_tmpout").trimmed(), QByteArray("allowed")); cfg.sandboxSettings.enabled = true; const auto restricted = run(cfg); QVERIFY2(restricted.result == CorrectAnswer, qPrintable(restricted.message)); - QCOMPARE(readFile(cfg.workingDirectory + "_tmpout").trimmed(), QByteArray("denied")); + QCOMPARE(read(cfg.workingDirectory + "_tmpout").trimmed(), QByteArray("denied")); } }; diff --git a/unix/watcher_linux.cpp b/unix/watcher_linux.cpp index 7779f7cb..2105d8bd 100644 --- a/unix/watcher_linux.cpp +++ b/unix/watcher_linux.cpp @@ -8,7 +8,6 @@ #include "memoryusage.h" #include #include -#include #include #include using namespace Lemon::Execution; diff --git a/unix/watcher_macos.mm b/unix/watcher_macos.mm index 0e25a798..11da2a4b 100644 --- a/unix/watcher_macos.mm +++ b/unix/watcher_macos.mm @@ -14,6 +14,6 @@ Bytes sampleMemory(pid_t pid) { if (proc_pidinfo(pid, PROC_PIDTASKINFO, 0, &info, sizeof(info)) != sizeof(info)) return -1; return static_cast(info.pti_resident_size); - } +} // macOS intentionally has no memory prelimit. bool applyMemoryLimit(Bytes) { return true; } diff --git a/unix/watcher_unix.cpp b/unix/watcher_unix.cpp index e6167c2c..6fd54d43 100644 --- a/unix/watcher_unix.cpp +++ b/unix/watcher_unix.cpp @@ -174,17 +174,16 @@ namespace { traced.insert(pid); #endif } - ~UnixProcess() { - if (! cleaned) - killAndReap(); - } - // Do not destroy the exit information until all final samples are consumed. - int poll() { - if (reaped + ~UnixProcess() { killAndReap(); } + bool finished() const { #ifdef __linux__ - && traced.empty() + return reaped && traced.empty(); +#else + return reaped; #endif - ) + } + int poll() { + if (finished()) return 1; #ifdef __linux__ for (;;) { @@ -278,7 +277,7 @@ namespace { ++it; } if (! progress) - return reaped && traced.empty() ? 1 : 0; + return finished() ? 1 : 0; } #else pid_t result = wait4(pid, &status, WNOHANG, &usage); @@ -293,20 +292,12 @@ namespace { } bool killAndReap() { if (cleaned) - return reaped -#ifdef __linux__ - && traced.empty() -#endif - ; + return finished(); cleaned = true; kill(-pid, SIGKILL); if (! reaped) kill(pid, SIGKILL); - if (reaped -#ifdef __linux__ - && traced.empty() -#endif - ) + if (finished()) return true; if (! events.arm(2000, false)) { perror("reaping events"); @@ -315,11 +306,7 @@ namespace { for (;;) { if (poll() < 0) return false; - if (reaped -#ifdef __linux__ - && traced.empty() -#endif - ) + if (finished()) break; int event = events.wait(); if (event < 0) { @@ -332,11 +319,7 @@ namespace { break; } } - return reaped -#ifdef __linux__ - && traced.empty() -#endif - ; + return finished(); } }; struct ChildError { @@ -426,14 +409,15 @@ int main(int argc, char **argv) { close(errors[1]); (void)setpgid(pid, pid); UnixProcess process(pid, events); - Bytes peak = -1; + Bytes &peak = process.peak; bool ready = events.arm(std::max(2000LL, 3LL * timeLimit), true); if (! ready) perror("events arm"); - int event = Events::Sample; + int event = 0; int verdict = RS_AC; #ifdef __APPLE__ + event = Events::Sample; int missing = 0; #endif ChildError childError{}; @@ -443,20 +427,14 @@ int main(int argc, char **argv) { verdict = RS_FAIL; break; } -#ifdef __linux__ - auto sample = Bytes(-1); -#else +#ifdef __APPLE__ auto sample = event & Events::Sample ? sampleMemory(pid) : Bytes(-1); -#endif peak = std::max(peak, sample); - // The fixed-size read is bounded by the destination object on every iteration. +#endif /* Flawfinder: ignore */ if (read(errors[0], &childError, sizeof(childError)) == sizeof(childError)) setupFailed = true; int finished = process.poll(); -#ifdef __linux__ - peak = std::max(peak, process.peak); -#endif if (setupFailed || finished < 0) { verdict = RS_FAIL; break; @@ -492,23 +470,18 @@ int main(int argc, char **argv) { } } // Catch setup errors delivered concurrently with the final wait. - // The final read uses the same destination-size bound. /* Flawfinder: ignore */ if (read(errors[0], &childError, sizeof(childError)) == sizeof(childError)) setupFailed = true; close(errors[0]); if (! process.killAndReap()) fprintf(stderr, "Process reaping deadline exceeded\n"); -#ifdef __linux__ - peak = std::max(peak, process.peak); -#endif if (setupFailed) { fprintf(stderr, "Child setup stage %d failed: errno %d\n", childError.stage, childError.error); verdict = RS_FAIL; } if (process.reaped) { #ifdef __APPLE__ - // Only macOS defines DeclaredUsage as RSS. Linux must not use RSS as a VSS fallback. peak = std::max(peak, static_cast(process.usage.ru_maxrss)); #endif if (verdict == RS_AC) { From 584b7b2288438039f30a5c0b3abe5d5d212d969e Mon Sep 17 00:00:00 2001 From: sgt57 <198590103+sgt57@users.noreply.github.com> Date: Mon, 9 Nov 2026 05:26:28 +0800 Subject: [PATCH 32/37] fix(ci): update macos ci target to 11.0 --- .github/workflows/macos-qt6.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/macos-qt6.yml b/.github/workflows/macos-qt6.yml index a871f90c..8e7ed49f 100644 --- a/.github/workflows/macos-qt6.yml +++ b/.github/workflows/macos-qt6.yml @@ -53,8 +53,8 @@ jobs: -DCMAKE_BUILD_TYPE=${{ matrix.build_type }} \ -DLEMON_BUILD_INFO="Build for macOS" \ -DLEMON_BUILD_EXTRA_INFO="Build on $(uname -sr)" \ - -DCMAKE_OSX_DEPLOYMENT_TARGET=10.15 \ - -DCMAKE_OSX_ARCHITECTURES="${{ matrix.arch }}" + -DCMAKE_OSX_DEPLOYMENT_TARGET=11.0 \ + -DCMAKE_OSX_ARCHITECTURES="${{ matrix.arch }}" cmake --build . --parallel $(sysctl -n hw.logicalcpu) - name: Run tests run: | From ab0137a26f983666e242e84cee6bf47dcbe9231f Mon Sep 17 00:00:00 2001 From: sgt57 <198590103+sgt57@users.noreply.github.com> Date: Mon, 9 Nov 2026 22:20:56 +0800 Subject: [PATCH 33/37] fix(windows): reap suspended processes outside the job --- src/core/processrunner_win.cpp | 7 ++- tests/windows-sandbox/main.cpp | 111 ++++++++++++++++++++++++++++++--- 2 files changed, 109 insertions(+), 9 deletions(-) diff --git a/src/core/processrunner_win.cpp b/src/core/processrunner_win.cpp index 51efc55b..bd1d7e79 100644 --- a/src/core/processrunner_win.cpp +++ b/src/core/processrunner_win.cpp @@ -64,8 +64,13 @@ namespace { } bool killAndReap(HANDLE process, HANDLE job) { - if (! TerminateJobObject(job, 1) && WaitForSingleObject(process, 0) != WAIT_OBJECT_0) + TerminateJobObject(job, 1); + const DWORD state = WaitForSingleObject(process, 0); + if (state == WAIT_OBJECT_0) + return true; + if (state != WAIT_TIMEOUT) return false; + TerminateProcess(process, 1); return WaitForSingleObject(process, 2000) == WAIT_OBJECT_0; } } // namespace diff --git a/tests/windows-sandbox/main.cpp b/tests/windows-sandbox/main.cpp index 10d62f3a..5d135b9f 100644 --- a/tests/windows-sandbox/main.cpp +++ b/tests/windows-sandbox/main.cpp @@ -18,6 +18,7 @@ #include "spdlog/sinks/stdout_color_sinks.h" #include #include +#include #include #include @@ -85,6 +86,52 @@ namespace { : UNPROTECTED_DACL_SECURITY_INFORMATION), nullptr, nullptr, acl, nullptr) == ERROR_SUCCESS; } + bool noLiveCaseProcess(const QString &executable, QString &error) { + Handle snapshot(CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)); + if (snapshot.get() == INVALID_HANDLE_VALUE) { + error = "Cannot enumerate testcase processes"; + return false; + } + const auto expected = QDir::cleanPath(QDir::fromNativeSeparators(executable)); + PROCESSENTRY32W entry{}; + entry.dwSize = sizeof(entry); + BOOL found = Process32FirstW(snapshot.get(), &entry); + while (found) { + if (entry.th32ParentProcessID == GetCurrentProcessId() && + QString::fromWCharArray(entry.szExeFile).compare(QFileInfo(executable).fileName(), + Qt::CaseInsensitive) == 0) { + Handle process(OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION | SYNCHRONIZE | + PROCESS_TERMINATE, FALSE, entry.th32ProcessID)); + if (! process) { + if (GetLastError() != ERROR_INVALID_PARAMETER) + error = "Cannot open candidate testcase process"; + } else { + wchar_t image[32768]; + DWORD size = DWORD(std::size(image)); + if (! QueryFullProcessImageNameW(process.get(), 0, image, &size)) { + if (GetLastError() != ERROR_INVALID_PARAMETER) + error = "Cannot query candidate testcase process"; + } else if (QDir::cleanPath(QDir::fromNativeSeparators( + QString::fromWCharArray(image, size))).compare(expected, Qt::CaseInsensitive) == 0) { + const DWORD state = WaitForSingleObject(process.get(), 0); + if (state == WAIT_TIMEOUT) { + error = QString("Live testcase process %1").arg(entry.th32ProcessID); + TerminateProcess(process.get(), 1); + if (WaitForSingleObject(process.get(), 2000) != WAIT_OBJECT_0) + error += " (reaping failed)"; + } else if (state != WAIT_OBJECT_0) { + error = "Cannot wait for candidate testcase process"; + } + } + } + } + found = Process32NextW(snapshot.get(), &entry); + } + if (GetLastError() != ERROR_NO_MORE_FILES) + error = "Testcase process enumeration failed"; + return error.isEmpty(); + } + } // namespace class WindowsSandboxTests : public QObject { @@ -845,9 +892,49 @@ class WindowsSandboxTests : public QObject { QCOMPARE(run(cpu).result, TimeLimitExceeded); } - void cancellation() { + void preStartCancellation_data() { + QTest::addColumn("stop"); + QTest::newRow("ordinary-future") << false; + QTest::newRow("ordinary-stop") << true; + } + + void preStartCancellation() { + QFETCH(bool, stop); auto cfg = config("burn 10000"); - const auto directory = root.path() + "/cancellation-runtime"; + cfg.sandboxSettings.enabled = false; + QPromise promise; + promise.start(); + std::stop_source source; + if (stop) { + cfg.stopToken = source.get_token(); + source.request_stop(); + } else { + promise.future().cancel(); + } + const auto result = ProcessRunner::create(cfg, promise.future())->run(); + QString error; + const bool reaped = noLiveCaseProcess(cfg.executableFile, error); + QVERIFY2(reaped, qPrintable(error)); + QCOMPARE(result.result, CorrectAnswer); + QVERIFY(result.message.isEmpty()); + QCOMPARE(result.timeUsed, -1); + QVERIFY(read(cfg.workingDirectory + "_tmpout").isEmpty()); + } + + void cancellation_data() { + QTest::addColumn("sandbox"); + QTest::addColumn("tree"); + QTest::newRow("ordinary-primary") << false << false; + QTest::newRow("sandbox-primary") << true << false; + QTest::newRow("ordinary-tree") << false << true; + } + + void cancellation() { + QFETCH(bool, sandbox); + QFETCH(bool, tree); + auto cfg = config(tree ? "spawn 10000" : "burn 10000"); + cfg.sandboxSettings.enabled = sandbox; + const auto directory = root.path() + QString("/cancellation-runtime-%1").arg(sequence); QVERIFY(QDir().mkpath(directory)); const auto resource = directory + "/resource.txt"; QVERIFY(write(resource, "runtime resource")); @@ -855,18 +942,22 @@ class WindowsSandboxTests : public QObject { const auto beforeRuntime = permissions(resource); QPromise promise; promise.start(); - Handle primary; + Handle primary, child; std::stop_source stopSource; cfg.stopToken = stopSource.get_token(); std::thread cancel([&] { QElapsedTimer timer; timer.start(); - while (! primary && timer.elapsed() < 5000) { - const auto match = QRegularExpression("process=(\\d+)") + while ((! primary || (tree && ! child)) && timer.elapsed() < 5000) { + const auto match = QRegularExpression(tree ? "parent=(\\d+) child=(\\d+)" : "process=(\\d+)") .match(QString::fromUtf8(read(cfg.workingDirectory + "_tmpout"))); - if (match.hasMatch()) - primary.reset(OpenProcess(SYNCHRONIZE, FALSE, match.captured(1).toULong())); - if (! primary) + if (match.hasMatch()) { + if (! primary) + primary.reset(OpenProcess(SYNCHRONIZE, FALSE, match.captured(1).toULong())); + if (tree && ! child) + child.reset(OpenProcess(SYNCHRONIZE, FALSE, match.captured(2).toULong())); + } + if (! primary || (tree && ! child)) QThread::msleep(10); } promise.future().cancel(); @@ -876,6 +967,10 @@ class WindowsSandboxTests : public QObject { cancel.join(); QVERIFY(bool(primary)); QCOMPARE(WaitForSingleObject(primary.get(), 0), DWORD(WAIT_OBJECT_0)); + if (tree) { + QVERIFY(bool(child)); + QCOMPARE(WaitForSingleObject(child.get(), 2000), DWORD(WAIT_OBJECT_0)); + } QCOMPARE(permissions(resource), beforeRuntime); QVERIFY(! permissions(cfg.workingDirectory).contains("S-1-15-2-")); QCOMPARE(result.result, CorrectAnswer); From b1837f1fe5c419ac203031f997c9c5c34edbd9d6 Mon Sep 17 00:00:00 2001 From: sgt57 <198590103+sgt57@users.noreply.github.com> Date: Mon, 9 Nov 2026 22:23:23 +0800 Subject: [PATCH 34/37] fix(windows): enforce memory limit before resuming the process --- .github/workflows/windows-qt6.yml | 2 +- src/core/processrunner_win.cpp | 11 ++++++++ tests/windows-sandbox/CMakeLists.txt | 28 +++++++++++--------- tests/windows-sandbox/helper.cpp | 14 ++++++++++ tests/windows-sandbox/main.cpp | 39 ++++++++++++++++++++++++++-- 5 files changed, 79 insertions(+), 15 deletions(-) diff --git a/.github/workflows/windows-qt6.yml b/.github/workflows/windows-qt6.yml index 3f0ff731..e79f67af 100644 --- a/.github/workflows/windows-qt6.yml +++ b/.github/workflows/windows-qt6.yml @@ -92,7 +92,7 @@ jobs: shell: pwsh run: | Get-ChildItem tests -Recurse -Filter *.exe | - Where-Object { $_.Name -ne 'sandbox-helper.exe' } | + Where-Object { $_.Name -notin @('sandbox-helper.exe', 'sandbox-static-memory-helper.exe') } | ForEach-Object { windeployqt $_.FullName if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } diff --git a/src/core/processrunner_win.cpp b/src/core/processrunner_win.cpp index bd1d7e79..d999030d 100644 --- a/src/core/processrunner_win.cpp +++ b/src/core/processrunner_win.cpp @@ -188,6 +188,17 @@ ProcessRunnerResult WinProcessRunner::run() { }); if (config.stopToken.stop_requested() || cancellation.isCanceled()) return res; + const auto initialMemory = sampleMemory(pi.hProcess); + if (initialMemory < 0) { + res.result = CannotStartProgram; + res.message = "Process statistics unavailable"; + return res; + } + res.memoryUsed = initialMemory; + if (memoryLimit >= 0 && initialMemory > memoryLimit) { + res.result = MemoryLimitExceeded; + return res; + } if ((! sandbox && ! AssignProcessToJobObject(job.get(), pi.hProcess)) || ResumeThread(pi.hThread) == DWORD(-1)) { TerminateProcess(pi.hProcess, 1); diff --git a/tests/windows-sandbox/CMakeLists.txt b/tests/windows-sandbox/CMakeLists.txt index a3fecb2a..243e322d 100644 --- a/tests/windows-sandbox/CMakeLists.txt +++ b/tests/windows-sandbox/CMakeLists.txt @@ -1,21 +1,25 @@ add_executable(sandbox-helper helper.cpp) -target_compile_definitions(sandbox-helper PRIVATE WIN32_LEAN_AND_MEAN) -set_target_properties(sandbox-helper PROPERTIES AUTOMOC OFF AUTOUIC OFF AUTORCC OFF) -if(MSVC) - set_property(TARGET sandbox-helper PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") -endif() -if(MINGW) - target_link_options(sandbox-helper PRIVATE -municode -static) - if(CMAKE_CXX_COMPILER_ID MATCHES "Clang") - target_compile_options(sandbox-helper PRIVATE -fms-extensions) +add_executable(sandbox-static-memory-helper helper.cpp) +target_compile_definitions(sandbox-static-memory-helper PRIVATE LEMON_TEST_STATIC_MEMORY) +foreach(helper IN ITEMS sandbox-helper sandbox-static-memory-helper) + target_compile_definitions(${helper} PRIVATE WIN32_LEAN_AND_MEAN) + set_target_properties(${helper} PROPERTIES AUTOMOC OFF AUTOUIC OFF AUTORCC OFF) + if(MSVC) + set_property(TARGET ${helper} PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") endif() -endif() -target_link_libraries(sandbox-helper PRIVATE advapi32 ws2_32 psapi) + if(MINGW) + target_link_options(${helper} PRIVATE -municode -static) + if(CMAKE_CXX_COMPILER_ID MATCHES "Clang") + target_compile_options(${helper} PRIVATE -fms-extensions) + endif() + endif() + target_link_libraries(${helper} PRIVATE advapi32 ws2_32 psapi) +endforeach() add_executable(windows-sandbox-tests main.cpp) target_compile_definitions(windows-sandbox-tests PRIVATE WIN32_LEAN_AND_MEAN) target_include_directories(windows-sandbox-tests PRIVATE ${CMAKE_SOURCE_DIR}/src ${spdlog_DIR}/include) target_link_libraries(windows-sandbox-tests PRIVATE lemon-core SingleApplication::SingleApplication ${LEMON_QT_LIBNAME}::Test spdlog::spdlog ws2_32) -add_dependencies(windows-sandbox-tests sandbox-helper) +add_dependencies(windows-sandbox-tests sandbox-helper sandbox-static-memory-helper) add_test(NAME windows-sandbox COMMAND windows-sandbox-tests -o sandbox-results.txt,txt -o -,txt) set_tests_properties(windows-sandbox PROPERTIES WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} TIMEOUT 180) diff --git a/tests/windows-sandbox/helper.cpp b/tests/windows-sandbox/helper.cpp index 74889c3e..ea7d395c 100644 --- a/tests/windows-sandbox/helper.cpp +++ b/tests/windows-sandbox/helper.cpp @@ -13,6 +13,10 @@ // psapi.h requires Windows types to be declared first. #include +#ifdef LEMON_TEST_STATIC_MEMORY +static volatile unsigned char staticMemory[64 * 1024 * 1024]; +#endif + static bool readsSecret(HANDLE handle) { #if defined(_MSC_VER) || defined(__clang__) __try { @@ -48,6 +52,16 @@ int wmain(int argc, wchar_t **argv) { if (argc < 2) return 1; const std::wstring mode = argv[1]; +#ifdef LEMON_TEST_STATIC_MEMORY + if (mode == L"static-memory") { + staticMemory[0] = 1; + staticMemory[sizeof(staticMemory) - 1] = 2; + if (staticMemory[0] != 1 || staticMemory[sizeof(staticMemory) - 1] != 2) + return 37; + puts("main-executed"); + return 0; + } +#endif if (mode == L"arguments") { for (int i = 2; i < argc; ++i) wprintf(L"%ls\n", argv[i]); diff --git a/tests/windows-sandbox/main.cpp b/tests/windows-sandbox/main.cpp index 5d135b9f..1723ade7 100644 --- a/tests/windows-sandbox/main.cpp +++ b/tests/windows-sandbox/main.cpp @@ -184,12 +184,12 @@ class WindowsSandboxTests : public QObject { return process.waitForFinished(5000) && process.exitCode() == 0; } - ProcessRunnerConfig config(const QString &arguments) { + ProcessRunnerConfig config(const QString &arguments, const QString &helper = QStringLiteral("sandbox-helper.exe")) { ProcessRunnerConfig cfg; cfg.workingDirectory = root.path() + QString("/case-%1/").arg(++sequence); QDir().mkpath(cfg.workingDirectory); cfg.executableFile = cfg.workingDirectory + "helper.exe"; - if (! QFile::copy(QDir::currentPath() + "/sandbox-helper.exe", cfg.executableFile)) + if (! QFile::copy(QDir::currentPath() + "/" + helper, cfg.executableFile)) qFatal("Cannot copy sandbox helper"); cfg.arguments = arguments; cfg.standardInputCheck = cfg.standardOutputCheck = true; @@ -892,6 +892,41 @@ class WindowsSandboxTests : public QObject { QCOMPARE(run(cpu).result, TimeLimitExceeded); } + void initialImageMemoryLimit() { + auto cfg = config("static-memory", "sandbox-static-memory-helper.exe"); + cfg.sandboxSettings.enabled = false; + STARTUPINFOW startup{}; + startup.cb = sizeof(startup); + PROCESS_INFORMATION pi{}; + QString command = quoteArgument(cfg.executableFile) + " static-memory"; + QVERIFY(CreateProcessW(nullptr, reinterpret_cast(command.data()), nullptr, nullptr, + FALSE, CREATE_SUSPENDED, nullptr, nullptr, &startup, &pi)); + const auto cleanup = qScopeGuard([&] { + TerminateProcess(pi.hProcess, 1); + WaitForSingleObject(pi.hProcess, 2000); + CloseHandle(pi.hThread); + CloseHandle(pi.hProcess); + }); + PROCESS_MEMORY_COUNTERS counters{}; + counters.cb = sizeof(counters); + QVERIFY(GetProcessMemoryInfo(pi.hProcess, &counters, sizeof(counters))); + QVERIFY(counters.PeakPagefileUsage > 32 * 1024 * 1024); + TerminateProcess(pi.hProcess, 1); + QCOMPARE(WaitForSingleObject(pi.hProcess, 2000), DWORD(WAIT_OBJECT_0)); + const auto control = run(cfg); + QVERIFY2(control.result == CorrectAnswer, qPrintable(control.message)); + QCOMPARE(read(cfg.workingDirectory + "_tmpout").trimmed(), QByteArray("main-executed")); + cfg.memoryLimit = cfg.rawMemoryLimit = 32; + const auto limited = run(cfg); + QString error; + const bool reaped = noLiveCaseProcess(cfg.executableFile, error); + QVERIFY2(reaped, qPrintable(error)); + QCOMPARE(limited.result, MemoryLimitExceeded); + QCOMPARE(limited.timeUsed, -1); + QVERIFY(limited.memoryUsed > 32 * 1024 * 1024); + QVERIFY(read(cfg.workingDirectory + "_tmpout").isEmpty()); + } + void preStartCancellation_data() { QTest::addColumn("stop"); QTest::newRow("ordinary-future") << false; From bdd9e4657f965fdcd3af3ef4987660c0d1f016e3 Mon Sep 17 00:00:00 2001 From: sgt57 <198590103+sgt57@users.noreply.github.com> Date: Mon, 9 Nov 2026 22:30:03 +0800 Subject: [PATCH 35/37] fix(linux): preserve stop and continue under ptrace --- unix/test/CMakeLists.txt | 4 ++ unix/test/memory_cases.cpp | 10 ++++ unix/test/scripts/stop_continue.py | 51 ++++++++++++++++++++ unix/watcher_unix.cpp | 75 +++++++++++++++++++++++------- 4 files changed, 122 insertions(+), 18 deletions(-) create mode 100644 unix/test/scripts/stop_continue.py diff --git a/unix/test/CMakeLists.txt b/unix/test/CMakeLists.txt index d1b3ab15..956b1f14 100644 --- a/unix/test/CMakeLists.txt +++ b/unix/test/CMakeLists.txt @@ -38,3 +38,7 @@ add_test(NAME watcher_memory_policy COMMAND python3 scripts/memory.py) set_tests_properties(watcher_memory_policy PROPERTIES TIMEOUT 30) add_test(NAME watcher_memory_accuracy COMMAND python3 scripts/memory_accuracy.py) set_tests_properties(watcher_memory_accuracy PROPERTIES TIMEOUT 30) +if(CMAKE_SYSTEM_NAME STREQUAL "Linux") + add_test(NAME watcher_stop_continue COMMAND python3 scripts/stop_continue.py) + set_tests_properties(watcher_stop_continue PROPERTIES TIMEOUT 30) +endif() diff --git a/unix/test/memory_cases.cpp b/unix/test/memory_cases.cpp index d3f0f32c..6667ee55 100644 --- a/unix/test/memory_cases.cpp +++ b/unix/test/memory_cases.cpp @@ -10,6 +10,7 @@ #include #else #include +#include #include #endif int main(int argc, char **argv) { @@ -54,6 +55,15 @@ int main(int argc, char **argv) { munmap(mapping, bytes); return 0; } +#ifdef __linux__ + if (! strcmp(argv[1], "stop-continue")) { + printf("pid=%ld\n", static_cast(getpid())); + fflush(stdout); + raise(SIGSTOP); + puts("resumed"); + return 0; + } +#endif if (! strcmp(argv[1], "abort")) std::abort(); if (! strcmp(argv[1], "caught") || ! strcmp(argv[1], "uncaught")) { diff --git a/unix/test/scripts/stop_continue.py b/unix/test/scripts/stop_continue.py new file mode 100644 index 00000000..c09c2410 --- /dev/null +++ b/unix/test/scripts/stop_continue.py @@ -0,0 +1,51 @@ +import os +import pathlib +import re +import signal +import subprocess # nosec B404 +import tempfile +import time + +with tempfile.TemporaryDirectory() as directory: + output = pathlib.Path(directory) / 'out' + error = pathlib.Path(directory) / 'err' + watcher = subprocess.Popen( # nosec B603 + ['./watcher_unix', './memory_cases', 'stop-continue', '', str(output), str(error), + '3000', '512', '3000', '512', '', ''], + stdout=subprocess.PIPE, stderr=subprocess.PIPE) + pid = None + try: + deadline = time.monotonic() + 5 + while time.monotonic() < deadline: + text = output.read_text() if output.exists() else '' + match = re.search(r'pid=(\d+)', text) + if match: + pid = int(match[1]) + status = pathlib.Path(f'/proc/{pid}/status').read_text() + if re.search(r'^State:\s+[Tt]\b', status, re.M): + break + assert watcher.poll() is None, (watcher.returncode, text) + time.sleep(0.01) + else: + raise AssertionError('fixture never entered stopped state') + assert 'resumed' not in text, text + os.kill(pid, signal.SIGCONT) + stdout, stderr = watcher.communicate(timeout=12) + assert watcher.returncode == 0, (stdout, stderr, error.read_text()) + fields = stdout.split() + assert len(fields) == 2 and all(int(x) >= 0 for x in fields), stdout + assert 'resumed' in output.read_text() + print('stop-continue: stopped, SIGCONT resumed, AC', stdout.decode().strip()) + finally: + if pid is not None: + try: + os.killpg(pid, signal.SIGKILL) + except ProcessLookupError: + pass + if watcher.poll() is None: + watcher.terminate() + try: + watcher.communicate(timeout=4) + except subprocess.TimeoutExpired: + watcher.kill() + watcher.communicate(timeout=4) diff --git a/unix/watcher_unix.cpp b/unix/watcher_unix.cpp index 6fd54d43..53599091 100644 --- a/unix/watcher_unix.cpp +++ b/unix/watcher_unix.cpp @@ -22,6 +22,7 @@ #include #include #include +#include #include #elif defined(__APPLE__) #include @@ -167,7 +168,6 @@ namespace { #ifdef __linux__ std::set traced; std::set newborn; - bool initialized = false; #endif explicit UnixProcess(pid_t pid, Events &events) : pid(pid), events(events) { #ifdef __linux__ @@ -214,14 +214,7 @@ namespace { } unsigned event = static_cast(state) >> 16; int signal = WSTOPSIG(state); - if (! initialized && tid == pid) { - if (signal != SIGSTOP || ptrace(PTRACE_SETOPTIONS, pid, nullptr, - PTRACE_O_TRACEEXIT | PTRACE_O_TRACEEXEC | - PTRACE_O_TRACECLONE | PTRACE_O_EXITKILL) < 0) - return -1; - initialized = true; - signal = 0; - } else if (event == PTRACE_EVENT_EXIT) { + if (event == PTRACE_EVENT_EXIT) { auto memory = sampleMemory(tid); if (memory < 0) return -1; @@ -261,16 +254,15 @@ namespace { continue; } signal = 0; - } else if (! event) { - siginfo_t info{}; - if (ptrace(PTRACE_GETSIGINFO, tid, nullptr, &info) < 0) { - if (errno != EINVAL) + } else if (event == PTRACE_EVENT_STOP) { + if (signal == SIGSTOP || signal == SIGTSTP || signal == SIGTTIN || signal == SIGTTOU) { + if (ptrace(PTRACE_LISTEN, tid, nullptr, nullptr) < 0 && errno != ESRCH) return -1; - // A group stop remains stopped until SIGCONT or cleanup. ++it; continue; } - } else + signal = 0; + } else if (event) signal = 0; if (ptrace(PTRACE_CONT, tid, nullptr, signal) < 0 && errno != ESRCH) return -1; @@ -360,15 +352,32 @@ int main(int argc, char **argv) { printf("-1\n-1\n"); return RS_FAIL; } +#ifdef __linux__ + int startup[2]; + if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0, startup) != 0) { + perror("socketpair"); + close(errors[0]); + close(errors[1]); + printf("-1\n-1\n"); + return RS_FAIL; + } +#endif pid_t pid = fork(); if (pid < 0) { perror("fork"); +#ifdef __linux__ + close(startup[0]); + close(startup[1]); +#endif close(errors[0]); close(errors[1]); printf("-1\n-1\n"); return RS_FAIL; } if (pid == 0) { +#ifdef __linux__ + close(startup[0]); +#endif events.restore(); close(errors[0]); auto fail = [&](int stage) { @@ -384,10 +393,17 @@ int main(int argc, char **argv) { if (! freopen(*argv[3 + i] ? argv[3 + i] : "/dev/null", modes[i], streams[i])) fail(2); #ifdef __linux__ - if (ptrace(PTRACE_TRACEME, 0, nullptr, nullptr) < 0) - fail(8); - if (raise(SIGSTOP) != 0) + char token = 0; + ssize_t received; + do { + received = recv(startup[1], &token, 1, 0); + } while (received < 0 && errno == EINTR); + if (received != 1 || token != 1) { + if (received >= 0) + errno = EPROTO; fail(8); + } + close(startup[1]); // Disable dump generation, including piped core handlers. if (prctl(PR_SET_DUMPABLE, 0) != 0) fail(6); @@ -407,12 +423,35 @@ int main(int argc, char **argv) { fail(5); } close(errors[1]); +#ifdef __linux__ + close(startup[1]); +#endif (void)setpgid(pid, pid); UnixProcess process(pid, events); Bytes &peak = process.peak; bool ready = events.arm(std::max(2000LL, 3LL * timeLimit), true); if (! ready) perror("events arm"); +#ifdef __linux__ + if (ready && ptrace(PTRACE_SEIZE, pid, nullptr, + PTRACE_O_TRACEEXIT | PTRACE_O_TRACEEXEC | PTRACE_O_TRACECLONE | + PTRACE_O_EXITKILL) < 0) { + perror("ptrace seize"); + ready = false; + } + if (ready) { + const char token = 1; + ssize_t sent; + do { + sent = send(startup[0], &token, 1, MSG_NOSIGNAL); + } while (sent < 0 && errno == EINTR); + if (sent != 1) { + perror("startup send"); + ready = false; + } + } + close(startup[0]); +#endif int event = 0; int verdict = RS_AC; From 68cab6c6ab40090401c0284644fdd5503652cac3 Mon Sep 17 00:00:00 2001 From: sgt57 <198590103+sgt57@users.noreply.github.com> Date: Mon, 9 Nov 2026 22:36:13 +0800 Subject: [PATCH 36/37] fix(linux): retain VSS peaks across exec --- unix/test/CMakeLists.txt | 2 + unix/test/memory_cases.cpp | 177 +++++++++++++++++++ unix/test/scripts/memory.py | 83 ++++++++- unix/test/scripts/memory_accuracy.py | 84 +++++++-- unix/watcher_unix.cpp | 248 +++++++++++++++++---------- 5 files changed, 482 insertions(+), 112 deletions(-) diff --git a/unix/test/CMakeLists.txt b/unix/test/CMakeLists.txt index 956b1f14..c4e1e60b 100644 --- a/unix/test/CMakeLists.txt +++ b/unix/test/CMakeLists.txt @@ -39,6 +39,8 @@ set_tests_properties(watcher_memory_policy PROPERTIES TIMEOUT 30) add_test(NAME watcher_memory_accuracy COMMAND python3 scripts/memory_accuracy.py) set_tests_properties(watcher_memory_accuracy PROPERTIES TIMEOUT 30) if(CMAKE_SYSTEM_NAME STREQUAL "Linux") + find_package(Threads REQUIRED) + target_link_libraries(memory_cases PRIVATE Threads::Threads) add_test(NAME watcher_stop_continue COMMAND python3 scripts/stop_continue.py) set_tests_properties(watcher_stop_continue PROPERTIES TIMEOUT 30) endif() diff --git a/unix/test/memory_cases.cpp b/unix/test/memory_cases.cpp index 6667ee55..7582849d 100644 --- a/unix/test/memory_cases.cpp +++ b/unix/test/memory_cases.cpp @@ -13,10 +13,59 @@ #include #include #endif +#ifdef __linux__ +#include +#include +#include +#include +#include +#include + +extern char **environ; + +namespace { +char executable[4096]; +// Keep these mappings alive until exec/exit: Linux accuracy measures VSS, not RSS. +bool mapAndReport(size_t mib, const char *label = "reference-bytes") { + const size_t bytes = mib * 1024 * 1024; + if (mmap(nullptr, bytes, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0) == MAP_FAILED) + return false; + unsigned long long pages = 0; + std::ifstream statm("/proc/thread-self/statm"); + const auto pageSize = sysconf(_SC_PAGESIZE); + if (! (statm >> pages) || pageSize <= 0) + return false; + printf("%s=%llu\n", label, pages * static_cast(pageSize)); + return fflush(stdout) == 0; +} + +int execSelf(const char *mode) { + execl(executable, "memory_cases", mode, static_cast(nullptr)); + return 31; +} + +pthread_t leader; + +void *execFromWorker(void *) { + if (pthread_join(leader, nullptr) != 0) + std::exit(32); + if (! mapAndReport(64)) + std::exit(33); + std::exit(execSelf("exec-sink")); +} +} +#endif int main(int argc, char **argv) { const bool accuracy = argc == 3 && ! strcmp(argv[1], "accuracy"); if (argc != 2 && ! accuracy) return 1; +#ifdef __linux__ + // /proc/self/exe and /proc/self/statm cease to describe a dead leader. + const auto length = readlink("/proc/self/exe", executable, sizeof(executable) - 1); + if (length <= 0 || static_cast(length) >= sizeof(executable) - 1) + return 30; + executable[length] = '\0'; +#endif if (accuracy) { const auto mib = std::strtoul(argv[2], nullptr, 10); if (mib != 16 && mib != 64) @@ -56,6 +105,134 @@ int main(int argc, char **argv) { return 0; } #ifdef __linux__ + if (! strcmp(argv[1], "exec-sink")) { + puts("exec-ok=1"); + return 0; + } + if (! strcmp(argv[1], "exec-chain") || ! strcmp(argv[1], "exec-chain-next")) { + const bool first = ! strcmp(argv[1], "exec-chain"); + if (! mapAndReport(first ? 128 : 64)) + return 34; + return execSelf(first ? "exec-chain-next" : "exec-sink"); + } + if (! strcmp(argv[1], "exec-failed")) { + if (! mapAndReport(64)) + return 35; + execl("/proc/self/lemon-watcher-no-such-executable", "missing", static_cast(nullptr)); + const int error = errno; + printf("failed-exec-errno=%d\n", error); + if (error != ENOENT) + return 36; + puts("failed-exec-handled=1"); + fflush(stdout); + return execSelf("exec-sink"); + } + if (! strcmp(argv[1], "execveat-peak")) { + if (! mapAndReport(64)) + return 37; + const int fd = open("/proc/self/exe", O_RDONLY | O_CLOEXEC); + if (fd < 0) + return 38; + char name[] = "memory_cases"; + char mode[] = "exec-sink"; + char *arguments[] = {name, mode, nullptr}; + // Deliberately no libc fallback: the execveat notification is under test. + syscall(SYS_execveat, fd, "", arguments, environ, AT_EMPTY_PATH); + close(fd); + return 39; + } + if (! strcmp(argv[1], "nonleader-exec")) { +#ifdef __GLIBC__ + // Avoid glibc's transient arena reservation obscuring this fixture's mapping peak. + if (! mallopt(M_ARENA_MAX, 1)) + return 40; +#endif + leader = pthread_self(); + pthread_t worker; + pthread_attr_t attributes; + if (pthread_attr_init(&attributes) != 0) + return 40; + const int sized = pthread_attr_setstacksize(&attributes, 1024 * 1024); + const int created = sized == 0 ? pthread_create(&worker, &attributes, execFromWorker, nullptr) : sized; + pthread_attr_destroy(&attributes); + if (created != 0) + return 40; + pthread_exit(nullptr); + } + if (! strcmp(argv[1], "fork-exec")) { + if (! mapAndReport(16, "root-reference-bytes")) + return 41; + const pid_t child = fork(); + if (child < 0) + return 42; + if (child == 0) { + if (! mapAndReport(128, "child-reference-bytes")) + _exit(43); + _exit(execSelf("exec-sink")); + } + int status = 0; + pid_t result; + do { + result = waitpid(child, &status, 0); + } while (result < 0 && errno == EINTR); + return result == child && WIFEXITED(status) && WEXITSTATUS(status) == 0 ? 0 : 44; + } + if (! strcmp(argv[1], "background-child")) { + int ready[2]; + if (pipe(ready) != 0) + return 45; + const pid_t child = fork(); + if (child < 0) { + close(ready[0]); + close(ready[1]); + return 46; + } + if (child == 0) { + close(ready[0]); + if (setsid() < 0) + _exit(47); + const char token = 1; + ssize_t sent; + do { + sent = write(ready[1], &token, 1); + } while (sent < 0 && errno == EINTR); + close(ready[1]); + if (sent != 1) + _exit(48); + for (;;) + pause(); + } + close(ready[1]); + char token = 0; + ssize_t received; + do { + received = read(ready[0], &token, 1); + } while (received < 0 && errno == EINTR); + close(ready[0]); + if (received != 1 || token != 1) { + kill(child, SIGKILL); + while (waitpid(child, nullptr, 0) < 0 && errno == EINTR) {} + return 49; + } + printf("child-pid=%ld\n", static_cast(child)); + fflush(stdout); + return 0; + } + if (! strcmp(argv[1], "syscall-burst")) { + unsigned long long checksum = 0; + const auto expected = static_cast(getpid()) * 100000; + for (int i = 0; i < 100000; ++i) { + const long pid = syscall(SYS_getpid); + if (pid <= 0) + return 50; + checksum += static_cast(pid); + } + if (checksum != expected) + return 51; + printf("syscall-checksum=%llu\n", checksum); + puts("syscall-burst-ok=1"); + return 0; + } if (! strcmp(argv[1], "stop-continue")) { printf("pid=%ld\n", static_cast(getpid())); fflush(stdout); diff --git a/unix/test/scripts/memory.py b/unix/test/scripts/memory.py index c4a04a9b..f0cdde3c 100644 --- a/unix/test/scripts/memory.py +++ b/unix/test/scripts/memory.py @@ -1,21 +1,88 @@ import os import platform +import pathlib +import signal +import time # subprocess is required to run the local regression-test fixtures. import subprocess # nosec B404 import tempfile with tempfile.TemporaryDirectory() as directory: + def child_state(pid): + try: + status = pathlib.Path(f'/proc/{pid}/status').read_text() + except FileNotFoundError: + return None + fields = dict(line.split(':', 1) for line in status.splitlines() if ':' in line) + return fields['State'].split()[0], int(fields['TracerPid']) + def run(mode, limit=64): output = os.path.join(directory, 'out') error = os.path.join(directory, 'err') + # Do not read a previous case's output if startup or execution fails. + pathlib.Path(output).write_text('') + pathlib.Path(error).write_text('') # Fixed local binaries and test-controlled arguments; no shell is involved. - p = subprocess.run(['./watcher_unix', './memory_cases', mode, '', output, error, # nosec B603 - '1000', str(limit), '1000', str(limit), '', ''], - stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=8) - fields = p.stdout.decode().split() - assert len(fields) == 2, (mode, p.stdout, p.stderr) - assert int(fields[1]) >= 0, (mode, p.stdout, p.stderr) - return p.returncode, open(output).read(), int(fields[1]) + p = subprocess.Popen(['./watcher_unix', './memory_cases', mode, '', output, error, # nosec B603 + '1000', str(limit), '1000', str(limit), '', ''], + stdout=subprocess.PIPE, stderr=subprocess.PIPE, + start_new_session=True) + try: + stdout, stderr = p.communicate(timeout=8) + fields = stdout.decode().split() + assert len(fields) == 2, (mode, stdout, stderr) + assert int(fields[0]) >= 0, (mode, stdout, stderr) + assert int(fields[1]) >= 0, (mode, stdout, stderr) + text = pathlib.Path(output).read_text() + if mode == 'background-child': + assert p.returncode == 0, (mode, p.returncode, stderr) + assert b'reaping deadline' not in stderr.lower(), stderr + assert 'reaping deadline' not in pathlib.Path(error).read_text().lower() + labels = dict(field.split('=', 1) for field in text.split()) + pid = int(labels['child-pid']) + assert pid > 1, text + deadline = time.monotonic() + 1 + state = child_state(pid) + while state is not None and state != ('Z', 0) and time.monotonic() < deadline: + time.sleep(0.01) + state = child_state(pid) + print(f'case={mode} child-pid={pid} state={state} ' + f'statistics={stdout.decode().strip()}', flush=True) + assert state is None or state == ('Z', 0), (pid, state) + elif mode == 'syscall-burst': + assert p.returncode == 0, (mode, p.returncode, stderr) + labels = dict(field.split('=', 1) for field in text.split()) + assert labels['syscall-burst-ok'] == '1', text + print(f'case={mode} syscall-burst-ok=1 ' + f'statistics={stdout.decode().strip()}', flush=True) + return p.returncode, text, int(fields[1]) + finally: + if p.poll() is None: + try: + os.killpg(p.pid, signal.SIGKILL) + except ProcessLookupError: + pass + p.communicate(timeout=3) + if mode == 'background-child': + # Even a timeout or malformed watcher report must not leave the + # fixture's detached, paused child alive. + for field in pathlib.Path(output).read_text().split(): + if field.startswith('child-pid='): + pid = int(field.split('=', 1)[1]) + if pid > 1: + state = child_state(pid) + if state is not None and state[0] != 'Z': + try: + os.kill(pid, signal.SIGKILL) + except ProcessLookupError: + pass + deadline = time.monotonic() + 2 + while time.monotonic() < deadline: + state = child_state(pid) + if state is None or state == ('Z', 0): + break + time.sleep(0.01) + assert state is None or state == ('Z', 0), (pid, state) assert run('abort')[0] == 2 if platform.system() == 'Linux': @@ -24,6 +91,8 @@ def run(mode, limit=64): assert run('reserve')[0:2] == (0, 'denied\n') # Prelimit refuses the allocation; a nonzero exit is RE, not MLE. assert run('resident')[0] == 2 + assert run('background-child', 512)[0] == 0 + assert run('syscall-burst', 512)[0] == 0 else: assert run('reserve')[0:2] == (0, 'reserved\n') assert run('resident')[0] == 4 diff --git a/unix/test/scripts/memory_accuracy.py b/unix/test/scripts/memory_accuracy.py index 7c2366e8..f5ee12f5 100644 --- a/unix/test/scripts/memory_accuracy.py +++ b/unix/test/scripts/memory_accuracy.py @@ -1,4 +1,6 @@ +import os import pathlib +import signal import sys # Only local test executables and fixed arguments are launched below. import subprocess # nosec B404 @@ -7,25 +9,73 @@ metric = "RSS" if sys.platform == "darwin" else "VSS" with tempfile.TemporaryDirectory() as directory: - for mib in (16, 64): - output = pathlib.Path(directory) / f"accuracy-{mib}.out" - error = pathlib.Path(directory) / f"accuracy-{mib}.err" - result = subprocess.run( # nosec B603 - ["./watcher_unix", "./memory_cases", f"accuracy {mib}", "", str(output), str(error), + def run(mode): + output = pathlib.Path(directory) / f"{mode.replace(' ', '-')}.out" + error = output.with_suffix(".err") + process = subprocess.Popen( # nosec B603 + ["./watcher_unix", "./memory_cases", mode, "", str(output), str(error), "2000", "512", "2000", "512", "", ""], - stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=10, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, start_new_session=True, ) - assert result.returncode == 0, (mib, result.returncode, result.stderr, - error.read_text() if error.exists() else "") - fields = result.stdout.decode().split() - assert len(fields) == 2, result.stdout + try: + stdout, stderr = process.communicate(timeout=10) + finally: + if process.poll() is None: + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + process.communicate(timeout=3) + assert process.returncode == 0, ( + mode, process.returncode, stderr, error.read_text() if error.exists() else "") + fields = stdout.decode().split() + assert len(fields) == 2, (mode, stdout, stderr) + assert int(fields[0]) >= 0, (mode, stdout) usage = int(fields[1]) - measurements = dict(field.split("=") for field in output.read_text().split()) - reference = int(measurements["reference-bytes"]) - allocation = mib * 1024 * 1024 - assert int(measurements["allocation-bytes"]) == allocation - assert reference >= allocation, (mib, reference) + assert usage >= 0, (mode, stdout) + measurements = {} + for field in output.read_text().split(): + key, value = field.split("=", 1) + measurements.setdefault(key, []).append(int(value)) + return usage, measurements + + def check(mode, usage, reference): # Kernel snapshots and lifetime peaks can differ slightly during final I/O. tolerance = max(1024 * 1024, reference // 100) - print(f"metric={metric} allocation={allocation} reference={reference} usage={usage} tolerance={tolerance}") - assert abs(usage - reference) <= tolerance, (mib, reference, usage, tolerance) + print(f"case={mode} metric={metric} reference={reference} usage={usage} tolerance={tolerance}", + flush=True) + assert abs(usage - reference) <= tolerance, (mode, reference, usage, tolerance) + + for mib in (16, 64): + mode = f"accuracy {mib}" + usage, measurements = run(mode) + reference = max(measurements["reference-bytes"]) + allocation = mib * 1024 * 1024 + assert measurements["allocation-bytes"] == [allocation] + assert reference >= allocation, (mib, reference) + print(f"allocation={allocation}", flush=True) + check(mode, usage, reference) + + if sys.platform.startswith("linux"): + for mode in ("exec-chain", "exec-failed", "execveat-peak", "nonleader-exec", + "fork-exec"): + usage, measurements = run(mode) + assert measurements["exec-ok"] == [1], (mode, measurements) + if mode == "fork-exec": + reference = max(measurements["root-reference-bytes"]) + child_reference = max(measurements["child-reference-bytes"]) + assert child_reference > reference + max(1024 * 1024, reference // 100) + print(f"case={mode} root-reference-bytes={reference} " + f"child-reference-bytes={child_reference} exec-ok=1", flush=True) + else: + references = measurements["reference-bytes"] + reference = max(references) + if mode == "exec-chain": + assert len(references) == 2, measurements + assert references[0] > references[1] + max(1024 * 1024, reference // 100) + if mode == "exec-failed": + assert measurements["failed-exec-errno"] == [2], measurements + assert measurements["failed-exec-handled"] == [1], measurements + print("failed-exec-errno=2 failed-exec-handled=1", flush=True) + print(f"case={mode} reference-bytes={references} exec-ok=1", flush=True) + check(mode, usage, reference) diff --git a/unix/watcher_unix.cpp b/unix/watcher_unix.cpp index 53599091..b6a551a1 100644 --- a/unix/watcher_unix.cpp +++ b/unix/watcher_unix.cpp @@ -18,7 +18,12 @@ #include #ifdef __linux__ #include -#include +#include +#include +#include +#include +#include +#include #include #include #include @@ -29,6 +34,64 @@ #endif using namespace Lemon::Execution; namespace { +#ifdef __linux__ + bool installExecTrace() { + sock_filter filter[] = { + BPF_STMT(BPF_LD | BPF_W | BPF_ABS, offsetof(seccomp_data, arch)), + BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, AUDIT_ARCH_X86_64, 6 - 1 - 1, 0), + BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, AUDIT_ARCH_I386, 17 - 2 - 1, 0), + BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, AUDIT_ARCH_AARCH64, 22 - 3 - 1, 0), + BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, AUDIT_ARCH_ARM, 27 - 4 - 1, 0), +#if defined(__x86_64__) || defined(__i386__) || defined(__aarch64__) || defined(__arm__) + BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW), +#else + // Other builds retain native SYS numbers, not guessed compat ABIs. + BPF_STMT(BPF_JMP | BPF_JA, 32 - 5 - 1), +#endif + BPF_STMT(BPF_LD | BPF_W | BPF_ABS, offsetof(seccomp_data, nr)), + BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 59, 8, 0), + BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 322, 7, 0), + BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x40000208, 6, 0), + BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x40000221, 5, 0), + BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 520, 4, 0), + BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 545, 3, 0), + BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x4000003b, 2, 0), + BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x40000142, 1, 0), + BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW), + BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_TRACE), + BPF_STMT(BPF_LD | BPF_W | BPF_ABS, offsetof(seccomp_data, nr)), + BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 11, 2, 0), + BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 358, 1, 0), + BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW), + BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_TRACE), + BPF_STMT(BPF_LD | BPF_W | BPF_ABS, offsetof(seccomp_data, nr)), + BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 221, 2, 0), + BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 281, 1, 0), + BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW), + BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_TRACE), + BPF_STMT(BPF_LD | BPF_W | BPF_ABS, offsetof(seccomp_data, nr)), + BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 11, 2, 0), + BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 387, 1, 0), + BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW), + BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_TRACE), +#if !defined(__x86_64__) && !defined(__i386__) && !defined(__aarch64__) && !defined(__arm__) + BPF_STMT(BPF_LD | BPF_W | BPF_ABS, offsetof(seccomp_data, nr)), +#ifdef SYS_execveat + BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, SYS_execve, 2, 0), + BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, SYS_execveat, 1, 0), +#else + BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, SYS_execve, 1, 0), +#endif + BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW), + BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_TRACE), +#endif + }; + sock_fprog program{static_cast(sizeof(filter) / sizeof(filter[0])), filter}; + // Inherited NNP forbids exec privilege gains; only exec syscalls notify the tracer. + return prctl(PR_SET_NO_NEW_PRIVS, 1L, 0L, 0L, 0L) == 0 && + prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &program, 0L, 0L) == 0; + } +#endif enum { RS_AC, RS_FAIL, RS_RE, RS_TLE, RS_MLE }; class Events { int signals[4] = {SIGCHLD, SIGTERM, SIGINT, SIGABRT}; @@ -166,110 +229,112 @@ namespace { Events &events; Bytes peak = -1; #ifdef __linux__ - std::set traced; - std::set newborn; + std::map traced; // tid -> tgid, zero until identified. + bool drained = false; #endif explicit UnixProcess(pid_t pid, Events &events) : pid(pid), events(events) { #ifdef __linux__ - traced.insert(pid); + traced.emplace(pid, pid); #endif } ~UnixProcess() { killAndReap(); } - bool finished() const { + bool finished() const { return reaped; } + bool allReaped() const { #ifdef __linux__ - return reaped && traced.empty(); + return drained && traced.empty() && reaped; #else return reaped; #endif } - int poll() { - if (finished()) +#ifdef __linux__ + void terminateTracee(pid_t tid, pid_t group) { + if (group) + (void)syscall(SYS_tgkill, group, tid, SIGKILL); + else + (void)syscall(SYS_tkill, tid, SIGKILL); + } +#endif + int poll(bool cleanup = false) { + if (! cleanup && finished()) return 1; #ifdef __linux__ for (;;) { - bool progress = false; - for (auto it = traced.begin(); it != traced.end();) { - pid_t tid = *it; - int state = 0; - rusage sample{}; - pid_t result = wait4(tid, &state, WNOHANG | __WALL, &sample); - if (result < 0) { - if (errno == EINTR) - return 0; - return -1; - } - if (result == 0) { - ++it; + int state = 0; + rusage sample{}; + const pid_t tid = wait4(-1, &state, WNOHANG | __WALL, &sample); + if (tid < 0) { + if (errno == EINTR) continue; + if (errno == ECHILD && traced.empty() && reaped) { + drained = true; + return 1; } - progress = true; - if (WIFEXITED(state) || WIFSIGNALED(state)) { - if (tid == pid) { - status = state; - usage = sample; - reaped = true; - } - it = traced.erase(it); - continue; + return -1; + } + if (! tid) + return ! cleanup && finished() ? 1 : 0; + if (WIFEXITED(state) || WIFSIGNALED(state)) { + traced.erase(tid); + if (tid == pid) { + status = state; + usage = sample; + reaped = true; + if (! cleanup) + return 1; } - unsigned event = static_cast(state) >> 16; - int signal = WSTOPSIG(state); - if (event == PTRACE_EVENT_EXIT) { - auto memory = sampleMemory(tid); - if (memory < 0) - return -1; - peak = std::max(peak, memory); - signal = 0; - } else if (event == PTRACE_EVENT_CLONE) { - unsigned long child = 0; - if (ptrace(PTRACE_GETEVENTMSG, tid, nullptr, &child) < 0) - return -1; - traced.insert(static_cast(child)); - newborn.insert(static_cast(child)); - signal = 0; - } else if (event == PTRACE_EVENT_EXEC) { - unsigned long oldTid = 0; - if (ptrace(PTRACE_GETEVENTMSG, tid, nullptr, &oldTid) < 0) - return -1; - if (static_cast(oldTid) != tid) - traced.erase(static_cast(oldTid)); - signal = 0; - } else if (newborn.erase(tid)) { - int group = -1; - auto path = "/proc/" + std::to_string(tid) + "/status"; - FILE *file = fopen(path.c_str(), "r"); - if (! file) - return -1; + continue; + } + if (! WIFSTOPPED(state)) + continue; + auto [it, newborn] = traced.try_emplace(tid, 0); + unsigned event = static_cast(state) >> 16; + int signal = WSTOPSIG(state); + if (! it->second) { + int group = 0; + const auto path = "/proc/" + std::to_string(tid) + "/status"; + FILE *file = fopen(path.c_str(), "r"); + if (file) { char line[512]; while (fgets(line, sizeof(line), file)) if (sscanf(line, "Tgid: %d", &group) == 1) break; fclose(file); - if (group < 0) - return -1; - if (group != pid) { - if (ptrace(PTRACE_DETACH, tid, nullptr, nullptr) < 0) - return -1; - it = traced.erase(it); - continue; - } - signal = 0; - } else if (event == PTRACE_EVENT_STOP) { - if (signal == SIGSTOP || signal == SIGTSTP || signal == SIGTTIN || signal == SIGTTOU) { - if (ptrace(PTRACE_LISTEN, tid, nullptr, nullptr) < 0 && errno != ESRCH) - return -1; - ++it; - continue; - } - signal = 0; - } else if (event) - signal = 0; - if (ptrace(PTRACE_CONT, tid, nullptr, signal) < 0 && errno != ESRCH) + } + if (group <= 0 && ! cleanup) + return -1; + it->second = group > 0 ? group : 0; + } + if ((event == PTRACE_EVENT_SECCOMP || event == PTRACE_EVENT_EXIT) && it->second == pid) { + const auto memory = sampleMemory(tid); + if (memory < 0 && ! cleanup) return -1; - ++it; + peak = std::max(peak, memory); } - if (! progress) - return finished() ? 1 : 0; + if (event == PTRACE_EVENT_EXEC) { + unsigned long oldTid = 0; + if (ptrace(PTRACE_GETEVENTMSG, tid, nullptr, &oldTid) < 0 && ! cleanup) + return -1; + // Exec replaces this thread group, including its former leader. + for (auto entry = traced.begin(); entry != traced.end();) { + if (entry->second == tid || entry->first == static_cast(oldTid)) + entry = traced.erase(entry); + else + ++entry; + } + traced[tid] = tid; + } + if (cleanup) { + terminateTracee(tid, traced.at(tid)); + signal = 0; + } else if (event == PTRACE_EVENT_STOP && ! newborn && + (signal == SIGSTOP || signal == SIGTSTP || signal == SIGTTIN || signal == SIGTTOU)) { + if (ptrace(PTRACE_LISTEN, tid, nullptr, nullptr) < 0 && errno != ESRCH) + return -1; + continue; + } else if (event) + signal = 0; + if (ptrace(PTRACE_CONT, tid, nullptr, signal) < 0 && errno != ESRCH) + return -1; } #else pid_t result = wait4(pid, &status, WNOHANG, &usage); @@ -284,21 +349,25 @@ namespace { } bool killAndReap() { if (cleaned) - return finished(); + return allReaped(); cleaned = true; kill(-pid, SIGKILL); if (! reaped) kill(pid, SIGKILL); - if (finished()) +#ifdef __linux__ + for (const auto &[tid, group] : traced) + terminateTracee(tid, group); +#endif + if (allReaped()) return true; if (! events.arm(2000, false)) { perror("reaping events"); return false; } for (;;) { - if (poll() < 0) + if (poll(true) < 0) return false; - if (finished()) + if (allReaped()) break; int event = events.wait(); if (event < 0) { @@ -306,12 +375,12 @@ namespace { return false; } if (event & Events::Deadline) { - if (poll() < 0) + if (poll(true) < 0) return false; break; } } - return finished(); + return allReaped(); } }; struct ChildError { @@ -404,6 +473,8 @@ int main(int argc, char **argv) { fail(8); } close(startup[1]); + if (! installExecTrace()) + fail(9); // Disable dump generation, including piped core handlers. if (prctl(PR_SET_DUMPABLE, 0) != 0) fail(6); @@ -434,7 +505,8 @@ int main(int argc, char **argv) { perror("events arm"); #ifdef __linux__ if (ready && ptrace(PTRACE_SEIZE, pid, nullptr, - PTRACE_O_TRACEEXIT | PTRACE_O_TRACEEXEC | PTRACE_O_TRACECLONE | + PTRACE_O_TRACEFORK | PTRACE_O_TRACEVFORK | PTRACE_O_TRACECLONE | + PTRACE_O_TRACEEXEC | PTRACE_O_TRACEEXIT | PTRACE_O_TRACESECCOMP | PTRACE_O_EXITKILL) < 0) { perror("ptrace seize"); ready = false; From 3bb93036690f8f4195bf14c4794242a2022ccfa4 Mon Sep 17 00:00:00 2001 From: "GitHub Action (clang-format)" Date: Mon, 9 Nov 2026 14:38:34 +0000 Subject: [PATCH 37/37] style: format codes --- tests/windows-sandbox/main.cpp | 21 +++++++----- unix/test/memory_cases.cpp | 62 ++++++++++++++++++---------------- unix/watcher_unix.cpp | 19 ++++++----- 3 files changed, 54 insertions(+), 48 deletions(-) diff --git a/tests/windows-sandbox/main.cpp b/tests/windows-sandbox/main.cpp index 1723ade7..404286a3 100644 --- a/tests/windows-sandbox/main.cpp +++ b/tests/windows-sandbox/main.cpp @@ -98,10 +98,11 @@ namespace { BOOL found = Process32FirstW(snapshot.get(), &entry); while (found) { if (entry.th32ParentProcessID == GetCurrentProcessId() && - QString::fromWCharArray(entry.szExeFile).compare(QFileInfo(executable).fileName(), - Qt::CaseInsensitive) == 0) { - Handle process(OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION | SYNCHRONIZE | - PROCESS_TERMINATE, FALSE, entry.th32ProcessID)); + QString::fromWCharArray(entry.szExeFile) + .compare(QFileInfo(executable).fileName(), Qt::CaseInsensitive) == 0) { + Handle process( + OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION | SYNCHRONIZE | PROCESS_TERMINATE, FALSE, + entry.th32ProcessID)); if (! process) { if (GetLastError() != ERROR_INVALID_PARAMETER) error = "Cannot open candidate testcase process"; @@ -111,8 +112,9 @@ namespace { if (! QueryFullProcessImageNameW(process.get(), 0, image, &size)) { if (GetLastError() != ERROR_INVALID_PARAMETER) error = "Cannot query candidate testcase process"; - } else if (QDir::cleanPath(QDir::fromNativeSeparators( - QString::fromWCharArray(image, size))).compare(expected, Qt::CaseInsensitive) == 0) { + } else if (QDir::cleanPath( + QDir::fromNativeSeparators(QString::fromWCharArray(image, size))) + .compare(expected, Qt::CaseInsensitive) == 0) { const DWORD state = WaitForSingleObject(process.get(), 0); if (state == WAIT_TIMEOUT) { error = QString("Live testcase process %1").arg(entry.th32ProcessID); @@ -184,7 +186,8 @@ class WindowsSandboxTests : public QObject { return process.waitForFinished(5000) && process.exitCode() == 0; } - ProcessRunnerConfig config(const QString &arguments, const QString &helper = QStringLiteral("sandbox-helper.exe")) { + ProcessRunnerConfig config(const QString &arguments, + const QString &helper = QStringLiteral("sandbox-helper.exe")) { ProcessRunnerConfig cfg; cfg.workingDirectory = root.path() + QString("/case-%1/").arg(++sequence); QDir().mkpath(cfg.workingDirectory); @@ -899,8 +902,8 @@ class WindowsSandboxTests : public QObject { startup.cb = sizeof(startup); PROCESS_INFORMATION pi{}; QString command = quoteArgument(cfg.executableFile) + " static-memory"; - QVERIFY(CreateProcessW(nullptr, reinterpret_cast(command.data()), nullptr, nullptr, - FALSE, CREATE_SUSPENDED, nullptr, nullptr, &startup, &pi)); + QVERIFY(CreateProcessW(nullptr, reinterpret_cast(command.data()), nullptr, nullptr, FALSE, + CREATE_SUSPENDED, nullptr, nullptr, &startup, &pi)); const auto cleanup = qScopeGuard([&] { TerminateProcess(pi.hProcess, 1); WaitForSingleObject(pi.hProcess, 2000); diff --git a/unix/test/memory_cases.cpp b/unix/test/memory_cases.cpp index 7582849d..c3d79cb5 100644 --- a/unix/test/memory_cases.cpp +++ b/unix/test/memory_cases.cpp @@ -9,8 +9,8 @@ #ifdef __APPLE__ #include #else -#include #include +#include #include #endif #ifdef __linux__ @@ -24,36 +24,36 @@ extern char **environ; namespace { -char executable[4096]; -// Keep these mappings alive until exec/exit: Linux accuracy measures VSS, not RSS. -bool mapAndReport(size_t mib, const char *label = "reference-bytes") { - const size_t bytes = mib * 1024 * 1024; - if (mmap(nullptr, bytes, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0) == MAP_FAILED) - return false; - unsigned long long pages = 0; - std::ifstream statm("/proc/thread-self/statm"); - const auto pageSize = sysconf(_SC_PAGESIZE); - if (! (statm >> pages) || pageSize <= 0) - return false; - printf("%s=%llu\n", label, pages * static_cast(pageSize)); - return fflush(stdout) == 0; -} + char executable[4096]; + // Keep these mappings alive until exec/exit: Linux accuracy measures VSS, not RSS. + bool mapAndReport(size_t mib, const char *label = "reference-bytes") { + const size_t bytes = mib * 1024 * 1024; + if (mmap(nullptr, bytes, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0) == MAP_FAILED) + return false; + unsigned long long pages = 0; + std::ifstream statm("/proc/thread-self/statm"); + const auto pageSize = sysconf(_SC_PAGESIZE); + if (! (statm >> pages) || pageSize <= 0) + return false; + printf("%s=%llu\n", label, pages * static_cast(pageSize)); + return fflush(stdout) == 0; + } -int execSelf(const char *mode) { - execl(executable, "memory_cases", mode, static_cast(nullptr)); - return 31; -} + int execSelf(const char *mode) { + execl(executable, "memory_cases", mode, static_cast(nullptr)); + return 31; + } -pthread_t leader; + pthread_t leader; -void *execFromWorker(void *) { - if (pthread_join(leader, nullptr) != 0) - std::exit(32); - if (! mapAndReport(64)) - std::exit(33); - std::exit(execSelf("exec-sink")); -} -} + void *execFromWorker(void *) { + if (pthread_join(leader, nullptr) != 0) + std::exit(32); + if (! mapAndReport(64)) + std::exit(33); + std::exit(execSelf("exec-sink")); + } +} // namespace #endif int main(int argc, char **argv) { const bool accuracy = argc == 3 && ! strcmp(argv[1], "accuracy"); @@ -153,7 +153,8 @@ int main(int argc, char **argv) { if (pthread_attr_init(&attributes) != 0) return 40; const int sized = pthread_attr_setstacksize(&attributes, 1024 * 1024); - const int created = sized == 0 ? pthread_create(&worker, &attributes, execFromWorker, nullptr) : sized; + const int created = + sized == 0 ? pthread_create(&worker, &attributes, execFromWorker, nullptr) : sized; pthread_attr_destroy(&attributes); if (created != 0) return 40; @@ -211,7 +212,8 @@ int main(int argc, char **argv) { close(ready[0]); if (received != 1 || token != 1) { kill(child, SIGKILL); - while (waitpid(child, nullptr, 0) < 0 && errno == EINTR) {} + while (waitpid(child, nullptr, 0) < 0 && errno == EINTR) { + } return 49; } printf("child-pid=%ld\n", static_cast(child)); diff --git a/unix/watcher_unix.cpp b/unix/watcher_unix.cpp index b6a551a1..0d1a75a1 100644 --- a/unix/watcher_unix.cpp +++ b/unix/watcher_unix.cpp @@ -17,17 +17,17 @@ #include #include #ifdef __linux__ -#include -#include #include #include #include #include -#include +#include +#include #include #include #include #include +#include #include #elif defined(__APPLE__) #include @@ -74,7 +74,7 @@ namespace { BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 387, 1, 0), BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW), BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_TRACE), -#if !defined(__x86_64__) && !defined(__i386__) && !defined(__aarch64__) && !defined(__arm__) +#if ! defined(__x86_64__) && ! defined(__i386__) && ! defined(__aarch64__) && ! defined(__arm__) BPF_STMT(BPF_LD | BPF_W | BPF_ABS, offsetof(seccomp_data, nr)), #ifdef SYS_execveat BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, SYS_execve, 2, 0), @@ -327,7 +327,8 @@ namespace { terminateTracee(tid, traced.at(tid)); signal = 0; } else if (event == PTRACE_EVENT_STOP && ! newborn && - (signal == SIGSTOP || signal == SIGTSTP || signal == SIGTTIN || signal == SIGTTOU)) { + (signal == SIGSTOP || signal == SIGTSTP || signal == SIGTTIN || + signal == SIGTTOU)) { if (ptrace(PTRACE_LISTEN, tid, nullptr, nullptr) < 0 && errno != ESRCH) return -1; continue; @@ -504,10 +505,10 @@ int main(int argc, char **argv) { if (! ready) perror("events arm"); #ifdef __linux__ - if (ready && ptrace(PTRACE_SEIZE, pid, nullptr, - PTRACE_O_TRACEFORK | PTRACE_O_TRACEVFORK | PTRACE_O_TRACECLONE | - PTRACE_O_TRACEEXEC | PTRACE_O_TRACEEXIT | PTRACE_O_TRACESECCOMP | - PTRACE_O_EXITKILL) < 0) { + if (ready && + ptrace(PTRACE_SEIZE, pid, nullptr, + PTRACE_O_TRACEFORK | PTRACE_O_TRACEVFORK | PTRACE_O_TRACECLONE | PTRACE_O_TRACEEXEC | + PTRACE_O_TRACEEXIT | PTRACE_O_TRACESECCOMP | PTRACE_O_EXITKILL) < 0) { perror("ptrace seize"); ready = false; }