From 7ef529724c66d639ed55c9a5e9906eaacf5a6342 Mon Sep 17 00:00:00 2001 From: ssfuisu Date: Fri, 4 Dec 2026 23:04:57 +0300 Subject: [PATCH 1/3] Cortex 1.29.2 - Both spellings of the app's storage (/data/user/0 and /data/data) mean the rootfs, in the hook and in gosys: ./script.sh, gcc's cc1, venv pip and bundled JDKs no longer fail with EACCES (#84) - openat2() with RESOLVE_* is emulated by a component walk where the kernel lacks it: tar 1.35 extracts on kernels before 5.6 (#84) - termios: TCGETS2/TCSETS2 fall back to TCGETS/TCSETS*, which SELinux allows on a pty: nano, stty, tty, mc, Python termios (#85) - gosys: syscalls past 5.1 answer ENOSYS (faccessat2 SIGSYS in go run); /proc/self/exe names the program behind the exec runner, so go finds its GOROOT (#85) - getcwd() gives the Ubuntu path like realpath(".") does: rsync works again - fexecve()/execveat() of rootfs programs go through the exec runner - apt: rust-coreutils and sudo-rs pinned away, an empty coreutils-from-uutils stand-in keeps build-essential installable with GNU coreutils (SIGILL on ARMv8.0 cores) - compat-nightly: results were never published (grep -q + pipefail SIGPIPE) - compat.sh: wget/curl fetch debian.org with retries - Docs: XFCE + Firefox desktop (no Openbox) Co-Authored-By: Claude Opus 5.5 --- .github/workflows/build-release.yml | 2 +- .github/workflows/compat-nightly.yml | 4 +- CHANGELOG.md | 48 ++++ README.md | 6 +- app/build.gradle.kts | 4 +- app/src/main/cpp/cortex-hook.c | 3 + app/src/main/cpp/gosys/gosys.c | 135 ++++++++++- app/src/main/cpp/gosys/gosys_abi.h | 2 +- app/src/main/cpp/hook/exec.c | 51 ++++ app/src/main/cpp/hook/fileops.c | 28 ++- app/src/main/cpp/hook/files.c | 6 +- app/src/main/cpp/hook/ids.c | 5 +- app/src/main/cpp/hook/openat2_walk.c | 222 ++++++++++++++++++ app/src/main/cpp/hook/paths.c | 71 +++++- app/src/main/cpp/hook/termios.c | 193 +++++++++++++++ .../terminal/runtime/AptConfigurator.kt | 47 ++++ .../terminal/runtime/BootstrapManager.kt | 2 +- .../terminal/runtime/AptConfiguratorTest.kt | 22 ++ docs/index.html | 6 +- docs/llms.txt | 2 +- .../android/en-US/changelogs/12902.txt | 4 + .../android/en-US/full_description.txt | 2 +- tests/e2e/compat.sh | 5 +- tests/native/test_cortex_native.c | 134 +++++++++++ 24 files changed, 975 insertions(+), 29 deletions(-) create mode 100644 app/src/main/cpp/hook/openat2_walk.c create mode 100644 app/src/main/cpp/hook/termios.c create mode 100644 fastlane/metadata/android/en-US/changelogs/12902.txt diff --git a/.github/workflows/build-release.yml b/.github/workflows/build-release.yml index e6905c74..971471aa 100644 --- a/.github/workflows/build-release.yml +++ b/.github/workflows/build-release.yml @@ -232,7 +232,7 @@ jobs: chmod 0644 extra-rootfs/etc/apt/sources.list.d/ubuntu.sources echo "# Disabled for Cortex" > extra-rootfs/etc/apt/apt.conf.d/docker-clean mkdir -p extra-rootfs/etc/apt/preferences.d - printf 'Explanation: Pin core glibc and linker packages to prevent upgrading to stock upstream packages that fail Android SECCOMP\nPackage: libc6 libc6-dev libc6-dbg\nPin: release *\nPin-Priority: -1\n\nPackage: libc-bin\nPin: release *\nPin-Priority: -1\n\nPackage: libc-dev-bin\nPin: release *\nPin-Priority: -1\n\nPackage: locales\nPin: release *\nPin-Priority: -1\n' > extra-rootfs/etc/apt/preferences.d/01cortex-pins + printf 'Explanation: Pin core glibc and linker packages to prevent upgrading to stock upstream packages that fail Android SECCOMP\nPackage: libc6 libc6-dev libc6-dbg\nPin: release *\nPin-Priority: -1\n\nPackage: libc-bin\nPin: release *\nPin-Priority: -1\n\nPackage: libc-dev-bin\nPin: release *\nPin-Priority: -1\n\nPackage: locales\nPin: release *\nPin-Priority: -1\n\nExplanation: Keep GNU coreutils and sudo: the Rust versions need ARMv8.1 instructions\nPackage: rust-coreutils sudo-rs\nPin: release *\nPin-Priority: -1\n' > extra-rootfs/etc/apt/preferences.d/01cortex-pins printf 'force-confdef\nforce-confold\nforce-unsafe-io\nno-debsig\n' > extra-rootfs/etc/dpkg/dpkg.cfg.d/01cortex printf 'export DPKG_DEB_THREADS_MAX=1\nexport XZ_OPT=-T1\nexport XZ_DEFAULTS=-T1\nexport TAR_OPTIONS=--no-same-owner\nexport DEBIAN_FRONTEND=noninteractive\nexport DEBCONF_FRONTEND=noninteractive\nexport DEBCONF_NONINTERACTIVE_SEEN=true\nunset PREFIX\nexport GODEBUG=netdns=cgo\nshopt -s checkwinsize 2>/dev/null\nexport PATH="/home/.local/bin:$HOME/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:$PATH"\nif [ -n "$CORTEX_ROOT" ]; then\n export SSL_CERT_FILE="$CORTEX_ROOT/etc/ssl/certs/ca-certificates.crt"\n export SSL_CERT_DIR="$CORTEX_ROOT/etc/ssl/certs:/system/etc/security/cacerts"\n export CURL_CA_BUNDLE="$CORTEX_ROOT/etc/ssl/certs/ca-certificates.crt"\n export NODE_EXTRA_CA_CERTS="$CORTEX_ROOT/etc/ssl/certs/ca-certificates.crt"\n export REQUESTS_CA_BUNDLE="$CORTEX_ROOT/etc/ssl/certs/ca-certificates.crt"\nelse\n export SSL_CERT_FILE=/etc/ssl/certs/ca-certificates.crt\n export CURL_CA_BUNDLE=/etc/ssl/certs/ca-certificates.crt\nfi\nexport TZDIR=/usr/share/zoneinfo\nif [ -d /etc/cortex/autostart ]; then\n for s in /etc/cortex/autostart/*; do\n if [ -f "$s" ]; then\n sname="$(basename "$s")"\n service "$sname" start >/dev/null 2>&1 || true\n fi\n done\nfi\n' > extra-rootfs/etc/profile.d/01cortex.sh diff --git a/.github/workflows/compat-nightly.yml b/.github/workflows/compat-nightly.yml index 873f8f7f..5add4f72 100644 --- a/.github/workflows/compat-nightly.yml +++ b/.github/workflows/compat-nightly.yml @@ -118,7 +118,9 @@ jobs: git config user.email "41898282+github-actions[bot]@users.noreply.github.com" git add docs/compat.json # Not a commit a day: only when a result or the release changed (the date alone does not) - if ! git diff --cached -U0 | grep '^[-+] ' | grep -vq '"date"'; then + # (no grep -q: it stops reading at its first match, git diff then dies of SIGPIPE, and with + # pipefail a big change looked like none: the results of 1.29.x were never published) + if ! git diff --cached -U0 | grep '^[-+] ' | grep -v '"date"' > /dev/null; then echo "The results did not change." exit 0 fi diff --git a/CHANGELOG.md b/CHANGELOG.md index f541ad18..7d745b11 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,54 @@ What changed in each version of Cortex Terminal, newest first. The release workf of a GitHub release from the section of its version here. Older versions are described on the [GitHub releases](https://github.com/ssfuisu/cortex/releases) page. +## 1.29.2 (2026-12-04) + +### Fixed + +- **`./script.sh`, gcc, a venv's python and bundled JDKs failed with "Permission denied"** + ([#84](https://github.com/ssfuisu/cortex/issues/84)). Android reaches the app's storage as both + `/data/user/0/…` and `/data/data/…`, and the kernel answers `getcwd()`, `/proc/self/cwd` and + `realpath()` with either. A rootfs path spelled the other way was taken for one of Android's: it was + not mapped and was started without the exec runner, which Android 10+ refuses for the app's storage + since 1.29.0 (`bash: ./start.sh: /bin/bash: bad interpreter: Permission denied`, + `gcc: fatal error: cannot execute '…/usr/bin/../libexec/gcc/…/cc1': execv: Permission denied`, + `python3 -m venv` then `v/bin/pip`). Both spellings now mean the rootfs, in the hook and in the code + added to Go programs. +- **`tar -x` failed with "Cannot open: Function not implemented" on kernels before 5.6** + ([#84](https://github.com/ssfuisu/cortex/issues/84)). GNU tar 1.35 opens every file it extracts + with `openat2(RESOLVE_BENEATH)` and has no fallback; where the kernel has no `openat2` (or Android's + seccomp filter refuses it) the hook now walks the path one component at a time with the same + guarantees (checked against the kernel's own `openat2` in the tests). +- **nano, stty, tty, mc and Python's termios: "Permission denied" / "not a tty"** + ([#85](https://github.com/ssfuisu/cortex/issues/85)). glibc 2.42+ reads and sets a terminal's + attributes only with the `TCGETS2`/`TCSETS2` ioctls, which the SELinux policy of apps refuses for a + pty. `tcgetattr`, `tcsetattr`, `isatty` and `ttyname` fall back to the old `TCGETS`/`TCSETS*` the + way glibc 2.43 would use them. +- **Go: "SIGSYS: bad system call" in `go run` and "cannot find GOROOT"** + ([#85](https://github.com/ssfuisu/cortex/issues/85)). Go 1.26's `os/exec.LookPath` calls + `faccessat2`, which Android's seccomp filter can refuse; system calls newer than Linux 5.1 now + answer `ENOSYS` in Go programs (Go falls back from it), as they already did in static C programs. + A program started through the exec runner saw the runner as `/proc/self/exe`; Go programs now see + their own path, so `go` finds its GOROOT without `export GOROOT=…`. +- **Every command after `apt install build-essential` died with "Illegal instruction"** on older + ARM cores (and on the emulator). Ubuntu 26.04's build-essential depends on + `coreutils-from-uutils`, which replaced GNU coreutils with the Rust uutils, built with ARMv8.1 + instructions. `rust-coreutils` and `sudo-rs` are now pinned away, and an empty stand-in for + `coreutils-from-uutils` keeps build-essential installable next to GNU coreutils. The nightly package + test of 1.29.1 failed 32 of 34 packages because of this and the first item. +- **rsync: "change_dir#2 … failed: No such file or directory"** for every local copy. `getcwd()` + answered the directory's Android path while `realpath(".")` and `/proc/self/cwd` gave the Ubuntu + one; rsync's receiver walks the directory from "/" and looked for `data/data/…` in the rootfs. + `getcwd()` now gives the Ubuntu path (`/tmp/x`) too. +- **`fexecve()` and `execveat()`** of a program in the rootfs (sudo can start the command this way) + go through the same path as `execve()` instead of being refused by Android. + +### Changed + +- README, store text and website: the desktop is XFCE with Firefox (Openbox was removed in 1.29.1). +- The package test fetches with `wget --tries` and `curl --retry` from debian.org: ubuntu.com refuses some of the CI + machines' connections. + ## 1.29.1 (2026-11-28) ### Fixed diff --git a/README.md b/README.md index b862eb75..2d922a3f 100644 --- a/README.md +++ b/README.md @@ -57,7 +57,7 @@ flowchart LR 3. **Android's restrictions are handled one by one.** Android forbids some system calls for apps (seccomp), hard links, System V shared memory and locks on memory files. Each of these has its own code in the library (see the table below). 4. **Static programs are patched, not traced.** A program that makes its own system calls never passes through libc. Before such a program starts for the first time, Cortex patches the forbidden calls in its file (static C and C++) or adds a small piece of code that maps its paths (Go 1.19 and newer, 64-bit). -The library is about 10,000 lines of C in [`app/src/main/cpp/hook`](app/src/main/cpp/hook), with tests that run it under qemu on every change. +The library is about 13,000 lines of C in [`app/src/main/cpp/hook`](app/src/main/cpp/hook), with tests that run it under qemu on every change. ### Is this PRoot or fakechroot? @@ -147,7 +147,7 @@ cortex-desktop install xfce # optional desktop, also f **Desktop and remote** -- X11 desktop (Openbox or XFCE, optional Firefox) shown inside the app, with touch and touchpad modes, shared clipboard and sound +- X11 desktop (XFCE with Firefox) shown inside the app, with touch and touchpad modes, shared clipboard and sound - Drawn by the CPU over a private socket, no network port - `cortex-sshd`: OpenSSH on port 8022 to use Cortex from a computer @@ -194,7 +194,7 @@ Most command-line software does. Every night a job installs a set of common pack No. Containers need Linux namespaces, mounts and cgroups, which Android never gives to an ordinary app. **Is there a GUI?** -Yes, as an add-on: *Desktop* in the menu installs Openbox or XFCE (and Firefox if you want) and shows it inside the app. It's drawn by the CPU, no GPU, so it suits editors and browsing more than games. +Yes, as an add-on: *Desktop* in the menu installs XFCE and Firefox and shows it inside the app. It's drawn by the CPU, no GPU, so it suits editors and browsing more than games. **Does it work on 32-bit phones?** Yes, `Cortex-armeabi-v7a-signed.apk` is Ubuntu's armhf. Every change builds it and installs and sets it up on an emulator, but the emulator can't run 32-bit Ubuntu programs, so the in-terminal tests only run for 64-bit. Reports from 32-bit phones help. diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 91b879f5..988b9478 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -16,8 +16,8 @@ android { // privacy warnings. Writable rootfs binaries (app_data_file) execute via libcortex-exec.so // in nativeLibraryDir (apk_data_file), which holds execute_no_trans under targetSdk >= 29. targetSdk = 35 - versionCode = 12901 - versionName = "1.29.1" + versionCode = 12902 + versionName = "1.29.2" // UbuntuOnDeviceTest (app/src/androidTest), on Firebase Test Lab testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" diff --git a/app/src/main/cpp/cortex-hook.c b/app/src/main/cpp/cortex-hook.c index 8e8e7582..7c5d30f8 100644 --- a/app/src/main/cpp/cortex-hook.c +++ b/app/src/main/cpp/cortex-hook.c @@ -45,6 +45,7 @@ #include #include #include +#include #ifndef RENAME_EXCHANGE #define RENAME_EXCHANGE (1 << 1) @@ -86,6 +87,7 @@ static void *cortex_next(void *own, const char *name) { #include "hook/ids.c" #include "hook/signals.c" #include "hook/setup.c" +#include "hook/openat2_walk.c" #include "hook/files.c" #include "hook/fileops.c" #include "hook/identity.c" @@ -100,3 +102,4 @@ static void *cortex_next(void *own, const char *name) { #include "hook/sockets.c" #include "hook/sysv_shm.c" #include "hook/memfd_locks.c" +#include "hook/termios.c" diff --git a/app/src/main/cpp/gosys/gosys.c b/app/src/main/cpp/gosys/gosys.c index a1ee323e..d93e8db2 100644 --- a/app/src/main/cpp/gosys/gosys.c +++ b/app/src/main/cpp/gosys/gosys.c @@ -109,6 +109,31 @@ static int in_root(const struct gosys_hdr *h, const char *p) { return p[n] == '/' || p[n] == '\0'; } +// The length of the rootfs's other spelling that `p` starts with (/data/data/PKG for /data/user/0/PKG +// and the other way, hook/paths.c), or 0. The kernel answers getcwd() with either. +static u64 alias_len(const struct gosys_hdr *h, const char *p, u64 lim) { + u64 rl = h->root_len; + const char *root = hstr(h, h->root_off); + const char *from, *to; + u64 fl, tl; + if (rl > 13 && root[0] == '/' && root[1] == 'd' && root[5] == '/' && root[6] == 'u') { + from = "/data/user/0/"; fl = 13; to = "/data/data/"; tl = 11; + } else if (rl > 11 && root[0] == '/' && root[1] == 'd' && root[5] == '/' && root[6] == 'd') { + from = "/data/data/"; fl = 11; to = "/data/user/0/"; tl = 13; + } else { + return 0; + } + for (u64 i = 0; i < fl; i++) + if (root[i] != from[i]) return 0; + // p[i] past lim (a buffer that is not NUL-terminated) counts as its end + for (u64 i = 0; i < tl; i++) + if (i >= lim || p[i] != to[i]) return 0; + for (u64 i = fl; i < rl; i++) + if (tl + i - fl >= lim || p[tl + i - fl] != root[i]) return 0; + u64 n = tl + rl - fl; + return (n >= lim || p[n] == '/' || p[n] == '\0') ? n : 0; +} + // Android's own mounts and files, which must never be redirected into the rootfs (hook/paths.c) static int is_host_path(const char *path) { switch (path[1]) { @@ -148,6 +173,14 @@ static const char *rw_path(const struct gosys_hdr *h, const char *path, char *bu return buf; } if (in_root(h, path)) return path; + u64 al = path[1] == 'd' ? alias_len(h, path, ~(u64)0) : 0; + if (al) { // the rootfs, spelled the other way: the hook's spelling, so that execve() finds it in the rootfs + u64 rest = slen(path + al); + if (rl + rest + 1 > cap) return path; + mcopy(buf, root, rl); + mcopy(buf + rl, path + al, rest + 1); + return buf; + } if (pre(path, "/dev/shm", 8)) { u64 rest = slen(path + 8); if (rl + 8 + rest + 1 > cap) return path; @@ -260,10 +293,17 @@ static void put_slot(const struct gosys_hdr *h, u32 held) { static i64 unmap_prefix(const struct gosys_hdr *h, char *buf, i64 n, int nul) { u64 rl = h->root_len; const char *root = hstr(h, h->root_off); - if (rl == 0 || n <= 0 || (u64)n < rl + (nul ? 1 : 0)) return n; - for (u64 i = 0; i < rl; i++) - if (buf[i] != root[i]) return n; + if (rl == 0 || n <= 0) return n; u64 end = (u64)n - (nul ? 1 : 0); // the path's own length + int same = end >= rl; + for (u64 i = 0; same && i < rl; i++) + if (buf[i] != root[i]) same = 0; + if (!same) { + // the other spelling of the rootfs (getcwd() answers with the one the kernel resolved) + u64 al = alias_len(h, buf, end); + if (al == 0) return n; + rl = al; + } if (end == rl) { // exactly the rootfs buf[0] = '/'; if (nul) { @@ -454,6 +494,82 @@ static int is_proc_version(const char *p) { return 1; } +#define NR_CLOSE 57 +#define NR_READ 63 + + +// A program started through libcortex-exec.so (Android 10 and newer refuse to start the files of an +// app's storage directly) is, for the kernel, that library: /proc/self/exe names it, and Go found +// neither its GOROOT ("go: cannot find GOROOT directory: 'go' binary is trimmed") nor itself in +// os.Executable(). The kernel's /proc/self/auxv names the runner too (AT_EXECFN is the path given to +// execve()), so the program's path is taken where the hook gave it to the runner: CORTEX_EXEC_BIN in +// the environment the process started with (the runner drops it from the list, the text stays), or +// else argv[0] (the hook passes the full path there). `buf` holds the n bytes readlink() gave; +// returns the new length. +static i64 exe_behind_runner(const struct gosys_hdr *h, const char *link, char *buf, i64 n, i64 bufsiz, char *slot) { + u64 rl = h->exec_runner_len; + if (rl == 0 || (u64)n != rl || !link || !slot) return n; + if (!(pre(link, "/proc/self/exe", 14) && link[14] == '\0') && + !(pre(link, "/proc/thread-self/exe", 21) && link[21] == '\0')) return n; + const char *runner = hstr(h, h->exec_runner_off); + for (u64 i = 0; i < rl; i++) + if (buf[i] != runner[i]) return n; + char *mem = slot + SLOT_ENV; + const i64 cap = 16384; + for (int pass = 0; pass < 2; pass++) { + i64 fd = sc(NR_OPENAT, AT_FDCWD, (i64)(pass == 0 ? "/proc/self/environ" : "/proc/self/cmdline"), + 0 /* O_RDONLY */ | 02000000 /* O_CLOEXEC */, 0, 0, 0); + if (fd < 0) continue; + i64 have = 0; + const char *found = 0; + u64 flen = 0; + for (;;) { + i64 k = sc(NR_READ, fd, (i64)(mem + have), cap - have, 0, 0, 0); + if (k > 0) have += k; + int eof = k <= 0; + // whole entries in mem[0..have) + i64 s = 0; + while (!found) { + i64 e = s; + while (e < have && mem[e] != '\0') e++; + if (e >= have && !eof) break; // cut entry: read more + const char *ent = mem + s; + if (pass == 0) { + if (e - s > 16 && pre(ent, "CORTEX_EXEC_BIN=", 16) && ent[16] == '/') { + found = ent + 16; + flen = (u64)(e - s - 16); + } + } else { + if (e > s && ent[0] == '/') { + found = ent; + flen = (u64)(e - s); + } + s = have; // only argv[0] + break; + } + s = e + 1; + if (s >= have) break; + } + if (found || eof || pass == 1) break; + if (s == 0) { + if (have < cap) continue; // a short read: the rest of the entry comes next + // an entry longer than the buffer: skip it + have = 0; + continue; + } + for (i64 i = s; i < have; i++) mem[i - s] = mem[i]; + have -= s; + } + sc(NR_CLOSE, fd, 0, 0, 0, 0, 0); + if (found && flen > 0) { + if (flen > (u64)bufsiz) flen = (u64)bufsiz; + for (u64 i = 0; i < flen; i++) buf[i] = found[i]; + return (i64)flen; + } + } + return n; +} + // Rewrites the path arguments `i1` and `i2` (an index into a[], -1: none) that are absolute, makes // the call, and shows the program the paths it expects in what the call returns. static i64 with_paths(const struct gosys_hdr *h, u32 *held, i64 nr, i64 *a, int i1, int i2) { @@ -486,12 +602,25 @@ static i64 with_paths(const struct gosys_hdr *h, u32 *held, i64 nr, i64 *a, int return 0; } } + if (proc_link && r > 0) r = exe_behind_runner(h, orig_p, (char *)a[2], r, a[3], slot); if (proc_link && r > 0) r = unmap_prefix(h, (char *)a[2], r, 0); return r; } // The call itself; a slot that it takes is given back by cxgo_entry static i64 handle(const struct gosys_hdr *h, u32 *held, i64 nr, i64 a0, i64 a1, i64 a2, i64 a3, i64 a4, i64 a5) { + // System calls newer than Linux 5.1 (424 and up: pidfd_*, clone3, openat2, faccessat2, ...) may + // be missing from Android's seccomp allowlist, and a call that it refuses kills a Go program with + // SIGSYS ("SIGSYS: bad system call" in os/exec.LookPath, which uses faccessat2 for AT_EACCESS, + // #85): the C library's code is patched the same way (hook/static_programs.c). Go falls back + // from ENOSYS for each of them; faccessat2 without flags is the plain faccessat. + if (nr >= 424 && nr < 512) { + if (nr == NR_FACCESSAT2 && a3 == 0) { + nr = NR_FACCESSAT; + } else { + return -38; // -ENOSYS + } + } i64 a[6] = { a0, a1, a2, a3, a4, a5 }; switch (nr) { case NR_OPENAT: case NR_FACCESSAT: case NR_FACCESSAT2: case NR_FCHMODAT: case NR_FCHMODAT2: diff --git a/app/src/main/cpp/gosys/gosys_abi.h b/app/src/main/cpp/gosys/gosys_abi.h index 813658b0..48e7f4fb 100644 --- a/app/src/main/cpp/gosys/gosys_abi.h +++ b/app/src/main/cpp/gosys/gosys_abi.h @@ -15,7 +15,7 @@ #include #ifndef GOSYS_VERSION -#define GOSYS_VERSION 4u // raised when the code or its header changes: patched programs are patched again +#define GOSYS_VERSION 6u // raised when the code or its header changes: patched programs are patched again #endif // The scratch memory for rewritten paths: a small state area and 64 slots, in zero-filled memory the diff --git a/app/src/main/cpp/hook/exec.c b/app/src/main/cpp/hook/exec.c index 3acefe0b..f930471e 100644 --- a/app/src/main/cpp/hook/exec.c +++ b/app/src/main/cpp/hook/exec.c @@ -472,6 +472,57 @@ int execve(const char *filename, char *const argv[], char *const envp[]) { return cortex_execve(filename, argv, envp, 0); } +// fexecve() and execveat(): the kernel would start the file itself, which is not possible for one +// in the app's storage (no exec from it for apps on Android 10 and newer; a dynamic program would +// also ask for an ld.so that Android does not have). A file with a name (sudo starts the command +// through its descriptor) is started by that name, like execve(); a nameless one (memfd) is left +// to the kernel. +static int exec_by_fd_path(int fd, char *out, size_t outsz) { + char link[64]; + snprintf(link, sizeof(link), "/proc/self/fd/%d", fd); + ssize_t n = (ssize_t)syscall(SYS_readlinkat, AT_FDCWD, link, out, outsz - 1); + if (n <= 0) return 0; + out[n] = '\0'; + if (out[0] != '/' || strstr(out, " (deleted)") != NULL) return 0; + init_cortex_hook(); + return rootfs_prefix_len(out) > 0; +} + +int fexecve(int fd, char *const argv[], char *const envp[]) { + char path[PATH_MAX]; + if (exec_by_fd_path(fd, path, sizeof(path))) return cortex_execve(path, argv, envp, 0); + static int (*orig)(int, char *const[], char *const[]) = NULL; + if (!orig) orig = (int (*)(int, char *const[], char *const[]))dlsym(RTLD_NEXT, "fexecve"); + if (!orig) { + errno = ENOSYS; + return -1; + } + return orig(fd, argv, envp); +} + +#ifndef AT_EMPTY_PATH +#define AT_EMPTY_PATH 0x1000 +#endif + +int execveat(int dirfd, const char *pathname, char *const argv[], char *const envp[], int flags) { + if (pathname && pathname[0] == '/') { + if (!(flags & AT_SYMLINK_NOFOLLOW)) return cortex_execve(pathname, argv, envp, 0); + } else if (pathname && pathname[0] == '\0' && (flags & AT_EMPTY_PATH)) { + char path[PATH_MAX]; + if (exec_by_fd_path(dirfd, path, sizeof(path))) return cortex_execve(path, argv, envp, 0); + } else if (pathname && dirfd == AT_FDCWD && !(flags & AT_SYMLINK_NOFOLLOW)) { + return cortex_execve(pathname, argv, envp, 0); + } else if (pathname && !(flags & AT_SYMLINK_NOFOLLOW)) { + char dir[PATH_MAX]; + if (exec_by_fd_path(dirfd, dir, sizeof(dir))) { + char path[PATH_MAX]; + int n = snprintf(path, sizeof(path), "%s/%s", dir, pathname); + if (n > 0 && (size_t)n < sizeof(path)) return cortex_execve(path, argv, envp, 0); + } + } + return (int)syscall(SYS_execveat, dirfd, pathname, argv, envp, flags); +} + // ---- fork() --------------------------------------------------------------------------------- // A shell (and make, dpkg, perl, ...) starts a program with fork() and then execve() in the child. // What the exec code above needs for the first time in a process (glibc's execve, fstat and readlink diff --git a/app/src/main/cpp/hook/fileops.c b/app/src/main/cpp/hook/fileops.c index d12797c0..c3df0a14 100644 --- a/app/src/main/cpp/hook/fileops.c +++ b/app/src/main/cpp/hook/fileops.c @@ -631,11 +631,30 @@ int fchdir(int fd) { return ret; } -// Hook getcwd +// Hook getcwd: the working directory as Ubuntu programs know it, "/tmp/x" for $CORTEX_ROOT/tmp/x +// (in either spelling of the rootfs), as readlink("/proc/self/cwd") and realpath(".") already +// answered. A program that walks the directory from "/" (rsync's receiver opens "/" and then each +// component) found "data/data/org.cortex.terminal/..." in the rootfs's "/", which does not exist +// ("change_dir#2 ... failed: No such file or directory"). A directory whose Ubuntu path would be +// taken for one of Android's (the rootfs's own /data, /proc, ...) keeps its real path, which the +// hook leaves alone. char *getcwd(char *buf, size_t size) { static char *(*orig_getcwd)(char *, size_t) = NULL; if (!orig_getcwd) orig_getcwd = (char *(*)(char *, size_t))dlsym(RTLD_NEXT, "getcwd"); - return orig_getcwd ? orig_getcwd(buf, size) : NULL; + char *res = orig_getcwd ? orig_getcwd(buf, size) : NULL; + if (!res) return res; + init_cortex_hook(); + size_t rlen = rootfs_prefix_len(res); + if (rlen == 0) return res; + const char *sub = res + rlen; + if (sub[0] == '\0') { + res[0] = '/'; + res[1] = '\0'; + return res; + } + if (is_android_host_path(sub)) return res; + memmove(res, sub, strlen(sub) + 1); + return res; } char *__getcwd_chk(char *buf, size_t size, size_t buflen) { @@ -669,8 +688,9 @@ char *realpath(const char *path, char *resolved_path) { const char *target = rewrite_path(path, pbuf, sizeof(pbuf)); char *res = orig_realpath ? orig_realpath(target, resolved_path) : NULL; if (res && g_cortex_root[0] != '\0') { - size_t rlen = g_cortex_root_len; - if (strncmp(res, g_cortex_root, rlen) == 0 && (res[rlen] == '/' || res[rlen] == '\0')) { + // either spelling of the rootfs: realpath() follows /data/user/0 -> /data/data where that is a link + size_t rlen = rootfs_prefix_len(res); + if (rlen > 0) { size_t rem_len = strlen(res + rlen); if (rem_len == 0) { res[0] = '/'; diff --git a/app/src/main/cpp/hook/files.c b/app/src/main/cpp/hook/files.c index 3a1a42ba..2f42f846 100644 --- a/app/src/main/cpp/hook/files.c +++ b/app/src/main/cpp/hook/files.c @@ -404,10 +404,10 @@ int openat2(int dirfd, const char *pathname, cortex_open_how_arg_t how, size_t u // RESOLVE_BENEATH, RESOLVE_NO_SYMLINKS and the other resolve flags restrict every component of // the path, which a plain openat() cannot do (a symlink in the middle would still be followed). - // Say so: callers such as gnulib's openat2 (GNU tar) then walk the path safely themselves. + // GNU tar 1.35 has no fallback of its own ("Cannot open: Function not implemented" for every + // file it extracted on kernels before 5.6, #84): the path is walked one component at a time. if (how->resolve != 0) { - errno = ENOSYS; - return -1; + return cortex_openat2_walk(dirfd, target, flags, mode, how->resolve); } if (open_needs_mode(flags)) { diff --git a/app/src/main/cpp/hook/ids.c b/app/src/main/cpp/hook/ids.c index 95d278a8..b4f33ac6 100644 --- a/app/src/main/cpp/hook/ids.c +++ b/app/src/main/cpp/hook/ids.c @@ -557,8 +557,9 @@ static int g_cwd_in_home = -1; static int is_in_cortex_home(const char *path) { if (!path || g_cortex_root_len == 0) return 0; - if (strncmp(path, g_cortex_root, g_cortex_root_len) != 0) return 0; - const char *sub = path + g_cortex_root_len; + size_t rlen = rootfs_prefix_len(path); // /proc/self/cwd may give the other spelling + if (rlen == 0) return 0; + const char *sub = path + rlen; return strncmp(sub, "/home", 5) == 0 && (sub[5] == '/' || sub[5] == '\0'); } diff --git a/app/src/main/cpp/hook/openat2_walk.c b/app/src/main/cpp/hook/openat2_walk.c new file mode 100644 index 00000000..14317c8e --- /dev/null +++ b/app/src/main/cpp/hook/openat2_walk.c @@ -0,0 +1,222 @@ +// Part of libcortex-hook.so, included by cortex-hook.c (one translation unit, so the +// parts share their static functions and are built with the same command as before). +// +// openat2() with RESOLVE_* flags where the kernel has no openat2 (Linux before 5.6, the kernel of +// many phones) or Android's seccomp filter refuses it: the path is walked one component at a +// time with openat(O_PATH | O_NOFOLLOW), so that RESOLVE_BENEATH, RESOLVE_IN_ROOT and +// RESOLVE_NO_SYMLINKS hold for every component, as the kernel's would. GNU tar 1.35 extracts every +// file through openat2(RESOLVE_BENEATH) and has no fallback of its own (#84). Also built by +// tests/native (no hooks used: only relative openat() calls, which the hook passes on unchanged). + +#define CORTEX_RESOLVE_NO_XDEV 0x01 +#define CORTEX_RESOLVE_NO_MAGICLINKS 0x02 +#define CORTEX_RESOLVE_NO_SYMLINKS 0x04 +#define CORTEX_RESOLVE_BENEATH 0x08 +#define CORTEX_RESOLVE_IN_ROOT 0x10 +#define CORTEX_RESOLVE_CACHED 0x20 +#define CORTEX_RESOLVE_ALL 0x3f +#define CORTEX_WALK_MAX_DEPTH 256 +#define CORTEX_WALK_MAX_LINKS 40 + +static void openat2_walk_close(int *fds, int depth) { + for (int i = depth; i >= 0; i--) { + if (fds[i] >= 0) close(fds[i]); + } +} + +// Returns the new descriptor, or -1 with errno set as the kernel's openat2() would set it. +static int cortex_openat2_walk(int dirfd, const char *path, int flags, mode_t mode, uint64_t resolve) { + if (!path) { + errno = EFAULT; + return -1; + } + if ((resolve & ~(uint64_t)CORTEX_RESOLVE_ALL) != 0 || + ((resolve & CORTEX_RESOLVE_BENEATH) && (resolve & CORTEX_RESOLVE_IN_ROOT))) { + errno = EINVAL; + return -1; + } + if (resolve & CORTEX_RESOLVE_CACHED) { + // "only from the cache": the kernel answers EAGAIN when it would have to block, callers retry + // without the flag + errno = EAGAIN; + return -1; + } + if (path[0] == '\0') { + errno = ENOENT; + return -1; + } + const int scoped = (resolve & (CORTEX_RESOLVE_BENEATH | CORTEX_RESOLVE_IN_ROOT)) != 0; + + // The rest of the path still to walk, in one of two buffers (a symlink's target is put in front + // of what is left of the path, in the other buffer) + static __thread char bufs[2][PATH_MAX]; + int cur_buf = 0; + size_t plen = strlen(path); + if (plen >= PATH_MAX) { + errno = ENAMETOOLONG; + return -1; + } + memcpy(bufs[0], path, plen + 1); + char *p = bufs[0]; + + int fds[CORTEX_WALK_MAX_DEPTH]; + int depth = 0; + if (p[0] == '/') { + if (resolve & CORTEX_RESOLVE_BENEATH) { + errno = EXDEV; + return -1; + } + // RESOLVE_IN_ROOT: "/" is dirfd itself; otherwise the real "/" + fds[0] = (resolve & CORTEX_RESOLVE_IN_ROOT) + ? (dirfd == AT_FDCWD ? openat(AT_FDCWD, ".", O_PATH | O_DIRECTORY | O_CLOEXEC) : fcntl(dirfd, F_DUPFD_CLOEXEC, 0)) + : (int)syscall(SYS_openat, AT_FDCWD, "/", O_PATH | O_DIRECTORY | O_CLOEXEC); + } else { + fds[0] = dirfd == AT_FDCWD ? openat(AT_FDCWD, ".", O_PATH | O_DIRECTORY | O_CLOEXEC) : fcntl(dirfd, F_DUPFD_CLOEXEC, 0); + } + if (fds[0] < 0) return -1; + const int root_fd_is_scope = scoped; + + int links = 0; + int result = -1; + int err = 0; + for (;;) { + while (*p == '/') p++; + if (*p == '\0') { + // the path ended in a directory ("dir/", ".", "..") + result = openat(fds[depth], ".", flags, mode); + if (result < 0) err = errno; + break; + } + char *end = strchr(p, '/'); + size_t clen = end ? (size_t)(end - p) : strlen(p); + char comp[NAME_MAX + 1]; + if (clen > NAME_MAX) { + err = ENAMETOOLONG; + break; + } + memcpy(comp, p, clen); + comp[clen] = '\0'; + char *rest = end ? end : p + clen; // starts with '/' or is "" + const int trailing_slash = end != NULL; + const char *after = rest; + while (*after == '/') after++; + const int is_last = *after == '\0'; + + if (strcmp(comp, ".") == 0) { + p = rest; + continue; + } + if (strcmp(comp, "..") == 0) { + if (depth > 0) { + close(fds[depth]); + depth--; + } else if (resolve & CORTEX_RESOLVE_BENEATH) { + err = EXDEV; + break; + } else if (!(resolve & CORTEX_RESOLVE_IN_ROOT)) { + // not scoped: the real parent of the starting directory + int up = openat(fds[0], "..", O_PATH | O_DIRECTORY | O_CLOEXEC); + if (up < 0) { + err = errno; + break; + } + close(fds[0]); + fds[0] = up; + } + // RESOLVE_IN_ROOT: ".." of the root is the root + p = rest; + continue; + } + + int fd = openat(fds[depth], comp, O_PATH | O_NOFOLLOW | O_CLOEXEC); + if (fd < 0) { + if (is_last && !trailing_slash && errno == ENOENT && (flags & O_CREAT)) { + result = openat(fds[depth], comp, flags | O_NOFOLLOW, mode); + if (result < 0) err = errno; + } else { + err = errno; + } + break; + } + struct stat st; + if (fstat(fd, &st) != 0) { + err = errno; + close(fd); + break; + } + if (S_ISLNK(st.st_mode)) { + if (is_last && !trailing_slash && (flags & O_NOFOLLOW)) { + // the link itself (O_PATH) or ELOOP, as the kernel decides + close(fd); + result = openat(fds[depth], comp, flags, mode); + if (result < 0) err = errno; + break; + } + if ((resolve & CORTEX_RESOLVE_NO_SYMLINKS) || ++links > CORTEX_WALK_MAX_LINKS) { + close(fd); + err = ELOOP; + break; + } + char target[PATH_MAX]; + ssize_t tlen = readlinkat(fds[depth], comp, target, sizeof(target) - 1); + close(fd); + if (tlen <= 0) { + err = tlen == 0 ? ENOENT : errno; + break; + } + target[tlen] = '\0'; + if (target[0] == '/') { + if (resolve & CORTEX_RESOLVE_BENEATH) { + err = EXDEV; + break; + } + // back to the root: dirfd's for RESOLVE_IN_ROOT, else the real "/" + if (!root_fd_is_scope) { + int r = (int)syscall(SYS_openat, AT_FDCWD, "/", O_PATH | O_DIRECTORY | O_CLOEXEC); + if (r < 0) { + err = errno; + break; + } + openat2_walk_close(fds, depth); + fds[0] = r; + depth = 0; + } else { + while (depth > 0) close(fds[depth--]); + } + } + // target + rest, in the other buffer + size_t rlen = strlen(rest); + if ((size_t)tlen + rlen >= PATH_MAX) { + err = ENAMETOOLONG; + break; + } + char *nb = bufs[cur_buf ^ 1]; + memcpy(nb, target, (size_t)tlen); + memcpy(nb + tlen, rest, rlen + 1); + cur_buf ^= 1; + p = nb; + continue; + } + if (is_last && !trailing_slash) { + close(fd); + result = openat(fds[depth], comp, flags | O_NOFOLLOW, mode); + if (result < 0) err = errno; + break; + } + if (!S_ISDIR(st.st_mode)) { + close(fd); + err = ENOTDIR; + break; + } + if (depth + 1 >= CORTEX_WALK_MAX_DEPTH) { + close(fd); + err = ENAMETOOLONG; + break; + } + fds[++depth] = fd; + p = rest; + } + openat2_walk_close(fds, depth); + if (result < 0) errno = err ? err : EIO; + return result; +} diff --git a/app/src/main/cpp/hook/paths.c b/app/src/main/cpp/hook/paths.c index 50fcd6da..b0ac1ebb 100644 --- a/app/src/main/cpp/hook/paths.c +++ b/app/src/main/cpp/hook/paths.c @@ -11,12 +11,69 @@ static char g_cortex_root[PATH_MAX] = {0}; static size_t g_cortex_root_len = 0; +static size_t cortex_append(char *out, size_t outsz, size_t used, const char *s, size_t len); + +// The other spelling of the rootfs's path. Android reaches an app's data directory as both +// /data/user/0/PKG and /data/data/PKG: the app is told one (Context.getFilesDir(), CORTEX_ROOT), +// while the kernel can answer with the other (getcwd(), /proc/self/cwd, realpath(), where one of +// them is a symlink to the other). A path in the rootfs spelled the other way was taken for one of +// Android's: not mapped, and started without the exec runner, so "./script.sh" failed with "bad +// interpreter: Permission denied" and gcc could not start cc1 (#84). Both spellings mean the rootfs. +static char g_cortex_root_alias[PATH_MAX] = {0}; +static size_t g_cortex_root_alias_len = 0; + +static void cortex_set_root_alias(void) { + static const char user0[] = "/data/user/0/"; + static const char data[] = "/data/data/"; + const char *from = NULL, *to = NULL; + size_t from_len = 0; + if (strncmp(g_cortex_root, user0, sizeof(user0) - 1) == 0) { + from = user0; from_len = sizeof(user0) - 1; to = data; + } else if (strncmp(g_cortex_root, data, sizeof(data) - 1) == 0) { + from = data; from_len = sizeof(data) - 1; to = user0; + } + g_cortex_root_alias[0] = '\0'; + g_cortex_root_alias_len = 0; + if (!from) return; + size_t n = cortex_append(g_cortex_root_alias, sizeof(g_cortex_root_alias), 0, to, strlen(to)); + n = cortex_append(g_cortex_root_alias, sizeof(g_cortex_root_alias), n, g_cortex_root + from_len, + g_cortex_root_len - from_len); + g_cortex_root_alias_len = n; +} + static void cortex_set_root(const char *root, size_t len) { if (!root) len = 0; if (len > sizeof(g_cortex_root) - 1) len = sizeof(g_cortex_root) - 1; if (len > 0) memcpy(g_cortex_root, root, len); g_cortex_root[len] = '\0'; g_cortex_root_len = len; + cortex_set_root_alias(); +} + +// Length of the rootfs prefix `p` starts with, in either spelling (followed by '/' or the end), or 0. +static size_t rootfs_prefix_len(const char *p) { + if (!p || g_cortex_root_len == 0) return 0; + if (strncmp(p, g_cortex_root, g_cortex_root_len) == 0 && + (p[g_cortex_root_len] == '/' || p[g_cortex_root_len] == '\0')) { + return g_cortex_root_len; + } + if (g_cortex_root_alias_len > 0 && strncmp(p, g_cortex_root_alias, g_cortex_root_alias_len) == 0 && + (p[g_cortex_root_alias_len] == '/' || p[g_cortex_root_alias_len] == '\0')) { + return g_cortex_root_alias_len; + } + return 0; +} + +// `p` spelled with the rootfs's other path: the same path with CORTEX_ROOT's spelling in buf, else NULL. +static const char *rootfs_alias_to_root(const char *p, char *buf, size_t bufsz) { + if (!p || g_cortex_root_alias_len == 0 || strncmp(p, g_cortex_root_alias, g_cortex_root_alias_len) != 0 || + (p[g_cortex_root_alias_len] != '/' && p[g_cortex_root_alias_len] != '\0')) { + return NULL; + } + size_t n = cortex_append(buf, bufsz, 0, g_cortex_root, g_cortex_root_len); + const char *rest = p + g_cortex_root_alias_len; + cortex_append(buf, bufsz, n, rest, strlen(rest)); + return buf; } // Appends s[0..len) to out[0..used) and NUL-terminates, truncating like snprintf. @@ -107,6 +164,10 @@ static const char *rewrite_path_in_root(const char *path, char *buffer, size_t b if (get_rootfs_subpath(path) != NULL) { return path; } + // Inside it, spelled the other way (/data/data/PKG for /data/user/0/PKG): CORTEX_ROOT's spelling + if (path[1] == 'd' && rootfs_alias_to_root(path, buffer, bufsize)) { + return buffer; + } // POSIX shared memory (/dev/shm) redirection to Cortex rootfs tmp/shm if (strncmp(path, "/dev/shm", 8) == 0 && (path[8] == '/' || path[8] == '\0')) { @@ -237,7 +298,15 @@ static ssize_t postprocess_readlink(const char *linkpath, char *buf, ssize_t ret // 1. Strip g_cortex_root if target starts with it if (g_cortex_root_len > 0 && !is_proc_fd_link(linkpath)) { size_t rlen = g_cortex_root_len; - if ((size_t)ret >= rlen && memcmp(buf, g_cortex_root, rlen) == 0 && + const char *prefix = g_cortex_root; + // the other spelling of the rootfs (/data/data/PKG for /data/user/0/PKG) is stripped as well + if (g_cortex_root_alias_len > 0 && (size_t)ret >= g_cortex_root_alias_len && + memcmp(buf, g_cortex_root_alias, g_cortex_root_alias_len) == 0 && + ((size_t)ret == g_cortex_root_alias_len || buf[g_cortex_root_alias_len] == '/')) { + rlen = g_cortex_root_alias_len; + prefix = g_cortex_root_alias; + } + if ((size_t)ret >= rlen && memcmp(buf, prefix, rlen) == 0 && ((size_t)ret == rlen || buf[rlen] == '/')) { size_t new_len = ret - rlen; if (new_len == 0) { diff --git a/app/src/main/cpp/hook/termios.c b/app/src/main/cpp/hook/termios.c new file mode 100644 index 00000000..7bbb2057 --- /dev/null +++ b/app/src/main/cpp/hook/termios.c @@ -0,0 +1,193 @@ +// Part of libcortex-hook.so, included by cortex-hook.c (one translation unit, so the +// parts share their static functions and are built with the same command as before). +// +// Terminal attributes where Android's SELinux policy refuses the termios2 ioctls. +// +// glibc 2.42 and newer (Ubuntu 26.04 has 2.43) read and set a terminal's attributes only with +// TCGETS2 / TCSETS2 (and isatty() is a TCGETS2), but the ioctl allowlist of the SELinux domain of +// apps only has the old TCGETS / TCSETS* for a pty: the new ones fail with EACCES. So isatty() said +// "not a terminal", and nano ("Standard input is not a terminal"), stty, tty, mc and Python's +// termios failed (#85). When the termios2 call is refused, these do what glibc 2.43 does with the +// old ioctls, which carry the same fields but the speeds only as the CBAUD bits of c_cflag. + +// The kernel's values (asm-generic, also ARM): the C library's headers that build the hook may be +// older than the glibc that runs it. +#define CX_TCGETS 0x5401 +#define CX_TCSETS 0x5402 +#define CX_TCGETS2 0x802c542aUL +#define CX_TCSETS2 0x402c542bUL +#define CX_CBAUD 0x0000100fu +#define CX_BOTHER 0x00001000u +#define CX_CIBAUD 0x100f0000u +#define CX_IBSHIFT 16 +#define CX_K_NCCS 19 + +struct cx_ktermios2 { + uint32_t c_iflag, c_oflag, c_cflag, c_lflag; + unsigned char c_line; + unsigned char c_cc[CX_K_NCCS]; + uint32_t c_ispeed, c_ospeed; +}; + +// The baud rate of a CBAUD code; `other` for BOTHER (and anything unknown), as glibc's ___cbaud_to_speed. +static uint32_t cx_cbaud_to_speed(uint32_t cbaud, uint32_t other) { + static const uint32_t low[16] = { 0, 50, 75, 110, 134, 150, 200, 300, 600, 1200, 1800, 2400, 4800, + 9600, 19200, 38400 }; + static const uint32_t high[16] = { 0, 57600, 115200, 230400, 460800, 500000, 576000, 921600, 1000000, + 1152000, 1500000, 2000000, 2500000, 3000000, 3500000, 4000000 }; + if ((cbaud & ~CX_CBAUD) != 0) return other; + if ((cbaud & CX_BOTHER) == 0) return low[cbaud & 0xf]; + if ((cbaud & 0xf) == 0) return other; // BOTHER + return high[cbaud & 0xf]; +} + +// The CBAUD code of a baud rate, BOTHER for one that has none (glibc's ___speed_to_cbaud). +static uint32_t cx_speed_to_cbaud(uint32_t speed) { + for (uint32_t c = 0; c < 16; c++) { + if (cx_cbaud_to_speed(c, 0xffffffffu) == speed) return c; + if (c > 0 && cx_cbaud_to_speed(CX_BOTHER | c, 0xffffffffu) == speed) return CX_BOTHER | c; + } + return CX_BOTHER; +} + +// glibc's ___termios2_canonicalize_speeds +static void cx_canonicalize_speeds(struct cx_ktermios2 *k) { + k->c_ospeed = cx_cbaud_to_speed(k->c_cflag & CX_CBAUD, k->c_ospeed); + k->c_ispeed = cx_cbaud_to_speed((k->c_cflag >> CX_IBSHIFT) & CX_CBAUD, k->c_ispeed); + if (!k->c_ispeed) k->c_ispeed = k->c_ospeed; + k->c_cflag &= ~(CX_CBAUD | CX_CIBAUD); + k->c_cflag |= cx_speed_to_cbaud(k->c_ospeed); + k->c_cflag |= cx_speed_to_cbaud(k->c_ispeed) << CX_IBSHIFT; +} + +// The kernel's attributes in glibc's struct termios, as glibc 2.43's tcgetattr() fills it. +static void cx_ktermios_to_termios(const struct cx_ktermios2 *k, struct termios *t) { + memset(t, 0, sizeof(*t)); + t->c_iflag = k->c_iflag; + t->c_oflag = k->c_oflag; + t->c_cflag = k->c_cflag; + t->c_lflag = k->c_lflag; + t->c_line = k->c_line; + size_t n = sizeof(t->c_cc) < CX_K_NCCS ? sizeof(t->c_cc) : CX_K_NCCS; + memcpy(t->c_cc, k->c_cc, n); + if (sizeof(t->c_cc) > n) memset(t->c_cc + n, _POSIX_VDISABLE, sizeof(t->c_cc) - n); + t->c_ispeed = k->c_ispeed; + t->c_ospeed = k->c_ospeed; +} + +// What glibc 2.43's tcsetattr() hands to the kernel. +static void cx_termios_to_ktermios(const struct termios *t, struct cx_ktermios2 *k) { + memset(k, 0, sizeof(*k)); + k->c_iflag = t->c_iflag; + k->c_oflag = t->c_oflag; + k->c_cflag = t->c_cflag; + k->c_lflag = t->c_lflag; + k->c_line = t->c_line; + k->c_ospeed = t->c_ospeed; + k->c_ispeed = t->c_ispeed; + cx_canonicalize_speeds(k); + memcpy(k->c_cc, t->c_cc, sizeof(t->c_cc) < CX_K_NCCS ? sizeof(t->c_cc) : CX_K_NCCS); + if (k->c_ospeed == k->c_ispeed) k->c_cflag &= ~CX_CIBAUD; +} + +#ifndef CORTEX_HOST_TEST + +// The attributes with the old TCGETS, for a terminal whose TCGETS2 is refused. 0, or -1 with errno. +static int cx_tcgets_old(int fd, struct cx_ktermios2 *k) { + memset(k, 0, sizeof(*k)); + if (syscall(SYS_ioctl, fd, CX_TCGETS, k) != 0) return -1; + cx_canonicalize_speeds(k); + return 0; +} + +int tcgetattr(int fd, struct termios *t) { + static int (*orig)(int, struct termios *) = NULL; + if (!orig) orig = (int (*)(int, struct termios *))cortex_next((void *)tcgetattr, "tcgetattr"); + int saved = errno; + int ret = orig ? orig(fd, t) : -1; + if (ret == 0 || (orig && errno != EACCES) || !t) return ret; + struct cx_ktermios2 k; + if (cx_tcgets_old(fd, &k) != 0) { + errno = EACCES; + return -1; + } + cx_ktermios_to_termios(&k, t); + errno = saved; + return 0; +} + +int tcsetattr(int fd, int optional_actions, const struct termios *t) { + static int (*orig)(int, int, const struct termios *) = NULL; + if (!orig) orig = (int (*)(int, int, const struct termios *))cortex_next((void *)tcsetattr, "tcsetattr"); + int saved = errno; + int ret = orig ? orig(fd, optional_actions, t) : -1; + if (ret == 0 || (orig && errno != EACCES) || !t) return ret; + unsigned long cmd = (unsigned long)((long)optional_actions - TCSANOW); + if (cmd > 2) { + errno = EINVAL; + return -1; + } + struct cx_ktermios2 k; + cx_termios_to_ktermios(t, &k); + // The old ioctls only carry speeds that have a CBAUD code, and one speed for both directions + // unless CIBAUD says otherwise: what a terminal emulator's pty is set to anyway + if ((k.c_cflag & CX_CBAUD) == CX_BOTHER || (((k.c_cflag >> CX_IBSHIFT) & CX_CBAUD) == CX_BOTHER)) { + errno = EACCES; + return -1; + } + if (syscall(SYS_ioctl, fd, CX_TCSETS + cmd, &k) != 0) return -1; + errno = saved; + return 0; +} + +int isatty(int fd) { + struct cx_ktermios2 k; + int saved = errno; + if (syscall(SYS_ioctl, fd, CX_TCGETS2, &k) == 0) return 1; + if (errno != EACCES) return 0; + if (syscall(SYS_ioctl, fd, CX_TCGETS, &k) == 0) { + errno = saved; + return 1; + } + return 0; +} + +int __isatty(int fd) { + return isatty(fd); +} + +// glibc's ttyname_r() asks its own (internal) isatty() first, which the hook cannot replace: a +// terminal it does not recognize is found as the link of /proc/self/fd/N, checked like glibc +// checks it (the same device and inode as the descriptor) +int ttyname_r(int fd, char *buf, size_t buflen) { + static int (*orig)(int, char *, size_t) = NULL; + if (!orig) orig = (int (*)(int, char *, size_t))dlsym(RTLD_NEXT, "ttyname_r"); + int ret = orig ? orig(fd, buf, buflen) : ENOTTY; + if (ret != ENOTTY && ret != EACCES) return ret; + if (!isatty(fd)) return ENOTTY; + char link[64]; + char path[PATH_MAX]; + snprintf(link, sizeof(link), "/proc/self/fd/%d", fd); + ssize_t n = (ssize_t)syscall(SYS_readlinkat, AT_FDCWD, link, path, sizeof(path) - 1); + if (n <= 0) return ENOTTY; + path[n] = '\0'; + struct stat fst, pst; + if (fstat(fd, &fst) != 0 || stat(path, &pst) != 0 || fst.st_rdev != pst.st_rdev || fst.st_ino != pst.st_ino) { + return ENOTTY; + } + if ((size_t)n + 1 > buflen) return ERANGE; + memcpy(buf, path, (size_t)n + 1); + return 0; +} + +char *ttyname(int fd) { + static char name[PATH_MAX]; + int ret = ttyname_r(fd, name, sizeof(name)); + if (ret != 0) { + errno = ret; + return NULL; + } + return name; +} + +#endif /* !CORTEX_HOST_TEST */ diff --git a/app/src/main/java/org/cortex/terminal/runtime/AptConfigurator.kt b/app/src/main/java/org/cortex/terminal/runtime/AptConfigurator.kt index 7df9bd31..46b645f1 100644 --- a/app/src/main/java/org/cortex/terminal/runtime/AptConfigurator.kt +++ b/app/src/main/java/org/cortex/terminal/runtime/AptConfigurator.kt @@ -195,6 +195,14 @@ object AptConfigurator { "Pin-Priority: -1\n\n" + "Package: locales\n" + "Pin: release *\n" + + "Pin-Priority: -1\n\n" + + // Ubuntu 26.04 switches coreutils to the Rust uutils (and could switch sudo to sudo-rs) as soon + // as an install such as build-essential lets apt choose: their binaries use ARMv8.1 atomics, + // which older ARM cores (and the emulator's ARM translator) do not have, so every command after + // it died with "Illegal instruction", apt and sudo included + "Explanation: Keep GNU coreutils and sudo: the Rust versions need ARMv8.1 instructions\n" + + "Package: rust-coreutils sudo-rs\n" + + "Pin: release *\n" + "Pin-Priority: -1\n", 420 ) @@ -319,6 +327,15 @@ object AptConfigurator { if (updated) { FileInstaller.install(statusFile, newBlocks.joinToString("\n\n") + "\n", 420) } + val withStandIn = uutilsStandIn(statusFile.readText()) + if (withStandIn != null) { + FileInstaller.install(statusFile, withStandIn, 420) + val list = File(root, "var/lib/dpkg/info/coreutils-from-uutils.list") + if (!list.exists()) { + list.parentFile?.mkdirs() + list.writeText("") + } + } } FileInstaller.install(checked, stamp(), 384) } catch (e: Exception) { @@ -328,6 +345,36 @@ object AptConfigurator { } } + /** + * Ubuntu 26.04's build-essential depends on coreutils-from-uutils, which replaces GNU coreutils with the + * Rust uutils (rust-coreutils): their binaries use ARMv8.1 atomics that older ARM cores and the + * emulator's ARM translator do not have, and every command after "apt install build-essential" died + * with "Illegal instruction", apt and sudo included. rust-coreutils is pinned away (01cortex-pins); + * this registers an empty coreutils-from-uutils, which provides nothing (so it does not conflict with + * coreutils-from-gnu), so that build-essential can be installed next to GNU coreutils. + * + * Returns [status] with the stand-in added, or null when it is not needed: no GNU coreutils from + * coreutils-from-gnu (Ubuntu 24.04), or a coreutils-from-uutils or rust-coreutils already installed. + */ + internal fun uutilsStandIn(status: String): String? { + if (!DevPackages.isInstalled(status, "coreutils-from-gnu")) return null + if (DevPackages.isInstalled(status, "coreutils-from-uutils") || DevPackages.isInstalled(status, "rust-coreutils")) return null + return DevPackages.mergeStatus(status, UUTILS_STAND_IN) + } + + internal const val UUTILS_STAND_IN = + "Package: coreutils-from-uutils\n" + + "Status: install ok installed\n" + + "Priority: optional\n" + + "Section: admin\n" + + "Installed-Size: 1\n" + + "Maintainer: Cortex Terminal\n" + + "Architecture: all\n" + + "Version: 0.0.0~ubuntu25+cortex1\n" + + "Description: stand-in registered by Cortex: GNU coreutils stay installed\n" + + " build-essential depends on this package, which would replace GNU coreutils with the Rust\n" + + " uutils. Those need ARMv8.1 instructions that older phones do not have.\n" + fun ensureUbuntuSources(root: File) { try { val sourcesDir = File(root, "etc/apt/sources.list.d") diff --git a/app/src/main/java/org/cortex/terminal/runtime/BootstrapManager.kt b/app/src/main/java/org/cortex/terminal/runtime/BootstrapManager.kt index 65aeaefe..34243b72 100644 --- a/app/src/main/java/org/cortex/terminal/runtime/BootstrapManager.kt +++ b/app/src/main/java/org/cortex/terminal/runtime/BootstrapManager.kt @@ -12,7 +12,7 @@ import java.util.zip.GZIPInputStream object BootstrapManager { private const val TAG = "BootstrapManager" - const val CURRENT_BOOTSTRAP_VERSION = 12901 + const val CURRENT_BOOTSTRAP_VERSION = 12902 fun initializeFileSystem(context: Context) { val root = Environment.getCortexRoot(context) diff --git a/app/src/test/java/org/cortex/terminal/runtime/AptConfiguratorTest.kt b/app/src/test/java/org/cortex/terminal/runtime/AptConfiguratorTest.kt index 9c37a0e2..83c208cd 100644 --- a/app/src/test/java/org/cortex/terminal/runtime/AptConfiguratorTest.kt +++ b/app/src/test/java/org/cortex/terminal/runtime/AptConfiguratorTest.kt @@ -189,6 +189,10 @@ class AptConfiguratorTest { block.lines().first { it.startsWith("Package:") }.removePrefix("Package:").trim().split(" ") }.toSet() assertTrue(pinned.containsAll(listOf("libc6", "libc6-dev", "libc6-dbg", "libc-bin", "libc-dev-bin", "locales"))) + // build-essential let apt replace GNU coreutils with the Rust uutils, which need ARMv8.1 + assertTrue(pinned.containsAll(listOf("rust-coreutils", "sudo-rs"))) + // its stand-in must stay installable: build-essential depends on it + assertFalse(pinned.contains("coreutils-from-uutils")) // a glob such as libc6* also blocked the 200 libc6-*-cross packages, which do not touch the runtime libc assertFalse("no glob over the libc6 family", pinned.any { it.contains("*") }) assertTrue(pins.lines().filter { it.startsWith("Pin-Priority:") }.all { it == "Pin-Priority: -1" }) @@ -216,4 +220,22 @@ class AptConfiguratorTest { assertTrue(text.contains("Package: libc6-dev\nStatus: install ok installed")) assertTrue(text.contains("Package: bash\nStatus: install ok installed")) } + + @Test + fun uutilsStandIn_isAddedNextToGnuCoreutilsOnly() { + val gnu = "Package: coreutils-from-gnu\nStatus: install ok installed\nVersion: 0.0.0~ubuntu25\n\n" + + "Package: bash\nStatus: install ok installed\nVersion: 5.3-2ubuntu1\n" + val added = AptConfigurator.uutilsStandIn(gnu) + assertTrue(added != null) + assertTrue(DevPackages.isInstalled(added!!, "coreutils-from-uutils")) + assertTrue(DevPackages.isInstalled(added, "coreutils-from-gnu")) + assertTrue(DevPackages.isInstalled(added, "bash")) + // it must not provide coreutils-from, which coreutils-from-gnu conflicts with + assertFalse(AptConfigurator.UUTILS_STAND_IN.contains("Provides:")) + // once there, nothing more to add + assertEquals(null, AptConfigurator.uutilsStandIn(added)) + // Ubuntu 24.04 (no coreutils-from-gnu), or the Rust coreutils already installed: left alone + assertEquals(null, AptConfigurator.uutilsStandIn("Package: coreutils\nStatus: install ok installed\nVersion: 9.4\n")) + assertEquals(null, AptConfigurator.uutilsStandIn(gnu + "\nPackage: rust-coreutils\nStatus: install ok installed\nVersion: 0.10.0\n")) + } } diff --git a/docs/index.html b/docs/index.html index cdf76a41..80896e03 100644 --- a/docs/index.html +++ b/docs/index.html @@ -56,7 +56,7 @@ { "@type": "Question", "name": "Which Android versions and CPUs does Cortex support?", "acceptedAnswer": { "@type": "Answer", "text": "Android 7.0 and newer, with separate APKs for 64-bit (arm64-v8a) and 32-bit (armeabi-v7a) ARM devices." } }, { "@type": "Question", "name": "How do I install software in Cortex?", "acceptedAnswer": { "@type": "Answer", "text": "Use apt like on any Ubuntu system, for example: apt install git python3 build-essential." } }, { "@type": "Question", "name": "A tool refuses to run as root. What now?", "acceptedAnswer": { "@type": "Answer", "text": "Run cortex-api no-fakeroot: a shell where programs see an ordinary user instead of root, until you exit. sudo still works in it." } }, - { "@type": "Question", "name": "Is there a desktop or GUI in Cortex?", "acceptedAnswer": { "@type": "Answer", "text": "Yes, as an add-on. The menu's Desktop button installs a light Openbox desktop or XFCE (and Firefox if you want it) and shows it inside the app. It is X11 drawn by the CPU, with no GPU and no Wayland." } } + { "@type": "Question", "name": "Is there a desktop or GUI in Cortex?", "acceptedAnswer": { "@type": "Answer", "text": "Yes, as an add-on. The menu's Desktop button installs XFCE and Firefox and shows it inside the app. It is X11 drawn by the CPU, with no GPU and no Wayland." } } ] } @@ -503,7 +503,7 @@

Android

Desktop and remote

    -
  • X11 desktopOpenbox or XFCE and Firefox, inside the app, with sound.
  • +
  • X11 desktopXFCE and Firefox, inside the app, with sound.
  • su & sudoPasswordless sudo for cortex@localhost; tsu invokes Android phone root separately.
  • 50 languagesThe app follows your system language.
@@ -573,7 +573,7 @@

Asked often, answered plainly.

How do sudo, su, and tsu work?

Sessions start as normal user cortex@localhost with passwordless sudo. sudo and su stay strictly inside Ubuntu; tsu (or su --android) invokes real Android host su on rooted phones without colliding with Ubuntu commands.

Can I run Docker or Podman?

No. Containers need Linux namespaces, mounts and cgroups, which Android does not give ordinary apps.

Why does Go need special code?

Go programs don't use the C library, they make their system calls themselves, so a preloaded library never sees them. Cortex adds a small piece of code to Go 1.19+ programs before their first start that does the same path mapping.

-
Is there a desktop or GUI?

Yes, as an add-on. The menu's Desktop button installs Openbox or XFCE, and Firefox if you want, and shows it inside the app with touch or touchpad control, a shared clipboard and sound. It is X11 drawn by the CPU, so it suits editors and browsing more than games.

+
Is there a desktop or GUI?

Yes, as an add-on. The menu's Desktop button installs XFCE and Firefox and shows it inside the app with touch or touchpad control, a shared clipboard and sound. It is X11 drawn by the CPU, so it suits editors and browsing more than games.

Which phones are supported?

Android 7.0 and newer (targetSdk 35), with APKs for 64-bit (arm64-v8a) and 32-bit (armeabi-v7a) ARM.

Where do I report problems?

Settings › Send a bug report writes a file with the versions and logs. Attach it to a GitHub issue or send it on Telegram.

diff --git a/docs/llms.txt b/docs/llms.txt index 7c307e6c..6b74a3e5 100644 --- a/docs/llms.txt +++ b/docs/llms.txt @@ -2,7 +2,7 @@ > Free, open-source Android terminal app that runs Ubuntu 26.04 LTS's own programs (glibc 2.43, apt) on unrooted devices through an LD_PRELOAD library, the technique of fakechroot and fakeroot, rewritten for Android. No ptrace (not PRoot), no virtual machine, no root. An alternative to Termux + proot-distro. Apache-2.0. -Cortex runs Ubuntu's unmodified binaries directly on the Android kernel. A preloaded library inside each program maps file paths such as /usr and /etc to the app's private storage, emulates user/group ownership, and handles what Android's seccomp filter forbids; statically linked programs are patched once before their first start (static C/C++, Go 1.19+), while an immutable native helper (libcortex-exec.so) invokes Ubuntu's dynamic linker under targetSdk 35. Sessions start as normal user cortex@localhost with passwordless sudo; other users (su, runuser, PostgreSQL) are emulated for the programs, ports below 1024 are moved 8000 up, and tsu / android-su / su --android invokes Android phone root separately without colliding with Ubuntu sudo/su. Not supported without kernel privileges: systemd, mount, containers. Packages come from the Ubuntu 26.04 archive via apt. The cortex-api command gives programs Android features (notifications, clipboard, opening links and files in Android apps, sharing, battery state). APKs exist for arm64-v8a and armeabi-v7a (Android 7.0+, targetSdk 35). The interface supports 50 languages. An optional X11 desktop (Openbox or XFCE, and Firefox) can be installed from the app and is shown inside it; Ubuntu's Xvnc runs on a private Unix socket with shared PulseAudio sound and everything is drawn by the CPU (no GPU, no Wayland). +Cortex runs Ubuntu's unmodified binaries directly on the Android kernel. A preloaded library inside each program maps file paths such as /usr and /etc to the app's private storage, emulates user/group ownership, and handles what Android's seccomp filter forbids; statically linked programs are patched once before their first start (static C/C++, Go 1.19+), while an immutable native helper (libcortex-exec.so) invokes Ubuntu's dynamic linker under targetSdk 35. Sessions start as normal user cortex@localhost with passwordless sudo; other users (su, runuser, PostgreSQL) are emulated for the programs, ports below 1024 are moved 8000 up, and tsu / android-su / su --android invokes Android phone root separately without colliding with Ubuntu sudo/su. Not supported without kernel privileges: systemd, mount, containers. Packages come from the Ubuntu 26.04 archive via apt. The cortex-api command gives programs Android features (notifications, clipboard, opening links and files in Android apps, sharing, battery state). APKs exist for arm64-v8a and armeabi-v7a (Android 7.0+, targetSdk 35). The interface supports 50 languages. An optional X11 desktop (XFCE and Firefox) can be installed from the app and is shown inside it; Ubuntu's Xvnc runs on a private Unix socket with shared PulseAudio sound and everything is drawn by the CPU (no GPU, no Wayland). ## Links - [Source code](https://github.com/ssfuisu/cortex): repository, issues and README diff --git a/fastlane/metadata/android/en-US/changelogs/12902.txt b/fastlane/metadata/android/en-US/changelogs/12902.txt new file mode 100644 index 00000000..956ef9b9 --- /dev/null +++ b/fastlane/metadata/android/en-US/changelogs/12902.txt @@ -0,0 +1,4 @@ +- ./script.sh, gcc, venv and bundled JDKs no longer fail with "Permission denied" (/data/data paths) +- tar extracts again on kernels before 5.6; nano, stty, tty and mc work (termios2 fallback) +- Go: no more SIGSYS in go run, and go finds its GOROOT by itself; rsync copies again +- apt install build-essential keeps GNU coreutils (the Rust ones crashed older phones) diff --git a/fastlane/metadata/android/en-US/full_description.txt b/fastlane/metadata/android/en-US/full_description.txt index c68d2251..fa12ee8c 100644 --- a/fastlane/metadata/android/en-US/full_description.txt +++ b/fastlane/metadata/android/en-US/full_description.txt @@ -9,7 +9,7 @@
  • Tabs and sessions that come back after Android ends the app, renamable with a long press
  • Extra keys you can define, pinch to zoom, hardware keyboard shortcuts, 14 color schemes
  • cortex-api: notifications, clipboard, opening links and files, sharing, battery, speech
  • -
  • Optional X11 desktop (Openbox or XFCE, Firefox) shown inside the app, with sound
  • +
  • Optional X11 desktop (XFCE and Firefox) shown inside the app, with sound
  • One-tap SSH server, notifications for local web servers you start
  • 50 interface languages
  • diff --git a/tests/e2e/compat.sh b/tests/e2e/compat.sh index 825fbf21..15c0703e 100644 --- a/tests/e2e/compat.sh +++ b/tests/e2e/compat.sh @@ -103,8 +103,9 @@ package lua "lua5.4" "2" 'lua5.4 -e "print(1 + 1)"' # Tools package git "git" "1 file changed" \ 'git init -q g && cd g && echo x > f && git add f && git -c user.name=t -c user.email=t@t commit -q -m x && git show --stat | tail -n 1' -package curl-https "curl ca-certificates" "HTTP/" 'curl -sSI https://ubuntu.com | head -n 1' -package wget "wget" "saved" 'wget -O index.html https://ubuntu.com 2>&1 | tail -n 2' +package curl-https "curl ca-certificates" "HTTP/" 'curl -sSI --retry 3 --max-time 60 https://www.debian.org/ | head -n 1' +# --tries: ubuntu.com refuses or drops some of the connections of CI's machines ("Connection refused") +package wget "wget" "saved" 'wget --tries=4 --timeout=30 -O index.html https://www.debian.org/ 2>&1 | tail -n 2' package jq "jq" "3" "echo '{\"a\": [1, 2]}' | jq '.a | add'" package sqlite3 "sqlite3" "2" 'sqlite3 :memory: "select 1 + 1;"' package zip-unzip "zip unzip" "zipped-ok" 'echo zipped-ok > z.txt && zip -q z.zip z.txt && rm z.txt && unzip -q z.zip && cat z.txt' diff --git a/tests/native/test_cortex_native.c b/tests/native/test_cortex_native.c index 8225d4bd..4d11ee02 100644 --- a/tests/native/test_cortex_native.c +++ b/tests/native/test_cortex_native.c @@ -1612,6 +1612,16 @@ static const char *ref_rewrite_path(const char *root, const char *path, char *bu if (strncmp(path, root, root_len) == 0 && (path[root_len] == '/' || path[root_len] == '\0')) { return path; } + /* 1.29.2: the rootfs spelled the other way (/data/data/PKG <-> /data/user/0/PKG) is the rootfs */ + char alias[PATH_MAX]; + alias[0] = '\0'; + if (strncmp(root, "/data/user/0/", 13) == 0) snprintf(alias, sizeof(alias), "/data/data/%s", root + 13); + else if (strncmp(root, "/data/data/", 11) == 0) snprintf(alias, sizeof(alias), "/data/user/0/%s", root + 11); + size_t alias_len = strlen(alias); + if (alias_len > 0 && strncmp(path, alias, alias_len) == 0 && (path[alias_len] == '/' || path[alias_len] == '\0')) { + snprintf(buffer, bufsize, "%s%s", root, path + alias_len); + return buffer; + } if (strncmp(path, "/dev/shm", 8) == 0 && (path[8] == '/' || path[8] == '\0')) { snprintf(buffer, bufsize, "%s/tmp/shm%s", root, path + 8); return buffer; @@ -2569,7 +2579,131 @@ static void test_spawn_attr_without_resetids(void) { posix_spawnattr_destroy(©); } +/* #84: the rootfs reached as /data/data/PKG while CORTEX_ROOT says /data/user/0/PKG (and the other way) */ +static void test_root_alias(void) { + char buf[PATH_MAX]; + const char *u = "/data/user/0/org.cortex.terminal/files/cortex"; + cortex_set_root(u, strlen(u)); + ASSERT_STR_EQ(g_cortex_root_alias, "/data/data/org.cortex.terminal/files/cortex", "alias of /data/user/0"); + ASSERT_STR_EQ(rewrite_path_in_root("/data/data/org.cortex.terminal/files/cortex/usr/bin/../libexec/cc1", buf, sizeof(buf)), + "/data/user/0/org.cortex.terminal/files/cortex/usr/bin/../libexec/cc1", "alias path mapped to CORTEX_ROOT"); + ASSERT_STR_EQ(rewrite_path_in_root("/data/data/org.cortex.terminal/files/cortex", buf, sizeof(buf)), u, "alias root itself"); + ASSERT_STR_EQ(rewrite_path_in_root("/data/data/org.cortex.terminal/files/cortexX/a", buf, sizeof(buf)), + "/data/data/org.cortex.terminal/files/cortexX/a", "no component boundary: Android's path"); + ASSERT_STR_EQ(rewrite_path_in_root("/data/data/other.app/x", buf, sizeof(buf)), "/data/data/other.app/x", "another app"); + ASSERT_EQ(rootfs_prefix_len("/data/data/org.cortex.terminal/files/cortex/home"), 43, "prefix length of the alias"); + ASSERT_EQ(rootfs_prefix_len("/data/user/0/org.cortex.terminal/files/cortex/home"), 45, "prefix length of the root"); + ASSERT_EQ(rootfs_prefix_len("/data/user/0/org.cortex.terminal/files/cortexX"), 0, "not the rootfs"); + ASSERT_TRUE(is_in_cortex_home("/data/data/org.cortex.terminal/files/cortex/home/x"), "home through the alias"); + + char link[PATH_MAX]; + strcpy(link, "/data/data/org.cortex.terminal/files/cortex/usr/bin/gcc-15"); + ssize_t n = postprocess_readlink("/usr/bin/gcc", link, (ssize_t)strlen(link), sizeof(link)); + link[n] = '\0'; + ASSERT_STR_EQ(link, "/usr/bin/gcc-15", "readlink strips the alias like the root"); + + const char *d = "/data/data/org.cortex.terminal/files/cortex"; + cortex_set_root(d, strlen(d)); + ASSERT_STR_EQ(rewrite_path_in_root("/data/user/0/org.cortex.terminal/files/cortex/etc", buf, sizeof(buf)), + "/data/data/org.cortex.terminal/files/cortex/etc", "the other direction"); + cortex_set_root("/r", 2); + ASSERT_EQ(g_cortex_root_alias_len, 0, "no alias for other roots"); + cortex_set_root("", 0); +} + +/* openat2() with RESOLVE_* flags emulated (kernels before 5.6, #84), against the kernel's own where it has one */ +static long raw_openat2(int dirfd, const char *path, int flags, uint64_t resolve) { + struct { uint64_t flags, mode, resolve; } how = { (uint64_t)(unsigned)flags, 0, resolve }; + return syscall(437, dirfd, path, &how, sizeof(how)); +} + +static void test_openat2_walk(void) { + char base[PATH_MAX]; + snprintf(base, sizeof(base), "%s/cortex_openat2_XXXXXX", get_test_tmp_dir()); + ASSERT_TRUE(mkdtemp(base) != NULL, "temp dir"); + char p[PATH_MAX + 64]; + snprintf(p, sizeof(p), "%s/in", base); mkdir(p, 0755); + snprintf(p, sizeof(p), "%s/in/d", base); mkdir(p, 0755); + snprintf(p, sizeof(p), "%s/in/d/f", base); close(open(p, O_CREAT | O_WRONLY, 0644)); + snprintf(p, sizeof(p), "%s/out", base); close(open(p, O_CREAT | O_WRONLY, 0644)); + snprintf(p, sizeof(p), "%s/in/rel", base); symlink("d/f", p); + snprintf(p, sizeof(p), "%s/in/up", base); symlink("../out", p); + snprintf(p, sizeof(p), "%s/in/abs", base); symlink("/etc", p); + snprintf(p, sizeof(p), "%s/in/dl", base); symlink("d", p); + snprintf(p, sizeof(p), "%s/in/loop", base); symlink("loop", p); + snprintf(p, sizeof(p), "%s/in", base); + int dfd = open(p, O_PATH | O_DIRECTORY); + ASSERT_TRUE(dfd >= 0, "open the scope"); + + static const char *const paths[] = { + "d", "d/", "d/f", "d/f/", "./d/./f", "d/../d/f", "..", "../out", "d/../../out", "rel", "up", "abs", + "abs/hostname", "dl/f", "dl/", "loop", "missing", "missing/x", "/etc", "d//f", ".", "rel/", NULL, + }; + static const uint64_t resolves[] = { 0x08, 0x10, 0x04, 0x0c, 0x14 }; + static const int flagsets[] = { + O_RDONLY | O_CLOEXEC, O_PATH | O_CLOEXEC, O_PATH | O_NOFOLLOW | O_CLOEXEC, + O_RDONLY | O_DIRECTORY | O_CLOEXEC, O_PATH | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC, + }; + errno = 0; + long probe = raw_openat2(dfd, "d", O_PATH, 0x08); + int have_kernel = probe >= 0; + if (probe >= 0) close((int)probe); + if (!have_kernel) fprintf(stderr, "SKIP the comparison with the kernel's openat2: not available here\n"); + + int mismatches = 0; + for (size_t r = 0; r < sizeof(resolves) / sizeof(resolves[0]); r++) { + for (size_t f = 0; f < sizeof(flagsets) / sizeof(flagsets[0]); f++) { + for (int i = 0; paths[i]; i++) { + errno = 0; + int got = cortex_openat2_walk(dfd, paths[i], flagsets[f], 0, resolves[r]); + int got_err = got < 0 ? errno : 0; + struct stat gs, ks; + if (got >= 0) fstat(got, &gs); + if (have_kernel) { + errno = 0; + long want = raw_openat2(dfd, paths[i], flagsets[f], resolves[r]); + int want_err = want < 0 ? errno : 0; + if (want >= 0) fstat((int)want, &ks); + int same = (got >= 0) == (want >= 0) && + (got < 0 ? got_err == want_err : (gs.st_ino == ks.st_ino && gs.st_dev == ks.st_dev)); + if (!same) { + fprintf(stderr, "openat2 mismatch: path='%s' flags=%#x resolve=%#llx got=%d/%s want=%ld/%s\n", + paths[i], flagsets[f], (unsigned long long)resolves[r], got, strerror(got_err), + want, strerror(want_err)); + mismatches++; + } + if (want >= 0) close((int)want); + } + if (got >= 0) close(got); + } + } + } + ASSERT_EQ(mismatches, 0, "the emulation must answer like the kernel's openat2"); + + /* without the kernel: the cases tar relies on */ + int fd = cortex_openat2_walk(dfd, "d/f", O_RDONLY, 0, 0x08); + ASSERT_TRUE(fd >= 0, "a file beneath"); + close(fd); + errno = 0; + ASSERT_EQ(cortex_openat2_walk(dfd, "../out", O_RDONLY, 0, 0x08), -1, ".. out of the scope"); + ASSERT_EQ(errno, EXDEV, "EXDEV for leaving the scope"); + errno = 0; + ASSERT_EQ(cortex_openat2_walk(dfd, "up", O_RDONLY, 0, 0x08), -1, "symlink out of the scope"); + ASSERT_EQ(errno, EXDEV, "EXDEV for a link leaving the scope"); + fd = cortex_openat2_walk(dfd, "new", O_WRONLY | O_CREAT | O_EXCL, 0600, 0x08); + ASSERT_TRUE(fd >= 0, "O_CREAT beneath"); + close(fd); + fd = cortex_openat2_walk(dfd, "rel", O_RDONLY, 0, 0x08); + ASSERT_TRUE(fd >= 0, "a relative link that stays beneath"); + close(fd); + + close(dfd); + rm_rf(base); +} + int main(void) { + test_root_alias(); + test_openat2_walk(); test_tar_path_helpers(); test_symlink_containment(); test_pax_header_parsing(); From a6127f62cb8282230df4e81e17d25be2ac85b527 Mon Sep 17 00:00:00 2001 From: ssfuisu Date: Fri, 4 Dec 2026 23:39:07 +0300 Subject: [PATCH 2/3] Address review: openat2 walk, getcwd, execveat, termios, gosys, stamp - openat2 walk: RESOLVE_NO_XDEV/NO_MAGICLINKS answer ENOSYS (not checkable from user space); O_CREAT of "name/" is EISDIR; O_CREAT|O_EXCL on a final symlink is EEXIST; a final entry swapped for a symlink is ELOOP; no depth limit (growable fd stack); six-argument syscall() - openat2 hook: open_how checked like the kernel (24 bytes, flags, mode); RESOLVE_IN_ROOT absolute paths are not rewritten to the rootfs - getcwd: the caller's size is checked against the path it sees, not the backing one - fexecve/execveat: only a regular file (or directory) still at its path is routed; unknown flags go to the kernel - termios: a BOTHER speed TCGETS cannot carry is refused instead of read as 0 baud - gosys: the runner-hidden exe path is unmapped before it is cut to the caller's buffer - holdGlibcPackages: versioned stamp, so 1.29.1 systems get the uutils stand-in on update - compat.sh: wget --retry-connrefused - tests: EISDIR/EEXIST against the kernel, NO_XDEV, 300 directories deep Co-Authored-By: Claude Opus 5.5 --- app/src/main/cpp/gosys/gosys.c | 11 +++- app/src/main/cpp/gosys/gosys_abi.h | 2 +- app/src/main/cpp/hook/exec.c | 48 ++++++++++------ app/src/main/cpp/hook/fileops.c | 56 ++++++++++++++----- app/src/main/cpp/hook/files.c | 9 ++- app/src/main/cpp/hook/openat2_walk.c | 54 +++++++++++++++--- app/src/main/cpp/hook/termios.c | 6 ++ .../terminal/runtime/AptConfigurator.kt | 10 +++- .../terminal/runtime/AptConfiguratorTest.kt | 9 +++ tests/e2e/compat.sh | 2 +- tests/native/test_cortex_native.c | 43 ++++++++++++++ 11 files changed, 205 insertions(+), 45 deletions(-) diff --git a/app/src/main/cpp/gosys/gosys.c b/app/src/main/cpp/gosys/gosys.c index d93e8db2..757292ed 100644 --- a/app/src/main/cpp/gosys/gosys.c +++ b/app/src/main/cpp/gosys/gosys.c @@ -506,7 +506,7 @@ static int is_proc_version(const char *p) { // the environment the process started with (the runner drops it from the list, the text stays), or // else argv[0] (the hook passes the full path there). `buf` holds the n bytes readlink() gave; // returns the new length. -static i64 exe_behind_runner(const struct gosys_hdr *h, const char *link, char *buf, i64 n, i64 bufsiz, char *slot) { +static i64 exe_behind_runner(const struct gosys_hdr *h, const char *link, char *buf, i64 n, i64 bufsiz, char *slot, int *shown) { u64 rl = h->exec_runner_len; if (rl == 0 || (u64)n != rl || !link || !slot) return n; if (!(pre(link, "/proc/self/exe", 14) && link[14] == '\0') && @@ -562,6 +562,10 @@ static i64 exe_behind_runner(const struct gosys_hdr *h, const char *link, char * } sc(NR_CLOSE, fd, 0, 0, 0, 0, 0); if (found && flen > 0) { + // the path as the program sees it, then cut to its buffer (a cut path then fills the + // buffer, and the caller asks again with a bigger one, as for any readlink) + flen = (u64)unmap_prefix(h, (char *)found, (i64)flen, 0); + *shown = 1; if (flen > (u64)bufsiz) flen = (u64)bufsiz; for (u64 i = 0; i < flen; i++) buf[i] = found[i]; return (i64)flen; @@ -602,8 +606,9 @@ static i64 with_paths(const struct gosys_hdr *h, u32 *held, i64 nr, i64 *a, int return 0; } } - if (proc_link && r > 0) r = exe_behind_runner(h, orig_p, (char *)a[2], r, a[3], slot); - if (proc_link && r > 0) r = unmap_prefix(h, (char *)a[2], r, 0); + int shown = 0; + if (proc_link && r > 0) r = exe_behind_runner(h, orig_p, (char *)a[2], r, a[3], slot, &shown); + if (proc_link && r > 0 && !shown) r = unmap_prefix(h, (char *)a[2], r, 0); return r; } diff --git a/app/src/main/cpp/gosys/gosys_abi.h b/app/src/main/cpp/gosys/gosys_abi.h index 48e7f4fb..0f5cb82d 100644 --- a/app/src/main/cpp/gosys/gosys_abi.h +++ b/app/src/main/cpp/gosys/gosys_abi.h @@ -15,7 +15,7 @@ #include #ifndef GOSYS_VERSION -#define GOSYS_VERSION 6u // raised when the code or its header changes: patched programs are patched again +#define GOSYS_VERSION 7u // raised when the code or its header changes: patched programs are patched again #endif // The scratch memory for rewritten paths: a small state area and 64 slots, in zero-filled memory the diff --git a/app/src/main/cpp/hook/exec.c b/app/src/main/cpp/hook/exec.c index f930471e..11bb0422 100644 --- a/app/src/main/cpp/hook/exec.c +++ b/app/src/main/cpp/hook/exec.c @@ -477,20 +477,29 @@ int execve(const char *filename, char *const argv[], char *const envp[]) { // also ask for an ld.so that Android does not have). A file with a name (sudo starts the command // through its descriptor) is started by that name, like execve(); a nameless one (memfd) is left // to the kernel. -static int exec_by_fd_path(int fd, char *out, size_t outsz) { +// The path of a rootfs file or directory that `fd` refers to, when the file at that path is still the +// one the descriptor refers to (same device and inode, a regular file or, with want_dir, a directory): +// otherwise 0, and the call is left to the kernel. +static int exec_by_fd_path(int fd, int want_dir, char *out, size_t outsz) { + struct stat fst; + if (fstat(fd, &fst) != 0) return 0; + if (want_dir ? !S_ISDIR(fst.st_mode) : !S_ISREG(fst.st_mode)) return 0; char link[64]; snprintf(link, sizeof(link), "/proc/self/fd/%d", fd); - ssize_t n = (ssize_t)syscall(SYS_readlinkat, AT_FDCWD, link, out, outsz - 1); + ssize_t n = (ssize_t)syscall(SYS_readlinkat, (long)AT_FDCWD, (long)link, (long)out, (long)(outsz - 1), 0L, 0L); if (n <= 0) return 0; out[n] = '\0'; if (out[0] != '/' || strstr(out, " (deleted)") != NULL) return 0; init_cortex_hook(); - return rootfs_prefix_len(out) > 0; + if (rootfs_prefix_len(out) == 0) return 0; + struct stat pst; + if (stat(out, &pst) != 0 || pst.st_dev != fst.st_dev || pst.st_ino != fst.st_ino) return 0; + return 1; } int fexecve(int fd, char *const argv[], char *const envp[]) { char path[PATH_MAX]; - if (exec_by_fd_path(fd, path, sizeof(path))) return cortex_execve(path, argv, envp, 0); + if (exec_by_fd_path(fd, 0, path, sizeof(path))) return cortex_execve(path, argv, envp, 0); static int (*orig)(int, char *const[], char *const[]) = NULL; if (!orig) orig = (int (*)(int, char *const[], char *const[]))dlsym(RTLD_NEXT, "fexecve"); if (!orig) { @@ -505,22 +514,27 @@ int fexecve(int fd, char *const argv[], char *const envp[]) { #endif int execveat(int dirfd, const char *pathname, char *const argv[], char *const envp[], int flags) { - if (pathname && pathname[0] == '/') { - if (!(flags & AT_SYMLINK_NOFOLLOW)) return cortex_execve(pathname, argv, envp, 0); - } else if (pathname && pathname[0] == '\0' && (flags & AT_EMPTY_PATH)) { - char path[PATH_MAX]; - if (exec_by_fd_path(dirfd, path, sizeof(path))) return cortex_execve(path, argv, envp, 0); - } else if (pathname && dirfd == AT_FDCWD && !(flags & AT_SYMLINK_NOFOLLOW)) { - return cortex_execve(pathname, argv, envp, 0); - } else if (pathname && !(flags & AT_SYMLINK_NOFOLLOW)) { - char dir[PATH_MAX]; - if (exec_by_fd_path(dirfd, dir, sizeof(dir))) { + // Only what the kernel knows is routed; anything else gets the kernel's answer (EINVAL) + if (pathname && (flags & ~(AT_EMPTY_PATH | AT_SYMLINK_NOFOLLOW)) == 0) { + if (pathname[0] == '/') { + if (!(flags & AT_SYMLINK_NOFOLLOW)) return cortex_execve(pathname, argv, envp, 0); + } else if (pathname[0] == '\0') { + // the descriptor itself: a regular file (a symlink opened with O_PATH | O_NOFOLLOW stays + // with the kernel, which refuses it) char path[PATH_MAX]; - int n = snprintf(path, sizeof(path), "%s/%s", dir, pathname); - if (n > 0 && (size_t)n < sizeof(path)) return cortex_execve(path, argv, envp, 0); + if ((flags & AT_EMPTY_PATH) && exec_by_fd_path(dirfd, 0, path, sizeof(path))) + return cortex_execve(path, argv, envp, 0); + } else if (!(flags & AT_SYMLINK_NOFOLLOW)) { + if (dirfd == AT_FDCWD) return cortex_execve(pathname, argv, envp, 0); + char dir[PATH_MAX]; + if (exec_by_fd_path(dirfd, 1, dir, sizeof(dir))) { + char path[PATH_MAX]; + int n = snprintf(path, sizeof(path), "%s/%s", dir, pathname); + if (n > 0 && (size_t)n < sizeof(path)) return cortex_execve(path, argv, envp, 0); + } } } - return (int)syscall(SYS_execveat, dirfd, pathname, argv, envp, flags); + return (int)syscall(SYS_execveat, (long)dirfd, (long)pathname, (long)argv, (long)envp, (long)flags, 0L); } // ---- fork() --------------------------------------------------------------------------------- diff --git a/app/src/main/cpp/hook/fileops.c b/app/src/main/cpp/hook/fileops.c index c3df0a14..7689e39a 100644 --- a/app/src/main/cpp/hook/fileops.c +++ b/app/src/main/cpp/hook/fileops.c @@ -641,20 +641,50 @@ int fchdir(int fd) { char *getcwd(char *buf, size_t size) { static char *(*orig_getcwd)(char *, size_t) = NULL; if (!orig_getcwd) orig_getcwd = (char *(*)(char *, size_t))dlsym(RTLD_NEXT, "getcwd"); - char *res = orig_getcwd ? orig_getcwd(buf, size) : NULL; - if (!res) return res; + if (!orig_getcwd) { + errno = ENOSYS; + return NULL; + } + if (buf && size == 0) { + errno = EINVAL; + return NULL; + } + // The real path in a buffer of its own: the caller's size is checked against the path it sees + char real[PATH_MAX]; + if (!orig_getcwd(real, sizeof(real))) { + // longer than PATH_MAX (or gone): as glibc answers + return orig_getcwd(buf, size); + } init_cortex_hook(); - size_t rlen = rootfs_prefix_len(res); - if (rlen == 0) return res; - const char *sub = res + rlen; - if (sub[0] == '\0') { - res[0] = '/'; - res[1] = '\0'; - return res; - } - if (is_android_host_path(sub)) return res; - memmove(res, sub, strlen(sub) + 1); - return res; + const char *shown = real; + size_t rlen = rootfs_prefix_len(real); + if (rlen > 0) { + const char *sub = real + rlen; + if (sub[0] == '\0') shown = "/"; + else if (!is_android_host_path(sub)) shown = sub; + } + size_t len = strlen(shown); + if (!buf) { + // glibc's extension: a buffer of `size` bytes, or of the path's length when size is 0 + size_t want = size ? size : len + 1; + if (len + 1 > want) { + errno = ERANGE; + return NULL; + } + char *out = malloc(want); + if (!out) { + errno = ENOMEM; + return NULL; + } + memcpy(out, shown, len + 1); + return out; + } + if (len + 1 > size) { + errno = ERANGE; + return NULL; + } + memmove(buf, shown, len + 1); + return buf; } char *__getcwd_chk(char *buf, size_t size, size_t buflen) { diff --git a/app/src/main/cpp/hook/files.c b/app/src/main/cpp/hook/files.c index 2f42f846..11b7cde1 100644 --- a/app/src/main/cpp/hook/files.c +++ b/app/src/main/cpp/hook/files.c @@ -376,7 +376,10 @@ int openat2(int dirfd, const char *pathname, cortex_open_how_arg_t how, size_t u } } char buf[PATH_MAX]; - const char *target = (pathname[0] == '/') ? rewrite_path(pathname, buf, sizeof(buf)) : pathname; + // With RESOLVE_IN_ROOT an absolute path is resolved beneath dirfd, not from "/": it is not the + // rootfs's path and is left as it is. + const int in_root = how && usize >= 24 && (how->resolve & 0x10 /* RESOLVE_IN_ROOT */); + const char *target = (pathname[0] == '/' && !in_root) ? rewrite_path(pathname, buf, sizeof(buf)) : pathname; if (orig_openat2) { int ret = orig_openat2(dirfd, target, how, usize); if (ret < 0 && how && (how->flags & O_ACCMODE) == O_RDONLY && @@ -395,7 +398,9 @@ int openat2(int dirfd, const char *pathname, cortex_open_how_arg_t how, size_t u return (int)sret; } #endif - if (!how || usize < 16) { + // The checks of the kernel's openat2 (struct open_how is 24 bytes since its first version) + if (!how || usize < 24 || (how->flags >> 32) != 0 || (how->mode & ~(uint64_t)07777u) != 0 || + (how->mode != 0 && !open_needs_mode((int)how->flags))) { errno = EINVAL; return -1; } diff --git a/app/src/main/cpp/hook/openat2_walk.c b/app/src/main/cpp/hook/openat2_walk.c index 14317c8e..df22385f 100644 --- a/app/src/main/cpp/hook/openat2_walk.c +++ b/app/src/main/cpp/hook/openat2_walk.c @@ -15,9 +15,19 @@ #define CORTEX_RESOLVE_IN_ROOT 0x10 #define CORTEX_RESOLVE_CACHED 0x20 #define CORTEX_RESOLVE_ALL 0x3f -#define CORTEX_WALK_MAX_DEPTH 256 +#define CORTEX_WALK_FDS_INLINE 64 #define CORTEX_WALK_MAX_LINKS 40 +static int openat2_walk_grow(int **fds, int *fds_inline, size_t *cap) { + size_t ncap = *cap * 2; + int *n = *fds == fds_inline ? malloc(ncap * sizeof(int)) : realloc(*fds, ncap * sizeof(int)); + if (!n) return 0; + if (*fds == fds_inline) memcpy(n, fds_inline, *cap * sizeof(int)); + *fds = n; + *cap = ncap; + return 1; +} + static void openat2_walk_close(int *fds, int depth) { for (int i = depth; i >= 0; i--) { if (fds[i] >= 0) close(fds[i]); @@ -30,6 +40,12 @@ static int cortex_openat2_walk(int dirfd, const char *path, int flags, mode_t mo errno = EFAULT; return -1; } + // RESOLVE_NO_XDEV and RESOLVE_NO_MAGICLINKS cannot be checked from user space (mounts that share + // a device, procfs links): such a request gets ENOSYS, as before the walk existed + if (resolve & (CORTEX_RESOLVE_NO_XDEV | CORTEX_RESOLVE_NO_MAGICLINKS)) { + errno = ENOSYS; + return -1; + } if ((resolve & ~(uint64_t)CORTEX_RESOLVE_ALL) != 0 || ((resolve & CORTEX_RESOLVE_BENEATH) && (resolve & CORTEX_RESOLVE_IN_ROOT))) { errno = EINVAL; @@ -59,7 +75,11 @@ static int cortex_openat2_walk(int dirfd, const char *path, int flags, mode_t mo memcpy(bufs[0], path, plen + 1); char *p = bufs[0]; - int fds[CORTEX_WALK_MAX_DEPTH]; + // One descriptor per directory walked into (".." goes back to the one before, never above the + // start); on the stack up to 64 levels, on the heap beyond + int fds_inline[CORTEX_WALK_FDS_INLINE]; + int *fds = fds_inline; + size_t fds_cap = CORTEX_WALK_FDS_INLINE; int depth = 0; if (p[0] == '/') { if (resolve & CORTEX_RESOLVE_BENEATH) { @@ -69,7 +89,7 @@ static int cortex_openat2_walk(int dirfd, const char *path, int flags, mode_t mo // RESOLVE_IN_ROOT: "/" is dirfd itself; otherwise the real "/" fds[0] = (resolve & CORTEX_RESOLVE_IN_ROOT) ? (dirfd == AT_FDCWD ? openat(AT_FDCWD, ".", O_PATH | O_DIRECTORY | O_CLOEXEC) : fcntl(dirfd, F_DUPFD_CLOEXEC, 0)) - : (int)syscall(SYS_openat, AT_FDCWD, "/", O_PATH | O_DIRECTORY | O_CLOEXEC); + : (int)syscall(SYS_openat, (long)AT_FDCWD, (long)"/", (long)(O_PATH | O_DIRECTORY | O_CLOEXEC), 0L, 0L, 0L); } else { fds[0] = dirfd == AT_FDCWD ? openat(AT_FDCWD, ".", O_PATH | O_DIRECTORY | O_CLOEXEC) : fcntl(dirfd, F_DUPFD_CLOEXEC, 0); } @@ -133,6 +153,8 @@ static int cortex_openat2_walk(int dirfd, const char *path, int flags, mode_t mo if (is_last && !trailing_slash && errno == ENOENT && (flags & O_CREAT)) { result = openat(fds[depth], comp, flags | O_NOFOLLOW, mode); if (result < 0) err = errno; + } else if (is_last && trailing_slash && errno == ENOENT && (flags & O_CREAT)) { + err = EISDIR; // "name/" cannot be created as a file } else { err = errno; } @@ -152,6 +174,12 @@ static int cortex_openat2_walk(int dirfd, const char *path, int flags, mode_t mo if (result < 0) err = errno; break; } + if (is_last && (flags & O_CREAT) && (flags & O_EXCL)) { + // O_CREAT | O_EXCL never follows the last name: a symlink there, dangling or not, exists + close(fd); + err = EEXIST; + break; + } if ((resolve & CORTEX_RESOLVE_NO_SYMLINKS) || ++links > CORTEX_WALK_MAX_LINKS) { close(fd); err = ELOOP; @@ -172,7 +200,7 @@ static int cortex_openat2_walk(int dirfd, const char *path, int flags, mode_t mo } // back to the root: dirfd's for RESOLVE_IN_ROOT, else the real "/" if (!root_fd_is_scope) { - int r = (int)syscall(SYS_openat, AT_FDCWD, "/", O_PATH | O_DIRECTORY | O_CLOEXEC); + int r = (int)syscall(SYS_openat, (long)AT_FDCWD, (long)"/", (long)(O_PATH | O_DIRECTORY | O_CLOEXEC), 0L, 0L, 0L); if (r < 0) { err = errno; break; @@ -200,7 +228,18 @@ static int cortex_openat2_walk(int dirfd, const char *path, int flags, mode_t mo if (is_last && !trailing_slash) { close(fd); result = openat(fds[depth], comp, flags | O_NOFOLLOW, mode); - if (result < 0) err = errno; + if (result < 0) { + err = errno; + } else if (!(flags & O_NOFOLLOW)) { + // replaced by a symlink since it was looked at: O_PATH opened the link itself, which + // the caller did not ask for (the kernel would have followed it, or refused it) + struct stat st2; + if (fstat(result, &st2) == 0 && S_ISLNK(st2.st_mode)) { + close(result); + result = -1; + err = ELOOP; + } + } break; } if (!S_ISDIR(st.st_mode)) { @@ -208,15 +247,16 @@ static int cortex_openat2_walk(int dirfd, const char *path, int flags, mode_t mo err = ENOTDIR; break; } - if (depth + 1 >= CORTEX_WALK_MAX_DEPTH) { + if ((size_t)depth + 1 >= fds_cap && !openat2_walk_grow(&fds, fds_inline, &fds_cap)) { close(fd); - err = ENAMETOOLONG; + err = ENOMEM; break; } fds[++depth] = fd; p = rest; } openat2_walk_close(fds, depth); + if (fds != fds_inline) free(fds); if (result < 0) errno = err ? err : EIO; return result; } diff --git a/app/src/main/cpp/hook/termios.c b/app/src/main/cpp/hook/termios.c index 7bbb2057..8388d97f 100644 --- a/app/src/main/cpp/hook/termios.c +++ b/app/src/main/cpp/hook/termios.c @@ -96,6 +96,12 @@ static void cx_termios_to_ktermios(const struct termios *t, struct cx_ktermios2 static int cx_tcgets_old(int fd, struct cx_ktermios2 *k) { memset(k, 0, sizeof(*k)); if (syscall(SYS_ioctl, fd, CX_TCGETS, k) != 0) return -1; + // A speed without a CBAUD code (BOTHER) is not in what TCGETS gives: refused, rather than read + // as 0 baud and set back so by a read-modify-write + if ((k->c_cflag & CX_CBAUD) == CX_BOTHER || ((k->c_cflag >> CX_IBSHIFT) & CX_CBAUD) == CX_BOTHER) { + errno = EACCES; + return -1; + } cx_canonicalize_speeds(k); return 0; } diff --git a/app/src/main/java/org/cortex/terminal/runtime/AptConfigurator.kt b/app/src/main/java/org/cortex/terminal/runtime/AptConfigurator.kt index 46b645f1..dd465ac7 100644 --- a/app/src/main/java/org/cortex/terminal/runtime/AptConfigurator.kt +++ b/app/src/main/java/org/cortex/terminal/runtime/AptConfigurator.kt @@ -288,7 +288,7 @@ object AptConfigurator { val statusFile = File(root, "var/lib/dpkg/status") if (!statusFile.isFile) return val checked = File(root, "var/lib/cortex/glibc-holds-checked") - fun stamp() = "${statusFile.length()}:${statusFile.lastModified()}\n" + fun stamp() = holdsStamp(statusFile.length(), statusFile.lastModified()) val lastStamp = try { if (checked.isFile) checked.readText() else null } catch (e: Exception) { null } if (lastStamp == stamp()) return val locks = DpkgStatus.tryLock(root) ?: return @@ -345,6 +345,14 @@ object AptConfigurator { } } + /** + * What [holdGlibcPackages] writes once dpkg's status file is checked. It names the checks' version: + * a stamp of an earlier version (1.29.1 wrote "length:time") no longer matches, so a status file + * that did not change since is checked again with what was added (the coreutils-from-uutils + * stand-in of 1.29.2). + */ + internal fun holdsStamp(length: Long, modified: Long) = "2:$length:$modified\n" + /** * Ubuntu 26.04's build-essential depends on coreutils-from-uutils, which replaces GNU coreutils with the * Rust uutils (rust-coreutils): their binaries use ARMv8.1 atomics that older ARM cores and the diff --git a/app/src/test/java/org/cortex/terminal/runtime/AptConfiguratorTest.kt b/app/src/test/java/org/cortex/terminal/runtime/AptConfiguratorTest.kt index 83c208cd..243d20a4 100644 --- a/app/src/test/java/org/cortex/terminal/runtime/AptConfiguratorTest.kt +++ b/app/src/test/java/org/cortex/terminal/runtime/AptConfiguratorTest.kt @@ -3,6 +3,7 @@ package org.cortex.terminal.runtime import org.junit.Assert.assertArrayEquals import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotEquals import org.junit.Assert.assertTrue import org.junit.Rule import org.junit.Test @@ -221,6 +222,14 @@ class AptConfiguratorTest { assertTrue(text.contains("Package: bash\nStatus: install ok installed")) } + @Test + fun holdsStamp_ofAnEarlierVersionDoesNotSkipTheChecks() { + // 1.29.1 wrote "length:time": an unchanged status file of such a system is checked again + val old = "1234:5678\n" + assertNotEquals(old, AptConfigurator.holdsStamp(1234, 5678)) + assertEquals(AptConfigurator.holdsStamp(1234, 5678), AptConfigurator.holdsStamp(1234, 5678)) + } + @Test fun uutilsStandIn_isAddedNextToGnuCoreutilsOnly() { val gnu = "Package: coreutils-from-gnu\nStatus: install ok installed\nVersion: 0.0.0~ubuntu25\n\n" + diff --git a/tests/e2e/compat.sh b/tests/e2e/compat.sh index 15c0703e..25cb0e50 100644 --- a/tests/e2e/compat.sh +++ b/tests/e2e/compat.sh @@ -105,7 +105,7 @@ package git "git" "1 file changed" \ 'git init -q g && cd g && echo x > f && git add f && git -c user.name=t -c user.email=t@t commit -q -m x && git show --stat | tail -n 1' package curl-https "curl ca-certificates" "HTTP/" 'curl -sSI --retry 3 --max-time 60 https://www.debian.org/ | head -n 1' # --tries: ubuntu.com refuses or drops some of the connections of CI's machines ("Connection refused") -package wget "wget" "saved" 'wget --tries=4 --timeout=30 -O index.html https://www.debian.org/ 2>&1 | tail -n 2' +package wget "wget" "saved" 'wget --tries=4 --retry-connrefused --timeout=30 -O index.html https://www.debian.org/ 2>&1 | tail -n 2' package jq "jq" "3" "echo '{\"a\": [1, 2]}' | jq '.a | add'" package sqlite3 "sqlite3" "2" 'sqlite3 :memory: "select 1 + 1;"' package zip-unzip "zip unzip" "zipped-ok" 'echo zipped-ok > z.txt && zip -q z.zip z.txt && rm z.txt && unzip -q z.zip && cat z.txt' diff --git a/tests/native/test_cortex_native.c b/tests/native/test_cortex_native.c index 4d11ee02..b862d4ab 100644 --- a/tests/native/test_cortex_native.c +++ b/tests/native/test_cortex_native.c @@ -2697,6 +2697,49 @@ static void test_openat2_walk(void) { ASSERT_TRUE(fd >= 0, "a relative link that stays beneath"); close(fd); + /* creation: "name/" and O_EXCL on a (dangling) symlink fail as the kernel's do, creating nothing */ + snprintf(p, sizeof(p), "%s/in/dang", base); symlink("d/nothing", p); + errno = 0; + ASSERT_EQ(cortex_openat2_walk(dfd, "nf/", O_WRONLY | O_CREAT, 0600, 0x08), -1, "O_CREAT of name/"); + ASSERT_EQ(errno, EISDIR, "EISDIR for O_CREAT of name/"); + errno = 0; + ASSERT_EQ(cortex_openat2_walk(dfd, "dang", O_WRONLY | O_CREAT | O_EXCL, 0600, 0x08), -1, "O_EXCL on a symlink"); + ASSERT_EQ(errno, EEXIST, "EEXIST for O_EXCL on a symlink"); + snprintf(p, sizeof(p), "%s/in/d/nothing", base); + ASSERT_TRUE(access(p, F_OK) != 0, "O_EXCL did not create the link's target"); + if (have_kernel) { + errno = 0; + ASSERT_EQ(raw_openat2(dfd, "nf/", O_WRONLY | O_CREAT, 0x08), -1, "kernel: O_CREAT of name/"); + ASSERT_EQ(errno, EISDIR, "kernel: EISDIR"); + errno = 0; + ASSERT_EQ(raw_openat2(dfd, "dang", O_WRONLY | O_CREAT | O_EXCL, 0x08), -1, "kernel: O_EXCL on a symlink"); + ASSERT_EQ(errno, EEXIST, "kernel: EEXIST"); + } + /* flags the walk cannot check are not accepted */ + errno = 0; + ASSERT_EQ(cortex_openat2_walk(dfd, "d/f", O_RDONLY, 0, 0x08 | 0x01), -1, "RESOLVE_NO_XDEV"); + ASSERT_EQ(errno, ENOSYS, "ENOSYS for RESOLVE_NO_XDEV"); + /* deeper than the descriptors kept on the stack */ + { + char deep[PATH_MAX]; + size_t n = 0; + snprintf(p, sizeof(p), "%s/in", base); + int cur = open(p, O_PATH | O_DIRECTORY); + for (int i = 0; i < 300 && cur >= 0; i++) { + mkdirat(cur, "a", 0755); + int next = openat(cur, "a", O_PATH | O_DIRECTORY); + close(cur); + cur = next; + deep[n++] = 'a'; + deep[n++] = '/'; + } + if (cur >= 0) close(cur); + deep[n] = '\0'; + fd = cortex_openat2_walk(dfd, deep, O_PATH | O_DIRECTORY, 0, 0x08); + ASSERT_TRUE(fd >= 0, "300 directories deep"); + if (fd >= 0) close(fd); + } + close(dfd); rm_rf(base); } From 8276b652f3dd2e7fb883a5c78fc472d8b5b4de3c Mon Sep 17 00:00:00 2001 From: ssfuisu Date: Sat, 5 Dec 2026 00:11:06 +0300 Subject: [PATCH 3/3] Address review: realpath keeps host-looking rootfs paths; stand-in next to an unused rust-coreutils Co-Authored-By: Claude Opus 5.5 --- app/src/main/cpp/hook/fileops.c | 4 +++- .../main/java/org/cortex/terminal/runtime/AptConfigurator.kt | 5 +++-- .../java/org/cortex/terminal/runtime/AptConfiguratorTest.kt | 5 +++-- 3 files changed, 9 insertions(+), 5 deletions(-) diff --git a/app/src/main/cpp/hook/fileops.c b/app/src/main/cpp/hook/fileops.c index 7689e39a..58540489 100644 --- a/app/src/main/cpp/hook/fileops.c +++ b/app/src/main/cpp/hook/fileops.c @@ -725,7 +725,9 @@ char *realpath(const char *path, char *resolved_path) { if (rem_len == 0) { res[0] = '/'; res[1] = '\0'; - } else { + } else if (!is_android_host_path(res + rlen)) { + // (a rootfs directory whose Ubuntu path would be taken for one of Android's, the + // rootfs's own /data, /proc, ..., keeps its real path, as in getcwd()) memmove(res, res + rlen, rem_len + 1); } } diff --git a/app/src/main/java/org/cortex/terminal/runtime/AptConfigurator.kt b/app/src/main/java/org/cortex/terminal/runtime/AptConfigurator.kt index dd465ac7..6745c2ef 100644 --- a/app/src/main/java/org/cortex/terminal/runtime/AptConfigurator.kt +++ b/app/src/main/java/org/cortex/terminal/runtime/AptConfigurator.kt @@ -362,11 +362,12 @@ object AptConfigurator { * coreutils-from-gnu), so that build-essential can be installed next to GNU coreutils. * * Returns [status] with the stand-in added, or null when it is not needed: no GNU coreutils from - * coreutils-from-gnu (Ubuntu 24.04), or a coreutils-from-uutils or rust-coreutils already installed. + * coreutils-from-gnu (Ubuntu 24.04), or a coreutils-from-uutils already installed (an unused rust-coreutils left + * installed does not provide it). */ internal fun uutilsStandIn(status: String): String? { if (!DevPackages.isInstalled(status, "coreutils-from-gnu")) return null - if (DevPackages.isInstalled(status, "coreutils-from-uutils") || DevPackages.isInstalled(status, "rust-coreutils")) return null + if (DevPackages.isInstalled(status, "coreutils-from-uutils")) return null return DevPackages.mergeStatus(status, UUTILS_STAND_IN) } diff --git a/app/src/test/java/org/cortex/terminal/runtime/AptConfiguratorTest.kt b/app/src/test/java/org/cortex/terminal/runtime/AptConfiguratorTest.kt index 243d20a4..7cef2bdb 100644 --- a/app/src/test/java/org/cortex/terminal/runtime/AptConfiguratorTest.kt +++ b/app/src/test/java/org/cortex/terminal/runtime/AptConfiguratorTest.kt @@ -243,8 +243,9 @@ class AptConfiguratorTest { assertFalse(AptConfigurator.UUTILS_STAND_IN.contains("Provides:")) // once there, nothing more to add assertEquals(null, AptConfigurator.uutilsStandIn(added)) - // Ubuntu 24.04 (no coreutils-from-gnu), or the Rust coreutils already installed: left alone + // Ubuntu 24.04 (no coreutils-from-gnu): left alone assertEquals(null, AptConfigurator.uutilsStandIn("Package: coreutils\nStatus: install ok installed\nVersion: 9.4\n")) - assertEquals(null, AptConfigurator.uutilsStandIn(gnu + "\nPackage: rust-coreutils\nStatus: install ok installed\nVersion: 0.10.0\n")) + // GNU coreutils active and an unused rust-coreutils still installed: build-essential needs the stand-in too + assertTrue(AptConfigurator.uutilsStandIn(gnu + "\nPackage: rust-coreutils\nStatus: install ok installed\nVersion: 0.10.0\n")?.contains("Package: coreutils-from-uutils") == true) } }