"""Tests for apps/desktop/scripts/appimage_elf.py (#4337: the bundled ripgrep, a static PIE, crashed in the Linux AppImage). A static PIE relocates itself at start-up by reading its own `.dynamic` section. linuxdeploy's RPATH rewrite moves that section and fills the old place; the program then does not start. The checks here: ELF files built in memory (run everywhere), and, on Linux with gcc and -static-pie, a real static PIE that runs, the same file with its `.dynamic` overwritten the way the reporters found it (it must crash at start, and the scan must say so). No downloads; nothing of the real install is touched. python -m unittest tools.test_appimage_elf """ from __future__ import annotations import os import shutil import struct import subprocess import sys import tempfile import unittest from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "apps" / "desktop" / "scripts")) import appimage_elf as E # noqa: E402 def make_static_pie(*, extra_tags=(), rela=True, garbage=False, filler=False, interp=False, loads=2, pie=True, entry=0x1000) -> bytes: """A small ELF64 ET_DYN: PT_LOADs, a PT_DYNAMIC inside the last one, optionally a PT_INTERP. Not runnable, only well formed.""" page = 0x1000 dyn = [(E.DT_RELA, 0x1100), (E.DT_RELASZ, 48), (E.DT_RELAENT, 24)] if rela else [] dyn += ([(E.DT_FLAGS_1, E.DF_1_PIE)] if pie else []) + list(extra_tags) + [(E.DT_NULL, 0)] dyn_bytes = b"".join(struct.pack("\n#include \n#include \n' 'static const char *n[]={"alpha","beta","gamma"};\n' 'int main(int c,char**v){char b[256];memset(b,0,sizeof b);for(int i=0;i<3;i++)strcat(b,n[i]);' 'printf("ok %s %d\\n",b,c);void*p=malloc(100000);memcpy(p,b,200);free(p);return 0;}\n') cls.good = Path(cls.tmp, "good") built = subprocess.run(["gcc", "-O2", "-static-pie", str(src), "-o", str(cls.good)], capture_output=True) cls.ok = built.returncode == 0 @classmethod def tearDownClass(cls): shutil.rmtree(cls.tmp, ignore_errors=True) def setUp(self): if not self.ok: self.skipTest("this gcc cannot build a static PIE") def test_the_real_program_runs_and_passes(self): out = subprocess.run([str(self.good)], capture_output=True, text=True) self.assertEqual(out.returncode, 0) self.assertIn("ok alphabetagamma", out.stdout) self.assertEqual(E.check_static_pie(self.good.read_bytes()), []) def test_a_real_shared_library_with_a_runpath_passes(self): src = Path(self.tmp, "lib.c") src.write_text("int answer(void) { return 42; }" + chr(10)) lib = Path(self.tmp, "libanswer.so.1") built = subprocess.run(["gcc", "-shared", "-fPIC", "-O2", "-Wl,-soname,libanswer.so.1", "-Wl,-rpath,$ORIGIN", str(src), "-o", str(lib)], capture_output=True) if built.returncode != 0: self.skipTest("this gcc cannot build a shared library") data = lib.read_bytes() self.assertEqual(E.check_static_pie(data), [], "a real library with RUNPATH $ORIGIN and no interpreter is not a static PIE") self.assertEqual(E.static_pie_kind(data, E.read_elf(data)), None) # and the real static PIE of this class is still told apart and still found when damaged good = self.good.read_bytes() self.assertEqual(E.static_pie_kind(good, E.read_elf(good)), "static-pie") def test_a_filled_dynamic_section_does_not_start_and_is_found(self): data = bytearray(self.good.read_bytes()) info = E.read_elf(bytes(data)) seg = next(p for p in info["phdrs"] if p["type"] == E.PT_DYNAMIC) data[seg["off"]:seg["off"] + seg["filesz"]] = b"Z" * seg["filesz"] bad = Path(self.tmp, "bad") bad.write_bytes(bytes(data)) bad.chmod(0o755) run = subprocess.run([str(bad)], capture_output=True) self.assertNotEqual(run.returncode, 0, "a static PIE whose .dynamic is overwritten must not run") self.assertTrue(E.check_static_pie(bytes(data))) self.assertEqual(E.main(["x", "scan", self.tmp]), 1) def test_the_repack_script_check_passes_a_sound_bundled_rg_and_stops_a_damaged_one(self): """The shell function of repack-appimage.sh --check, run on a fixture AppDir whose `rg` is a real static PIE.""" if sys.platform != "linux" or os.uname().machine != "x86_64" or not shutil.which("bash") or not shutil.which("python3"): self.skipTest("the check runs the bundled rg: x86-64 Linux with bash and python3") script = ROOT / "apps" / "desktop" / "scripts" / "repack-appimage.sh" src = Path(self.tmp, "rg.c") src.write_text(chr(10).join(["#include ", "#include ", 'int main(int c, char **v) { for (int i = 1; i < c; i++) if (!strcmp(v[i], "--version")) { puts("ripgrep 0"); return 0; }', ' FILE *f = fopen(v[c - 1], "r"); if (!f) return 2; char b[256]; int n = 0; while (fgets(b, 256, f)) if (strstr(b, "needle")) n++;', ' printf("%d", n); return 0; }', ""])) lib = Path(self.tmp, "AppDir-lib") rg = lib / "harness/node_modules/@vscode/ripgrep-linux-x64/bin/rg" rg.parent.mkdir(parents=True) built = subprocess.run(["gcc", "-O2", "-static-pie", str(src), "-o", str(rg)], capture_output=True) if built.returncode != 0: self.skipTest("this gcc cannot build a static PIE") snippet = 'source <(sed -n "/^elf_and_rg_check()/,/^}/p" "$SCRIPT"); elf_and_rg_check' env = dict(os.environ, SCRIPT=str(script), LIB=str(lib), HERE=str(script.parent)) ok = subprocess.run(["bash", "-c", snippet], env=env, capture_output=True, text=True) self.assertEqual(ok.returncode, 0, ok.stdout + ok.stderr) self.assertIn("bundled rg runs: ok", ok.stdout) data = bytearray(rg.read_bytes()) info = E.read_elf(bytes(data)) seg = next(p for p in info["phdrs"] if p["type"] == E.PT_DYNAMIC) data[seg["off"]:seg["off"] + seg["filesz"]] = b"Z" * seg["filesz"] rg.write_bytes(bytes(data)) bad = subprocess.run(["bash", "-c", snippet], env=env, capture_output=True, text=True) self.assertNotEqual(bad.returncode, 0) self.assertIn("BROKEN", bad.stdout) self.assertIn("does not run", bad.stderr) if __name__ == "__main__": unittest.main()