diff --git a/.github/workflows/macos-qt6.yml b/.github/workflows/macos-qt6.yml index da0ece58..8e7ed49f 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: @@ -50,22 +53,16 @@ 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 - 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 diff --git a/.github/workflows/watcher_linux.yml b/.github/workflows/watcher_linux.yml index 0967e6ca..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/**"] + paths: ["unix/**", "src/core/memoryunits.h"] pull_request: branches: ["master"] - paths: ["unix/**"] + paths: ["unix/**", "src/core/memoryunits.h"] workflow_dispatch: env: diff --git a/.github/workflows/watcher_macos.yml b/.github/workflows/watcher_macos.yml index d8e26fef..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/**"] + paths: ["unix/**", "src/core/memoryunits.h"] pull_request: branches: ["master"] - paths: ["unix/**"] + paths: ["unix/**", "src/core/memoryunits.h"] workflow_dispatch: env: 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/CMakeLists.txt b/CMakeLists.txt index 523dd1fe..2b8d50a5 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -40,6 +40,10 @@ set(CMAKE_CXX_STANDARD 23) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_EXTENSIONS OFF) +if(MINGW) + add_compile_definitions(__USE_MINGW_ANSI_STDIO=1) +endif() + set(CMAKE_EXPORT_COMPILE_COMMANDS ON) cmake_policy(SET CMP0072 NEW) diff --git a/src/core/casejudger.cpp b/src/core/casejudger.cpp index 4a5a0b4a..ab21a8af 100644 --- a/src/core/casejudger.cpp +++ b/src/core/casejudger.cpp @@ -721,6 +721,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 39b4e854..8a9a6be0 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/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.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_unix.cpp b/src/core/processrunner_unix.cpp index 486e2926..db4fb8f1 100644 --- a/src/core/processrunner_unix.cpp +++ b/src/core/processrunner_unix.cpp @@ -98,7 +98,8 @@ ProcessRunnerResult UnixProcessRunner::run() { argumentsList << config.outputFileName; } - argumentsList << QString("%1").arg(extraTime); + if (! config.interpreterAsWatcher) + argumentsList << QString("%1").arg(extraTime); qDebug() << argumentsList; @@ -161,7 +162,8 @@ ProcessRunnerResult UnixProcessRunner::run() { argumentsList << config.outputFileName; } - argumentsList << QString("%1").arg(extraTime); + if (! config.interpreterAsWatcher) + argumentsList << QString("%1").arg(extraTime); qDebug() << argumentsList; @@ -171,7 +173,7 @@ ProcessRunnerResult UnixProcessRunner::run() { #endif - if (! runner.waitForStarted(-1)) { + if (! runner.waitForStarted(5000)) { res.score = 0; res.result = CannotStartProgram; res.message = "Start runner failed"; @@ -182,9 +184,10 @@ ProcessRunnerResult UnixProcessRunner::run() { QElapsedTimer timer; timer.start(); - // The watcher itself enforces the wall clock (timeLimit + extraTime) and exits shortly - // after the timer fires; this loop only guards against a hung watcher, with 1s of slack. - long long killTimeLimit = 1LL * config.timeLimit + extraTime + 1000; + // Leave room for the watcher's explicit wall deadline and bounded reaping. + long long killTimeLimit = 1LL * config.timeLimit + extraTime + 5000LL; + if (config.interpreterAsWatcher) + killTimeLimit = qMax(2000LL, 3LL * config.timeLimit) + extraTime + 5000LL; while (timer.elapsed() <= killTimeLimit) { if (runner.waitForFinished(10)) { isProgramFinishedInExtraTimeLimit = true; @@ -193,15 +196,20 @@ ProcessRunnerResult UnixProcessRunner::run() { if (cancellation.isCanceled()) { runner.terminate(); - runner.waitForFinished(-1); - + if (! runner.waitForFinished(2500)) { + runner.kill(); + runner.waitForFinished(-1); + } return res; } } 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 @@ -227,7 +235,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/src/core/processrunner_win.cpp b/src/core/processrunner_win.cpp index fa6fd7e7..d999030d 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 "memoryunits.h" #include "windowsprocessutils.h" #include "windowssandbox.h" @@ -18,7 +19,6 @@ #include #include #include -#include #include #include @@ -30,6 +30,51 @@ using namespace Lemon::Windows; +namespace { + 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; + } + 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); + 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) { + 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 + ProcessRunnerResult WinProcessRunner::run() { ProcessRunnerResult res; res.result = CorrectAnswer; @@ -94,7 +139,15 @@ ProcessRunnerResult WinProcessRunner::run() { CloseHandle(siex.StartupInfo.hStdError); }); - if (sandbox && ! sandbox->prepareProcess(siex, res.message)) { + Lemon::Execution::Bytes memoryLimit; + 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; + } + if (sandbox && ! sandbox->prepareProcess(siex, job.get(), res.message)) { res.result = CannotStartProgram; return res; } @@ -106,8 +159,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(); @@ -120,70 +173,86 @@ ProcessRunnerResult WinProcessRunner::run() { } auto closeProcessHandle = qScopeGuard([&] { - if (sandbox) - WaitForSingleObject(pi.hProcess, 5000); CloseHandle(pi.hProcess); 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; - } + auto reap = qScopeGuard([&] { + 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; + const auto initialMemory = sampleMemory(pi.hProcess); + if (initialMemory < 0) { + res.result = CannotStartProgram; + res.message = "Process statistics unavailable"; + return res; } - - bool isProgramFinishedInExtraTimeLimit = false; - QElapsedTimer timer; - timer.start(); - - while (timer.elapsed() <= config.timeLimit + extraTime) { - if (WaitForSingleObject(pi.hProcess, 0) == WAIT_OBJECT_0) { - isProgramFinishedInExtraTimeLimit = true; - break; - } - - 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; - } - } - - if (cancellation.isCanceled()) { - TerminateProcess(pi.hProcess, 0); - 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); + res.result = CannotStartProgram; + res.message = "Cannot attach or resume process"; + if (config.stopToken.stop_requested()) { + res.result = CorrectAnswer; + res.message.clear(); } - - QThread::msleep(10); + return res; } - - if (! isProgramFinishedInExtraTimeLimit) { - TerminateProcess(pi.hProcess, 0); - - res.score = 0; + Handle deadline(CreateWaitableTimerW(nullptr, TRUE, nullptr)); + LARGE_INTEGER due{}; + // Negative values specify a relative interval in 100 ns units. + due.QuadPart = -qMax(1LL, (static_cast(config.timeLimit) + extraTime) * 10000LL); + 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()}; + 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; - res.timeUsed = -1; + } + auto sample = sampleMemory(pi.hProcess); + res.memoryUsed = sample; + if (res.result == TimeLimitExceeded) + return res; + if (sample < 0) { + res.result = CannotStartProgram; + res.message = "Process statistics unavailable"; + return res; + } + if (memoryLimit >= 0 && res.memoryUsed > memoryLimit) { + res.result = MemoryLimitExceeded; return res; } - unsigned long exitCode; GetExitCodeProcess(pi.hProcess, &exitCode); @@ -199,7 +268,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 +283,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/taskjudger.cpp b/src/core/taskjudger.cpp index 78fc2a38..98d72acb 100644 --- a/src/core/taskjudger.cpp +++ b/src/core/taskjudger.cpp @@ -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, 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/src/core/windowssandbox.cpp b/src/core/windowssandbox.cpp index f6d4c590..73d50b7c 100644 --- a/src/core/windowssandbox.cpp +++ b/src/core/windowssandbox.cpp @@ -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,8 +248,6 @@ struct WindowsSandbox::Data { session(config.sandboxSession ? config.sandboxSession : WindowsSandbox::createSession()) {} ~Data() { - job.reset(); - if (! workingDirectory.isEmpty()) { QMutexLocker lock(&permissionsMutex); revokeSid(workingDirectory, packageSid, true); @@ -295,7 +293,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 +303,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 +319,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 +672,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; diff --git a/tests/integrated-test/main.cpp b/tests/integrated-test/main.cpp index 21be5d14..58b55ca5 100644 --- a/tests/integrated-test/main.cpp +++ b/tests/integrated-test/main.cpp @@ -201,13 +201,19 @@ 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}}, + {CorrectAnswer, TimeLimitExceeded, allocationVerdict, WrongAnswer, RunTimeError, WrongAnswer}}, {"user2", 1, CompileSuccessfully, @@ -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/CMakeLists.txt b/tests/windows-sandbox/CMakeLists.txt index 522ab307..6ac6a4f6 100644 --- a/tests/windows-sandbox/CMakeLists.txt +++ b/tests/windows-sandbox/CMakeLists.txt @@ -1,18 +1,22 @@ 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) -endif() -target_link_libraries(sandbox-helper PRIVATE advapi32 ws2_32) +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() + if(MINGW) + target_link_options(${helper} PRIVATE -municode -static -fms-extensions) + 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 4f3fe5a9..ea7d395c 100644 --- a/tests/windows-sandbox/helper.cpp +++ b/tests/windows-sandbox/helper.cpp @@ -10,16 +10,26 @@ #include #include #include +// 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) { -#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; } @@ -42,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]); @@ -288,18 +308,75 @@ int wmain(int argc, wchar_t **argv) { return int(code); } - 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) { - Sleep(100); - return 12; - } - for (int j = 0; j < 1024 * 1024; j += 4096) - memory[j] = 1; + 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); + if (p) + 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; } - return 13; + printf("reference-bytes=%llu allocation-bytes=%llu\n", + static_cast(counters.PeakPagefileUsage), + static_cast(bytes)); + fflush(stdout); + 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, + 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); + UnmapViewOfFile(const_cast(pages)); + CloseHandle(mapping); + return measured ? 0 : 42; } return 14; } diff --git a/tests/windows-sandbox/main.cpp b/tests/windows-sandbox/main.cpp index 403ebfa4..404286a3 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,54 @@ 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 { @@ -137,12 +186,13 @@ 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; @@ -760,11 +810,70 @@ 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))); - QCOMPARE(result.memoryUsed, qint64(memory.PeakWorkingSetSize)); - QVERIFY(result.memoryUsed < 64ll * 1024 * 1024); + QVERIFY(GetProcessMemoryInfo(primary.get(), reinterpret_cast(&memory), + sizeof(memory))); + QCOMPARE(result.memoryUsed, qint64(memory.PeakPagefileUsage)); + 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(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(); + 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); + 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(read(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); + 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 +885,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,14 +893,86 @@ class WindowsSandboxTests : public QObject { auto cpu = config("burn 3000"); cpu.timeLimit = 100; QCOMPARE(run(cpu).result, TimeLimitExceeded); - auto memory = config("memory"); - memory.memoryLimit = 24; - QCOMPARE(run(memory).result, MemoryLimitExceeded); } - void cancellation() { + 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; + 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")); @@ -799,29 +980,40 @@ 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(); + stopSource.request_stop(); }); const auto result = ProcessRunner::create(cfg, promise.future())->run(); 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); QCOMPARE(result.timeUsed, -1); - QCOMPARE(result.memoryUsed, -1); + QVERIFY(result.memoryUsed > 0); } void runtimeDirectoryWithInput() { @@ -865,6 +1057,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(); @@ -874,6 +1068,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(); diff --git a/unix/memoryusage.h b/unix/memoryusage.h new file mode 100644 index 00000000..8ad16b15 --- /dev/null +++ b/unix/memoryusage.h @@ -0,0 +1,6 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +#pragma once +#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 2c5edfbb..1aada9b5 100644 --- a/unix/test/CMakeLists.txt +++ b/unix/test/CMakeLists.txt @@ -34,3 +34,15 @@ 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) +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 new file mode 100644 index 00000000..c3d79cb5 --- /dev/null +++ b/unix/test/memory_cases.cpp @@ -0,0 +1,279 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +#include +#include +#include +#include +#include +#include +#include +#ifdef __APPLE__ +#include +#else +#include +#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")); + } +} // namespace +#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) + 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); + munmap(mapping, bytes); + 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); + raise(SIGSTOP); + puts("resumed"); + return 0; + } +#endif + 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; + 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"); + return 0; + } + if (! strcmp(argv[1], "sleep")) { + 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 new file mode 100644 index 00000000..e1fa0e79 --- /dev/null +++ b/unix/test/scripts/memory.py @@ -0,0 +1,99 @@ +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.Popen(['./watcher_unix', './memory_cases', mode, '', output, error, # nosec B603 + '1000', str(limit), '1000', str(limit), '', '', '0'], + 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': + 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 + 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 + assert run('sleep')[0] == 3 diff --git a/unix/test/scripts/memory_accuracy.py b/unix/test/scripts/memory_accuracy.py new file mode 100644 index 00000000..183c907a --- /dev/null +++ b/unix/test/scripts/memory_accuracy.py @@ -0,0 +1,81 @@ +import os +import pathlib +import signal +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: + 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", "", "", "0"], + stdout=subprocess.PIPE, stderr=subprocess.PIPE, start_new_session=True, + ) + 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]) + 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"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/test/scripts/mle_static.py b/unix/test/scripts/mle_static.py index de2f1f58..0a7a6993 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/test/scripts/stop_continue.py b/unix/test/scripts/stop_continue.py new file mode 100644 index 00000000..17d68ce2 --- /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', '', '', '0'], + 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_linux.cpp b/unix/watcher_linux.cpp index cd113c8b..2105d8bd 100644 --- a/unix/watcher_linux.cpp +++ b/unix/watcher_linux.cpp @@ -5,94 +5,37 @@ * SPDX-License-Identifier: GPL-3.0-or-later * */ - -#include -#include +#include "memoryusage.h" +#include #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; +using namespace Lemon::Execution; +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) + 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 = std::max(result, Bytes(kib) * KiB); + } + fclose(file); + return result; } -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; +bool applyMemoryLimit(Bytes limit) { + if (limit >= 0) { + rlimit memory{static_cast(limit), static_cast(limit)}; + if (setrlimit(RLIMIT_AS, &memory) != 0) + return false; } - - 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; + 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; } - -ssize_t getMemoryRLimit(ssize_t memoryLimitInMB) { return memoryLimitInMB * 1024 * 1024; } - -size_t getMaxRSSInByte(long ru_maxrss) { return ru_maxrss * 1024; } diff --git a/unix/watcher_macos.mm b/unix/watcher_macos.mm index 73fc1be3..11da2a4b 100644 --- a/unix/watcher_macos.mm +++ b/unix/watcher_macos.mm @@ -5,144 +5,15 @@ * 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) { +#include "memoryusage.h" +#include +#include +using namespace Lemon::Execution; +Bytes sampleMemory(pid_t pid) { + proc_taskinfo info{}; + if (proc_pidinfo(pid, PROC_PIDTASKINFO, 0, &info, sizeof(info)) != sizeof(info)) 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; -} - -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; + return static_cast(info.pti_resident_size); } - -ssize_t getMemoryRLimit(ssize_t memoryLimitInMB) { return memoryLimitInMB * 1024 * (isAppleSilicon ? 4 : 1); } - -size_t getMaxRSSInByte(long ru_maxrss) { return ru_maxrss / (isAppleSilicon ? 4 : 1); } +// macOS intentionally has no memory prelimit. +bool applyMemoryLimit(Bytes) { return true; } diff --git a/unix/watcher_unix.cpp b/unix/watcher_unix.cpp index 08742b6e..6280d389 100644 --- a/unix/watcher_unix.cpp +++ b/unix/watcher_unix.cpp @@ -5,342 +5,613 @@ * SPDX-License-Identifier: GPL-3.0-or-later * */ - -#include +#include "memoryusage.h" +#include #include #include -#include #include #include -#include -#include +#include #include -#include #include -#include -#include #include -#if defined(__linux__) -#include +#include +#ifdef __linux__ +#include +#include +#include +#include +#include #include +#include +#include +#include +#include #include #include -#elif defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || \ - defined(__DragonFly__) +#elif defined(__APPLE__) #include #endif -#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]: 选手程序只写的文件 - * argv[12]: wall clock 额外超时时间(毫秒) - */ -auto main(int argc, char *argv[]) -> int { - if (argc != 13) { - printf("-1\n-1\n"); - fprintf(stderr, "Expected 12 arguments, found %d\n", argc - 1); - return RS_FAIL; +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; } - 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]; - long long extraTimeMs = std::stoll(argv[12]); - - 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) { - printf("-1\n-1\n"); - fprintf(stderr, "Error in calculating static memory usage\n"); - return RS_FAIL; +#endif + enum { RS_AC, RS_FAIL, RS_RE, RS_TLE, RS_MLE }; + class Events { + int signals[4] = {SIGCHLD, SIGTERM, SIGINT, SIGABRT}; + sigset_t previous{}; + bool masked = false; +#ifdef __linux__ + int descriptors[2] = {-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; } - 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; + 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] = 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) + 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 } - } - - ssize_t actualMemoryRLimit = getMemoryRLimit(memoryLimitMib); - -#if defined(__linux__) - int childPfd = -1; - struct clone_args args{}; - args.flags = CLONE_PIDFD; - args.pidfd = reinterpret_cast(&childPfd); - args.exit_signal = SIGCHLD; - pid = syscall(SYS_clone3, &args, sizeof(args)); - - if (pid < 0) { - perror("clone3"); - printf("-1\n-1\n"); - return RS_FAIL; - } + bool arm(long long milliseconds, bool sampling) { +#ifdef __linux__ + (void)sampling; + itimerspec spec{}; + spec.it_value = {milliseconds / 1000, (milliseconds % 1000) * 1000000}; + return timerfd_settime(descriptors[0], 0, &spec, nullptr) == 0; #else - pid = fork(); - - if (pid < 0) { - perror("fork"); + 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[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 < 2; ++i) { + if (ready[i].revents & (POLLERR | POLLHUP | POLLNVAL)) { + errno = EIO; + return -1; + } + if (! (ready[i].revents & POLLIN)) + continue; + if (i == 0) { + uint64_t count; + if (read(descriptors[i], &count, sizeof(count)) != sizeof(count)) + return -1; + events |= Deadline; + } else { + signalfd_siginfo info; + while (read(descriptors[1], &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; + int status = 0; + rusage usage{}; + bool reaped = false; + bool cleaned = false; + Events &events; + Bytes peak = -1; +#ifdef __linux__ + 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.emplace(pid, pid); +#endif + } + ~UnixProcess() { killAndReap(); } + bool finished() const { return reaped; } + bool allReaped() const { +#ifdef __linux__ + return drained && traced.empty() && reaped; +#else + return reaped; +#endif + } +#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 (;;) { + 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; + } + 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; + } + 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 && ! 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; + peak = std::max(peak, memory); + } + 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); + if (result == pid) { + reaped = true; + return 1; + } + if (result < 0 && errno != EINTR) + return -1; + return 0; +#endif + } + bool killAndReap() { + if (cleaned) + return allReaped(); + cleaned = true; + kill(-pid, SIGKILL); + if (! reaped) + kill(pid, SIGKILL); +#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(true) < 0) + return false; + if (allReaped()) + break; + int event = events.wait(); + if (event < 0) { + perror("reaping wait"); + return false; + } + if (event & Events::Deadline) { + if (poll(true) < 0) + return false; + break; + } + } + return allReaped(); + } + }; + struct ChildError { + int stage; + int error; + }; +} // namespace +int main(int argc, char **argv) { + if (argc != 13) { printf("-1\n-1\n"); + fprintf(stderr, "Expected 12 arguments, found %d\n", argc - 1); return RS_FAIL; } -#endif - - if (pid > 0) { - // Parent process - signal(SIGINT, cleanUp); - signal(SIGABRT, cleanUp); - signal(SIGTERM, cleanUp); - struct rusage usage{}; - int status = 0; - - // Time limit is enforced by a wall-clock timer instead of `setrlimit(RLIMIT_CPU)`: - // RLIMIT_CPU counts CPU time while the judge measures user time, and a program that - // merely sleeps never hits it. - long long wallClockMs = timeLimitMs + extraTimeMs; -#if defined(__linux__) - int timerFd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK | TFD_CLOEXEC); - if (timerFd < 0) { - perror("timerfd_create"); - kill(pid, SIGKILL); - wait4(pid, &status, 0, nullptr); - close(childPfd); + try { + long long timeLimit = std::stoll(argv[6]); + int extraTime = std::stoi(argv[12]); + Bytes limit; + if (! memoryBytes(std::stoll(argv[7]), limit) || timeLimit < 0 || timeLimit > 86400000LL || + extraTime < 0) { printf("-1\n-1\n"); return RS_FAIL; } - - struct itimerspec ts{}; - ts.it_value.tv_sec = wallClockMs / 1000; - ts.it_value.tv_nsec = (wallClockMs % 1000) * 1000000; - if (timerfd_settime(timerFd, 0, &ts, nullptr) < 0) { - perror("timerfd_settime"); - kill(pid, SIGKILL); - wait4(pid, &status, 0, nullptr); - close(childPfd); - close(timerFd); + int errors[2]; + if (pipe(errors) != 0) { + perror("pipe"); printf("-1\n-1\n"); return RS_FAIL; } - - struct pollfd pfds[2]{}; - pfds[0].fd = childPfd; - pfds[0].events = POLLIN; - pfds[1].fd = timerFd; - pfds[1].events = POLLIN; - - int pollResult; - do { - pollResult = poll(pfds, 2, -1); - } while (pollResult < 0 && errno == EINTR); - - if (pollResult < 0) { - perror("poll"); - kill(pid, SIGKILL); - wait4(pid, &status, 0, nullptr); - close(childPfd); - close(timerFd); + 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"); return RS_FAIL; } - - bool childExited = pfds[0].revents & POLLIN; - bool timedOut = pfds[1].revents & POLLIN; - - if (! childExited) - kill(pid, SIGKILL); - - if (wait4(pid, &status, 0, &usage) == -1) { - perror("wait4"); - close(childPfd); - close(timerFd); + Events events; + if (! events.initialize()) { + perror("events"); + close(errors[0]); + close(errors[1]); printf("-1\n-1\n"); return RS_FAIL; } - - close(childPfd); - close(timerFd); - - // If the watcher is scheduled late, the pidfd and the timer may become readable in - // the same poll round. Since the child has already exited, classify it normally - // instead of reporting a false TLE; the normal path still checks the measured time. - if (timedOut && ! childExited) { - printf("-1\n-1\n"); - return RS_TLE; - } -#elif defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || \ - defined(__DragonFly__) - int kq = kqueue(); - if (kq < 0) { - perror("kqueue"); - kill(pid, SIGKILL); - wait4(pid, &status, 0, nullptr); +#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; } - - struct kevent changes[2]; - EV_SET(&changes[0], pid, EVFILT_PROC, EV_ADD | EV_ONESHOT, NOTE_EXIT, 0, NULL); - EV_SET(&changes[1], 0, EVFILT_TIMER, EV_ADD | EV_ONESHOT, 0, wallClockMs, NULL); - - struct kevent events[2]; - int n; - do { - n = kevent(kq, changes, 2, events, 2, NULL); - } while (n < 0 && errno == EINTR); - - if (n < 0) { - perror("kevent"); - kill(pid, SIGKILL); - wait4(pid, &status, 0, nullptr); - close(kq); +#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; } - - bool childExited = false; - bool timedOut = false; - for (int i = 0; i < n; i++) { - if (events[i].filter == EVFILT_PROC) - childExited = true; - else if (events[i].filter == EVFILT_TIMER) - timedOut = true; - } - - if (timedOut && ! childExited) - kill(pid, SIGKILL); - - if (wait4(pid, &status, 0, &usage) == -1) { - perror("wait4"); - close(kq); - 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) { + 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__ + 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]); + if (! installExecTrace()) + fail(9); + // Disable dump generation, including piped core handlers. + if (prctl(PR_SET_DUMPABLE, 0) != 0) + fail(6); +#endif + rlimit core{0, 0}; + if (setrlimit(RLIMIT_CORE, &core) != 0) + fail(7); + if (! applyMemoryLimit(limit)) + fail(3); + // 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(kq); - - if (timedOut && ! childExited) { - printf("-1\n-1\n"); - return RS_TLE; + 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(1LL, timeLimit + extraTime), true); + 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) { + perror("ptrace seize"); + ready = false; } -#else - if (wait4(pid, &status, 0, &usage) == -1) { - printf("-1\n-1\n"); - perror("wait4"); - return RS_FAIL; + 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; - 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; +#ifdef __APPLE__ + event = Events::Sample; + int missing = 0; +#endif + ChildError childError{}; + bool setupFailed = false; + for (;;) { + if (! ready) { + verdict = RS_FAIL; + break; } - if (timeUsedMs > timeLimitMs) { - return RS_TLE; +#ifdef __APPLE__ + auto sample = event & Events::Sample ? sampleMemory(pid) : Bytes(-1); + peak = std::max(peak, sample); +#endif + /* Flawfinder: ignore */ + if (read(errors[0], &childError, sizeof(childError)) == sizeof(childError)) + setupFailed = true; + int finished = process.poll(); + if (setupFailed || finished < 0) { + verdict = RS_FAIL; + break; } - if (memoryUsed > memoryLimitMib * 1024 * 1024) { - return RS_MLE; + if (limit >= 0 && peak > limit) { + verdict = RS_MLE; + 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) == SIGKILL || WTERMSIG(status) == SIGABRT) { - return RS_MLE; + if (finished) + break; + if (event & Events::Deadline) { + verdict = RS_TLE; + break; + } + if (event & Events::Stop) { + verdict = RS_FAIL; + break; + } +#ifdef __APPLE__ + if (event & Events::Sample) + missing = sample < 0 ? missing + 1 : 0; + if (missing >= 10) { + fprintf(stderr, "Memory statistics unavailable\n"); + verdict = RS_FAIL; + break; + } +#endif + event = events.wait(); + if (event < 0) { + perror("events wait"); + verdict = RS_FAIL; + break; } - return RS_RE; - } - } else { - // Child process - std::string finalStdinRedirect = stdinRedirect.empty() ? "/dev/null" : stdinRedirect; - if (freopen(finalStdinRedirect.c_str(), "r", stdin) == NULL) { - perror("freopen stdin"); - exit(RS_FAIL); - } - std::string finalStdoutRedirect = stdoutRedirect.empty() ? "/dev/null" : stdoutRedirect; - if (freopen(finalStdoutRedirect.c_str(), "w", stdout) == NULL) { - perror("freopen stdout"); - exit(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{}; - - 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}; + // Catch setup errors delivered concurrently with the final wait. + /* 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"); + if (setupFailed) { + fprintf(stderr, "Child setup stage %d failed: errno %d\n", childError.stage, childError.error); + verdict = RS_FAIL; } - - setrlimit(RLIMIT_AS, &memlim); - setrlimit(RLIMIT_STACK, &stalim); - - if (execlp("bash", "bash", "-c", runCmd.c_str(), NULL) == -1) { - perror("execlp"); - exit(RS_FAIL); + if (process.reaped) { +#ifdef __APPLE__ + peak = std::max(peak, static_cast(process.usage.ru_maxrss)); +#endif + if (verdict == RS_AC) { + if (limit >= 0 && peak > limit) + verdict = RS_MLE; + 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(peak)); + return verdict; + } catch (...) { + printf("-1\n-1\n"); + fprintf(stderr, "Invalid watcher arguments\n"); + return RS_FAIL; } - - return 0; }