Files
DroidDeck/tools/nativeguest/hook/env.c
T
LunaDLandKurt Himebauch 88d44b0dc6 Feat: Improve ARMv8.0 Steam compatibility with LSE emulation (#3720)
* feat: emulate LSE atomics so the Steam client starts on ARMv8.0 CPUs

* fix: keep NZCV across patched LSE min/max stubs and catch st* aliases

* fix: fail the LSE check when objdump fails

* fix: validate the CASP pair on a mismatch in the LSE emulator

* fix: sandboxes switch on the LSE emulator when it is preloaded

* fix: keep the MaliBridge pointer from main

* Handle LSE atomics before preload constructors

* Support early LSE handling in root guest processes

* Fix LSE-Emu signal and patching review findings

* Assert CASP and min/max sites use patched stubs

* Correct patch test statistics regexes

* Validate SIGILL syscall ABI and retain active state on restore failure

* Preserve the previous SIGILL disposition during early install

* Synchronize instruction fetch on generated LSE stubs

* Address LSE-Emu follow-up review findings

* Fix missing LSE signal handler state declarations

* Honor application signal mask when forwarding SIGILL

* Preserve SA_RESETHAND mask during handler forwarding

* Fix LSE opt-out after early handler install

* Avoid recursive SIGILL forwarding during LSE emulation

* Fix LSE SIGILL handler re-entry tracking

* Honor SA_NODEFER in forwarded SIGILL mask

* Preserve nested SIGILL delivery semantics

* Preserve explicit SIGILL mask with SA_NODEFER

* Reduce LSE patch contention across threads

* Guard nested faults before acquiring patch lock

* Fix early SIGILL restore and wake patch waiters

* Preserve libc restorer when restoring application SIGILL

* Wait for concurrent LSE patch instead of skipping

* Fix LSE patch lock release and fork recovery

* Avoid reinstalling the early SIGILL handler

* chore: retrigger CI

* Avoid proc maps reads in concurrent SIGILL patching

* Prevent late IFUNC handler install when emulation is disabled

* Clarify cached mapping lookup

* Move cached map declarations before find_gap

* Default LSE instruction patching to off

* Document conservative LSE emulation default

* Keep LSE instruction patching opt-in in sandbox preload

* Document default and opt-in LSE emulation checks

* Assert LSE patching remains opt-in in sandbox tests

* Align LSE device checks with SDK 34 patching behavior

* Check expected mprotect failures in opt-in device run

* Clarify LSE emulator device validation criteria

* Specify controlled SDK mprotect validation

* fix(lse-emu): publish SIGILL actions atomically

* fix(runtime): honor LSE_EMU=0 before preload

* test(runtime): keep LSE preload disabled when opted out

* fix(runtime): fully honor LSE_EMU=0 opt-out

* test(runtime): verify LSE opt-out removes inherited preload

* fix(runtime): filter inherited LSE preload without preload file

* fix(lse-emu): use bounded signal-safe action snapshots

* fix(runtime): split inherited preloads on spaces and colons

* test(runtime): cover both LSE preload entry orders

* fix(lse-emu): recycle displaced SIGILL snapshots

* fix(preload): preserve colliding path cache entries

* test(lse-emu): report patch failure details

* fix(lse-emu): serialize action snapshot publishers

* fix(lse-emu): fall back to reachable arena mapping

* fix(lse-emu): make signal action publication nonblocking

* refactor(lse-emu): remove obsolete publisher lock

* Fix SIGILL snapshot retirement and honor session LSE opt-out

* Preserve the Java staging API and isolate the SIGILL stress test

* fix(nativeguest): filter LSE preload when disabled

* fix(lse-emu): tighten seccomp and signal setup

* fix(session): preserve active LSE override while staging

* fix(lse-emu): return atomically displaced signal actions

* fix(lse-emu): stage raw signal masks safely

* fix(lse-emu): distinguish seccomp listener success

* fix(lse-emu): publish seccomp veto atomically

* fix(lse-emu): fail closed on RX restore errors

* fix(lse-emu): keep stack-using atomic stubs on trap path

* fix(lse-emu): allow patching with inherited seccomp

* test(lse-emu): cover LDAPR patch path

* test(lse-emu): assert LDAPR-only patching

* fix(nativeguest): filter disabled LSE from preload chains

* docs(lse-emu): define inherited seccomp patch policy

* fix(lse-emu): emulate LDAPR trap fallback

* refactor(lse-emu): remove unused seccomp query

* fix(nativeguest): release filtered preload chain in scope

* test(lse-emu): allow forwarded udf diagnostic

* fix(nativeguest): avoid unsafe preload fallback when disabled

* test(lse-emu): match full zero instruction field

* test(lse-emu): match complete instruction diagnostics

* Keep nested native preloads from duplicating host libraries

* fix(nativeguest): fail exec when disabled preload cannot map

* fix(nativeguest): stop exec when preload mapping fails

* fix(nativeguest): propagate preload filter allocation failures

* Consume only the selected one-shot SIGILL action

* Reclaim abandoned SIGILL action slots after fork

* Revalidate the live file mapping before optional LSE patching

---------

Co-authored-by: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com>
2026-12-05 19:09:28 -05:00

465 lines
17 KiB
C

// Part of libddnatv-hook.so, included by ddnatv-hook.c (one translation unit, so the
// parts share their static functions and are built with the same command as before).
//
// The environment of started programs: Android programs get it without the hook, rootfs
// programs with it.
#ifndef DDNATV_HOST_TEST
static const char *ddnatv_hook_library(char *buf, size_t bufsz);
static char **clean_env_for_system(char *const envp[]) {
int count = 0;
while (envp && envp[count]) count++;
char **new_env = calloc(count + 3, sizeof(char *));
int dst = 0;
int has_path = 0;
for (int i = 0; i < count; i++) {
char first = envp[i][0];
if (!((first == 'L' && (strncmp(envp[i], "LD_PRELOAD=", 11) == 0 ||
strncmp(envp[i], "LD_LIBRARY_PATH=", 16) == 0)) ||
(first == 'G' && strncmp(envp[i], "GLIBC_TUNABLES=", 15) == 0))) {
if (first == 'P' && strncmp(envp[i], "PATH=", 5) == 0) {
has_path = 1;
size_t plen = strlen(envp[i]);
char *new_path = malloc(plen + 64);
if (new_path) {
snprintf(new_path, plen + 64, "PATH=/system/bin:/system/xbin:/sbin:/vendor/bin:%s", envp[i] + 5);
new_env[dst++] = new_path;
} else {
new_env[dst++] = envp[i];
}
} else {
new_env[dst++] = envp[i];
}
}
}
if (!has_path) {
new_env[dst++] = strdup("PATH=/system/bin:/system/xbin:/sbin:/vendor/bin");
}
new_env[dst] = NULL;
return new_env;
}
static int preload_has_entry(const char *chain, const char *entry, size_t entry_len) {
if (!chain || !entry_len) return 0;
const char *p = chain;
while (*p) {
size_t len = strcspn(p, ": ");
if (len == entry_len && memcmp(p, entry, len) == 0) return 1;
p += len;
if (*p) p++;
}
return 0;
}
static char *merge_preload_env(const char *host, const char *mapped) {
size_t host_len = host ? strlen(host) : 0;
char *out = malloc(11 + host_len + 1 + strlen(mapped) + 1);
if (!out) return NULL;
memcpy(out, "LD_PRELOAD=", 11);
size_t used = 11;
if (host_len) {
memcpy(out + used, host, host_len);
used += host_len;
}
for (const char *p = mapped; *p; ) {
size_t n = strcspn(p, ": ");
if (n && !preload_has_entry(host, p, n)) {
if (used > 11) out[used++] = ':';
memcpy(out + used, p, n);
used += n;
}
p += n;
if (*p) p++;
}
out[used] = '\0';
return out;
}
// Filter the LSE emulator from colon/space-separated preload chains when explicitly disabled.
static char *filter_lse_emu_preloads(const char *value, int lse_emu_disabled) {
if (!value) return NULL;
size_t len = strlen(value);
char *out = malloc(len + 1);
if (!out) return NULL;
size_t used = 0;
const char *p = value;
while (*p) {
size_t n = strcspn(p, ": ");
if (n) {
const char *base = p + n;
while (base > p && base[-1] != '/' && base[-1] != ':' && base[-1] != ' ') base--;
int is_lse_emu = n - (size_t)(base - p) == strlen("liblse_emu.so") &&
memcmp(base, "liblse_emu.so", strlen("liblse_emu.so")) == 0;
if (!(lse_emu_disabled && is_lse_emu)) {
if (used) out[used++] = ':';
memcpy(out + used, p, n);
used += n;
}
}
p += n;
if (*p) p++;
}
out[used] = '\0';
return out;
}
// LD_PRELOAD with every absolute path that is not in the rootfs yet mapped into it. Entries are
// separated by ':' or ' '. free() the result.
static char *map_preload_paths(const char *value, int lse_emu_disabled) {
if (!value) return NULL;
size_t cap = strlen(value) + (g_ddnatv_root_len + 1) * 16 + 16;
char *out = malloc(cap);
if (!out) return NULL;
size_t used = 0;
out[0] = '\0';
const char *p = value;
while (*p) {
size_t len = strcspn(p, ": ");
if (len > 0 && len < PATH_MAX) {
char entry[PATH_MAX];
memcpy(entry, p, len);
entry[len] = '\0';
const char *base = strrchr(entry, '/');
base = base ? base + 1 : entry;
if (lse_emu_disabled && strcmp(base, "liblse_emu.so") == 0) {
p += len;
if (*p) p++;
continue;
}
char buf[PATH_MAX];
const char *mapped = entry[0] == '/' ? rewrite_path_in_root(entry, buf, sizeof(buf)) : entry;
size_t mlen = strlen(mapped);
if (used + mlen + 2 >= cap) break;
if (used) out[used++] = ':';
memcpy(out + used, mapped, mlen);
used += mlen;
out[used] = '\0';
}
p += len;
if (*p) p++;
}
return out;
}
static void free_modified_env(char **modified_env, char *const orig_env[]);
static char **prepare_ddnatv_env(char *const envp[], const char *real_exe, const char *lib_path) {
init_ddnatv_hook();
int count = 0;
int has_preload = 0;
int lse_emu_disabled = 0;
int has_root = 0;
int has_tunables = 0;
int has_path = 0;
int has_tmp = 0;
int has_threads_max = 0;
int has_xz_opt = 0;
int has_xz_defaults = 0;
int has_frontend = 0;
int has_debconf_frontend = 0;
int has_debconf_seen = 0;
const char *chosen_real_exe = (real_exe && real_exe[0] != '\0') ? real_exe : (g_real_exe[0] != '\0' ? g_real_exe : NULL);
// Every variable is looked at on every exec, so only the names that start with its first letter
// 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;
int has_preload_list = 0;
const char *preload_value = NULL;
const char *become = NULL;
while (envp && envp[count]) {
const char *e = envp[count];
switch (e[0]) {
case 'L':
if (strncmp(e, "LD_PRELOAD=", 11) == 0) { has_preload = 1; preload_value = e + 11; }
else if (strncmp(e, "LSE_EMU=0", 9) == 0 && e[9] == '\0') lse_emu_disabled = 1;
break;
case 'G':
if (strncmp(e, "GLIBC_TUNABLES=", 15) == 0) has_tunables = 1;
break;
case 'P':
if (strncmp(e, "PATH=", 5) == 0) has_path = 1;
break;
case 'T':
if (strncmp(e, "TMPDIR=", 7) == 0) has_tmp = 1;
break;
case 'X':
if (strncmp(e, "XZ_OPT=", 7) == 0) has_xz_opt = 1;
else if (strncmp(e, "XZ_DEFAULTS=", 12) == 0) has_xz_defaults = 1;
break;
case 'D':
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;
else if (strncmp(e, "DDNATV_EXEC=", 12) == 0) has_exec_loader = 1;
else if (strncmp(e, "DDNATV_BECOME=", 14) == 0) become = e + 14;
else if (strncmp(e, "DPKG_DEB_THREADS_MAX=", 21) == 0) has_threads_max = 1;
else if (strncmp(e, "DEBIAN_FRONTEND=", 16) == 0) has_frontend = 1;
else if (strncmp(e, "DEBCONF_FRONTEND=", 17) == 0) has_debconf_frontend = 1;
else if (strncmp(e, "DEBCONF_NONINTERACTIVE_SEEN=", 28) == 0) has_debconf_seen = 1;
break;
default:
break;
}
count++;
}
char *filtered_host_chain = lse_emu_disabled ? filter_lse_emu_preloads(g_preload_host, 1) : NULL;
if (lse_emu_disabled && g_preload_host && !filtered_host_chain) {
errno = ENOMEM;
return NULL;
}
const char *host_preload = lse_emu_disabled ? (filtered_host_chain ? filtered_host_chain : "") : g_preload_host;
char **new_env = calloc(count + 26, sizeof(char *));
int dst = 0;
// The user the program runs as (hardlinks.c): this process's, whatever the environment it passes
// says, unless DDNATV_BECOME asks for one, or the program is set-user-ID root's (the app's files
// are root's), as the kernel would start it. First in the block, where a peer looks (sockets.c).
int as_app = app_user_mode();
if (become) as_app = strcmp(become, "app") == 0;
else if (as_app && real_exe && real_exe[0] == '/') {
struct stat st;
if (real_fstatat(AT_FDCWD, real_exe, &st, 0) == 0 && S_ISREG(st.st_mode) && (st.st_mode & S_ISUID)
&& st.st_uid == app_uid_now()) as_app = 0;
}
if (as_app) new_env[dst++] = strdup("DDNATV_USER=app");
for (int i = 0; i < count; i++) {
if (envp[i][0] == 'D' && (strncmp(envp[i], "DDNATV_USER=", 12) == 0 || strncmp(envp[i], "DDNATV_BECOME=", 14) == 0)) {
continue;
}
if (lse_emu_disabled && envp[i][0] == 'D' && strncmp(envp[i], "DDNATV_PRELOAD=", 15) == 0) {
char *filtered = filter_lse_emu_preloads(envp[i] + 15, 1);
if (!filtered) {
free_modified_env(new_env, envp);
free(filtered_host_chain);
errno = ENOMEM;
return NULL;
}
size_t len = 15 + strlen(filtered) + 1;
char *str = malloc(len);
if (!str) {
free(filtered);
free_modified_env(new_env, envp);
free(filtered_host_chain);
errno = ENOMEM;
return NULL;
}
snprintf(str, len, "DDNATV_PRELOAD=%s", filtered);
new_env[dst++] = str;
free(filtered);
continue;
}
if (has_preload && envp[i][0] == 'L' && strncmp(envp[i], "LD_PRELOAD=", 11) == 0) {
// ld.so opens these itself: the guest's paths are mapped to the rootfs, and the libraries every
// program loads (DDNATV_PRELOAD) come first
char *mapped = map_preload_paths(preload_value, lse_emu_disabled);
if (mapped) {
char *str = merge_preload_env(host_preload, mapped);
free(mapped);
if (str) {
new_env[dst++] = str;
continue;
}
}
if (lse_emu_disabled) {
free_modified_env(new_env, envp);
free(filtered_host_chain);
errno = ENOMEM;
return NULL;
}
}
// If we have an explicit real executable, drop the inherited entry to replace with the fresh target
if (chosen_real_exe && envp[i][0] == 'D' && strncmp(envp[i], "DDNATV_REAL_EXE=", 16) == 0) {
continue;
}
if (chosen_real_exe && envp[i][0] == 'D' && strncmp(envp[i], "DDNATV_LIBRARY_PATH=", 20) == 0) {
continue;
}
new_env[dst++] = envp[i];
}
// Exact-size strings: this runs before every exec, often in a freshly forked child where each
// newly touched page is a copy-on-write fault.
if (chosen_real_exe) {
size_t len = strlen(chosen_real_exe);
char *str = malloc(16 + len + 1);
if (str) {
memcpy(str, "DDNATV_REAL_EXE=", 16);
memcpy(str + 16, chosen_real_exe, len + 1);
new_env[dst++] = str;
}
}
if (chosen_real_exe && lib_path && lib_path[0] != '\0') {
size_t len = strlen(lib_path);
char *str = malloc(20 + len + 1);
if (str) {
memcpy(str, "DDNATV_LIBRARY_PATH=", 20);
memcpy(str + 20, lib_path, len + 1);
new_env[dst++] = str;
}
}
char hook_buf[PATH_MAX];
const char *hook = (!has_preload && g_ddnatv_root[0] != '\0') ? ddnatv_hook_library(hook_buf, sizeof(hook_buf)) : NULL;
if (hook) {
size_t hook_len = strlen(hook);
size_t host_len = host_preload ? strlen(host_preload) + 1 : 0;
size_t size = 11 + host_len + hook_len + 1;
char *str = malloc(size);
if (str) {
size_t n = ddnatv_append(str, size, 0, "LD_PRELOAD=", 11);
if (host_len) {
n = ddnatv_append(str, size, n, host_preload, host_len - 1);
n = ddnatv_append(str, size, n, ":", 1);
}
ddnatv_append(str, size, n, hook, hook_len);
new_env[dst++] = str;
}
}
if (!has_preload_list && g_preload_guest) {
char *filtered = lse_emu_disabled ? filter_lse_emu_preloads(g_preload_guest, 1) : NULL;
if (lse_emu_disabled && !filtered) {
free_modified_env(new_env, envp);
free(filtered_host_chain);
errno = ENOMEM;
return NULL;
}
const char *guest_preload = lse_emu_disabled ? filtered : g_preload_guest;
if (guest_preload) {
size_t len = strlen(guest_preload);
char *str = malloc(15 + len + 1);
if (!str) {
free(filtered);
free_modified_env(new_env, envp);
free(filtered_host_chain);
errno = ENOMEM;
return NULL;
}
memcpy(str, "DDNATV_PRELOAD=", 15);
memcpy(str + 15, guest_preload, len + 1);
new_env[dst++] = str;
}
free(filtered);
}
if (!has_root && g_ddnatv_root[0] != '\0') {
char *str = malloc(PATH_MAX + 16);
if (str) {
snprintf(str, PATH_MAX + 16, "DDNATV_ROOT=%s", g_ddnatv_root);
new_env[dst++] = str;
}
}
if (!has_exec_loader && g_exec_loader[0] != '\0') {
size_t len = strlen(g_exec_loader);
char *str = malloc(12 + len + 1);
if (str) {
memcpy(str, "DDNATV_EXEC=", 12);
memcpy(str + 12, g_exec_loader, len + 1);
new_env[dst++] = str;
}
}
if (!has_link_root && g_link_root_len) {
char *str = malloc(17 + g_link_root_len + 1);
if (str) {
memcpy(str, "DDNATV_LINK_ROOT=", 17);
memcpy(str + 17, g_link_root, g_link_root_len + 1);
new_env[dst++] = str;
}
}
if (!has_hostname && g_hostname[0]) {
char *str = malloc(16 + sizeof(g_hostname));
if (str) {
snprintf(str, 16 + sizeof(g_hostname), "DDNATV_HOSTNAME=%s", g_hostname);
new_env[dst++] = str;
}
}
if (!has_binds && g_binds_raw) {
size_t len = strlen(g_binds_raw);
char *str = malloc(13 + len + 1);
if (str) {
memcpy(str, "DDNATV_BINDS=", 13);
memcpy(str + 13, g_binds_raw, len + 1);
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) {
new_env[dst++] = strdup("DDNATV_NT=0");
}
if (!has_tunables) {
new_env[dst++] = strdup("GLIBC_TUNABLES=glibc.pthread.rseq=0");
}
if (!has_path) {
new_env[dst++] = strdup("PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin");
}
if (!has_tmp && g_ddnatv_root[0] != '\0') {
char *str = malloc(PATH_MAX + 16);
if (str) {
snprintf(str, PATH_MAX + 16, "TMPDIR=%s/tmp", g_ddnatv_root);
new_env[dst++] = str;
}
}
if (!has_threads_max) {
new_env[dst++] = strdup("DPKG_DEB_THREADS_MAX=1");
}
if (!has_xz_opt) {
new_env[dst++] = strdup("XZ_OPT=-T1");
}
if (!has_xz_defaults) {
new_env[dst++] = strdup("XZ_DEFAULTS=-T1");
}
if (!has_frontend) {
new_env[dst++] = strdup("DEBIAN_FRONTEND=noninteractive");
}
if (!has_debconf_frontend) {
new_env[dst++] = strdup("DEBCONF_FRONTEND=noninteractive");
}
if (!has_debconf_seen) {
new_env[dst++] = strdup("DEBCONF_NONINTERACTIVE_SEEN=true");
}
new_env[dst] = NULL;
free(filtered_host_chain);
return new_env;
}
static void free_modified_env(char **modified_env, char *const orig_env[]) {
if (!modified_env) return;
for (int i = 0; modified_env[i] != NULL; i++) {
int is_orig = 0;
if (orig_env) {
for (int j = 0; orig_env[j] != NULL; j++) {
if (modified_env[i] == orig_env[j]) {
is_orig = 1;
break;
}
}
}
if (!is_orig) {
free(modified_env[i]);
}
}
free(modified_env);
}
#endif /* !DDNATV_HOST_TEST */