fix(sdl): clear the PulseAudio write callback before closing a stream #26132

Merged
GeremC merged 1 commit from upstream-pr/26132 into main 2026-11-23 11:21:50 +00:00
GeremC commented 2026-11-23 10:00:20 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by GeremC on 2026-11-23T10:00:20Z.


What

The bundled SDL2's PulseAudio backend writes to freed memory when an audio device is closed while the server still sends requests for its stream. That is the crash of #23020 (pa_stream_unref → pa_hashmap_free on the libpulse mainloop thread). As found there, it is not specific to the test: any title that closes a playing AudioOut port on a PulseAudio or pipewire-pulse host can hit it.

PULSEAUDIO_CloseDevice (3rdparty/SDL2/src/audio/pulseaudio/SDL_pulseaudio.c) calls pa_stream_disconnect and pa_stream_unref, then frees this->hidden. libpulse keeps the stream until the server answers DELETE_PLAYBACK_STREAM, and its write callback still has this->hidden as userdata. A REQUEST that arrives first runs WriteCallback, which does h->bytes_requested += nbytes on the freed block. SDL's SDL2 branch and SDL3 main have the same code.

This patches the bundled source the way cmake/PatchSdlWayland.cmake already patches SDL's Wayland files: cmake/PatchSdlPulseAudio.cmake copies SDL_pulseaudio.c into the build tree, applies a one-line patch and swaps the file in SDL2-static's sources. The patch calls pa_stream_set_write_callback(stream, NULL, NULL) before pa_stream_disconnect. That runs under the threaded mainloop lock that PULSEAUDIO_CloseDevice already holds, and the callbacks run on the mainloop thread with that lock held, so no callback can be running at the same time. Configuration stops if SDL2-static no longer builds that file, and git apply fails it if the context moves. It applies only when SDL is built with PulseAudio (HAVE_PULSEAUDIO), so builds without libpulse are unchanged. The read callback ignores its userdata, and the state callback has none. #23060 keeps the port bounds test on SDL's dummy driver. This PR does not change that and does not depend on it.

The other problem reported in #23020, PULSEAUDIO_OpenDevice waiting forever for PA_STREAM_READY when the server runs out of descriptors, is not addressed here.

Tested

Linux Mint 22.3 (Ubuntu 24.04 base), kernel 7.0, i7-13700K, PipeWire 1.0.5 (pipewire-pulse), libpulse 16.1.

  • AddressSanitizer A/B on the bundled SDL2. I built 3rdparty/SDL2 alone twice with clang 18 and -fsanitize=address, with the PulseAudio backend only: once unchanged, and once with the patch text from cmake/PatchSdlPulseAudio.cmake applied by the same git apply command. A small program opens 32 devices (48 kHz, stereo, F32), queues audio, unpauses them, waits 5 ms and closes them, for 30 rounds. I ran it 60 times per build, 4 at a time, with 6 busy-loop processes loading the CPU:

    SDL2 runs heap-use-after-free exit 0
    unchanged 60 42 18
    patched 60 0 60

    Every report has the same stack as #23020's ASan run: READ of size 4 ... thread T1 (PulseMainloop), #0 WriteCallback SDL_pulseaudio.c:381, pa_pdispatch_run. An earlier run of 40 on the unchanged build gave 26.

  • Full build (GCC 13.3, Release, BUILD_TESTING=ON): configuration writes build/sdl-pulseaudio/src/audio/pulseaudio/SDL_pulseaudio.c with the added line, and the build compiles that file instead of the submodule's. ctest -R 'audio|Audio|pad_|vibration|voice': 186/186 passed.

  • guest_audio_out_port_bounds_tests against the real pipewire-pulse, before the change: 300 runs, 4 at a time with the CPU loaded, all passed. The race is rarer with this PipeWire version than with the 1.6.11 of #23020, which is why I used ASan for the A/B. With 12 at a time, the processes hang in PULSEAUDIO_OpenDevice while pipewire-pulse logs can't load spa node: Too many open files. That is the separate hang above, and it happens without this change.

python3 tools/check_conventions.py --base origin/main passes.

Checklist

  • Based on current main; no other open PR implements the same functions
  • One topic per PR; follow-ups go in a new PR
  • No comments in code except technical debt and the licence notice of code adapted from upstream (see AGENTS.md)
  • Unimplemented paths throw (NotImplemented_nid_no_patch); silent stubs are listed under Silent stubs in their library's technical debt file
  • No notes, investigation .md files or images added to the repository (attach them to this PR)
  • New third-party code is a submodule built from source
  • Generic behaviour, not specific to one title
  • Depends on: none
  • Fixes: none (the cause of the #23020 crash in the real audio path; #23060 fixes the test)
  • Unblocks: none
  • GPUs tested: n/a
  • AI-assisted: yes (Claude Code)

🤖 Generated with Claude Code

https://claude.ai/code/session_014W1f1RvDMX4BmYudy9J2Vj

<!-- greyfinch-sync:boykopovar/AnyPS5:issue:5450910417 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/26132). Originally posted by [GeremC](https://github.com/GeremC) on 2026-11-23T10:00:20Z. --- ### What The bundled SDL2's PulseAudio backend writes to freed memory when an audio device is closed while the server still sends requests for its stream. That is the crash of #23020 (`pa_stream_unref` → `pa_hashmap_free` on the libpulse mainloop thread). As found there, it is not specific to the test: any title that closes a playing AudioOut port on a PulseAudio or `pipewire-pulse` host can hit it. `PULSEAUDIO_CloseDevice` (`3rdparty/SDL2/src/audio/pulseaudio/SDL_pulseaudio.c`) calls `pa_stream_disconnect` and `pa_stream_unref`, then frees `this->hidden`. libpulse keeps the stream until the server answers `DELETE_PLAYBACK_STREAM`, and its write callback still has `this->hidden` as userdata. A `REQUEST` that arrives first runs `WriteCallback`, which does `h->bytes_requested += nbytes` on the freed block. SDL's `SDL2` branch and SDL3 `main` have the same code. This patches the bundled source the way `cmake/PatchSdlWayland.cmake` already patches SDL's Wayland files: `cmake/PatchSdlPulseAudio.cmake` copies `SDL_pulseaudio.c` into the build tree, applies a one-line patch and swaps the file in `SDL2-static`'s sources. The patch calls `pa_stream_set_write_callback(stream, NULL, NULL)` before `pa_stream_disconnect`. That runs under the threaded mainloop lock that `PULSEAUDIO_CloseDevice` already holds, and the callbacks run on the mainloop thread with that lock held, so no callback can be running at the same time. Configuration stops if `SDL2-static` no longer builds that file, and `git apply` fails it if the context moves. It applies only when SDL is built with PulseAudio (`HAVE_PULSEAUDIO`), so builds without libpulse are unchanged. The read callback ignores its userdata, and the state callback has none. #23060 keeps the port bounds test on SDL's dummy driver. This PR does not change that and does not depend on it. The other problem reported in #23020, `PULSEAUDIO_OpenDevice` waiting forever for `PA_STREAM_READY` when the server runs out of descriptors, is not addressed here. ### Tested Linux Mint 22.3 (Ubuntu 24.04 base), kernel 7.0, i7-13700K, PipeWire 1.0.5 (`pipewire-pulse`), libpulse 16.1. - **AddressSanitizer A/B on the bundled SDL2.** I built `3rdparty/SDL2` alone twice with clang 18 and `-fsanitize=address`, with the PulseAudio backend only: once unchanged, and once with the patch text from `cmake/PatchSdlPulseAudio.cmake` applied by the same `git apply` command. A small program opens 32 devices (48 kHz, stereo, F32), queues audio, unpauses them, waits 5 ms and closes them, for 30 rounds. I ran it 60 times per build, 4 at a time, with 6 busy-loop processes loading the CPU: | SDL2 | runs | `heap-use-after-free` | exit 0 | |---|---|---|---| | unchanged | 60 | 42 | 18 | | patched | 60 | 0 | 60 | Every report has the same stack as #23020's ASan run: `READ of size 4 ... thread T1 (PulseMainloop)`, `#0 WriteCallback SDL_pulseaudio.c:381`, `pa_pdispatch_run`. An earlier run of 40 on the unchanged build gave 26. - **Full build** (GCC 13.3, Release, `BUILD_TESTING=ON`): configuration writes `build/sdl-pulseaudio/src/audio/pulseaudio/SDL_pulseaudio.c` with the added line, and the build compiles that file instead of the submodule's. `ctest -R 'audio|Audio|pad_|vibration|voice'`: 186/186 passed. - `guest_audio_out_port_bounds_tests` against the real `pipewire-pulse`, before the change: 300 runs, 4 at a time with the CPU loaded, all passed. The race is rarer with this PipeWire version than with the 1.6.11 of #23020, which is why I used ASan for the A/B. With 12 at a time, the processes hang in `PULSEAUDIO_OpenDevice` while `pipewire-pulse` logs `can't load spa node: Too many open files`. That is the separate hang above, and it happens without this change. `python3 tools/check_conventions.py --base origin/main` passes. ### Checklist <!-- Rules behind each item: https://github.com/boykopovar/AnyPS5/blob/main/CONTRIBUTING.md --> - [x] Based on current `main`; no other open PR implements the same functions - [x] One topic per PR; follow-ups go in a new PR - [x] No comments in code except [technical debt](https://github.com/boykopovar/AnyPS5/blob/main/docs/dev/CONVENTIONS.md) and the licence notice of code adapted from upstream (see AGENTS.md) - [x] Unimplemented paths throw (`NotImplemented_nid_no_patch`); silent stubs are listed under Silent stubs in their library's [technical debt](https://github.com/boykopovar/AnyPS5/tree/main/docs/dev/debt) file - [x] No notes, investigation `.md` files or images added to the repository (attach them to this PR) - [x] New third-party code is a submodule built from source - [x] Generic behaviour, not specific to one title - [x] Depends on: none - [x] Fixes: none (the cause of the #23020 crash in the real audio path; #23060 fixes the test) - [x] Unblocks: none - [x] GPUs tested: n/a - [x] AI-assisted: yes (Claude Code) 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_014W1f1RvDMX4BmYudy9J2Vj
MarcZX10 commented 2026-11-23 10:10:42 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-11-23T10:10:42Z.

Review: COMMENTED


Reviewed — no blocking findings

The changed CMake integration and patch are coherent by inspection, but build and runtime checks were not run in this review.

What I ran

Reviewed head bcdd50b12040a04ac04e60354eec1c5154253888 using the provided review reader. No shell or test runner was available.

Results

Check Result Note
Changed-file review passed Both changed files read
Build and tests not run No command runner available
SDL callback implementation not run Source was not available through reader search

Findings

Blocking

None found in the changed code reviewed.

Non-blocking

  • Consider attaching the build and test output to the PR so the patch application and behavior can be confirmed on the reviewed head.

Sources

Not verified

The bundled SDL PulseAudio implementation was not readable through the provided reader, so callback locking, callback userdata use, and close ordering were not independently confirmed. Build configuration, compilation, tests, and runtime behavior were not run. The PR description's test results were not independently verified.

Files read: description.md, commits.md, manifest.json, diff.patch, CMakeLists.txt, cmake/PatchSdlPulseAudio.cmake, and the first 90 lines of cmake/PatchSdlWayland.cmake as targeted context. Changed files reviewed: CMakeLists.txt and cmake/PatchSdlPulseAudio.cmake (2 of 2). No changed files were excluded.

To get this to a good state

Nothing is required. Optional: attach the reported build and test output for this head.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:6019729993 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/26132#pullrequestreview-6019729993). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-11-23T10:10:42Z. **Review:** COMMENTED --- # Reviewed — no blocking findings The changed CMake integration and patch are coherent by inspection, but build and runtime checks were not run in this review. ## What I ran Reviewed head `bcdd50b12040a04ac04e60354eec1c5154253888` using the provided review reader. No shell or test runner was available. ## Results | Check | Result | Note | |---|---|---| | Changed-file review | passed | Both changed files read | | Build and tests | not run | No command runner available | | SDL callback implementation | not run | Source was not available through reader search | ## Findings ### Blocking None found in the changed code reviewed. ### Non-blocking - Consider attaching the build and test output to the PR so the patch application and behavior can be confirmed on the reviewed head. ## Sources - [CMake integration at the reviewed head](https://github.com/boykopovar/AnyPS5/blob/bcdd50b12040a04ac04e60354eec1c5154253888/CMakeLists.txt#L1080-L1083) - [PulseAudio patch setup at the reviewed head](https://github.com/boykopovar/AnyPS5/blob/bcdd50b12040a04ac04e60354eec1c5154253888/cmake/PatchSdlPulseAudio.cmake#L22-L42) ## Not verified The bundled SDL PulseAudio implementation was not readable through the provided reader, so callback locking, callback userdata use, and close ordering were not independently confirmed. Build configuration, compilation, tests, and runtime behavior were not run. The PR description's test results were not independently verified. Files read: `description.md`, `commits.md`, `manifest.json`, `diff.patch`, `CMakeLists.txt`, `cmake/PatchSdlPulseAudio.cmake`, and the first 90 lines of `cmake/PatchSdlWayland.cmake` as targeted context. Changed files reviewed: `CMakeLists.txt` and `cmake/PatchSdlPulseAudio.cmake` (2 of 2). No changed files were excluded. ## To get this to a good state Nothing is required. Optional: attach the reported build and test output for this head.
mihiii1337 commented 2026-11-23 10:12:49 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by mihiii1337 on 2026-11-23T10:12:49Z.

Review: APPROVED


Reviewed exact head bcdd50b12040a04ac04e60354eec1c5154253888 against the pinned SDL2 source and PulseAudio 16.1 API implementation.

  • The added callback clear runs under SDL's existing threaded-mainloop lock, before drop/disconnect/unref. PulseAudio documents that event callbacks run with this lock held, so a write callback cannot execute concurrently across this point.
  • The PulseAudio setter only replaces the write callback/userdata fields and has no stream-direction guard. SDL's capture read callback ignores its userdata and the state callback is registered with null userdata, so the unconditional clear does not disturb capture teardown.
  • A C11 stub fixture extracted the original and patched close function and verified the exact call order for playback, capture with and without buffered data, and a null stream.
  • The exact embedded patch applies to the pinned SDL2 blob. Minimal CMake fixtures with 3.20.6 and 4.3.1 verified source replacement, original include-directory preservation, repeat configuration/idempotence, the disabled path, and both stale-source/context fatal controls.
  • Conventions, diff and merge checks were clean; #23060 only isolates the bounds test on the dummy driver and does not duplicate this production fix.

I did not run Linux/PipeWire audio, ASan or the reported 186-test suite, so the author's 42/60 to 0/60 UAF A/B remains external runtime evidence. The separate OpenDevice descriptor-exhaustion hang remains out of scope.

AI-assisted: yes.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:6019756629 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/26132#pullrequestreview-6019756629). Originally posted by [mihiii1337](https://github.com/mihiii1337) on 2026-11-23T10:12:49Z. **Review:** APPROVED --- Reviewed exact head `bcdd50b12040a04ac04e60354eec1c5154253888` against the pinned SDL2 source and PulseAudio 16.1 API implementation. - The added callback clear runs under SDL's existing threaded-mainloop lock, before drop/disconnect/unref. PulseAudio documents that event callbacks run with this lock held, so a write callback cannot execute concurrently across this point. - The PulseAudio setter only replaces the write callback/userdata fields and has no stream-direction guard. SDL's capture read callback ignores its userdata and the state callback is registered with null userdata, so the unconditional clear does not disturb capture teardown. - A C11 stub fixture extracted the original and patched close function and verified the exact call order for playback, capture with and without buffered data, and a null stream. - The exact embedded patch applies to the pinned SDL2 blob. Minimal CMake fixtures with 3.20.6 and 4.3.1 verified source replacement, original include-directory preservation, repeat configuration/idempotence, the disabled path, and both stale-source/context fatal controls. - Conventions, diff and merge checks were clean; #23060 only isolates the bounds test on the dummy driver and does not duplicate this production fix. I did not run Linux/PipeWire audio, ASan or the reported 186-test suite, so the author's 42/60 to 0/60 UAF A/B remains external runtime evidence. The separate OpenDevice descriptor-exhaustion hang remains out of scope. AI-assisted: yes.
Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
boykopovar/AnyPS5!26132
No description provided.