Repository navigation
Fix overlapping LOAD mappings after executable header rewrites - #672
Conversation
e248f80 to
f935e1c
Compare
|
cc @fzakaria for review. |
|
This helped me understand it:
A single run on a fresh binary doesn't trigger it, because the small header segment doesn't exist yet. The picture A segment is a byte range of the file that the loader maps into memory with one set of permissions. After run 1 there are two segments side by side, which is fine: Run 2, before the fix: the header segment grows to hold the moved data, but the code segment's start is never moved forward: The loader maps HEADERS first, then CODE on top of it. In the overlap, CODE's permissions win, so those bytes become read+execute with no write. If .dynamic was moved into that region, the loader crashes when it tries to write to it at startup. Run 2, after the fix: before growing the header segment, patchelf moves the start of the code segment forward past the region it's taking over (trimLoadSegments): No overlap, so each byte has one set of permissions. The two smaller parts
|
fzakaria
left a comment
There was a problem hiding this comment.
Conceptually the algorithm and bug seem real and fine.
I did AI-assisted review to help break down the code;
It might be good to leave comments in the code because the code is becoming very dense and many offset calculations are tough to follow.
More nits:
- trimLoadSegments can leave a LOAD with p_filesz == 0 and a nonzero p_memsz when its file bytes end before startOffset but its zero-filled tail doesn't. That's harmless but odd.
- The Makefile hunk removes a trailing blank line, which is unrelated noise.
- The test hardcodes 4096-byte pages and only runs on x86_64. It checks that the binary runs, but never directly checks that .dynamic ended up writable.
| /* strip may remove file padding while leaving a virtual gap. | ||
| Reserve enough space in both the file and virtual memory. */ | ||
| Elf_Addr reservedPage = startAddr - startAddr % getPageSize(); | ||
| size_t fileGrowth = neededSpace > startOffset ? neededSpace - startOffset : 0; | ||
| size_t virtualGrowth = originalHeaderBase + neededSpace > reservedPage | ||
| ? originalHeaderBase + neededSpace - reservedPage : 0; | ||
| size_t growth = std::max(fileGrowth, virtualGrowth); | ||
| if (growth != 0) | ||
| neededPages = roundUp(growth, getPageSize()) / getPageSize(); | ||
| } else if (neededSpace > startOffset || | ||
| (needWritable && (originalHeaderFlags & PF_X) != 0 && | ||
| neededSpace + sizeof(Elf_Phdr) <= startOffset && firstPage >= getPageSize())) | ||
| { | ||
| /* Split the header area into its own R/W LOAD when more space is | ||
| needed, or to avoid making an executable LOAD writable. For the | ||
| latter, fall back to W+X if the extra header or page cannot fit. */ | ||
| neededSpace += sizeof(Elf_Phdr); | ||
| /* The loader rounds the remaining LOAD down to the page containing | ||
| startOffset, so the new header LOAD must end below that page. */ | ||
| size_t startPage = startOffset - startOffset % getPageSize(); | ||
| size_t growth = neededSpace > startPage ? neededSpace - startPage : 0; | ||
| neededPages = roundUp(growth, getPageSize()) / getPageSize(); |
There was a problem hiding this comment.
should this be it's own method?
There was a problem hiding this comment.
I kept the growth calculation inline because it depends on several related offsets and updates neededSpace when splitting a LOAD. Extracting it would need several parameters or a new state struct. I added comments explaining the file and virtual-space requirements. Do you think a helper would still make this easier to follow?
f935e1c to
59acc3d
Compare
|
Any idea how bad this bug is if we let it into |
The nixpkgs bump in a057c27 moved stdenv to patchelf 0.19.2. Growing this binary's headers for a /nix/store interpreter, 0.19 stretches the new segment over the original first LOAD and shifts it; kimi then SIGSEGVs, failing the installCheck (exit 139). 0.15.2 adds a separate page and the binary runs. Same pin nixpkgs uses for its bootstrap tools (NixOS/patchelf#672). Co-Authored-By: Claude Opus 5.5 <[email protected]> Entire-Checkpoint: 255a190ec6f3
|
I encountered failures with patchelf 0.19.2 while patching opencode 2.0.32 and This PR fixes the opencode failure on x86_64 and aarch64, including repeated rewrites. Those execution checks used the separate DT_VERDEF fix on top. With this PR, the Grpc.Tools patch sequence still produces invalid output or aborts:
I traced these to header lookup and split accounting in the rewrite path (using llm):
Input: Grpc.Tools 2.83.0, patchelf --set-interpreter /tmp/some/longer/ld-linux-x86-64.so.2 "$protoc"
patchelf --add-needed libicui18n.so --add-needed libicuuc.so \
--add-needed libz.so --add-needed libssl.so "$protoc"
readelf -lW "$protoc"
patchelf --add-rpath /tmp/lib "$protoc"For comparison, this branch passes both cases and the opencode checks. Its header coverage and split accounting changes may be useful here. |
I think overwrites would work in musl/gnat. |
For what it's worth, the A manylinux_2_28 toolchain is also failing with segfaults: I think for now, we'll just override patchelf to the previous version, but we try to avoid diverging from nixpkgs too much. |
@asp345 Is this something we should be tracking separately? |
nixpkgs' patchelf 0.19.2 corrupts executables whose headers it must move when --set-interpreter runs before --set-rpath, which is autoPatchelf's order: the new read-only LOAD overlaps the RW one, .dynamic lands read-only and ld.so faults (NixOS/patchelf#674). The pinned node segfaulted on start, so every npm build (hermes-tui first) died with exit 139 after the flake update moved patchelf off 0.15. Apply upstream's fix (NixOS/patchelf#672, merged, not yet released) to the patchelf the pm derivations use. Linux only; darwin derivations unchanged.
|
Uh, is a release planned? We should do something about the default patchelf in nixpkgs soon... The last release/tag has a weird title, by the way: https://github.com/NixOS/patchelf/releases |
|
Prepping a release: #678
…On Thu, Oct 29, 2026 at 6:04 AM Vladimír Čunát ***@***.***> wrote:
*vcunat* left a comment (NixOS/patchelf#672)
<#672 (comment)>
Uh, is a release planned? We should do *something* about the default
patchelf in nixpkgs soon...
The last release/tag has a weird title, by the way:
https://github.com/NixOS/patchelf/releases
—
Reply to this email directly, view it on GitHub
<#672?email_source=notifications&email_token=AAA63AYNPTIVQ2RRTKLSCWT5WLMW3A5CNFSNUABFM5UWIORPF5TWS5BNNB2WEL2JONZXKZKDN5WW2ZLOOQXTMNBYHEZDSNJVGYYKM4TFMFZW63VMON2GC5DFL5RWQYLOM5S2KZLWMVXHJLDGN5XXIZLSL5RWY2LDNM#issuecomment-6489295560>,
or unsubscribe
<https://github.com/notifications/unsubscribe-auth/AAA63A7RRGSIXF2HQYMTTDT5WLMW3AVCNFSNUABDKJSXA33TNF2G64TZHMZDSMRYGE3DIO2JONZXKZJ3GU4DINZTGU2DKOBVUF3AE>
.
You are receiving this because you modified the open/close state.Message
ID: ***@***.***>
|
* Follow this flake's own nixpkgs on the flake-lib input This flake tracked nixos-26.05, which carries no pedantix, and mkFormatting puts pkgs.pedantix in the nixfmt wrapper's runtime inputs, so following flake-lib's nixpkgs there makes the flake fail to evaluate: the formatter and checks.formatting both come from that one binding, and nix fmt becomes unreachable in the tree rather than merely unchecked. nixos-unstable carries pedantix, and tracking it is the right channel for a flake whose purpose is pulling in upstream releases. An input follows every input the parent already pins unless a specific technical reason blocks it, and there is none here. Leaving the edge off gave this tree two nixpkgs: flake-lib's library evaluated against its own pin while the packages built against ours. Following collapses them into one. The documented reason for dropping the edge was that flake-lib's formatter tools resolve from flake-lib's nixpkgs, and following would let a repo format differently from the rest of the fleet. That reasoning is corrected in jgus-org/flake-lib#118: a flake's formatter runs only in its own root against its own lock, so the version that root resolves is already canonical for that tree. What flake-lib keeps fixed is the program set and the style files, both delivered by absolute store path. * Point the agent instruction at the fleet flake standard The standard for our flake structure lives with the shared implementation it describes, so this repository links it instead of carrying a copy. CLAUDE.md is the usual compatibility symlink. * Apply rpath before interpreter when patching the tc32 tools The pinned tc32-elf binaries are 2009 non-PIE x86-64 ELF files whose .interp reservation is far smaller than a nix-store loader path, so setting the interpreter adds a PT_LOAD covering the header page. Setting the rpath afterwards grows .dynstr and relocates .dynamic onto a page that the following executable PT_LOAD also maps, which strips writability from the tail of .dynamic; the loader's write of DT_DEBUG then faults before main. Measured with gdb: SIGSEGV in dl_main, si_addr 0x400300, inside .dynamic at 0x400218+0x1f0, faulting instruction mov %r13,0x8(%rax) just before _dl_debug_change_state. The operation order decides it, not the patchelf version. On this exact binary, with patchelf built from release tarballs using nixpkgs' recipe so only the version varies: interpreter first: runs on 0.15.2, 0.16.1, 0.18.0, 0.19.0, 0.19.1, 0.19.3; segfaults on 0.17.0, 0.17.2, 0.19.2 rpath first: runs on all nine both flags at once: same outcome as interpreter first Upstream repairs the 0.19.2 instance in 59acc3d ("Fix overlapping LOAD mappings when rewriting executable headers", NixOS/patchelf#672), released in 0.19.3; nixpkgs still builds 0.19.2 and the bump is open as NixOS/nixpkgs#582116. Rewriting in rpath-first order sidesteps the whole defect class on every version tested rather than pinning around one release. mod-batt-l4r4-dongle-v103 and mod-battery-ctrl-v109 come out byte-identical to main's, so the payloads this flake ships are unchanged. --------- Co-authored-by: Agent <[email protected]>
…le module mono-sgen dies in ld.so (DT_DEBUG write, SEGV_ACCERR) because nixpkgs' patchelf 0.19.2 leaves .dynamic inside the r-x LOAD. Build this package's fixup with an overridden patchelf 0.19.3 (upstream NixOS/patchelf#672) instead of waiting for nixpkgs#582116 to reach nixos-unstable. Only patchelf and roon-bridge rebuild. pbstation reaches the bridge over the LAN, not the tailnet, so its per-device RAAT connections to the dynamic ports were refused and enabling a device hung in the Roon client. Restore the source-IP rules dropped in 27c8a48. avahi's publish.* options are obsolete since 26.11; use the equivalent settings.publish keys (the same three values the compat shim mapped to).
From the CodeRabbit full review (#184, findings 6, 19, 22, 23). - `code-common/extensions.nix`: re-enable `mkt.ms-python.python` and `pkgs.vscode-extensions.anthropic.claude-code`. The comments waited on jedi-language-server 0.46.0 and the yanked claude-code 2.1.88; the lock now has 0.47.0 and 2.1.312, and both build. - `flake.nix`: the hermes pin is still needed (patchelf is 0.19.2 in the lock). Its comment now links the fix, upstream: NixOS/patchelf#672 (released in 0.19.3) and the nixpkgs bump NixOS/nixpkgs#582116 (open, staging), and says to drop it once nixpkgs has patchelf >= 0.19.3. The triage's "nixpkgs #143332" was wrong (that's an xmrig bump). - Remove `.pre-commit-config-with-version-check.yaml`: nothing in any kleinbem repo references it, and git-hooks.nix in flake.nix is what runs. Tested: - Built `vscode-extensions.anthropic.claude-code` (2.1.312) and `vscode-marketplace.ms-python.python` (2026.11.2026102901) with this flake's nixpkgs + nix-vscode-extensions overlay: both ok. - Built `packages.x86_64-linux.{antigravity,cursor,windsurf}-extensions-bundle`: ok; the windsurf bundle contains `anthropic.claude-code` and `ms-python.python`. - `patchelf.version` from the lock: 0.19.2. - Not tested: whether 0.19.3 fixes the node 26.12.1 segfault itself. #672 fixes overlapping LOAD mappings after header rewrites of ET_EXEC binaries, which matches; recheck when the bump lands. 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **New Features** * The Python extension is now included in the common editor configuration. * Claude Code is now available in the AI editor configuration. * **Chores** * The separate pre-commit configuration for checking version consistency has been removed. This does not change the Hermes input URL or the configured extensions. <!-- end of auto-generated comment: release notes by coderabbit.ai --> Co-authored-by: Claude Opus 5.5 <[email protected]>
0.19.2 grafts a LOAD for the Nix-length interpreter and then grows it to hold the RPATH. On this binary, whose segments are 2 MiB-aligned, the executable segment was left overlapping that LOAD, putting .dynamic on a page the loader maps read-only: ld.so faults writing DT_DEBUG in dl_main. auto-patchelf sets the interpreter first and the RPATH second, which is the order that trips it. Use 0.19.3 for packages that need it until upstream nixpkgs gets it. NixOS/patchelf#672
patchelf 0.19.3 already includes NixOS/patchelf#672. Applying the 0.19.2 backport again can fail the Nix package build. Keep the patch only for patchelf 0.19.0–0.19.2 and cover the upstream-fixed version through the real pm-node derivation in nix flake checks. Follow-up to lassulus's version guard in NousResearch#152542. Tests: NOT RUN.
patchelf 0.19.3 already contains NixOS/patchelf#672, so applying the backport there would apply it twice. Assisted-by: Hermes:claude-opus-5-5
* deploy(poweredge): bump ocrflow to ebaf690 (engine policy, scoped status API, claim guard) * deploy(poweredge): ocrflow 5559437 — one engine option, readable Google key * deploy(poweredge): ocrflow 1fba10e — seeding unit names the real nextcloud user * deploy(poweredge): ocrflow 937db35 — Google batch project id * poweredge(ocr): point google-ocr at the ocr-project-tmp bucket, not a bucket it may create * poweredge(ocr): worker moves bytes over the app API, not WebDAV * deploy(poweredge): ocrflow api-transport fixes (byte fetch + enqueue id) * deploy(poweredge): ocrflow pages/chars reporting * feat(nc-rag): enable cross-encoder reranking in nextcloud-mcp SEARCH_RERANK_URL points at serenity's llama-reranker (:8082/v1/rerank) via the direct Cohere-protocol path, so no gateway M2M token is needed. Also opens 8082 on tailscale0 explicitly instead of relying on the port happening to be reachable. * fix(nc-rag): rerank top-50 with a 120s timeout The upstream 30s default times out when 200 chunks of up to 2000 chars are scored on the 1660, and nc-mcp degrades silently to retrieval order — so reranking was on paper only. Measured ~0.09s/doc; 50 candidates keeps latency ~8s and 120s absorbs a cold GPU. * deploy(poweredge): four OCR failure-class fixes * deploy(poweredge): real failure sites (#57) * deploy(poweredge): pdfio, reason codes, empty-source skip, readiness, retry * deploy(poweredge): reason codes, stage events, 422 classification (#64-#69) * feat(hermes): bump to v0.23.1 with a local patchelf gate v0.23.1's nix/pm-packages.nix backports NixOS/patchelf#672 onto patchelf unconditionally. That patch is written for 0.19 and rejects 4/6 hunks against the 0.15.2 that nixpkgs reverted to (61a15beb37, 2026-10-30, tracking #577387), so nothing built. - apply upstream PR NousResearch/hermes-agent#152542 (gates the backport to 0.19.0-0.19.2) over the flake source and callPackage from it - use hermes-agent's OWN uv2nix/pyproject stack: its python.nix passes default-groups, which our older uv2nix rejects - pin nix/pnpm-deps-hash to the store hash fetchPnpmDeps produces on our nixpkgs; upstream's was made with 02c087f Drop both patches once a released tag carries the gate and we bump nixpkgs. * test(smoke): read the expected hermes version from /etc The probe hardcoded *v0.21.7*, so the 0.23.1 build reported HERMES_VERSION_BAD and the gate failed on a stale literal rather than on the system. The aspect now writes /etc/hermes-expected-version from the same hermesVersion that builds the package; the probe compares against it and keeps a literal only as a loud fallback. VM smoke: PASS (28 running / 68 loaded services, both ZFS pool imports allowlisted as guest-impossible). --------- Co-authored-by: Likivik <[email protected]>
…#60334) ### What does this PR do? Give Linux FIPS Go binaries a RUNPATH to their embedded libraries with Go's `-r` in `dd_agent_go_binary`, so that `msgo` loads the embedded OpenSSL. For "versioned" install directories, as under `datadog-packages`, have that RUNPATH fall back to the "stable" version's libraries, for the installer, which an upgrade runs _before its version is unpacked_. This is the last prerequisite to lifting #59511's guard against Bazel-built FIPS binaries, which #60204 will do. ### Motivation Bazel-built FIPS binaries had no RUNPATH to the embedded libraries, so `msgo` `dlopen`ed OpenSSL from the default search path, loading the **system** one (or panicking without one). Omnibus' `CGO_LDFLAGS`, whose `-rpath` the external linker honors for cgo binaries, never reach Bazel, whose own rpath only lists its `$ORIGIN`-relative solib directories, while Go's internal linker, which cgo-less binaries go through, ignores such flags anyway. Go's `-r` sets the search path whichever linker writes it, as #56351 does for the omnibus-built installer, listing both directories since #57045's `patchelf --set-rpath` of the bootstrap copy **segfaults** on such a binary: - NixOS/patchelf#146 - NixOS/patchelf#152 - NixOS/patchelf#446 - NixOS/patchelf#674 - NixOS/patchelf#672 - NixOS/patchelf#623 💡 the PR/commit is therefore meant to be reverted when `patchelf` no longer exhibits the issue. ### Describe how you validated your changes - the FIPS installer has `<install_dir>/embedded/lib` as `DT_RUNPATH` and loads `libcrypto.so.3` from there, - in a versioned install directory, its RUNPATH then lists the stable version's libraries, from which it loads `libcrypto.so.3` when its own version lacks it, - the FIPS agent uses cgo for `rtloader`, so the external linker writes its rpath: those directories come first, then Bazel's solib ones, - `replace_prefix`, which `--enable-bazel` agent builds run, keeps `<install_dir>/embedded/lib` in that rpath, - non-FIPS binaries keep their RUNPATH. ### Additional Notes The RUNPATH comes from an `EMBEDDED_LIB_DIRS` make variable of `//bazel/rules/variables`, which already derives `AGENT_PACKAGE_VERSION` from the install directory. Co-authored-by: regis.desgroppes <[email protected]>
Ciel is Hermes Agent from the official flake module, used through the hermes CLI and the dashboard at hermes.<domain> (nginx, Pocket ID). It thinks on the pilot's ChatGPT subscription (openai-codex provider, model chosen at login) and hands real work to T3 Code threads over T3's own MCP server, so Claude only ever runs inside Claude Code. Terminal, file, code-execution and browser toolsets are disabled; SOUL.md tells Ciel to pick T3 models from the live catalog by cost/quality instead of a list. The calendar MCP is ni-c/caldav-mcp 0.2.1, signed in as the calendars' owner because it discovers calendars through the signed-in principal. Upstream c13419ca does not build: nix/pm-packages.nix patches `patchelf` with NixOS/patchelf#672, written for 0.19.2, but its pinned nixpkgs ships 0.15.2 there. The package is overridden with patchelfUnstable, which already contains #672. Verified: - nix build of inari's toplevel succeeds; hermes --version runs and the patched node 26 starts. - Hermes reads the generated config: `hermes mcp list` shows calendar and t3; the resolved cli and cron toolsets contain no terminal, file, code_execution or browser. - caldav-mcp against a throwaway Radicale 3.7.4 with an owner login: list_calendars, create_event and list_events work. - https://t3code.<domain>/mcp answers 401 with OAuth resource metadata. - Generated nginx: Host and the own Origin rewritten to 127.0.0.1:8404, auth_request in front. - just lint, just check-quick; hardening-report lists the added directives on hermes-agent and hermes-backend.
Growing an ET_EXEC interpreter and then rewriting its RPATH can extend the writable header LOAD across an older read-only or executable LOAD. The older mapping overwrites the page permissions, causing musl bootstrap GCC to crash while reclaiming padding and GNAT frontends to crash when the loader writes DT_DEBUG.
Trim or remove LOAD mappings for sections relocated into the header LOAD, and reuse that LOAD when further growth is needed. Reserve enough space in both the file and virtual memory so later rewrites cannot recreate the overlap or overwrite reserved sections after strip has compacted file padding. Keep the one-page allocation check and extend the strip-gap regression to cover 64 KiB pages and a 16,000-byte RPATH.
Add a generated non-PIE fixture with large symbol tables and tests for existing and missing RPATHs, repeated growth, disjoint LOAD pages using the host page size, writable LOAD coverage of
.dynamic, and execution. Both cases fail with unmodified 0.19.2 and pass with this change.Reproduced failures:
Validation of
59acc3d:make check: 68 passed, 4 skipped, with no sanitizer diagnostics. Leak detection disabled because it cannot run in the local sandbox.68736a3, before the file-space fix, with a corrupted Verneed record. It guards against a regression in the header LOAD reuse path introduced by this PR..dynamicassertion passes for the patched executable and rejects a temporary fixture with write permission removed from the covering LOAD.tests/*.sh; whitespace check against the PR base.Wider validation of
f935e1c, before the review naming, comment, and test changes:19f0155bb242faf77ae4f00581ad0d778a1cfe50, including C/C++ compilation and GNU Hello.--enable-languages=c,adaconfiguration, using a GNAT bootstrap compiler patched with this fix. The installed package compiles, links, and runs C and Ada programs.