A high-performance Android storage analyzer that bypasses MTP using a native C++ daemon, a Rust TCP bridge, and a React Treemap UI.
Rust
Share the Android daemon build across development and CI (#126)
Vishnu Srivatsava6cc0585fe727
diff --git a/.github/workflows/build.yml b/.github/workflows/build.ymlindex 8102d15..fcea402 100644--- a/.github/workflows/build.yml+++ b/.github/workflows/build.yml@@ -90,65 +90,8 @@ jobs:sudo -n env CXX=g++ python3 -m unittest discover -s tests -p test_root_scan.py -vsudo -n env CXX=g++ python3 -m unittest discover -s tests -p test_owned_session.py -v- # ── Cross-compile C++ daemon for Android aarch64 ──────────────────────- # The daemon always targets Android ARM64, regardless of host OS.- # Uses the pre-installed Android NDK on GitHub Actions runners.- - name: Cross-compile C++ daemon (Unix)- if: runner.os != 'Windows'- run: |- NDK="${ANDROID_NDK_LATEST_HOME:-$ANDROID_NDK_HOME}"- TOOLCHAIN=$(ls -d "$NDK/toolchains/llvm/prebuilt/"*/ | head -1)- CC="${TOOLCHAIN}bin/aarch64-linux-android31-clang++"- mkdir -p daemon-symbols-- echo "NDK: $NDK"- echo "Compiler: $CC"-- "$CC" \- -std=c++17 -O2 -pthread -Wall -Wextra -Wpedantic \- -fno-exceptions -fno-rtti -DNDEBUG \- -static-libstdc++ \- -g -Wl,--build-id=sha1 \- -o daemon-symbols/socketsweep_daemon engine/daemon.cpp-- "${TOOLCHAIN}bin/llvm-strip" --strip-all \- -o src-tauri/bin/daemon daemon-symbols/socketsweep_daemon- python3 tests/check_daemon_symbols.py \- --tools "${TOOLCHAIN}bin" --platform "${{ matrix.platform }}" \- --commit "$GITHUB_SHA"-- file src-tauri/bin/daemon- echo "✓ C++ daemon cross-compiled for Android aarch64"-- - name: Cross-compile C++ daemon (Windows)- if: runner.os == 'Windows'- shell: pwsh- run: |- $NDK = $env:ANDROID_NDK_LATEST_HOME- $Prebuilt = Get-ChildItem "$NDK\toolchains\llvm\prebuilt" -Directory | Select-Object -First 1- $CC = Join-Path $Prebuilt.FullName "bin\aarch64-linux-android31-clang++.cmd"- $Strip = Join-Path $Prebuilt.FullName "bin\llvm-strip.exe"- New-Item -ItemType Directory -Path daemon-symbols | Out-Null-- Write-Host "NDK: $NDK"- Write-Host "Compiler: $CC"-- & $CC `- -std=c++17 -O2 -pthread -Wall -Wextra -Wpedantic `- -fno-exceptions -fno-rtti -DNDEBUG `- -static-libstdc++ `- -g "-Wl,--build-id=sha1" `- -o daemon-symbols/socketsweep_daemon engine/daemon.cpp- if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }-- & $Strip --strip-all -o src-tauri/bin/daemon daemon-symbols/socketsweep_daemon- if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }- python tests/check_daemon_symbols.py `- --tools (Join-Path $Prebuilt.FullName "bin") --platform "${{ matrix.platform }}" `- --commit $env:GITHUB_SHA- if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }-- Write-Host "✓ C++ daemon cross-compiled for Android aarch64"+ - name: Cross-compile C++ daemon+ run: ${{ runner.os == 'Windows' && 'python' || 'python3' }} engine/build_daemon.py --platform "${{ matrix.platform }}" --commit "${{ github.sha }}"# Keep symbols outside Tauri resources. Each host build can use a# different NDK; the manifest identifies its exact stripped daemon.diff --git a/README.md b/README.mdindex d70725d..ce9fc5e 100644--- a/README.md+++ b/README.md@@ -246,6 +246,7 @@ sequenceDiagram2. **Rust** (v1.89+ with Cargo; native file locking for scan history)3. **Android NDK** (v26d or newer)4. **Android SDK / ADB** installed and added to your system `$PATH`.+5. **Python 3** for building the daemon.### 1. Compile the C++ DaemonCross-compile the daemon for `aarch64-linux-android`:@@ -254,11 +255,11 @@ Cross-compile the daemon for `aarch64-linux-android`:# export NDK="/path/to/your/android-ndk-r26d"# Build the daemon-cd engine-bash ./build.sh+bash engine/build.sh```+On Windows, run `python engine/build_daemon.py` from the repository root.The script prefers `NDK`, then `ANDROID_NDK_LATEST_HOME`, then `ANDROID_NDK_HOME`.-If none is set, it searches the default Linux/macOS SDK directories. An invalid+If none is set, it searches configured and default Android SDK directories. An invalidconfigured path fails explicitly rather than selecting a different toolchain.*This generates the stripped `daemon` binary in the `engine/` directory anddiff --git a/engine/build.sh b/engine/build.shindex 00a3f0e..c48ea9a 100644--- a/engine/build.sh+++ b/engine/build.sh@@ -1,73 +1,5 @@#!/usr/bin/env bash-# ============================================================================-# build.sh — Cross-compile daemon.cpp for Android aarch64-# ============================================================================set -euo pipefail-# Match Unix CI discovery while retaining an explicit NDK override.-NDK="${NDK:-${ANDROID_NDK_LATEST_HOME:-${ANDROID_NDK_HOME:-}}}"--if [ -z "${NDK:-}" ]; then- for candidate in \- "$HOME/Android/Sdk/ndk/"* \- "$HOME/Library/Android/sdk/ndk/"*; do- if [ -d "$candidate/toolchains/llvm/prebuilt" ]; then- NDK="$candidate"- break- fi- done-fi--if [ -z "${NDK:-}" ]; then- echo "ERROR: Android NDK not found. Set NDK, ANDROID_NDK_LATEST_HOME, or ANDROID_NDK_HOME."- exit 1-fi--echo "[build] Using NDK: $NDK"--case "$(uname -s)" in- Linux*) HOST_TAG="linux-x86_64" ;;- Darwin*) HOST_TAG="darwin-x86_64" ;;- *) echo "Unsupported host OS"; exit 1 ;;-esac--TOOLCHAIN="$NDK/toolchains/llvm/prebuilt/$HOST_TAG"-CC="$TOOLCHAIN/bin/aarch64-linux-android31-clang++"--if [ ! -x "$CC" ]; then- echo "ERROR: Compiler not found at $CC"- exit 1-fi-SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"-SRC="$SCRIPT_DIR/daemon.cpp"-OUT="$SCRIPT_DIR/daemon"--if [ -e "$OUT" ] && [ ! -f "$OUT" ]; then- echo "ERROR: Output path is not a regular file: $OUT"- exit 1-fi--# A failed compiler/linker may have already written its output. Stage beside-# the destination so only a successful build replaces the working artifact.-DAEMON_BUILD_TMP="$(mktemp -d "$SCRIPT_DIR/.daemon-build.XXXXXX")"-trap 'rm -rf "$DAEMON_BUILD_TMP"' EXIT--echo "[build] Compiling daemon.cpp → daemon (aarch64-linux-android) ..."--"$CC" \- -std=c++17 -O2 -pthread -Wall -Wextra -Wpedantic \- -fno-exceptions -fno-rtti -DNDEBUG \- -static-libstdc++ \- -s \- -o "$DAEMON_BUILD_TMP/daemon" "$SRC"--mv -f "$DAEMON_BUILD_TMP/daemon" "$OUT"--# Tauri bundles this copy, rather than engine/daemon. Keep both in sync so-# local development uses the same protocol and guards as release builds.-cp "$OUT" "$SCRIPT_DIR/../src-tauri/bin/daemon"--echo "[build] Output: $OUT ($(wc -c < "$OUT" | tr -d ' ') bytes)"-echo "[build] Updated src-tauri/bin/daemon"-echo "[build] Done."+exec python3 "$SCRIPT_DIR/build_daemon.py" "$@"diff --git a/engine/build_daemon.py b/engine/build_daemon.pynew file mode 100644index 0000000..b1c3e64--- /dev/null+++ b/engine/build_daemon.py@@ -0,0 +1,104 @@+"""Build the Android ARM64 daemon with an installed Android NDK."""++import argparse+import os+from pathlib import Path+import shutil+import subprocess+import sys+from tempfile import TemporaryDirectory++REPO = Path(__file__).resolve().parent.parent+HOSTS = {+ "linux": "linux-x86_64",+ "darwin": "darwin-x86_64",+ "win32": "windows-x86_64",+}+++def toolchain():+ host = HOSTS.get(sys.platform)+ if host is None:+ raise ValueError(f"Unsupported build host: {sys.platform}")+ override = next((os.environ[name] for name in (+ "NDK", "ANDROID_NDK_LATEST_HOME", "ANDROID_NDK_HOME"+ ) if os.environ.get(name)), None)+ suffix = ".cmd" if sys.platform == "win32" else ""+ compiler_name = f"aarch64-linux-android31-clang++{suffix}"+ if override:+ candidates = [Path(override)]+ else:+ sdk_roots = [+ Path(os.environ[name]) for name in ("ANDROID_HOME", "ANDROID_SDK_ROOT")+ if os.environ.get(name)+ ]+ sdk_roots.extend([+ Path.home() / "Android/Sdk",+ Path.home() / "Library/Android/sdk",+ Path.home() / "AppData/Local/Android/Sdk",+ ])+ candidates = [ndk for sdk in sdk_roots for ndk in sorted((sdk / "ndk").glob("*"))]+ for ndk in candidates:+ compiler = ndk / "toolchains/llvm/prebuilt" / host / "bin" / compiler_name+ if compiler.is_file() and os.access(compiler, os.X_OK):+ return compiler+ if override:+ raise ValueError(f"Compiler not found at {compiler}")+ raise ValueError("Android NDK not found. Set NDK, ANDROID_NDK_LATEST_HOME, or ANDROID_NDK_HOME.")+++def build(platform, commit):+ compiler = toolchain()+ bundle = REPO / "src-tauri/bin/daemon"+ local = REPO / "engine/daemon"+ for output in (bundle,) if platform else (bundle, local):+ if output.exists() and not output.is_file():+ raise ValueError(f"Output path is not a regular file: {output}")+ print(f"[build] Compiler: {compiler}", flush=True)+ # Stage beside the destination so compiler or strip failures preserve it.+ with TemporaryDirectory(prefix=".daemon-build-", dir=bundle.parent) as stage:+ staged = Path(stage) / "daemon"+ args = [+ str(compiler), "-std=c++17", "-O2", "-pthread", "-Wall", "-Wextra",+ "-Wpedantic", "-fno-exceptions", "-fno-rtti", "-DNDEBUG",+ "-static-libstdc++",+ ]+ if platform:+ symbols = REPO / "daemon-symbols/socketsweep_daemon"+ symbols.parent.mkdir(exist_ok=True)+ subprocess.run([+ *args, "-g", "-Wl,--build-id=sha1", "-o", str(symbols),+ str(REPO / "engine/daemon.cpp"),+ ], check=True)+ strip = compiler.with_name("llvm-strip.exe" if sys.platform == "win32" else "llvm-strip")+ subprocess.run([str(strip), "--strip-all", "-o", str(staged), str(symbols)], check=True)+ else:+ subprocess.run([*args, "-s", "-o", str(staged), str(REPO / "engine/daemon.cpp")], check=True)+ with TemporaryDirectory(prefix=".daemon-build-", dir=local.parent) as local_stage:+ local_copy = Path(local_stage) / "daemon"+ shutil.copy2(staged, local_copy)+ local_copy.replace(local)+ staged.replace(bundle)+ if platform:+ subprocess.run([+ sys.executable, str(REPO / "tests/check_daemon_symbols.py"),+ "--tools", str(compiler.parent), "--platform", platform, "--commit", commit,+ ], cwd=REPO, check=True)+ print(f"[build] Updated {bundle}")+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--platform", choices=("linux", "macos", "windows"))+ parser.add_argument("--commit", help="Commit for the CI symbol manifest")+ args = parser.parse_args()+ if bool(args.platform) != bool(args.commit):+ parser.error("--platform and --commit must be passed together")+ try:+ build(args.platform, args.commit)+ except (ValueError, OSError, subprocess.CalledProcessError) as error:+ parser.exit(1, f"ERROR: {error}\n")+++if __name__ == "__main__":+ main()diff --git a/tests/test_engine_build.py b/tests/test_engine_build.pyindex 186e869..b3678a6 100644--- a/tests/test_engine_build.py+++ b/tests/test_engine_build.py@@ -15,11 +15,12 @@ class EngineBuildTests(unittest.TestCase):def setUp(self):self.temp = tempfile.TemporaryDirectory(prefix="socketsweep build fixture ")self.addCleanup(self.temp.cleanup)- self.root = Path(self.temp.name)+ self.root = Path(self.temp.name).resolve()self.engine = self.root / "repository with spaces/engine"self.engine.mkdir(parents=True)- script = Path(__file__).resolve().parents[1] / "engine/build.sh"- shutil.copyfile(script, self.engine / "build.sh")+ scripts = Path(__file__).resolve().parents[1] / "engine"+ for name in ("build.sh", "build_daemon.py"):+ shutil.copyfile(scripts / name, self.engine / name)# Fail closed if a broken discovery path ever selects a real compiler.(self.engine / "daemon.cpp").write_text('#error "Use the fake compiler fixture"\n')self.bundled = self.engine.parent / "src-tauri/bin/daemon"@@ -58,7 +59,7 @@ class EngineBuildTests(unittest.TestCase):args = json.loads((self.ndks[label] / "calls.json").read_text())staged = Path(args[args.index("-o") + 1])self.assertEqual(staged.name, "daemon")- self.assertEqual(staged.parent.parent, self.engine)+ self.assertEqual(staged.parent.parent, self.bundled.parent)self.assertFalse(staged.parent.exists(), "Staging directory leaked after success")self.assertTrue(os.access(self.engine / "daemon", os.X_OK))self.assertEqual(args, ["-std=c++17", "-O2", "-pthread", "-Wall", "-Wextra", "-Wpedantic",@@ -103,14 +104,14 @@ class EngineBuildTests(unittest.TestCase):self.assertNotEqual(result.returncode, 0)self.assertEqual((self.engine / "daemon").read_bytes(), b"existing engine")self.assertEqual(self.bundled.read_bytes(), b"existing bundle")- self.assertEqual(list(self.engine.glob(".daemon-build.*")), [])+ self.assertEqual(list(self.engine.glob(".daemon-build-*")) + list(self.bundled.parent.glob(".daemon-build-*")), [])def test_compiler_success_without_output_cannot_publish_a_stale_binary(self):result = self.build(NDK=self.ndks["explicit"], FAKE_COMPILER_NO_OUTPUT="1")self.assertNotEqual(result.returncode, 0)self.assertEqual((self.engine / "daemon").read_bytes(), b"existing engine")self.assertEqual(self.bundled.read_bytes(), b"existing bundle")- self.assertEqual(list(self.engine.glob(".daemon-build.*")), [])+ self.assertEqual(list(self.engine.glob(".daemon-build-*")) + list(self.bundled.parent.glob(".daemon-build-*")), [])def test_output_directory_is_rejected_without_mutation(self):output = self.engine / "daemon"@@ -120,7 +121,7 @@ class EngineBuildTests(unittest.TestCase):sentinel.write_bytes(b"keep")result = self.build(NDK=self.ndks["explicit"])self.assertNotEqual(result.returncode, 0)- self.assertIn("Output path is not a regular file", result.stdout)+ self.assertIn("Output path is not a regular file", result.stderr)self.assertEqual(sentinel.read_bytes(), b"keep")self.assertEqual(list(output.iterdir()), [sentinel])self.assertEqual(self.bundled.read_bytes(), b"existing bundle")