fix(native): programs started through the rootfs loader show their own command line (#3055)

* fix(native): programs started through the rootfs loader show their own command line

Without proot every dynamic guest program runs as "ld.so --preload <hook>
--library-path <dirs> --argv0 <name> <program> <args>", and the kernel's
/proc/<pid>/cmdline kept all of it. Launchers and the session match programs
by their command line, and Wine only moves its Windows command line over its
loader's name when its arguments follow each other, so the Battle.net launcher
never saw Battle.net.exe, gave up after five minutes and ended the session
with the game still running.

The hook now moves the program's own arguments to the front of that area at
start, as an exec of the program would have laid them out.

* fix(native): programs the app starts natively keep their path for /proc/<pid>/exe

* fix(native): the rewritten command line keeps AT_EXECFN naming the program

---------

Co-authored-by: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com>
This commit is contained in:
The412BannerandKurt Himebauch authored and GitHub committed 2026-11-24 17:48:17 -05:00
1 parent 3c4ac03656
commit 1772291da7
8 files changed
+335 -31

No files matched your search

+118 -17
View File
@@ -134,8 +134,11 @@ static void init_ddnatv_hook(void) {
// environment is kept in. A program that had changed its environment (putenv, setenv) and passed it
// to execv() before its first call into the hook handed the exec code a block that was freed by the
// time it was read.
__attribute__((constructor(103))) static void init_ddnatv_hook_early(void) {
static void compact_loader_args(int argc, char **argv);
__attribute__((constructor(103))) static void init_ddnatv_hook_early(int argc, char **argv) {
init_ddnatv_hook();
compact_loader_args(argc, argv);
// The kernel names the process after what it executed, the rootfs ld.so: process monitors, and
// the app's own checks of /proc/<pid>/comm (steam, wineserver), saw only "ld-linux-aarch64.so.1"
const char *name = program_invocation_short_name;
@@ -232,27 +235,39 @@ static ssize_t (*real_readlinkat_fn(void))(int, const char *, char *, size_t) {
return fn;
}
static int proc_env_value(pid_t pid, const char *key, char *out, size_t outsz) {
char path[64];
snprintf(path, sizeof(path), "/proc/%d/environ", (int)pid);
int fd = open(path, O_RDONLY | O_CLOEXEC);
if (fd < 0) return 0;
size_t cap = 65536, used = 0, keylen = strlen(key);
char *env = malloc(cap + 1);
ssize_t got;
while (env && (got = read(fd, env + used, cap - used)) > 0) {
static char *read_proc_file(const char *path, size_t *len, int *whole) {
*len = 0;
*whole = 0;
int fd = (int)syscall(SYS_openat, AT_FDCWD, path, O_RDONLY | O_CLOEXEC);
if (fd < 0) return NULL;
size_t cap = 65536, used = 0;
char *text = malloc(cap + 1);
ssize_t got = 0;
while (text && (got = (ssize_t)syscall(SYS_read, fd, text + used, cap - used)) > 0) {
used += (size_t)got;
if (used == cap) {
char *bigger = cap < (8u << 20) ? realloc(env, cap * 2 + 1) : NULL;
char *bigger = cap < (8u << 20) ? realloc(text, cap * 2 + 1) : NULL;
if (!bigger) break;
env = bigger;
text = bigger;
cap *= 2;
}
}
close(fd);
syscall(SYS_close, fd);
if (!text) return NULL;
text[used] = '\0';
*len = used;
*whole = got == 0;
return text;
}
static int proc_env_value(pid_t pid, const char *key, char *out, size_t outsz) {
char path[64];
snprintf(path, sizeof(path), "/proc/%d/environ", (int)pid);
size_t used, keylen = strlen(key);
int whole;
char *env = read_proc_file(path, &used, &whole);
int found = 0;
if (env) {
env[used] = '\0';
for (char *e = env; e < env + used; e += strlen(e) + 1) {
if (strncmp(e, key, keylen) == 0 && e[keylen] == '=' && e[keylen + 1] != '\0') {
ddnatv_copy_cstr(out, outsz, e + keylen + 1);
@@ -265,6 +280,94 @@ static int proc_env_value(pid_t pid, const char *key, char *out, size_t outsz) {
return found;
}
static int is_loader_option(const char *arg) {
return strcmp(arg, "--preload") == 0 || strcmp(arg, "--library-path") == 0 || strcmp(arg, "--argv0") == 0;
}
static int is_exec_loader(const char *path) {
const char *base = strrchr(path, '/');
return strcmp(base ? base + 1 : path, "libddexec.so") == 0;
}
static size_t next_arg(const char *text, size_t pos) {
return pos + strlen(text + pos) + 1;
}
static uintptr_t *execfn_entry(int argc, char **argv) {
if (argv[argc]) return NULL;
char **env = argv + argc + 1;
while (*env) env++;
for (uintptr_t *aux = (uintptr_t *)(env + 1); aux[0] != AT_NULL; aux += 2) {
if (aux[0] == AT_EXECFN) return aux + 1;
}
return NULL;
}
static void compact_loader_args(int argc, char **argv) {
if (g_ddnatv_root[0] == '\0' || argc < 1 || !argv || !argv[0]) return;
size_t len;
int whole;
char *text = read_proc_file("/proc/self/cmdline", &len, &whole);
size_t *at = text && whole && len > 0 && text[len - 1] == '\0' ? malloc(sizeof(size_t) * (size_t)argc) : NULL;
size_t pos = 0, program = 0;
if (at && is_exec_loader(text)) {
pos = next_arg(text, pos);
if (pos < len) pos = next_arg(text, pos);
}
int ok = at && pos < len && is_ld_linux(text + pos), named = 0;
if (ok) pos = next_arg(text, pos);
while (ok && pos < len && is_loader_option(text + pos)) {
size_t value = next_arg(text, pos);
ok = value < len;
if (ok && strcmp(text + pos, "--argv0") == 0) {
at[0] = value;
named = 1;
}
if (ok) pos = next_arg(text, value);
}
int count = 0;
if (ok && named && pos < len) {
program = pos;
pos = next_arg(text, pos);
for (count = 1; pos < len && count < argc; count++) {
at[count] = pos;
pos = next_arg(text, pos);
}
}
char *base = count == argc && pos == len ? argv[0] - at[0] : NULL;
for (int i = 1; base && i < argc; i++) {
if (argv[i] != base + at[i]) base = NULL;
}
if (base && memcmp(base, text, len) != 0) base = NULL;
uintptr_t *execfn = base ? execfn_entry(argc, argv) : NULL;
char *execfn_text = NULL;
if (execfn && *execfn >= (uintptr_t)base && *execfn < (uintptr_t)base + len) {
execfn_text = strdup(text + (*execfn - (uintptr_t)base));
if (!execfn_text) base = NULL;
}
if (base) {
char *old_name = argv[0];
size_t name_len = strlen(old_name);
char *name = program_invocation_name, *short_name = program_invocation_short_name;
size_t used = 0;
for (int i = 0; i < argc; i++) {
size_t n = strlen(text + at[i]) + 1;
memcpy(base + used, text + at[i], n);
argv[i] = base + used;
used += n;
}
memset(base + used, 0, len - used);
if (name >= old_name && name <= old_name + name_len) program_invocation_name = argv[0] + (name - old_name);
if (short_name >= old_name && short_name <= old_name + name_len) {
program_invocation_short_name = argv[0] + (short_name - old_name);
}
if (g_real_exe[0] == '\0') ddnatv_copy_cstr(g_real_exe, sizeof(g_real_exe), text + program);
if (execfn_text) *execfn = (uintptr_t)execfn_text;
}
free(at);
free(text);
}
// Overlay filesystems report a different device to stat() than in /proc/<pid>/maps; the path, as the
// kernel resolved it, then stands in for the device.
static int proc_maps_file(pid_t pid, dev_t dev, ino_t ino, const char *resolved) {
@@ -320,9 +423,7 @@ static ssize_t handle_proc_other_exe(const char *path, char *buf, size_t bufsiz)
ssize_t n = real_readlinkat(AT_FDCWD, path, loader, sizeof(loader) - 1);
if (n <= 0) return -1;
loader[n] = '\0';
const char *base = strrchr(loader, '/');
base = base ? base + 1 : loader;
if (strcmp(base, "libddexec.so") != 0 && !is_ld_linux(loader)) return -1;
if (!is_exec_loader(loader) && !is_ld_linux(loader)) return -1;
char real_exe[PATH_MAX] = "";
if (!proc_env_value(pid, "DDNATV_REAL_EXE", real_exe, sizeof(real_exe))) {
+179
View File
@@ -0,0 +1,179 @@
import os
from pathlib import Path
import subprocess
import tempfile
import unittest
from tools.tests.test_usr2_preload import runner
REPO = Path(__file__).resolve().parents[2]
HOOK_BUILD = REPO / "tools/nativeguest/build.sh"
DDEXEC = REPO / "app/src/main/cpp/ddexec/ddexec.c"
DDEXEC_FLAGS = ["-shared", "-fPIC", "-O2", "-ffreestanding", "-fno-builtin", "-fno-stack-protector",
"-fno-asynchronous-unwind-tables", "-nostdlib", "-Wl,-e,_start", "-Wl,-z,noexecstack",
"-Wl,--no-undefined", "-Wl,-Bsymbolic"]
WINDOWS_PROGRAM = "C:\\Program Files (x86)\\Battle.net\\Battle.net.exe"
PROBE = r"""
#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <sys/auxv.h>
#include <sys/syscall.h>
#include <unistd.h>
static void show_cmdline(const char *label) {
static char buf[1 << 20];
int fd = (int)syscall(SYS_openat, AT_FDCWD, "/proc/self/cmdline", O_RDONLY);
ssize_t len = 0, n;
while (fd >= 0 && (n = read(fd, buf + len, sizeof(buf) - len)) > 0) len += n;
if (fd >= 0) close(fd);
while (len > 0 && buf[len - 1] == '\0') len--;
printf("%s", label);
for (ssize_t at = 0; at < len; at += (ssize_t)strlen(buf + at) + 1) printf("\t%s", buf + at);
printf("\n");
}
int main(int argc, char **argv) {
int contiguous = 1;
for (int i = 1; i < argc; i++) {
if (argv[i] != argv[i - 1] + strlen(argv[i - 1]) + 1) contiguous = 0;
}
printf("execfn\t%s\n", (const char *)getauxval(AT_EXECFN));
printf("contiguous\t%d\n", contiguous);
printf("argv");
for (int i = 0; i < argc; i++) printf("\t%s", argv[i]);
printf("\n");
printf("name\t%s\t%s\n", program_invocation_name, program_invocation_short_name);
show_cmdline("cmdline");
if (argc > 1 && contiguous) {
size_t offset = (size_t)(argv[1] - argv[0]);
char *end = argv[argc - 1] + strlen(argv[argc - 1]) + 1;
memmove(argv[0], argv[1], (size_t)(end - argv[1]));
memset(end - offset, 0, offset);
show_cmdline("shifted");
}
return 0;
}
"""
class NativeHookCmdlineTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.cc, cls.prefix = runner()
if cls.cc is None:
raise unittest.SkipTest("no aarch64 compiler and runner")
cls.tmp = tempfile.TemporaryDirectory()
tmp = Path(cls.tmp.name)
cls.hook = tmp / "hook.so"
subprocess.run(["bash", str(HOOK_BUILD), str(cls.hook), cls.cc], check=True, capture_output=True)
(tmp / "probe.c").write_text(PROBE)
cls.probe = tmp / "probe"
subprocess.run([cls.cc, "-O1", "-o", str(cls.probe), str(tmp / "probe.c")], check=True)
cls.ddexec = tmp / "lib/libddexec.so"
cls.ddexec.parent.mkdir()
subprocess.run([cls.cc, *DDEXEC_FLAGS, "-o", str(cls.ddexec), str(DDEXEC)], check=True)
cls.ddexec_runs = subprocess.run(list(cls.prefix) + [str(cls.ddexec), str(cls.probe), str(cls.probe)],
capture_output=True, timeout=120).returncode == 0
cls.root = tmp / "root"
cls.root.mkdir()
if cls.prefix:
libs = Path(cls.prefix[cls.prefix.index("-L") + 1]) / "lib"
else:
libs = next(Path(p) for p in ("/lib/aarch64-linux-gnu", "/usr/lib/aarch64-linux-gnu", "/lib64")
if (Path(p) / "libc.so.6").exists())
cls.ld_so = next(str(p) for p in (libs / "ld-linux-aarch64.so.1", Path("/lib/ld-linux-aarch64.so.1"))
if p.exists())
cls.libs = str(libs)
@classmethod
def tearDownClass(cls):
cls.tmp.cleanup()
def run_probe(self, argv, root=True, preload=False):
env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "DDNATV_ROOT", "DDNATV_REAL_EXE")}
if root:
env["DDNATV_ROOT"] = str(self.root)
runner_args = list(self.prefix)
if preload and self.prefix:
runner_args += ["-E", f"LD_PRELOAD={self.hook}"]
elif preload:
env["LD_PRELOAD"] = str(self.hook)
out = subprocess.run(runner_args + argv, env=env, capture_output=True, text=True, timeout=120)
self.assertEqual(out.returncode, 0, out.stderr)
return {line.split("\t")[0]: line.split("\t")[1:] for line in out.stdout.splitlines()}
def loader_argv(self, *args, name="/usr/bin/wine"):
named = ["--argv0", name] if name else []
return [self.ld_so, "--preload", str(self.hook), "--library-path", self.libs, *named, str(self.probe), *args]
def test_a_program_its_loader_starts_has_its_arguments_together(self):
seen = self.run_probe(self.loader_argv(WINDOWS_PROGRAM, "--in-tray"))
self.assertEqual(["/usr/bin/wine", WINDOWS_PROGRAM, "--in-tray"], seen["argv"])
self.assertEqual(["1"], seen["contiguous"])
self.assertEqual(["/usr/bin/wine", "wine"], seen["name"])
@unittest.skipIf(runner()[1], "qemu answers /proc/self/cmdline from its own copy of the arguments")
def test_the_command_line_shows_the_arguments_the_program_was_started_with(self):
seen = self.run_probe(self.loader_argv(WINDOWS_PROGRAM, "--in-tray"))
self.assertEqual(["/usr/bin/wine", WINDOWS_PROGRAM, "--in-tray"], seen["cmdline"])
self.assertEqual([WINDOWS_PROGRAM, "--in-tray"], seen["shifted"])
@unittest.skipIf(runner()[1], "qemu answers /proc/self/cmdline from its own copy of the arguments")
def test_the_app_loader_in_front_of_the_loader_is_left_out(self):
if not self.ddexec_runs:
self.skipTest("libddexec.so does not start a program on this host")
seen = self.run_probe([str(self.ddexec), self.ld_so] + self.loader_argv(WINDOWS_PROGRAM))
self.assertEqual(["/usr/bin/wine", WINDOWS_PROGRAM], seen["argv"])
self.assertEqual(["/usr/bin/wine", WINDOWS_PROGRAM], seen["cmdline"])
self.assertEqual([WINDOWS_PROGRAM], seen["shifted"])
@unittest.skipIf(runner()[1], "qemu answers AT_EXECFN from its own copy of the arguments")
def test_a_program_its_loader_starts_still_finds_its_own_path(self):
unchanged = self.run_probe(self.loader_argv(WINDOWS_PROGRAM), root=False)
self.assertEqual([str(self.probe)], unchanged["execfn"])
seen = self.run_probe(self.loader_argv(WINDOWS_PROGRAM, "--in-tray"))
self.assertEqual([WINDOWS_PROGRAM, "--in-tray"], seen["shifted"])
self.assertEqual(unchanged["execfn"], seen["execfn"])
@unittest.skipIf(runner()[1], "qemu answers AT_EXECFN from its own copy of the arguments")
def test_a_program_the_app_loader_starts_still_finds_its_own_path(self):
if not self.ddexec_runs:
self.skipTest("libddexec.so does not start a program on this host")
argv = [str(self.ddexec), self.ld_so] + self.loader_argv(WINDOWS_PROGRAM)
unchanged = self.run_probe(argv, root=False)
seen = self.run_probe(argv)
self.assertEqual([WINDOWS_PROGRAM], seen["shifted"])
self.assertEqual(unchanged["execfn"], seen["execfn"])
self.assertNotEqual([""], seen["execfn"])
def test_a_loader_run_without_a_program_name_keeps_its_command_line(self):
argv = self.loader_argv(WINDOWS_PROGRAM, name=None)
seen = self.run_probe(argv)
self.assertEqual([str(self.probe), WINDOWS_PROGRAM], seen["argv"])
self.assertEqual(["1"], seen["contiguous"])
if not self.prefix:
self.assertEqual(argv, seen["cmdline"])
def test_outside_the_native_userland_the_command_line_is_unchanged(self):
argv = self.loader_argv(WINDOWS_PROGRAM)
seen = self.run_probe(argv, root=False)
self.assertEqual(["/usr/bin/wine", WINDOWS_PROGRAM], seen["argv"])
self.assertEqual(["0"], seen["contiguous"])
if not self.prefix:
self.assertEqual(argv, seen["cmdline"])
def test_a_program_started_directly_is_unchanged(self):
seen = self.run_probe([str(self.probe), WINDOWS_PROGRAM, "--in-tray"], preload=True)
self.assertEqual([str(self.probe), WINDOWS_PROGRAM, "--in-tray"], seen["argv"])
self.assertEqual(["1"], seen["contiguous"])
if not self.prefix:
self.assertEqual([str(self.probe), WINDOWS_PROGRAM, "--in-tray"], seen["cmdline"])
if __name__ == "__main__":
unittest.main()
+15 -5
View File
@@ -74,8 +74,8 @@ class NativeHookProcExeTest(unittest.TestCase):
shutil.copy(shutil.which(cls.prefix[0]), cls.loader)
cls.loader_args = list(cls.prefix[1:])
else:
ld = next(p for p in ("/lib/ld-linux-aarch64.so.1", "/lib64/ld-linux-aarch64.so.1") if os.path.exists(p))
shutil.copy(ld, cls.loader)
cls.ld_so = next(p for p in ("/lib/ld-linux-aarch64.so.1", "/lib64/ld-linux-aarch64.so.1") if os.path.exists(p))
shutil.copy(cls.ld_so, cls.loader)
cls.loader_args = []
@classmethod
@@ -83,11 +83,13 @@ class NativeHookProcExeTest(unittest.TestCase):
cls.tmp.cleanup()
def start(self, loader, real_exe=None, program=None):
env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "DDNATV_REAL_EXE")}
if real_exe:
env["DDNATV_REAL_EXE"] = real_exe
program = program or Path(self.tmp.name) / "sleeper"
cmd = ([str(self.loader), *self.loader_args] if loader else list(self.prefix)) + [str(program)]
return self.spawn(cmd, {"DDNATV_REAL_EXE": real_exe} if real_exe else {})
def spawn(self, cmd, extra_env):
env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "DDNATV_ROOT", "DDNATV_REAL_EXE")}
env.update(extra_env)
child = subprocess.Popen(cmd, env=env, stdout=subprocess.PIPE, text=True)
self.addCleanup(child.stdout.close)
self.addCleanup(child.wait)
@@ -141,6 +143,14 @@ class NativeHookProcExeTest(unittest.TestCase):
link = f"/proc/{pid}/exe"
self.assertEqual(os.readlink(link), self.readlink(link)[link])
@unittest.skipIf(runner()[1], "qemu answers /proc/self/cmdline from its own copy of the arguments")
def test_a_program_whose_hook_moved_its_arguments_is_still_named(self):
cmd = [self.ld_so, "--preload", str(self.hook), "--argv0", self.kwin.name, str(self.kwin)]
pid = self.spawn(cmd, {"DDNATV_ROOT": str(self.root), "DDNATV_REAL_EXE": str(self.kwin)})
self.assertEqual(b"kwin_wayland", Path(f"/proc/{pid}/cmdline").read_bytes().rstrip(b"\0"))
link = f"/proc/{pid}/exe"
self.assertEqual("/usr/bin/kwin_wayland", self.readlink(link)[link])
def test_a_loader_without_a_known_program_keeps_the_kernel_link(self):
pid = self.start(loader=True)
link = f"/proc/{pid}/exe"