Compare commits

...
Author SHA1 Message Date
MaxsTechReview 1f016211f2 perf(nativeguest): resolve mount sources once per session instead of in every process (#3276)
* perf(nativeguest): resolve mount sources once per session instead of in every process

Each new process walked every mount source of the session through
realpath() before main(), one readlinkat per path component (about 960
calls for a desktop session), which made a process start about three
times slower than with no mounts. The sources are now looked up through
the kernel (one open and one readlink each), a source named twice is
looked up once, and the resolved table is handed to child processes in
DDNATV_BINDS_KERNEL, keyed by a hash of DDNATV_BINDS so a changed mount
list is resolved afresh. Sources under /proc are never handed down,
since they name the process itself.

* fix(nativeguest): hand the bind table to children on its own and keep unsafe sources out of it

A child given the bind specification without its table now gets the table
too. Sources reached through /proc with extra leading slashes, and real
places that hold the table's separator, are left for each child to look up.

* test(nativeguest): skip the child exec check where the host cannot start the probe

* fix(nativeguest): keep a bind table too long for the environment out of it

* fix(nativeguest): resolve libc path helpers before any fork can race them
2026-11-26 15:45:51 -05:00
4 changed files with 193 additions and 12 deletions

No files matched your search

+11
View File
@@ -93,6 +93,7 @@ static char **prepare_ddnatv_env(char *const envp[], const char *real_exe, const
// are compared (this was 13 strncmp() calls for each of the 30 or so variables)
int has_nt = 0;
int has_binds = 0;
int has_binds_kernel = 0;
int has_hostname = 0;
int has_link_root = 0;
int has_exec_loader = 0;
@@ -121,6 +122,7 @@ static char **prepare_ddnatv_env(char *const envp[], const char *real_exe, const
if (strncmp(e, "DDNATV_ROOT=", 12) == 0) has_root = 1;
else if (strncmp(e, "DDNATV_NT=", 10) == 0) has_nt = 1;
else if (strncmp(e, "DDNATV_BINDS=", 13) == 0) has_binds = 1;
else if (strncmp(e, "DDNATV_BINDS_KERNEL=", 20) == 0) has_binds_kernel = 1;
else if (strncmp(e, "DDNATV_PRELOAD=", 15) == 0) has_preload_list = 1;
else if (strncmp(e, "DDNATV_HOSTNAME=", 16) == 0) has_hostname = 1;
else if (strncmp(e, "DDNATV_LINK_ROOT=", 17) == 0) has_link_root = 1;
@@ -255,6 +257,15 @@ static char **prepare_ddnatv_env(char *const envp[], const char *real_exe, const
new_env[dst++] = str;
}
}
if (!has_binds_kernel && g_binds_kernel) {
size_t kernel_len = strlen(g_binds_kernel);
char *kernel = malloc(20 + kernel_len + 1);
if (kernel) {
memcpy(kernel, "DDNATV_BINDS_KERNEL=", 20);
memcpy(kernel + 20, g_binds_kernel, kernel_len + 1);
new_env[dst++] = kernel;
}
}
// This process looked for the ARM translator's files and found none: the programs it starts
// need not look again (it takes a look at /proc/self/fd in each of them, see privileged.c)
if (!has_nt && g_no_translator) {
+91 -9
View File
@@ -14,15 +14,36 @@ static size_t g_ddnatv_root_len = 0;
// The path the kernel reports for [path] (/proc/self/fd, getcwd(), realpath()): for a targetSdk 30+
// app, Android's own /data/user/0 is a link to /data/data, so the app's paths are not what the kernel
// gives back for them. Into out, or path itself when it cannot be resolved; returns out's length.
static size_t ddnatv_kernel_path(const char *path, size_t len, char *out, size_t outsz) {
static char *(*libc_realpath)(const char *, char *) = NULL;
static char *(*libc_realpath)(const char *, char *) = NULL;
static long (*libc_syscall)(long, ...) = NULL;
static void ddnatv_resolve_libc(void) {
if (!libc_realpath) libc_realpath = (char *(*)(const char *, char *))dlsym(RTLD_NEXT, "realpath");
if (!libc_syscall) libc_syscall = (long (*)(long, ...))dlsym(RTLD_NEXT, "syscall");
}
static size_t ddnatv_resolve_path(const char *path, size_t len, char *out, size_t outsz, int *found) {
ddnatv_resolve_libc();
char given[PATH_MAX];
if (len >= sizeof(given)) len = sizeof(given) - 1;
memcpy(given, path, len);
given[len] = '\0';
char resolved[PATH_MAX];
const char *use = (libc_realpath && libc_realpath(given, resolved)) ? resolved : given;
const char *use = given;
int fd = libc_syscall && given[0] == '/' && strncmp(given, "/proc/", 6) != 0
? (int)libc_syscall(SYS_openat, AT_FDCWD, given, O_PATH | O_CLOEXEC) : -1;
if (fd >= 0) {
char link[32];
snprintf(link, sizeof(link), "/proc/self/fd/%d", fd);
ssize_t n = libc_syscall(SYS_readlinkat, AT_FDCWD, link, resolved, sizeof(resolved) - 1);
libc_syscall(SYS_close, fd);
if (n > 0 && resolved[0] == '/') {
resolved[n] = '\0';
use = resolved;
}
}
if (use == given && libc_realpath && libc_realpath(given, resolved)) use = resolved;
if (found) *found = use != given;
size_t n = strlen(use);
if (n >= outsz) n = outsz - 1;
memcpy(out, use, n);
@@ -30,6 +51,10 @@ static size_t ddnatv_kernel_path(const char *path, size_t len, char *out, size_t
return n;
}
static size_t ddnatv_kernel_path(const char *path, size_t len, char *out, size_t outsz) {
return ddnatv_resolve_path(path, len, out, outsz, NULL);
}
static void ddnatv_set_root(const char *root, size_t len) {
if (!root) len = 0;
if (len > 0) len = ddnatv_kernel_path(root, len, g_ddnatv_root, sizeof(g_ddnatv_root));
@@ -45,12 +70,14 @@ struct ddnatv_bind {
size_t src_len, dst_len;
int identity;
int links;
int resolved;
int order; // position in DDNATV_BINDS: the earlier of two mounts of one folder is its guest path
};
// as many as the session has: a fixed table dropped what came after its 128th entry
static struct ddnatv_bind *g_binds = NULL;
static int g_nbinds = 0;
static char *g_binds_raw = NULL;
static char *g_binds_kernel = NULL;
// The session's host name (DDNATV_HOSTNAME), what proot put in uname(): Android's kernel says "localhost"
static char g_hostname[65];
// A Flatpak sandbox's: the session's rootfs (DDNATV_LINK_ROOT), whose hook stored absolute guest
@@ -64,7 +91,18 @@ static int ddnatv_bind_longer_first(const void *a, const void *b) {
return (y->dst_len > x->dst_len) - (y->dst_len < x->dst_len);
}
static void ddnatv_load_binds(const char *spec) {
static size_t ddnatv_append(char *out, size_t outsz, size_t used, const char *s, size_t len);
static uint64_t ddnatv_hash(const char *s) {
uint64_t h = 1469598103934665603ULL;
for (; *s; s++) {
h ^= (unsigned char)*s;
h *= 1099511628211ULL;
}
return h;
}
static void ddnatv_load_binds(const char *spec, const char *known) {
if (!spec || !spec[0]) return;
char *raw = strdup(spec);
char *copy = strdup(spec);
@@ -73,18 +111,47 @@ static void ddnatv_load_binds(const char *spec) {
size_t count = 1;
for (const char *c = spec; *c; c++) count += *c == '|';
g_binds = calloc(count, sizeof(*g_binds));
if (!g_binds) { free(raw); free(copy); return; }
const char **given = calloc(count, sizeof(*given));
if (!g_binds || !given) { free(g_binds); g_binds = NULL; free(given); free(raw); free(copy); return; }
char hash[17];
snprintf(hash, sizeof(hash), "%016llx", (unsigned long long)ddnatv_hash(spec));
char *cache = known && strncmp(known, hash, 16) == 0 && known[16] == '|' ? strdup(known + 17) : NULL;
char *next = cache;
for (char *entry = strtok_r(copy, "|", &save); entry && (size_t)g_nbinds < count; entry = strtok_r(NULL, "|", &save)) {
char *colon = strchr(entry, ':');
const char *src = entry;
const char *dst = colon ? colon + 1 : entry;
if (colon) *colon = '\0';
if (src[0] != '/' || dst[0] != '/' || strcmp(dst, "/") == 0) continue;
struct ddnatv_bind *b = &g_binds[g_nbinds++];
char *cached = next;
if (next) {
char *bar = strchr(next, '|');
if (bar) *bar = '\0';
next = bar ? bar + 1 : NULL;
}
int index = g_nbinds++;
struct ddnatv_bind *b = &g_binds[index];
given[index] = src;
char kernel_src[PATH_MAX];
if (strcmp(src, dst) != 0) {
ddnatv_kernel_path(src, strlen(src), kernel_src, sizeof(kernel_src));
if (strncmp(kernel_src, "/proc/", 6) != 0 || kernel_src[6] < '0' || kernel_src[6] > '9') src = kernel_src;
if (cached && cached[0] == '/') {
src = cached;
b->resolved = 1;
} else {
for (int j = 0; j < index && !b->resolved; j++) {
if (g_binds[j].resolved && strcmp(given[j], src) == 0) {
src = g_binds[j].src;
b->resolved = 1;
}
}
if (!b->resolved) {
ddnatv_resolve_path(src, strlen(src), kernel_src, sizeof(kernel_src), &b->resolved);
const char *lead = src;
while (lead[0] == '/' && lead[1] == '/') lead++;
if (strncmp(lead, "/proc/", 6) == 0 || strchr(kernel_src, '|')) b->resolved = 0;
if (strncmp(kernel_src, "/proc/", 6) != 0 || kernel_src[6] < '0' || kernel_src[6] > '9') src = kernel_src;
}
}
}
b->src = strdup(src);
b->dst = strdup(dst);
@@ -93,8 +160,23 @@ static void ddnatv_load_binds(const char *spec) {
while (b->dst_len > 1 && b->dst[b->dst_len - 1] == '/') b->dst[--b->dst_len] = '\0';
while (b->src_len > 1 && b->src[b->src_len - 1] == '/') b->src[--b->src_len] = '\0';
b->identity = strcmp(b->src, b->dst) == 0;
b->order = g_nbinds - 1;
b->order = index;
}
size_t size = 17;
for (int i = 0; i < g_nbinds; i++) size += 1 + (g_binds[i].resolved ? g_binds[i].src_len : 0);
long page = sysconf(_SC_PAGESIZE);
char *table = size + 21 <= (size_t)(page > 0 ? page : 4096) * 32 ? malloc(size + 1) : NULL;
if (table) {
size_t used = ddnatv_append(table, size + 1, 0, hash, 16);
for (int i = 0; i < g_nbinds; i++) {
used = ddnatv_append(table, size + 1, used, "|", 1);
if (g_binds[i].resolved) used = ddnatv_append(table, size + 1, used, g_binds[i].src, g_binds[i].src_len);
}
if (!known || strcmp(known, table) != 0) setenv("DDNATV_BINDS_KERNEL", table, 1);
g_binds_kernel = table;
}
free(cache);
free(given);
free(copy);
qsort(g_binds, (size_t)g_nbinds, sizeof(g_binds[0]), ddnatv_bind_longer_first);
g_binds_raw = raw;
+2 -1
View File
@@ -36,7 +36,7 @@ static void init_ddnatv_hook(void) {
}
}
}
ddnatv_load_binds(getenv("DDNATV_BINDS"));
ddnatv_load_binds(getenv("DDNATV_BINDS"), getenv("DDNATV_BINDS_KERNEL"));
const char *mount_table = getenv("DDNATV_MOUNTINFO");
if (mount_table && mount_table[0] == '/' && strlen(mount_table) < sizeof(g_mount_table))
ddnatv_copy_cstr(g_mount_table, sizeof(g_mount_table), mount_table);
@@ -228,6 +228,7 @@ static void adopt_forwarded_fds(void) {
__attribute__((constructor(103))) static void init_ddnatv_hook_early(int argc, char **argv) {
adopt_forwarded_fds();
ddnatv_resolve_libc();
init_ddnatv_hook();
compact_loader_args(argc, argv);
// The kernel names the process after what it executed, the rootfs ld.so: process monitors, and
+89 -2
View File
@@ -42,6 +42,27 @@ int main(int argc, char **argv) {
if (fd >= 0) close(fd);
continue;
}
if (strncmp(argv[i], "exec-without:", 13) == 0) {
extern char **environ;
char *program = strchr(argv[i] + 13, '=');
if (!program) continue;
size_t n = 0, len = (size_t)(program++ - (argv[i] + 13));
while (environ[n]) n++;
char **env = calloc(n + 1, sizeof(char *));
size_t used = 0;
for (size_t k = 0; k < n; k++)
if (strncmp(environ[k], argv[i] + 13, len) != 0 || environ[k][len] != '=') env[used++] = environ[k];
char *args[] = {program, "env:DDNATV_BINDS_KERNEL", NULL};
fflush(stdout);
pid_t pid = fork();
if (pid == 0) {
execve(program, args, env);
_exit(127);
}
waitpid(pid, NULL, 0);
free(env);
continue;
}
if (strncmp(argv[i], "fork:", 5) == 0) {
fflush(stdout);
pid_t pid = fork();
@@ -163,6 +184,8 @@ class NativeHookMountTest(unittest.TestCase):
(cls.links / "real/sub/deeper/more/leaf.txt").write_text("leaf")
os.symlink("real", cls.links / "dir")
os.symlink(str(cls.links / "real"), cls.links / "hostdir")
(cls.links / "real|data").mkdir()
os.symlink(str(cls.links / "real|data"), cls.links / "barlink")
os.symlink("/etc/hostname", cls.links / "guest")
os.symlink("real/sub/file.txt", cls.links / "file")
os.symlink("/mnt/links/real", cls.links / "real/up")
@@ -178,10 +201,12 @@ class NativeHookMountTest(unittest.TestCase):
def tearDownClass(cls):
cls.tmp.cleanup()
def run_probe(self, *args, binds=None, mounts=None, syscalls=False):
def run_probe(self, *args, binds=None, mounts=None, syscalls=False, table=None):
if binds is None:
binds = f"{self.library}:/mnt/library|{self.private}:/mnt/private|{self.eqlen_src}:{self.eqlen_dst}"
hook_env = {"DDNATV_ROOT": str(self.root), "DDNATV_BINDS": binds, "LD_PRELOAD": str(self.hook)}
if table is not None:
hook_env["DDNATV_BINDS_KERNEL"] = table
if mounts is not None:
table = Path(self.tmp.name) / f"mountinfo-{len(list(Path(self.tmp.name).glob('mountinfo-*')))}"
table.write_text("".join(f"{i + 20} 1 0:{i + 40} / {point} rw - {kind} {source} rw\n"
@@ -195,7 +220,7 @@ class NativeHookMountTest(unittest.TestCase):
if syscalls and not shutil.which("strace"):
self.skipTest("no strace")
if syscalls:
cmd = ["strace", "-f", "-qq", "-e", "trace=readlinkat,newfstatat,fstatat64,statx"]
cmd = ["strace", "-f", "-qq", "-e", "trace=openat,readlinkat,newfstatat,fstatat64,statx"]
cmd += [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")]
else:
cmd = []
@@ -206,6 +231,68 @@ class NativeHookMountTest(unittest.TestCase):
result = {line.split("\t")[0]: line.split("\t")[1:] for line in out.stdout.splitlines()}
return (result, out.stderr) if syscalls else result
def bind_table(self, binds, *sources):
h = 1469598103934665603
for byte in binds.encode():
h = ((h ^ byte) * 1099511628211) & 0xFFFFFFFFFFFFFFFF
return "%016x" % h + "".join("|" + source for source in sources)
def test_a_bind_source_through_a_link_is_resolved_once_and_handed_to_children(self):
binds = f"{self.links}/hostdir:/mnt/viahost|{self.links}/hostdir:/mnt/again|/dev:/dev"
out, log = self.run_probe("cd:/mnt/viahost/sub/", "env:DDNATV_BINDS_KERNEL", binds=binds, syscalls=True)
self.assertEqual(["/mnt/viahost/sub"], out["cd:/mnt/viahost/sub/"])
real = os.path.realpath(self.links / "real")
self.assertEqual([self.bind_table(binds, real, real, "")], out["env:DDNATV_BINDS_KERNEL"])
self.assertEqual(1, log.count(f'"{self.links}/hostdir"'))
def test_a_child_given_the_bind_spec_without_its_table_gets_the_table(self):
binds = f"{self.links}/hostdir:/mnt/viahost"
child = self.root / "child-probe"
subprocess.run([self.cc, "-static", "-O1", "-o", str(child), str(self.probe) + ".c"], check=True)
try:
subprocess.run([str(child)], capture_output=True, timeout=60)
except OSError:
self.skipTest("the host cannot start the probe's architecture directly")
out =self.run_probe("exec-without:DDNATV_BINDS_KERNEL=/child-probe", binds=binds)
self.assertEqual([self.bind_table(binds, os.path.realpath(self.links / "real"))], out["env:DDNATV_BINDS_KERNEL"])
def test_process_specific_bind_sources_are_not_handed_to_children(self):
binds = "/proc/self/fd/0:/dev/stdin|/proc/self/fd:/dev/fd|//proc/self/fd/0:/mnt/input"
out = self.run_probe("env:DDNATV_BINDS_KERNEL", binds=binds)
self.assertEqual([self.bind_table(binds, "", "", "")], out["env:DDNATV_BINDS_KERNEL"])
def test_a_bind_source_whose_real_place_holds_the_separator_is_not_handed_to_children(self):
binds = f"{self.links}/barlink:/mnt/bar"
out = self.run_probe("cd:/mnt/bar/", "env:DDNATV_BINDS_KERNEL", binds=binds)
self.assertEqual(["/mnt/bar"], out["cd:/mnt/bar/"])
self.assertEqual([self.bind_table(binds, "")], out["env:DDNATV_BINDS_KERNEL"])
def test_a_bind_table_too_long_for_the_environment_is_not_handed_to_children(self):
far = self.links.joinpath(*["f" * 200] * 9)
far.mkdir(parents=True, exist_ok=True)
(far / "marker").write_text("far")
if not (self.links / "farlink").is_symlink():
os.symlink(str(far), self.links / "farlink")
binds = "|".join(f"{self.links}/farlink:/mnt/far{n}" for n in range(80))
out = self.run_probe("ls:/mnt/far79", "env:DDNATV_BINDS_KERNEL", binds=binds)
self.assertEqual(["marker"], out["ls:/mnt/far79"])
self.assertEqual(["-"], out["env:DDNATV_BINDS_KERNEL"])
def test_a_handed_down_bind_table_is_used_without_looking_the_sources_up(self):
binds = f"{self.links}/hostdir:/mnt/viahost"
real = os.path.realpath(self.links / "real")
table = self.bind_table(binds, real)
out, log = self.run_probe("cd:/mnt/viahost/sub/", binds=binds, table=table, syscalls=True)
self.assertEqual(["/mnt/viahost/sub"], out["cd:/mnt/viahost/sub/"])
self.assertNotIn(f"{self.links}/hostdir", log)
def test_a_bind_table_for_other_binds_is_ignored(self):
binds = f"{self.links}/hostdir:/mnt/viahost"
stale = self.bind_table(f"{self.library}:/mnt/viahost", str(self.library))
out = self.run_probe("cd:/mnt/viahost/sub/", "env:DDNATV_BINDS_KERNEL", binds=binds, table=stale)
self.assertEqual(["/mnt/viahost/sub"], out["cd:/mnt/viahost/sub/"])
self.assertEqual([self.bind_table(binds, os.path.realpath(self.links / "real"))], out["env:DDNATV_BINDS_KERNEL"])
def readlinks_of(self, log, host):
return [line for line in log.splitlines()
if (m := re.search(r'readlinkat\([^,"]*,\s*"([^"]*)"', line)) and m.group(1) == host]