fix(agc): avoid a misaligned wide load in the ASan CopyGuestBytes helper #9570

Closed
jotitadev wants to merge 1 commit from upstream-pr/9570 into main
jotitadev commented 2026-10-22 02:39:49 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by jotitadev on 2026-10-22T02:39:49Z.


What

GuestMemory::CopyGuestBytes has an #ifdef ANYPS5_ENABLE_ASAN variant that copies
guest memory word by word so the reads stay volatile (to force the access through the
write-watch / read-guard machinery). The load side did a raw wide dereference:

const std::uint64_t word = *reinterpret_cast<const volatile std::uint64_t*>(from + index);

from is a guest address with no 8-byte alignment guarantee, so this is a misaligned
load — undefined behavior, flagged by -fsanitize=undefined. x86 tolerates it in hardware,
so there is no misbehavior today, but it is UB and would fault on alignment-strict targets.

This affects ASan builds only. The shipping non-ASan path (std::memcpy) is untouched
and was already clean.

Fix

Keep the wide volatile read on the aligned fast path; when from + index is not 8-byte
aligned, read those 8 bytes volatile byte-by-byte and assemble the word:

std::uint64_t word;
if (reinterpret_cast<std::uintptr_t>(from + index) % alignof(std::uint64_t) == 0) {
    word = *reinterpret_cast<const volatile std::uint64_t*>(from + index);
} else {
    const volatile unsigned char* wide = from + index;
    unsigned char buffer[sizeof(std::uint64_t)];
    for (std::size_t offset = 0; offset < sizeof(std::uint64_t); ++offset) buffer[offset] = wide[offset];
    std::memcpy(&word, buffer, sizeof(word));
}
std::memcpy(to + index, &word, sizeof(word));

Every one of the 8 bytes is still read through a volatile access, in order, so the forced
read semantics the helper exists for are preserved — the volatile is not removed and the
function is not rewritten. Only the raw wide dereference of a possibly-unaligned address is
avoided. <cstdint> is added to the unconditional include block so std::uintptr_t is
available on every platform (it was previously pulled in only on the non-Windows branch).
The non-ASan branch is not touched.

Tested

Repro

cmake -S . -B build-asan -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo -DBUILD_TESTING=ON \
  -DANYPS5_ENABLE_ASAN=ON \
  -DCMAKE_CXX_FLAGS="-fsanitize=undefined -fno-sanitize-recover=undefined -fno-sanitize=vptr" \
  -DCMAKE_C_FLAGS="-fsanitize=undefined -fno-sanitize-recover=undefined -fno-sanitize=vptr"
ninja -C build-asan -j3 agc_driver_memory_value_fill_tests
VK_ICD_FILENAMES=/usr/share/vulkan/icd.d/lvp_icd.json ANYPS5_NO_SHADER_CACHE=1 \
  UBSAN_OPTIONS=print_stacktrace=1 ./build-asan/tests/agc_driver_memory_value_fill_tests

Linux, GCC 15.2, RelWithDebInfo, ASan + UBSan. GPU tests run under lavapipe (Mesa
llvmpipe software rasterizer) to avoid non-ASan-clean GPU driver noise.

Red -> green

Three independent execution tests hit the exact same line via GuestMemory::Read -> CopyGuestBytes.

Before the fix — all three abort (fno-sanitize-recover), exit code 1:

core/libs/prx/libSceAgcDriver/Execution/src/GuestMemory.cpp:2326:36: runtime error: load of misaligned address 0x... for type 'volatile const uint64_t', which requires 8 byte alignment
    #0 AgcDriver::GuestMemory::CopyGuestBytes(void*, void const*, unsigned long) GuestMemory.cpp:2326
    #1 AgcDriver::GuestMemory::Read(unsigned long, std::span<std::byte, ...>, unsigned long) GuestMemory.cpp:2317
test before after
agc_driver_memory_value_fill_tests abort, misaligned load @ 2326 pass, exit 0, 0 UBSan hits
agc_driver_storage_file_write_tests abort, misaligned load @ 2326 pass, exit 0, 0 UBSan hits
agc_driver_stream_copy_tests abort, misaligned load @ 2326 pass, exit 0, 0 UBSan hits

After the fix — all three print their "tests passed" line and exit 0 with no UBSan runtime
error. A sample of extra execution tests (incl. unaligned-base coverage) was also run under
the same ASan+UBSan build with no new failures, and the normal build (no sanitizers, no
ANYPS5_ENABLE_ASAN) still compiles the touched translation unit.

Introduced by 257894965 (run the AGC GPU tests in an ANYPS5_ENABLE_ASAN build); the UBSan
alignment hit there was almost certainly unintended.

AI-assisted (Claude Code); the builds and tests above were run on my machine.

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
  • 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
  • Unblocks: none
  • GPUs tested: Mesa lavapipe (llvmpipe software rasterizer) on Ubuntu 26.04, under ASan + UBSan; no hardware GPU in the sanitizer build
  • AI-assisted: yes (Claude Code)
<!-- greyfinch-sync:boykopovar/AnyPS5:issue:4961268084 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/9570). Originally posted by [jotitadev](https://github.com/jotitadev) on 2026-10-22T02:39:49Z. --- ### What `GuestMemory::CopyGuestBytes` has an `#ifdef ANYPS5_ENABLE_ASAN` variant that copies guest memory word by word so the reads stay `volatile` (to force the access through the write-watch / read-guard machinery). The load side did a raw wide dereference: ```cpp const std::uint64_t word = *reinterpret_cast<const volatile std::uint64_t*>(from + index); ``` `from` is a guest address with no 8-byte alignment guarantee, so this is a misaligned load — undefined behavior, flagged by `-fsanitize=undefined`. x86 tolerates it in hardware, so there is no misbehavior today, but it is UB and would fault on alignment-strict targets. This affects **ASan builds only**. The shipping non-ASan path (`std::memcpy`) is untouched and was already clean. **Fix** Keep the wide `volatile` read on the aligned fast path; when `from + index` is not 8-byte aligned, read those 8 bytes `volatile` byte-by-byte and assemble the word: ```cpp std::uint64_t word; if (reinterpret_cast<std::uintptr_t>(from + index) % alignof(std::uint64_t) == 0) { word = *reinterpret_cast<const volatile std::uint64_t*>(from + index); } else { const volatile unsigned char* wide = from + index; unsigned char buffer[sizeof(std::uint64_t)]; for (std::size_t offset = 0; offset < sizeof(std::uint64_t); ++offset) buffer[offset] = wide[offset]; std::memcpy(&word, buffer, sizeof(word)); } std::memcpy(to + index, &word, sizeof(word)); ``` Every one of the 8 bytes is still read through a `volatile` access, in order, so the forced read semantics the helper exists for are preserved — the `volatile` is not removed and the function is not rewritten. Only the raw wide dereference of a possibly-unaligned address is avoided. `<cstdint>` is added to the unconditional include block so `std::uintptr_t` is available on every platform (it was previously pulled in only on the non-Windows branch). The non-ASan branch is not touched. ### Tested **Repro** ``` cmake -S . -B build-asan -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo -DBUILD_TESTING=ON \ -DANYPS5_ENABLE_ASAN=ON \ -DCMAKE_CXX_FLAGS="-fsanitize=undefined -fno-sanitize-recover=undefined -fno-sanitize=vptr" \ -DCMAKE_C_FLAGS="-fsanitize=undefined -fno-sanitize-recover=undefined -fno-sanitize=vptr" ninja -C build-asan -j3 agc_driver_memory_value_fill_tests VK_ICD_FILENAMES=/usr/share/vulkan/icd.d/lvp_icd.json ANYPS5_NO_SHADER_CACHE=1 \ UBSAN_OPTIONS=print_stacktrace=1 ./build-asan/tests/agc_driver_memory_value_fill_tests ``` Linux, GCC 15.2, RelWithDebInfo, ASan + UBSan. GPU tests run under **lavapipe** (Mesa llvmpipe software rasterizer) to avoid non-ASan-clean GPU driver noise. **Red -> green** Three independent execution tests hit the exact same line via `GuestMemory::Read -> CopyGuestBytes`. **Before the fix** — all three abort (`fno-sanitize-recover`), exit code 1: ``` core/libs/prx/libSceAgcDriver/Execution/src/GuestMemory.cpp:2326:36: runtime error: load of misaligned address 0x... for type 'volatile const uint64_t', which requires 8 byte alignment #0 AgcDriver::GuestMemory::CopyGuestBytes(void*, void const*, unsigned long) GuestMemory.cpp:2326 #1 AgcDriver::GuestMemory::Read(unsigned long, std::span<std::byte, ...>, unsigned long) GuestMemory.cpp:2317 ``` | test | before | after | | --- | --- | --- | | `agc_driver_memory_value_fill_tests` | abort, misaligned load @ 2326 | pass, exit 0, 0 UBSan hits | | `agc_driver_storage_file_write_tests` | abort, misaligned load @ 2326 | pass, exit 0, 0 UBSan hits | | `agc_driver_stream_copy_tests` | abort, misaligned load @ 2326 | pass, exit 0, 0 UBSan hits | **After the fix** — all three print their "tests passed" line and exit 0 with no UBSan runtime error. A sample of extra execution tests (incl. unaligned-base coverage) was also run under the same ASan+UBSan build with no new failures, and the normal build (no sanitizers, no `ANYPS5_ENABLE_ASAN`) still compiles the touched translation unit. Introduced by `257894965` (run the AGC GPU tests in an ANYPS5_ENABLE_ASAN build); the UBSan alignment hit there was almost certainly unintended. AI-assisted (Claude Code); the builds and tests above were run on my machine. ### 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) - [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 - [x] Unblocks: none - [x] GPUs tested: Mesa lavapipe (llvmpipe software rasterizer) on Ubuntu 26.04, under ASan + UBSan; no hardware GPU in the sanitizer build - [x] AI-assisted: yes (Claude Code)
MarcZX10 commented 2026-10-22 03:57:54 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-22T03:57:54Z.

Review: CHANGES_REQUESTED


The code change is narrowly scoped and preserves the volatile accesses on both the aligned and bytewise paths. The reported UBSan reproduction and three post-fix test results are relevant evidence, and I found no competing edit to CopyGuestBytes in the manually checked shared-file warnings.

I am requesting changes because the hosted conventions check fails, and this PR body does not use the repository's required .github/pull_request_template.md (it omits the template's checklist and required Depends on, Fixes, Unblocks, GPUs tested, and AI-assisted fields in their prescribed form). Please copy the current template, keep every line, fill each required field, and rerun the conventions check. Eligibility, intake, labels and report pass; the hosted Linux, Windows and relinker jobs are skipped. I did not treat the author-reported local runs as hosted checks.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5609083376 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/9570#pullrequestreview-5609083376). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-22T03:57:54Z. **Review:** CHANGES_REQUESTED --- The code change is narrowly scoped and preserves the volatile accesses on both the aligned and bytewise paths. The reported UBSan reproduction and three post-fix test results are relevant evidence, and I found no competing edit to `CopyGuestBytes` in the manually checked shared-file warnings. I am requesting changes because the hosted `conventions` check fails, and this PR body does not use the repository's required `.github/pull_request_template.md` (it omits the template's checklist and required `Depends on`, `Fixes`, `Unblocks`, `GPUs tested`, and AI-assisted fields in their prescribed form). Please copy the current template, keep every line, fill each required field, and rerun the conventions check. Eligibility, intake, labels and report pass; the hosted Linux, Windows and relinker jobs are skipped. I did not treat the author-reported local runs as hosted checks.
jotitadev commented 2026-10-22 04:46:24 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by jotitadev on 2026-10-22T04:46:24Z.


Thanks for the review. Addressed: the body now follows .github/pull_request_template.md — the summary and repro are under ### What / ### Tested, and the full ### Checklist is filled (including GPUs tested: and AI-assisted: yes). The hosted Conventions check is green now. The code change itself is unchanged from what you reviewed (the aligned fast path keeps the wide volatile read; the unaligned path reads the 8 bytes volatile byte-by-byte). Could you take another look when you have a moment?

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6332939649 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/9570#issuecomment-6332939649). Originally posted by [jotitadev](https://github.com/jotitadev) on 2026-10-22T04:46:24Z. --- Thanks for the review. Addressed: the body now follows `.github/pull_request_template.md` — the summary and repro are under `### What` / `### Tested`, and the full `### Checklist` is filled (including `GPUs tested:` and `AI-assisted: yes`). The hosted **Conventions** check is green now. The code change itself is unchanged from what you reviewed (the aligned fast path keeps the wide `volatile` read; the unaligned path reads the 8 bytes `volatile` byte-by-byte). Could you take another look when you have a moment?
fogydes commented 2026-10-22 08:13:33 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by fogydes on 2026-10-22T08:13:33Z.


The Conventions check fails on the head of this PR (job 119607257405): Fill in the pull request template: section 'What' is missing or empty, and the same for Tested and Checklist.

The relinker, relinker-asan, register-context and write-watch jobs all pass on the same commit, and python3 tools/check_conventions.py --base origin/main prints the same three template findings locally. Filling in every line of .github/pull_request_template.md (What, Tested, Depends on, Unblocks, GPUs tested, AI-assisted, and tick the boxes) is all that appears to block CI.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6336045845 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/9570#issuecomment-6336045845). Originally posted by [fogydes](https://github.com/fogydes) on 2026-10-22T08:13:33Z. --- The Conventions check fails on the head of this PR ([job 119607257405](https://github.com/boykopovar/AnyPS5/actions/runs/39712617904/job/119607257405)): `Fill in the pull request template: section 'What' is missing or empty`, and the same for `Tested` and `Checklist`. The relinker, relinker-asan, register-context and write-watch jobs all pass on the same commit, and `python3 tools/check_conventions.py --base origin/main` prints the same three template findings locally. Filling in every line of `.github/pull_request_template.md` (What, Tested, Depends on, Unblocks, GPUs tested, AI-assisted, and tick the boxes) is all that appears to block CI.
jotitadev commented 2026-10-22 08:27:37 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by jotitadev on 2026-10-22T08:27:37Z.


Thanks. That job ran on the old body; the body now follows the template and Conventions passes on the same head: https://github.com/boykopovar/AnyPS5/actions/runs/39722571996/job/119639169696

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6336303687 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/9570#issuecomment-6336303687). Originally posted by [jotitadev](https://github.com/jotitadev) on 2026-10-22T08:27:37Z. --- Thanks. That job ran on the old body; the body now follows the template and Conventions passes on the same head: https://github.com/boykopovar/AnyPS5/actions/runs/39722571996/job/119639169696
MarcZX10 commented 2026-10-22 11:17:10 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-22T11:17:10Z.

Review: APPROVED


Re-reviewed exact head c65ab7596ea86149b91249f0b2d38d465c5ff75a. The fix retains the aligned volatile 64-bit load and uses eight ordered volatile byte reads only for unaligned blocks, then copies the assembled word without changing the non-ASan path. I found no correctness issue in the changed code. The current PR description now includes the repository template fields and the latest hosted conventions run passes. I attempted an independent Linux UBSan run in an isolated detached worktree with the three reported targets (agc_driver_memory_value_fill_tests, agc_driver_storage_file_write_tests, agc_driver_stream_copy_tests), ANYPS5_ENABLE_ASAN=ON, and the PR's UBSan flags. CMake configuration succeeded and the build progressed through 599/808 steps, but stopped before reaching those targets because the root filesystem ran out of space while compiling unrelated library/shader objects (No space left on device). No test executable ran, so I am not claiming a local test pass. The PR-reported red/green runs remain author-reported. Hosted Linux/Windows product jobs are skipped; eligibility, intake, labels, report passed, while the original conventions failure was followed by a passing run after the body update. Current-main sync is 1 ahead / 107 behind (6ef5a1c4c merge base), with a clean merge. Please refresh from current main before merge under the repository's branch rule. The change is narrowly scoped, and I found no competing edit to CopyGuestBytes in the open file list.

I’ve noticed that holding this PR because of #5239 isn’t necessary. It’s fine for PRs to keep coming in; they’ll be handled in due course. Please disregard my earlier request to hold or defer it.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5613314877 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/9570#pullrequestreview-5613314877). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-22T11:17:10Z. **Review:** APPROVED --- Re-reviewed exact head `c65ab7596ea86149b91249f0b2d38d465c5ff75a`. The fix retains the aligned volatile 64-bit load and uses eight ordered volatile byte reads only for unaligned blocks, then copies the assembled word without changing the non-ASan path. I found no correctness issue in the changed code. The current PR description now includes the repository template fields and the latest hosted conventions run passes. I attempted an independent Linux UBSan run in an isolated detached worktree with the three reported targets (`agc_driver_memory_value_fill_tests`, `agc_driver_storage_file_write_tests`, `agc_driver_stream_copy_tests`), `ANYPS5_ENABLE_ASAN=ON`, and the PR's UBSan flags. CMake configuration succeeded and the build progressed through 599/808 steps, but stopped before reaching those targets because the root filesystem ran out of space while compiling unrelated library/shader objects (`No space left on device`). No test executable ran, so I am not claiming a local test pass. The PR-reported red/green runs remain author-reported. Hosted Linux/Windows product jobs are skipped; eligibility, intake, labels, report passed, while the original conventions failure was followed by a passing run after the body update. Current-main sync is 1 ahead / 107 behind (`6ef5a1c4c` merge base), with a clean merge. Please refresh from current `main` before merge under the repository's branch rule. The change is narrowly scoped, and I found no competing edit to `CopyGuestBytes` in the open file list. I’ve noticed that holding this PR because of #5239 isn’t necessary. It’s fine for PRs to keep coming in; they’ll be handled in due course. Please disregard my earlier request to hold or defer it.
MarcZX10 commented 2026-10-22 14:22:28 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-22T14:22:28Z.

Review: DISMISSED


I reviewed exact head c65ab7596ea86149b91249f0b2d38d465c5ff75a. The alignment branch keeps the existing wide volatile read for aligned addresses and assembles unaligned words from eight volatile byte reads; I found no defect in that helper. I also ran a focused UBSan harness using the exact helper body across source offsets 0–7 and lengths 0–40; all byte comparisons and destination canaries passed. As a negative control, the current upstream/main helper aborts on the first unaligned wide load with UBSan’s misaligned-address diagnostic. This is a focused helper harness, not the repository AGC test targets.

The current branch is 1 commit ahead and 152 behind upstream/main (329efe1bfdaff116c57cdf62718026ee4f5521ae). Five intervening main commits touched GuestMemory.cpp, so please rebase onto current main and rerun the three reported ASan+UBSan regression targets before merge, as required by CONTRIBUTING’s current-main rule. The current-base git diff --check and conventions check pass, and merge-tree is clean.

The overlap scan could not compare 14 open PRs that also touch GuestMemory.cpp because they conflict with main. I inspected their changed hunks around CopyGuestBytes: none modifies this helper; #6188 changes adjacent speculative-read code and its combined merge tree retains this fix. I found no duplicate implementation of the misaligned-load correction. Hosted product build jobs remain skipped; I did not treat the author-reported three-target runs as hosted or as my local project test.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5615757962 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/9570#pullrequestreview-5615757962). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-22T14:22:28Z. **Review:** DISMISSED --- I reviewed exact head `c65ab7596ea86149b91249f0b2d38d465c5ff75a`. The alignment branch keeps the existing wide volatile read for aligned addresses and assembles unaligned words from eight volatile byte reads; I found no defect in that helper. I also ran a focused UBSan harness using the exact helper body across source offsets 0–7 and lengths 0–40; all byte comparisons and destination canaries passed. As a negative control, the current upstream/main helper aborts on the first unaligned wide load with UBSan’s misaligned-address diagnostic. This is a focused helper harness, not the repository AGC test targets. The current branch is 1 commit ahead and 152 behind upstream/main (`329efe1bfdaff116c57cdf62718026ee4f5521ae`). Five intervening main commits touched `GuestMemory.cpp`, so please rebase onto current main and rerun the three reported ASan+UBSan regression targets before merge, as required by CONTRIBUTING’s current-main rule. The current-base `git diff --check` and conventions check pass, and merge-tree is clean. The overlap scan could not compare 14 open PRs that also touch `GuestMemory.cpp` because they conflict with main. I inspected their changed hunks around `CopyGuestBytes`: none modifies this helper; #6188 changes adjacent speculative-read code and its combined merge tree retains this fix. I found no duplicate implementation of the misaligned-load correction. Hosted product build jobs remain skipped; I did not treat the author-reported three-target runs as hosted or as my local project test.

Pull request closed

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!9570
No description provided.