#!/usr/bin/env python3 """Is every static-PIE program inside an AppImage still the program it was staged as? (#4337) Why: the bundled ripgrep (`harness/node_modules/@vscode/ripgrep-linux-x64/bin/rg`) is a statically linked PIE. Such a program relocates itself at start-up by reading its own `.dynamic` section through a fixed offset in its code. linuxdeploy, which Tauri runs over the AppDir, treats every ELF file as a library to fix up and rewrites its RPATH; for a static PIE that moves `.dynamic` to a new segment and leaves the old place filled with a filler byte, so the start-up code reads garbage. Reporters on #4337 see the same crash offset in every run (`rg + 0x3ffcf1`) and filler bytes (0x5A) where `.rela.dyn` and `.dynamic` were. A static PIE whose `.dynamic` is filled does not start: tools/test_appimage_elf.py shows that on a real one. apps/desktop/scripts/repack-appimage.sh puts the staged bytes back; this file is the check that says whether it did. appimage_elf.py scan every static PIE under must have a sound .dynamic (exit 1 if not) appimage_elf.py compare the same files, byte for byte, plus what differs in their ELF headers What is checked: only static PIE programs. A shared library (.so, Python's and Node's native modules, Pillow, numpy, sharp) is not one, however it is named: it has no entry point, or a DT_SONAME and no DF_1_PIE flag, and its RPATH/RUNPATH is normal. A static PIE is an ET_DYN with no interpreter, an entry point, and DF_1_PIE in DT_FLAGS_1; one whose .dynamic cannot be read at all (overwritten) is reported as damaged, since the overwrite takes the flags too. Standard library only; reads ELF64 little endian (x86-64 and arm64), anything else is ignored. """ import os import struct import sys ET_DYN = 3 PT_LOAD, PT_DYNAMIC, PT_INTERP = 1, 2, 3 DT_NULL, DT_NEEDED, DT_RELA, DT_RELASZ, DT_RELAENT, DT_SONAME, DT_RPATH, DT_RUNPATH = 0, 1, 7, 8, 9, 14, 15, 29 DT_FLAGS_1, DF_1_PIE = 0x6FFFFFFB, 0x08000000 FILLERS = (0x5A, 0x58) # 'Z' (what the reports found) and 'X' (what patchelf documents) RUN = 128 # that many equal filler bytes in a row is not code or data def _known_tag(tag): """The dynamic tags the ELF specification and the GNU and processor ranges define: anything else is garbage.""" return 0 <= tag <= 0x22 or 0x6000000D <= tag <= 0x6FFFFFFF or 0x70000000 <= tag <= 0x7FFFFFFF def read_elf(data): """The facts about an ELF64 little-endian file, or None when it is not one.""" if len(data) < 64 or data[:4] != b"\x7fELF" or data[4] != 2 or data[5] != 1: return None e_type = struct.unpack_from(" len(data): return {"type": e_type, "entry": e_entry, "phdrs": [], "broken": "the program header table is outside the file"} phdrs = [] for i in range(phnum): p_type, flags, off, vaddr, _paddr, filesz, memsz, align = struct.unpack_from(" len(data): return [], "the dynamic segment is outside the file" out = [] for at in range(seg["off"], seg["off"] + seg["filesz"] - 15, 16): tag, val = struct.unpack_from("= min(RUN, size): problems.append("the relocation table is filled with one byte") for p in info["phdrs"]: if p["type"] == PT_LOAD and _longest_filler(data, p["off"], p["off"] + p["filesz"]) >= RUN: problems.append(f"{RUN} or more filler bytes (0x5A or 0x58) in a row inside a loaded segment") break return problems def elf_differences(staged, packaged): """What differs between two builds of one program in the parts that matter for start-up: for the report.""" a, b = read_elf(staged), read_elf(packaged) if not a or not b: return [] if staged == packaged else ["one of the two is not an ELF64 file"] out = [] ta, tb = [p["type"] for p in a["phdrs"]], [p["type"] for p in b["phdrs"]] if ta != tb: out.append(f"program headers {len(ta)} -> {len(tb)} ({ta.count(PT_LOAD)} -> {tb.count(PT_LOAD)} loaded segments)") if is_pie_candidate(a) and is_pie_candidate(b): da, _ = dynamic_entries(staged, a) db, _ = dynamic_entries(packaged, b) if da != db: out.append(f"dynamic section: {len(da)} -> {len(db)} entries" + ("; an RPATH/RUNPATH was added" if any(t in (DT_RPATH, DT_RUNPATH) for t, _ in db) and not any(t in (DT_RPATH, DT_RUNPATH) for t, _ in da) else "")) return out def _files(folder): for base, dirs, names in os.walk(folder): dirs.sort() for name in sorted(names): path = os.path.join(base, name) if os.path.islink(path) or not os.path.isfile(path): continue yield path def scan(folder): """{relative path: problems} for every static PIE under `folder` that has any.""" found = {} for path in _files(folder): try: with open(path, "rb") as f: head = f.read(4) if head != b"\x7fELF": continue data = head + f.read() except OSError: continue problems = check_static_pie(data) if problems: found[os.path.relpath(path, folder)] = problems return found def compare(staged_folder, folder): """{relative path: sentences} for every staged ELF file that is missing or differs in `folder`.""" found = {} for path in _files(staged_folder): rel = os.path.relpath(path, staged_folder) with open(path, "rb") as f: want = f.read() if want[:4] != b"\x7fELF": continue other = os.path.join(folder, rel) if not os.path.isfile(other): found[rel] = ["missing"] continue with open(other, "rb") as f: have = f.read() if have != want: found[rel] = ["bytes differ"] + elf_differences(want, have) return found def main(argv): if len(argv) >= 3 and argv[1] == "scan": bad = scan(argv[2]) for rel, problems in bad.items(): print(f"BROKEN {rel}: " + "; ".join(problems)) print(f"{len(bad)} static PIE file(s) with a damaged dynamic section") return 1 if bad else 0 if len(argv) >= 4 and argv[1] == "compare": bad = compare(argv[2], argv[3]) for rel, why in bad.items(): print(f"DIFFERS {rel}: " + "; ".join(why)) print(f"{len(bad)} ELF file(s) differ from what was staged") return 1 if bad else 0 print(__doc__) return 2 if __name__ == "__main__": sys.exit(main(sys.argv))