Skip to content

fix(binfmt): prevent WSL interop handler loss across distro lifecycle - #40610

Closed
Ben Hillis (benhillis) wants to merge 7 commits into
masterfrom
benhill/fix-binfmt-13885
Closed

Ben Hillis (benhillis) wants to merge 7 commits into
masterfrom
benhill/fix-binfmt-13885

Conversation

@benhillis

Copy link
Copy Markdown
Member

Summary of the Pull Request

Fixes the WSL binfmt_misc interpreter being lost or corrupted in several scenarios, resulting in exec format error when running Windows executables (cmd.exe, notepad.exe, etc.) from inside a WSL2 distro.

Builds on top of @gordonlam-msft's branch workitem/13885-fix-binfmt-config-cleared-on-termination (commits 57ca57c..0f2a71b) and adds polish based on code review feedback.

PR Checklist

Detailed Description of the Pull Request / Additional comments

Root cause

binfmt_misc is not namespaced in the Linux kernel — there is a single global registration table shared across all WSL2 distros in the same utility VM. The previous design had several failure modes:

  1. Distro shutdown wiped the table. When a distro with systemd shut down, systemd unmounted /proc/sys/fs/binfmt_misc, which flushes the global table for all distros in the VM.
  2. systemd-binfmt.service re-registered without the F flag. Distros that included an /etc/binfmt.d/WSLInterop.conf would clear and re-register the entry, losing the fix-binary flag. Without F, the kernel resolves /init in the calling mount namespace at exec time, which breaks interop from Docker containers, chroots, and other altered mount namespaces.
  3. Competing MZ handlers (mono, wine, cli) could take priority when registered via binfmt.d after WSL's in-mini-init registration.
  4. Stale config could persist across config changes (protectBinfmt=true → false).

Fixes (per commit)

  • 57ca57c prevent binfmt_misc handler loss on distro termination — drops in proc-sys-fs-binfmt_misc.mount.d/override.conf with DefaultDependencies=no + Before=umount.target so the mount survives shutdown.
  • 55644b8 split binfmt registration macros for WSL1/WSL2 compatibility — introduces BINFMT_INTEROP_REGISTRATION_STRING_VM with :FP; the WSL1 (lxcore) path keeps :P because lxcore doesn't support F.
  • 3e83210 add ExecStartPost to ensure WSL binfmt handler priority — generates /run/binfmt.d/WSLInterop.conf (highest-priority binfmt.d directory) and replaces the ExecStart= override on systemd-binfmt.service / binfmt-support.service with an ExecStartPost= that re-asserts WSL's handler.
  • 7e38183 clean up stale binfmt config when protectBinfmt is disabled — unlinks /run/binfmt.d/WSLInterop.conf in the else branch.
  • 0f2a71b log error on binfmt config cleanup failure — logs cleanup unlink errors other than ENOENT.
  • 0a2d4b2 add multi-distro binfmt handler survival test — TAEF test that imports a second WSL2 distro, enables systemd in both, terminates the second, and verifies that interop still works in the first and that the live kernel entry retains the F flag.
  • 4283c9d make ExecStartPost race-tolerant and strengthen test — review polish: tolerate concurrent registration from another distro by allowing the echo writes to fail silently, then verify the live kernel entry via grep; wait for systemd to actually be running in both distros before the termination assertion.

ExecStartPost command

The ExecStartPost looks like:

/bin/sh -c '(echo -1 > /proc/sys/fs/binfmt_misc/WSLInterop 2>/dev/null || true) ; \
            (echo ":WSLInterop:M::MZ::/init:FP" > /proc/sys/fs/binfmt_misc/register 2>/dev/null || true) ; \
            grep -q "^interpreter /init$" /proc/sys/fs/binfmt_misc/WSLInterop && \
            grep -q "^flags:.*F" /proc/sys/fs/binfmt_misc/WSLInterop'

The two writes are best-effort so systemd-binfmt.service isn't marked failed in races; the trailing greps verify the live kernel entry has the correct interpreter and the F flag.

Validation Steps Performed

  • clang-format --dry-run --Werror clean on all changed files.
  • python3 tools/devops/validate-copyright-headers.py no new issues introduced.
  • Existing SystemdBinfmtIsRestored test continues to validate generated unit overrides.
  • New BinfmtSurvivesDistroTermination test covers the multi-distro scenario and asserts the F flag is preserved on the live kernel entry.
  • Pending: full local Windows build + test run on hardware.

Fixes the issue where terminating a WSL2 distro with systemd clears
binfmt_misc handlers across all running distros. Changes:
- Add mount unit override to prevent binfmt_misc unmount during shutdown
- Fix FP vs P flag inconsistency in WSLInterop registration
- Use declarative /run/binfmt.d/ approach for handler persistence

Fixes #13885

Co-authored-by: Copilot <[email protected]>
Introduce BINFMT_INTEROP_REGISTRATION_STRING_VM with ':FP' flags for
WSL2-only paths (mini_init, systemd generator), while keeping the
original BINFMT_INTEROP_REGISTRATION_STRING with ':P' for WSL1 (lxcore)
which does not support the 'F' (fix-binary) flag.

- binfmt.h: Add _VM variant macro with ':FP', restore base macro to ':P'
- main.cpp: Use _VM macro for mini_init registration (WSL2 only)
- init.cpp: Use _VM macro for /run/binfmt.d/ config (systemd, WSL2 only)
- config.cpp: Unchanged, continues using ':P' for WSL1 registration

Co-authored-by: Copilot <[email protected]>
The pure declarative approach via /run/binfmt.d/ does not handle conflicting
binfmt configs. When a distro installs its own binfmt handler with the same
name (WSLInterop), systemd-binfmt processes files alphabetically, potentially
letting the conflicting handler win.

Add ExecStartPost to the systemd-binfmt service override that forcefully
unregisters any conflicting handler and re-registers WSL's after
systemd-binfmt's normal ExecStart completes. This combines declarative config
for proper re-registration with imperative override for guaranteed priority.

Co-authored-by: Copilot <[email protected]>
When protectBinfmt or interopEnabled is turned off, remove the
/run/binfmt.d/WSLInterop.conf file from any previous run to ensure
config changes take effect without requiring a full VM restart.

Co-authored-by: Copilot <[email protected]>
Tolerate ENOENT (file doesn't exist) but log unexpected errors
when removing stale /run/binfmt.d/WSLInterop.conf, matching the
pattern used in timezone.cpp and plan9.cpp.

Co-authored-by: Copilot <[email protected]>
Validates the core scenario this PR fixes: terminating one WSL2
distro with systemd doesn't break binfmt_misc interop in another
running distro. Imports a second distro, enables systemd on both,
terminates one, and verifies cmd.exe interop + binfmt handler
registration still works in the remaining distro.

Co-authored-by: Copilot <[email protected]>
Addresses review feedback:
- ExecStartPost: tolerate concurrent register from another distro by
  allowing the echo writes to fail silently, then verifying the live
  kernel entry via grep on /proc/sys/fs/binfmt_misc/WSLInterop. This
  prevents systemd-binfmt.service from being marked failed when a
  second distro races to register the same handler.
- mount override: drop the unused [Mount] Options block (the unmount
  prevention comes from DefaultDependencies=no, not the options).
- BinfmtSurvivesDistroTermination test:
  * VERIFY the second distro's wsl.conf write succeeds.
  * Wait for systemd to actually be running (or degraded) in both
    distros before relying on shutdown behavior.
  * Assert the live kernel WSLInterop entry retains the 'F' flag,
    not just that it is 'enabled'.

Co-authored-by: Copilot <[email protected]>
Copilot AI review requested due to automatic review settings May 20, 2026 21:31

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR hardens WSL2 Windows interop (binfmt_misc WSLInterop handler) so it survives distro shutdown/termination and maintains correct handler behavior (notably preserving the F flag for cross-mount-namespace execution) by generating systemd overrides and validating them with new unit tests.

Changes:

  • Generate systemd unit overrides and a /run/binfmt.d/WSLInterop.conf to keep binfmt_misc mounted through shutdown and re-assert WSL’s handler after systemd-binfmt runs.
  • Centralize the WSL2 (VM) binfmt registration string (:...:FP) behind a dedicated macro.
  • Add/extend TAEF coverage to verify generated files, multi-distro termination survival, and F flag retention.

Reviewed changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated 1 comment.

File Description
test/windows/UnitTests.cpp Extends SystemdBinfmtIsRestored validation of generated overrides and adds BinfmtSurvivesDistroTermination coverage.
src/linux/init/main.cpp Switches binfmt registration to use the new VM-specific registration macro.
src/linux/init/init.cpp Generates /run/binfmt.d/WSLInterop.conf, adds ExecStartPost handler re-assertion, and installs mount/service overrides; cleans up stale config when disabled.
src/linux/init/binfmt.h Introduces BINFMT_INTEROP_REGISTRATION_STRING_VM (:FP) alongside the existing non-VM (:P) macro.

Comment thread src/linux/init/init.cpp
Comment on lines +390 to +396
const auto execStartPostCommand = std::format(
R"(/bin/sh -c '(echo -1 > {0}/{1} 2>/dev/null || true) ; (echo "{2}" > {3} 2>/dev/null || true) ; )"
R"(grep -q "^interpreter /init$" {0}/{1} && grep -q "^flags:.*F" {0}/{1}')",
BINFMT_MISC_MOUNT_TARGET,
LX_INIT_BINFMT_NAME,
BINFMT_INTEROP_REGISTRATION_STRING_VM(LX_INIT_BINFMT_NAME),
BINFMT_MISC_REGISTER_FILE);
@benhillis

Copy link
Copy Markdown
Member Author

Closing — after a closer look, this is essentially a re-post of Gordon Lam (@yeelam-gordon)'s existing branch workitem/13885-fix-binfmt-config-cleared-on-termination with only minor editorial polish on top. Gordon's branch already has the substantive fixes; opening a separate PR steps on his work for no real gain.

I'll leave my suggestions as feedback on the underlying issue so Gordon Lam (@yeelam-gordon) can take them (or not) when opening the PR from their own branch.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants