From 42b68d0423da30b3b8316bc72eb17d49bea68c6f Mon Sep 17 00:00:00 2001 From: Wleeaf Date: Fri, 20 Nov 2026 13:36:01 +0300 Subject: [PATCH] Wine memory helper: run inside a Proton or Flatpak container When Wine reserves the space a hook needs, Cheat Engine asks Wine itself for the block through a small generated Windows program. For a game in a Proton (Steam Runtime) or Flatpak container, the program could not reach the container's Wine, prefix and wineserver, so this failed with not_supported. The helper now joins the target's namespaces before starting Wine: the user namespace first (its owner may then join the rest), then mount, IPC, network, UTS and PID, with one more fork so the Wine process lives in the container's PID namespace and dies with its parent. The helper file is written to the container's /tmp (else its runtime directory or the prefix) through /proc//root with openat2(RESOLVE_IN_ROOT), so no link in the container leads outside it, and the loader is checked the same way. A failure to enter the container is reported as not_supported. wine_integration calls the helper directly on the busy 64-bit and 32-bit targets and prints whether the target shared our namespaces. The Proton gate requires the helper to pass, and inside the Steam Runtime to have run in the container. Fixes #9 --- CHANGELOG.md | 16 +++ core/autoasm.cpp | 4 +- platform/linux/wine_memory.cpp | 202 ++++++++++++++++++++++++++---- platform/linux/wine_memory.hpp | 8 +- test/proton_compatibility_gate.py | 9 +- test/wine_integration.cpp | 25 ++++ 6 files changed, 232 insertions(+), 32 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1cc62475..edcf8bc1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,22 @@ reimplementation of Cheat Engine). --- +## Unreleased + +### Fixes + +- Memory that Wine commits for a hook (see v1.2.0 and + [#9](https://github.com/wleeaf/cheat-engine-linux/issues/9)) now also works + for a game inside a Proton (Steam Runtime) or Flatpak container. The small + Windows program that asks Wine for the block runs inside the game's + container: it joins the game's user, mount and process namespaces, so it + reaches the container's own Wine, prefix and wineserver, and its file is + written to the container's `/tmp` without following any link out of it. + Entering the container needs the user who started it (Steam and Flatpak run + games as you) or root. + +--- + ## v1.2.0: Cheat Engine's remaining windows, encrypted tables, remote stepping and RPM packages (2026-11-20) The windows this port only partly had (Changed Addresses, Code Filter, Break diff --git a/core/autoasm.cpp b/core/autoasm.cpp index 63ebc8a5..14210ff4 100644 --- a/core/autoasm.cpp +++ b/core/autoasm.cpp @@ -2411,8 +2411,8 @@ AutoAsmResult AutoAssembler::run(ProcessHandle& proc, std::string enableCode, co if (proc.targetDescription().runtime == TargetRuntime::Wine) nearHint += " This Wine version reserves the address space around the program's code for its own " "allocations, and asking Wine for memory there failed. Wine runs that request on one of " - "the program's own threads, so the program must not be stopped, and it works only for a " - "program in this user's own mount namespace, not inside a Proton or Flatpak container " + "the program's own threads, so the program must not be stopped. For a program inside a " + "Proton or Flatpak container, Cheat Engine must run as the user who started it, or as root " "(https://github.com/wleeaf/cheat-engine-linux/issues/9)."; }; auto rollback = [&]() -> AutoAsmResult { diff --git a/platform/linux/wine_memory.cpp b/platform/linux/wine_memory.cpp index 6e27b975..7120d2d8 100644 --- a/platform/linux/wine_memory.cpp +++ b/platform/linux/wine_memory.cpp @@ -5,6 +5,7 @@ #include #include #include +#include #include #include #include @@ -15,12 +16,22 @@ #include #include #include +#include +#include #include #include +#include #include +#include #include #include +#include #include +#include + +#ifndef SYS_openat2 +#define SYS_openat2 437 // the same number on every architecture +#endif namespace ce::os { namespace { @@ -186,12 +197,75 @@ uint32_t windowsProtection(MemProt protection) { return read ? 0x02 : 0x01; // READONLY, NOACCESS } +class Fd { +public: + Fd() = default; + explicit Fd(int fd) : fd_(fd) {} + Fd(Fd&& other) noexcept : fd_(std::exchange(other.fd_, -1)) {} + Fd& operator=(Fd&& other) noexcept { + if (this != &other) { reset(); fd_ = std::exchange(other.fd_, -1); } + return *this; + } + ~Fd() { reset(); } + int get() const { return fd_; } + explicit operator bool() const { return fd_ >= 0; } + void reset() { if (fd_ >= 0) ::close(fd_); fd_ = -1; } +private: + int fd_ = -1; +}; + +// Opens `path` as the process whose root is `root` sees it: absolute symlinks +// and ".." stay inside that root (a container cannot point us at our files). +Fd openInRoot(int root, const std::string& path, int flags) { + struct { uint64_t flags, mode, resolve; } how{static_cast(flags | O_CLOEXEC), 0, 0x10 /* RESOLVE_IN_ROOT */}; + return Fd(static_cast(::syscall(SYS_openat2, root, path.c_str(), &how, sizeof(how)))); +} + struct Launch { std::string loader; std::vector environment; std::optional> switchTo; // when running as root for another user + // A target in a Proton (pressure-vessel) or Flatpak container: its root + // directory, and the namespaces the helper joins, the user namespace + // first since it grants the right to join the others. + Fd root; + std::vector> namespaces; + bool joinsUser = false, joinsPid = false; }; +// A container sees other files at the same paths, runs its own wineserver +// behind its own /tmp, and numbers processes in its own PID namespace, so the +// helper must run in the target's namespaces. Joining a mount namespace needs +// CAP_SYS_ADMIN over it: root has that, and so does the user who created the +// container's user namespace (bwrap, as Flatpak and pressure-vessel use it). +std::expected containerFor(const std::string& proc, Launch& launch) { + auto same = [&](const char* kind) -> std::optional { + struct stat ours{}, theirs{}; + const std::string name = std::string("/ns/") + kind; + if (::stat(("/proc/self" + name).c_str(), &ours) || ::stat((proc + name).c_str(), &theirs)) return std::nullopt; + return ours.st_ino == theirs.st_ino && ours.st_dev == theirs.st_dev; + }; + const auto sameMount = same("mnt"); + if (!sameMount) return std::unexpected(error(std::errc::not_supported)); + if (*sameMount) return {}; + + struct Kind { const char* name; int type; }; + static constexpr Kind kinds[] = {{"user", CLONE_NEWUSER}, {"mnt", CLONE_NEWNS}, {"ipc", CLONE_NEWIPC}, + {"net", CLONE_NEWNET}, {"uts", CLONE_NEWUTS}, {"pid", CLONE_NEWPID}}; + for (const auto& kind : kinds) { + if (same(kind.name).value_or(true)) continue; + Fd fd(::open((proc + "/ns/" + kind.name).c_str(), O_RDONLY | O_CLOEXEC)); + if (!fd) return std::unexpected(error(std::errc::permission_denied)); + launch.joinsUser |= kind.type == CLONE_NEWUSER; + launch.joinsPid |= kind.type == CLONE_NEWPID; + launch.namespaces.emplace_back(std::move(fd), kind.type); + } + if (!launch.joinsUser && ::geteuid() != 0) return std::unexpected(error(std::errc::not_supported)); + launch.root = Fd(::open((proc + "/root").c_str(), O_PATH | O_DIRECTORY | O_CLOEXEC)); + if (!launch.root) return std::unexpected(error(std::errc::permission_denied)); + return {}; +} + std::optional> processOwner(pid_t pid) { std::ifstream status("/proc/" + std::to_string(pid) + "/status"); std::string line; @@ -210,14 +284,8 @@ std::optional> processOwner(pid_t pid) { // its environment (prefix, home, server directory) and its user. std::expected launchFor(pid_t pid) { const std::string proc = "/proc/" + std::to_string(pid); - struct stat ours{}, theirs{}; - if (::stat("/proc/self/ns/mnt", &ours) || ::stat((proc + "/ns/mnt").c_str(), &theirs)) - return std::unexpected(error(std::errc::not_supported)); - // A Proton or Flatpak container sees other files at the same paths. - if (ours.st_ino != theirs.st_ino || ours.st_dev != theirs.st_dev) - return std::unexpected(error(std::errc::not_supported)); - Launch launch; + if (auto container = containerFor(proc, launch); !container) return std::unexpected(container.error()); auto owner = processOwner(pid); if (!owner) return std::unexpected(error(std::errc::no_such_process)); if (owner->first != ::getuid()) { @@ -231,12 +299,20 @@ std::expected launchFor(pid_t pid) { const std::filesystem::path exe = std::filesystem::read_symlink(proc + "/exe", ec); if (ec) return std::unexpected(ec); // wine-preloader and wine64-preloader map the program; the loader beside - // them (wine, wine64) starts a new one. + // them (wine, wine64) starts a new one. In a container both paths are the + // container's own. std::string name = exe.filename().string(); if (const std::string suffix = "-preloader"; name.size() > suffix.size() && name.ends_with(suffix)) name.resize(name.size() - suffix.size()); const auto loader = exe.parent_path() / name; - if (::access(loader.c_str(), X_OK)) return std::unexpected(error(std::errc::not_supported)); + if (launch.root) { + struct stat info{}; + const Fd file = openInRoot(launch.root.get(), loader.string(), O_PATH); + if (!file || ::fstat(file.get(), &info) || !S_ISREG(info.st_mode) || !(info.st_mode & 0111)) + return std::unexpected(error(std::errc::not_supported)); + } else if (::access(loader.c_str(), X_OK)) { + return std::unexpected(error(std::errc::not_supported)); + } launch.loader = loader.string(); std::ifstream environ(proc + "/environ", std::ios::binary); @@ -300,18 +376,49 @@ std::expected, std::error_code> runHelper(pid_t pid, con if (!launch) return std::unexpected(launch.error()); if (everyThreadStopped(pid)) return std::unexpected(error(std::errc::resource_unavailable_try_again)); - // Readable by the target's user when the helper runs as that user. - std::string directory = "/tmp"; - if (!launch->switchTo) - if (const char* runtime = std::getenv("XDG_RUNTIME_DIR"); runtime && *runtime == '/') directory = runtime; - std::string path = directory + "/ce-wine-memory-XXXXXX.exe"; - const int file = ::mkstemps(path.data(), 4); - if (file < 0) return std::unexpected(std::error_code(errno, std::generic_category())); - struct Remove { const std::string& path; ~Remove() { ::unlink(path.c_str()); } } remove{path}; - const bool written = ::fchmod(file, 0644) == 0 && - ::write(file, image.data(), image.size()) == static_cast(image.size()); - ::close(file); - if (!written) return std::unexpected(error(std::errc::io_error)); + // The image goes where the helper's Wine can read it as the target's user: + // our runtime directory, else /tmp; in a container, the container's /tmp + // (else its runtime directory or the prefix, which Wine writes anyway). + auto targetVariable = [&](std::string_view key) -> std::string { + for (const auto& entry : launch->environment) + if (entry.size() > key.size() + 1 && entry.starts_with(key) && entry[key.size()] == '=' && entry[key.size() + 1] == '/') + return entry.substr(key.size() + 1); + return {}; + }; + std::vector directories; + if (launch->root) { + directories = {"/tmp", targetVariable("XDG_RUNTIME_DIR"), targetVariable("WINEPREFIX")}; + } else { + if (const char* runtime = std::getenv("XDG_RUNTIME_DIR"); !launch->switchTo && runtime && *runtime == '/') + directories.emplace_back(runtime); + directories.emplace_back("/tmp"); + } + Fd directory; + std::string name, path; + for (const auto& candidate : directories) { + if (candidate.empty()) continue; + Fd folder = launch->root ? openInRoot(launch->root.get(), candidate, O_PATH | O_DIRECTORY) + : Fd(::open(candidate.c_str(), O_PATH | O_DIRECTORY | O_CLOEXEC)); + if (!folder) continue; + std::random_device random; + char unique[48]; + std::snprintf(unique, sizeof(unique), "ce-wine-memory-%08x%08x.exe", random(), random()); + Fd file(::openat(folder.get(), unique, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0644)); + if (!file) continue; + const bool written = ::fchmod(file.get(), 0644) == 0 && + ::write(file.get(), image.data(), image.size()) == static_cast(image.size()); + if (!written) { + ::unlinkat(folder.get(), unique, 0); + return std::unexpected(error(std::errc::io_error)); + } + directory = std::move(folder); + name = unique; + path = candidate + (candidate.ends_with('/') ? "" : "/") + name; + break; + } + if (!directory) return std::unexpected(error(std::errc::permission_denied)); + struct Remove { const Fd& directory; const std::string& name; ~Remove() { ::unlinkat(directory.get(), name.c_str(), 0); } } + remove{directory, name}; // Everything the child needs is built before fork: after it, only // async-signal-safe calls. @@ -322,13 +429,46 @@ std::expected, std::error_code> runHelper(pid_t pid, con int output[2]; if (::pipe2(output, O_CLOEXEC)) return std::unexpected(std::error_code(errno, std::generic_category())); const int null = ::open("/dev/null", O_RDWR | O_CLOEXEC); + // Exit codes of the child before it starts Wine. + constexpr int kSwitchFailed = 126, kJoinFailed = 125, kForkFailed = 124; const pid_t child = ::fork(); if (child == 0) { if (null >= 0) { ::dup2(null, STDIN_FILENO); ::dup2(null, STDERR_FILENO); } ::dup2(output[1], STDOUT_FILENO); - if (launch->switchTo && - (::setgroups(0, nullptr) || ::setgid(launch->switchTo->second) || ::setuid(launch->switchTo->first))) - ::_exit(126); + auto switchUser = [&] { + return !launch->switchTo || + (!::setgroups(0, nullptr) && !::setgid(launch->switchTo->second) && !::setuid(launch->switchTo->first)); + }; + // The target's user owns its user namespace and may join it; without + // one, only root can enter the container, so switch after. + if (launch->joinsUser && !switchUser()) ::_exit(kSwitchFailed); + // The user, mount and PID namespaces are what Wine needs (files, the + // server socket, process ids); the others are joined when allowed. + for (const auto& [fd, type] : launch->namespaces) + if (::setns(fd.get(), type) && (type == CLONE_NEWUSER || type == CLONE_NEWNS || type == CLONE_NEWPID)) + ::_exit(kJoinFailed); + if (!launch->joinsUser && !switchUser()) ::_exit(kSwitchFailed); + if (launch->root && ::chdir("/")) ::_exit(kJoinFailed); + if (launch->joinsPid) { + // Only children enter the PID namespace. _Fork runs no fork + // handlers (other threads of ours may hold their locks), and the + // Wine process dies with this one when we give up waiting. +#if defined(__GLIBC__) && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 34)) + const pid_t inner = ::_Fork(); +#else + const pid_t inner = ::fork(); +#endif + if (inner < 0) ::_exit(kForkFailed); + if (inner == 0) { + ::prctl(PR_SET_PDEATHSIG, SIGKILL); + ::execve(argv[0], argv.data(), envp.data()); + ::_exit(127); + } + ::close(STDOUT_FILENO); + int status = 0; + while (::waitpid(inner, &status, 0) < 0 && errno == EINTR) {} + ::_exit(WIFEXITED(status) ? WEXITSTATUS(status) : 128 + WTERMSIG(status)); + } ::execve(argv[0], argv.data(), envp.data()); ::_exit(127); } @@ -355,14 +495,24 @@ std::expected, std::error_code> runHelper(pid_t pid, con bytes.append(chunk, static_cast(n)); } ::close(output[0]); + // The output closes as the helper exits; give it a moment to be reaped + // so a failure before Wine started can be told apart. int status = 0; - if (::waitpid(child, &status, WNOHANG) == 0) { + pid_t reaped = 0; + for (int attempt = 0; attempt < 50 && (reaped = ::waitpid(child, &status, WNOHANG)) == 0; ++attempt) + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + if (reaped == 0) { ::kill(child, SIGKILL); ::waitpid(child, &status, 0); } const auto magic = bytes.find(std::string_view(kResultMagic, sizeof(kResultMagic))); if (magic == std::string::npos || bytes.size() - magic < 24) { - ce::log::warn(ce::log::Cat::Memory, "Wine memory helper for pid {} gave no result (status {:#x})", pid, status); + const int code = WIFEXITED(status) ? WEXITSTATUS(status) : -1; + ce::log::warn(ce::log::Cat::Memory, "Wine memory helper for pid {} gave no result (status {:#x}{})", pid, status, + code == kJoinFailed ? ", could not enter the target's container" : + code == kSwitchFailed ? ", could not switch to the target's user" : ""); + if (code == kJoinFailed) return std::unexpected(error(std::errc::not_supported)); + if (code == kSwitchFailed) return std::unexpected(error(std::errc::permission_denied)); return std::unexpected(error(std::errc::io_error)); } std::array result{}; diff --git a/platform/linux/wine_memory.hpp b/platform/linux/wine_memory.hpp index 899949b2..608be540 100644 --- a/platform/linux/wine_memory.hpp +++ b/platform/linux/wine_memory.hpp @@ -30,9 +30,11 @@ std::expected wineWindowsProcessId(pid_t pid); /// Commits `size` bytes in the Wine process `pid` through Wine. The block /// starts in [low, high], nearest to `preferred`, searched in 64 KiB steps -/// (Windows' allocation granularity). Fails with not_supported when the -/// helper cannot run for this target: another mount namespace (a Proton or -/// Flatpak container), another user, or no Wine loader beside its executable. +/// (Windows' allocation granularity). A target in a Proton (pressure-vessel) +/// or Flatpak container gets the helper run inside its namespaces. Fails with +/// not_supported when the helper cannot run for this target: a container we +/// may not enter (no user namespace of the target's user, and not root), +/// another user while not root, or no Wine loader beside its executable. std::expected wineVirtualAlloc(pid_t pid, size_t size, MemProt protection, uintptr_t preferred, uintptr_t low, uintptr_t high); diff --git a/test/proton_compatibility_gate.py b/test/proton_compatibility_gate.py index cfc95252..af65e84c 100644 --- a/test/proton_compatibility_gate.py +++ b/test/proton_compatibility_gate.py @@ -124,8 +124,15 @@ def run_proton(build, proton, work, fixtures, report, client, in_runtime, runtim print(stdout, end="", flush=True) if stderr: print(stderr, end="", flush=True) + # Wine's own allocation helper runs where the program runs: inside + # the container when Proton is in the Steam Runtime (issue #9). A + # legacy 32-bit Unix loader never uses it. + namespace = "container" if in_runtime else "shared" + helper_widths = (8,) if legacy else (8, 4) if (code != 0 or "FAILED:" in stdout or "0 failed Wine integration checks\n" not in stdout or - any(f"WINE_BUSY_RESULT=PASSED programWidth={width}\n" not in stdout for width in (8, 4))): + any(f"WINE_BUSY_RESULT=PASSED programWidth={width}\n" not in stdout for width in (8, 4)) or + any(f"WINE_HELPER_RESULT=PASSED programWidth={width} namespace={namespace}\n" not in stdout + for width in helper_widths)): raise RuntimeError(f"{proton.name} compatibility checks failed") entry["checks"] = sum(line.startswith("OK: ") for line in stdout.splitlines()) # The same programs through the user-facing CLI, Lua and (when diff --git a/test/wine_integration.cpp b/test/wine_integration.cpp index a91deee8..f25d1649 100644 --- a/test/wine_integration.cpp +++ b/test/wine_integration.cpp @@ -1,6 +1,7 @@ #include "platform/linux/linux_process.hpp" #include "platform/linux/ptrace_wrapper.hpp" #include "platform/linux/target_syscall.hpp" +#include "platform/linux/wine_memory.hpp" #include "arch/target_arch.hpp" #include "core/autoasm.hpp" #include "core/expression.hpp" @@ -31,6 +32,7 @@ #include #include #include +#include #include #include @@ -506,6 +508,29 @@ static void exercise(const char* wine, const char* path, unsigned width, bool re restoredContext->instructionPointer()>=code-0x300 && restoredContext->instructionPointer()(block ? *block : 0),sizeof(observed)}; + bool usable=block && *block<=high && process.write(*block,&sentinel,sizeof(sentinel)) && + process_vm_readv(pid,&local,1,&remote,1,0)==sizeof(observed) && observed==sentinel; + check(usable,"Wine's own VirtualAllocEx commits a block in the busy target through the helper"); + auto released=block ? os::wineVirtualFree(pid,*block) : Result(std::unexpected(block.error())); + if (block && !released) printf("Wine helper release error: %s\n",released.error().message().c_str()); + check(released && process_vm_readv(pid,&local,1,&remote,1,0)<0, + "Wine's own VirtualFreeEx releases the helper's block"); + printf("WINE_HELPER_RESULT=%s programWidth=%u namespace=%s\n",usable && released ? "PASSED" : "FAILED",width, + contained ? "container" : "shared"); + } uint32_t zero=0; auto cleared=process.write(busyFlag,&zero,sizeof(zero)); check(cleared && *cleared==sizeof(zero) && fixture.value('r',31415933),