Skip to content

The agent that grows with you

fix(build): preserve toolchain state and Termux assembly ownership

ethernetfebb908bd1e4
diff --git a/scripts/bundles/native.py b/scripts/bundles/native.py
index d40ecc7ef04..5e15ecaee51 100644
--- a/scripts/bundles/native.py
+++ b/scripts/bundles/native.py
@@ -90,6 +90,10 @@ def stage_native(args) -> int:
from scripts.build.windows_deps import prepare_windows_environment
base_env = prepare_windows_environment(source=root, state=out.parent / ".build-deps", env=base_env)
+ # Rustup resolves its installed toolchain under HOME unless these are explicit.
+ # Preserve the build host's compiler and Cargo cache before isolating app state.
+ for key, directory in (("CARGO_HOME", ".cargo"), ("RUSTUP_HOME", ".rustup")):
+ base_env.setdefault(key, str(Path.home() / directory))
with tempfile.TemporaryDirectory(prefix=".build-", dir=out) as work:
env = {**base_env, "HOME": work, "USERPROFILE": work,
"HERMES_HOME": str(Path(work) / ".hermes"),
diff --git a/scripts/termux/assembly_permissions.sh b/scripts/termux/assembly_permissions.sh
new file mode 100644
index 00000000000..acb906dbbd0
--- /dev/null
+++ b/scripts/termux/assembly_permissions.sh
@@ -0,0 +1,18 @@
+#!/usr/bin/env bash
+# Host-side ownership handoff for the disposable environment assembly mount.
+
+prepare_assembly() {
+ ASSEMBLY="$(mktemp -d "$PAYLOAD_ABS/.environments-XXXXXX")"
+ # Docker would create the parent of the nested tool mounts as root:root.
+ # Pre-create it and hand off the private scratch tree to Termux's system uid.
+ mkdir "$ASSEMBLY/tools"
+ docker run --rm --user 0:0 --network none --entrypoint chown \
+ -v "$ASSEMBLY:/assembly" "$IMAGE" 1000:1000 /assembly /assembly/tools
+}
+
+restore_assembly_owner() {
+ # No input mounts are present here: never recurse through mounted tools/app.
+ # Bypass Termux's entrypoint, which otherwise drops root to uid 1000.
+ docker run --rm --user 0:0 --network none --entrypoint chown \
+ -v "$ASSEMBLY:/assembly" "$IMAGE" -R "$(id -u):$(id -g)" /assembly
+}
diff --git a/scripts/termux/build_deb.sh b/scripts/termux/build_deb.sh
index 1bfc200f253..d9b889ae65c 100644
--- a/scripts/termux/build_deb.sh
+++ b/scripts/termux/build_deb.sh
@@ -135,15 +135,16 @@ sys.path.insert(0, sys.argv[1])
from build_wheels import write_reqs_file
write_reqs_file(Path(sys.argv[2]), Path(sys.argv[3]))
PYREQS
-# The bind mount is runner-owned: the container (any uid) can only write
-# into a dir the HOST pre-created with open perms (same as the wheelhouse).
-ASSEMBLY="$(mktemp -d "$PAYLOAD_ABS/.environments-XXXXXX")"
-chmod 0777 "$ASSEMBLY"
+# shellcheck source=scripts/termux/assembly_permissions.sh
+. "$HERE/assembly_permissions.sh"
+prepare_assembly
+# Restore host ownership on failure too, after Docker has removed input mounts.
+trap restore_assembly_owner EXIT
# Mount the payload at its REAL on-device path: the venv records
# absolute paths (interpreter symlink, pyvenv.cfg) that must be correct
# on-device from birth -- a /payload alias would bake container paths in.
docker run --rm --platform linux/arm64 \
- --user root --network none \
+ --user 1000:1000 --network none \
-v "$ASSEMBLY:/data/data/com.termux/files/usr/lib/hermes-agent" \
-v "$PAYLOAD_ABS/python:/data/data/com.termux/files/usr/lib/hermes-agent/tools/python" \
-v "$PAYLOAD_ABS/node:/data/data/com.termux/files/usr/lib/hermes-agent/tools/node" \
@@ -172,6 +173,8 @@ docker run --rm --platform linux/arm64 \
"$PY" "$ROOT/app/scripts/termux/build_environment.py" assemble \
--root "$ROOT" --python "$PY" --requirements "$ROOT/.work/resolved-reqs.txt"
' || fail "venv assembly failed inside the container (offline wheelhouse install)"
+restore_assembly_owner
+trap - EXIT
# They were built at the final on-device paths, not at host scratch paths.
mv "$ASSEMBLY/venv" "$ASSEMBLY/pm-runtime" "$PAYLOAD_ABS/"
rm -rf "$ASSEMBLY"
diff --git a/scripts/windows-build-deps.ps1 b/scripts/windows-build-deps.ps1
index 67bea20790c..18c3ecfcab2 100644
--- a/scripts/windows-build-deps.ps1
+++ b/scripts/windows-build-deps.ps1
@@ -88,19 +88,29 @@ function Initialize-HermesArm64BuildTools {
if (-not $clangPath) { throw 'The Clang compiler is still missing after Visual Studio setup.' }
}
Write-Host "ARM64 C++ build tools found: $vs"
- $devCmd = Join-Path $vs 'Common7\Tools\VsDevCmd.bat'
- # The batch file configures SDK, compiler, and linker paths only for this setup process.
- $startInfo = New-Object System.Diagnostics.ProcessStartInfo
- $startInfo.FileName = $env:ComSpec
- $startInfo.Arguments = "/d /s /c `"`"$devCmd`" -no_logo -arch=arm64 -host_arch=arm64 >nul && set`""
- $startInfo.UseShellExecute = $false
- $startInfo.RedirectStandardOutput = $true
- $process = [System.Diagnostics.Process]::Start($startInfo)
- $lines = $process.StandardOutput.ReadToEnd() -split "`r?`n"
- $process.WaitForExit()
- if ($process.ExitCode -ne 0) { throw 'Could not initialize the ARM64 Visual Studio developer environment' }
- foreach ($line in $lines) {
- if ($line -match '^([^=]+)=(.*)$') { Set-Item -LiteralPath "env:$($matches[1])" -Value $matches[2] }
+ # CI, desktop builds and native staging can inherit the same developer
+ # environment. VsDevCmd prepends its paths again on every call, eventually
+ # overflowing cmd.exe's line limit. Reuse only a matching, usable environment.
+ $vsReady = $env:VSINSTALLDIR -and $env:VSINSTALLDIR.TrimEnd('\') -eq $vs.TrimEnd('\') -and
+ $env:VSCMD_ARG_HOST_ARCH -eq 'arm64' -and $env:VSCMD_ARG_TGT_ARCH -eq 'arm64' -and
+ $env:INCLUDE -and $env:LIB -and (Get-Command cl.exe -ErrorAction SilentlyContinue)
+ if (-not $vsReady) {
+ $devCmd = Join-Path $vs 'Common7\Tools\VsDevCmd.bat'
+ # Keep cmd's outer quotes intact on Windows PowerShell 5 as well as pwsh.
+ $startInfo = New-Object System.Diagnostics.ProcessStartInfo
+ $startInfo.FileName = $env:ComSpec
+ $startInfo.Arguments = "/d /s /c `"`"$devCmd`" -no_logo -arch=arm64 -host_arch=arm64 >nul && set`""
+ $startInfo.UseShellExecute = $false
+ $startInfo.RedirectStandardOutput = $true
+ $process = [System.Diagnostics.Process]::Start($startInfo)
+ try {
+ $lines = $process.StandardOutput.ReadToEnd() -split "`r?`n"
+ $process.WaitForExit()
+ if ($process.ExitCode -ne 0) { throw 'Could not initialize the ARM64 Visual Studio developer environment' }
+ } finally { $process.Dispose() }
+ foreach ($line in $lines) {
+ if ($line -match '^([^=]+)=(.*)$') { Set-Item -LiteralPath "env:$($matches[1])" -Value $matches[2] }
+ }
}
if (-not (Get-Command cl.exe -ErrorAction SilentlyContinue)) { throw 'ARM64 C++ compiler is unavailable after environment setup' }
@@ -111,7 +121,7 @@ function Initialize-HermesArm64BuildTools {
$env:CARGO_HOME = [IO.Path]::GetFullPath($env:CARGO_HOME)
$env:RUSTUP_HOME = [IO.Path]::GetFullPath($env:RUSTUP_HOME)
$cargoBin = Join-Path $env:CARGO_HOME 'bin'
- $env:PATH = "$cargoBin;$env:PATH"
+ if ($cargoBin -notin ($env:PATH -split ';')) { $env:PATH = "$cargoBin;$env:PATH" }
$rustup = Get-Command rustup.exe -ErrorAction SilentlyContinue
if (-not $rustup) {
$installer = Join-Path $buildRoot 'rustup-init.exe'
diff --git a/tests/pm/test_windows_build_deps.py b/tests/pm/test_windows_build_deps.py
index 622e10d3a4f..e9b5e084e8f 100644
--- a/tests/pm/test_windows_build_deps.py
+++ b/tests/pm/test_windows_build_deps.py
@@ -132,7 +132,15 @@ $ErrorActionPreference = 'Stop'
$vs = Join-Path $Root 'VS with spaces'
$devDir = Join-Path $vs 'Common7\Tools'
New-Item -ItemType Directory -Force $devDir | Out-Null
-[IO.File]::WriteAllText((Join-Path $devDir 'VsDevCmd.bat'), "@echo off`r`nset INCLUDE=fixture SDK include`r`nset LIB=fixture SDK lib`r`n")
+[IO.File]::WriteAllText((Join-Path $devDir 'VsDevCmd.bat'), @"
+@echo off
+set "PATH=%~dp0;%PATH%"
+set "INCLUDE=fixture SDK include"
+set "LIB=fixture SDK lib"
+set "VSCMD_ARG_HOST_ARCH=arm64"
+set "VSCMD_ARG_TGT_ARCH=arm64"
+set "VSINSTALLDIR=$vs\"
+"@)
$rustcPath = Join-Path $Root 'rustc.cmd'
[IO.File]::WriteAllText($rustcPath, "@echo off`r`necho host: aarch64-pc-windows-msvc`r`n")
$vcpkg = Join-Path $Root 'vcpkg checkout'
@@ -172,13 +180,45 @@ if ($Homes -eq 'explicit') {
$rustupHome = Join-Path $HOME '.rustup'
}
$inheritedPath = $env:PATH
+$cargoBin = Join-Path $cargoHome 'bin'
+$expectedPath = $devDir + '\;' + $inheritedPath
+if ($cargoBin -notin ($expectedPath -split ';')) { $expectedPath = $cargoBin + ';' + $expectedPath }
Initialize-HermesArm64BuildTools -StateRoot $Root -OpenSSLRoot $openssl
if ($env:CARGO_HOME -ne $cargoHome -or $env:RUSTUP_HOME -ne $rustupHome) { throw 'Rust homes lost' }
if ($env:RUSTUP_TOOLCHAIN -ne 'caller-selected-toolchain') { throw 'Caller Rust toolchain lost' }
-if ($env:PATH -ne ((Join-Path $cargoHome 'bin') + ';' + $inheritedPath)) { throw 'PATH lost or reordered' }
+if ($env:PATH -ne $expectedPath) { throw 'PATH lost or reordered' }
if ($env:OPENSSL_DIR -ne $prefix -or $env:OPENSSL_STATIC -ne '1') { throw 'Wrong OpenSSL tree' }
if ($env:INCLUDE -ne 'fixture SDK include' -or $env:LIB -ne 'fixture SDK lib') { throw 'SDK environment lost' }
if ($env:CC_aarch64_pc_windows_msvc -ne (Join-Path $vs 'clang.exe')) { throw 'Compiler lost' }
+# CI initializes once, desktop again, then its native staging child a third time.
+# Re-running VsDevCmd grows PATH until cmd.exe hits its 8191-character limit.
+$prepared = @{}
+foreach ($name in @('PATH', 'INCLUDE', 'LIB', 'VSCMD_ARG_HOST_ARCH', 'VSCMD_ARG_TGT_ARCH', 'VSINSTALLDIR')) {
+ $prepared[$name] = (Get-Item "env:$name").Value
+}
+foreach ($i in 1..3) {
+ Initialize-HermesArm64BuildTools -StateRoot $Root -OpenSSLRoot $openssl
+ foreach ($name in $prepared.Keys) {
+ if ((Get-Item "env:$name").Value -cne $prepared[$name]) { throw "Repeated setup changed $name" }
+ }
+}
+# Inherited VS markers are not sufficient if the SDK, install or architecture differs.
+foreach ($invalid in @('INCLUDE', 'LIB', 'VSCMD_ARG_HOST_ARCH', 'VSCMD_ARG_TGT_ARCH', 'VSINSTALLDIR')) {
+ foreach ($name in $prepared.Keys) { Set-Item "env:$name" $prepared[$name] }
+ Set-Item "env:$invalid" $(if ($invalid -in @('INCLUDE', 'LIB')) { '' } else { 'other' })
+ Initialize-HermesArm64BuildTools -StateRoot $Root -OpenSSLRoot $openssl
+ foreach ($name in $prepared.Keys | Where-Object { $_ -ne 'PATH' }) {
+ if ((Get-Item "env:$name").Value -cne $prepared[$name]) { throw "Did not repair $invalid" }
+ }
+}
+$env:VSCMD_ARG_TGT_ARCH = 'x64'
+[IO.File]::WriteAllText((Join-Path $devDir 'VsDevCmd.bat'), "@exit /b 19`r`n")
+$failed = $false
+try { Initialize-HermesArm64BuildTools -StateRoot $Root -OpenSSLRoot $openssl } catch {
+ if ($_.Exception.Message -notmatch 'Could not initialize') { throw }
+ $failed = $true
+}
+if (-not $failed) { throw 'Failed VS activation was accepted' }
Write-Output 'PASS'
''', encoding="utf-8")
result = _powershell(script, HELPER, tmp_path, rust_homes)
diff --git a/tests/scripts/test_bundle_native.py b/tests/scripts/test_bundle_native.py
index 74e38a2e0d5..4ab2347bcb8 100644
--- a/tests/scripts/test_bundle_native.py
+++ b/tests/scripts/test_bundle_native.py
@@ -13,6 +13,8 @@ from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from types import SimpleNamespace
+import pytest
+
from scripts.bundles import native
@@ -233,3 +235,36 @@ def test_native_dispatch_keeps_cache_across_failed_children(tmp_path, monkeypatc
assert all(not home.exists() for home in attempts)
assert not (tmp_path / "ambient-cache").exists()
assert dict(os.environ) == original
+
+
[email protected]("explicit", [False, True])
+def test_native_dispatch_preserves_compiler_homes_inside_isolated_home(tmp_path, monkeypatch, explicit):
+ host_home = tmp_path / "host"
+ monkeypatch.setattr(Path, "home", lambda: host_home)
+ monkeypatch.setattr("scripts.build.windows_deps.prepare_windows_environment", lambda **kwargs: dict(kwargs["env"]))
+ homes = {}
+ for key, name in (("CARGO_HOME", ".cargo"), ("RUSTUP_HOME", ".rustup")):
+ directory = (tmp_path / "custom" if explicit else host_home) / name
+ directory.mkdir(parents=True)
+ (directory / "fixture-state").write_text(key, encoding="utf-8")
+ homes[key] = str(directory)
+ if explicit:
+ monkeypatch.setenv(key, str(directory))
+ else:
+ monkeypatch.delenv(key, raising=False)
+ before = dict(os.environ)
+ run = subprocess.run
+
+ def child(command, *, cwd, env):
+ assert env["HOME"] != str(host_home)
+ assert env["USERPROFILE"] == env["HOME"]
+ assert {key: env.get(key) for key in homes} == homes
+ return run([sys.executable, "-c",
+ "import os; from pathlib import Path; "
+ "assert all((Path(os.environ[k]) / 'fixture-state').read_text() == k "
+ "for k in ('CARGO_HOME', 'RUSTUP_HOME'))"],
+ cwd=cwd, env=env, check=True)
+
+ monkeypatch.setattr(native.subprocess, "run", child)
+ assert native.stage_native(SimpleNamespace(out=tmp_path / "out", ref="HEAD")) == 0
+ assert dict(os.environ) == before
diff --git a/tests/scripts/test_termux_assembly_permissions.py b/tests/scripts/test_termux_assembly_permissions.py
new file mode 100644
index 00000000000..24630de2b7a
--- /dev/null
+++ b/tests/scripts/test_termux_assembly_permissions.py
@@ -0,0 +1,78 @@
+"""Exercise the build mount's real Linux UID permissions, not Android binaries."""
+import json
+import os
+from pathlib import Path
+import shutil
+import subprocess
+
+import pytest
+
+
+ROOT = Path(__file__).resolve().parents[2]
+# Only the stdlib facts publisher runs here; the bionic tool bytes are never
+# executed. A native Linux image keeps this kernel-permissions test off QEMU.
+IMAGE = "python@sha256:ffb752e139c0a19692a43af8d8523b274222dd68eebad5d583b45c2201c6e30a"
+
+
[email protected]("build_exit", [0, 23], ids=["success", "failed-build"])
+def test_assembly_publishes_facts_as_termux_uid_and_returns_host_owned_output(tmp_path, build_exit):
+ if not shutil.which("docker"):
+ pytest.skip("Docker is required for the bind-mount ownership regression")
+ available = subprocess.run(
+ ["docker", "info"], capture_output=True, timeout=15,
+ )
+ if available.returncode:
+ pytest.skip("Docker daemon is unavailable")
+ image = subprocess.run(
+ ["docker", "image", "inspect", IMAGE], capture_output=True, timeout=15,
+ )
+ if image.returncode:
+ pytest.skip(f"Pre-pull the native Linux test image: docker pull {IMAGE}")
+
+ payload = tmp_path / "payload"
+ payload.mkdir()
+ for name in ("python", "uv"):
+ entry = payload / name
+ entry.mkdir()
+ (entry / "bytes").write_bytes(b"read-only staged tool bytes")
+ before = {path: (path.stat().st_uid, path.stat().st_gid, path.stat().st_mode)
+ for path in payload.rglob("*")}
+ result = subprocess.run(
+ ["bash", "-c", r'''
+set -euo pipefail
+IMAGE="$1"; PAYLOAD_ABS="$2"; REPO="$3"
+source "$REPO/scripts/termux/assembly_permissions.sh"
+prepare_assembly
+trap restore_assembly_owner EXIT
+docker run --rm --user 1000:1000 --network none \
+ -v "$ASSEMBLY:/assembly" \
+ -v "$PAYLOAD_ABS/python:/assembly/tools/python:ro" \
+ -v "$PAYLOAD_ABS/uv:/assembly/tools/uv:ro" \
+ -v "$REPO:/app:ro" \
+ -e HERMES_HOME=/tmp/hermes \
+ "$IMAGE" sh -ec '
+ python -B /app/scripts/termux/build_environment.py prepare-tools \
+ --root /assembly --source-tools /assembly/tools
+ mkdir /assembly/venv /assembly/pm-runtime
+ umask 077
+ printf "private build output" > /assembly/pm-runtime/receipt
+ stat -c "%u:%g" /assembly/tools/facts.json > /assembly/writer
+ exit "$1"
+ ' sh "$4"
+''', "assembly-permissions-test", IMAGE, str(payload), str(ROOT), str(build_exit)],
+ cwd=ROOT, capture_output=True, text=True, timeout=90,
+ )
+ assert result.returncode == build_exit, result.stdout + result.stderr
+ assembly, = payload.glob(".environments-*")
+ facts = json.loads((assembly / "tools/facts.json").read_text())
+ assert set(facts["packages"]) == {"python", "uv"}
+ assert (assembly / "writer").read_text().strip() == "1000:1000"
+ assert (assembly / "pm-runtime/receipt").read_text() == "private build output"
+ for path in [assembly, *assembly.rglob("*")]:
+ info = path.stat()
+ assert (info.st_uid, info.st_gid) == (os.getuid(), os.getgid()), path
+ assert not info.st_mode & 0o022, path
+ assert {path: (path.stat().st_uid, path.stat().st_gid, path.stat().st_mode)
+ for path in before} == before
+ shutil.rmtree(assembly)