Skip to content

fix(libc): probe vasprintf destination pointer before writing - #26638

Merged
oneandonlydean merged 1 commit into
boykopovar:mainfrom
kattkaries:fix/libc-vasprintf-guest-output
Nov 24, 2026
Merged

oneandonlydean merged 1 commit into
boykopovar:mainfrom
kattkaries:fix/libc-vasprintf-guest-output

Conversation

@kattkaries

Copy link
Copy Markdown
Contributor

What

vasprintf_nid_postfix in core/libs/prx/libc/src/Formatting.cpp wrote through the guest-supplied char** destination as a raw host pointer write at two points — the initial *destination = nullptr and the post-allocation *destination = output — with only a null check on destination itself. Every other failure path in the function is error-coded (null destination/format/args → -1/errno 22; heap exhaustion → -1/errno 12), but an unguarded write to a non-null, unmapped guest pointer faults the host with SIGSEGV (exit 139) instead of failing gracefully.

Both writes are now routed through GuestCopyOut_nid_no_patch (the same fault-safe copy helper used by the fopen_s_nid_postfix sibling in core/libs/prx/libc/src/FileAndHeap.cpp, and by GuestCopyOut callers across General.cpp/Backtrace.cpp/Radix64.cpp/Time.cpp):

  • The initial write doubles as an up-front probe (GuestCopyOut(destination, &nullOutput, sizeof(char*))), mirroring fopen_s_nid_postfix; on an inaccessible destination it sets errno = 22 and returns -1 before any formatting or heap allocation, saving/restoring errno around the probe.
  • The post-allocation write is guarded; if it fails the guest-heap allocation is released (ApplicationHeapFree_nid_no_patch) and the function returns -1/errno 22, closing the otherwise-unreachable guest-heap leak — the analogue of fopen_s closing its stream on a later write failure.

Existing contracts are unchanged: null destination/format/args → -1/errno 22; heap exhaustion → -1/errno 12; the success path is identical. asprintf and dprintf/vdprintf route through vasprintf and inherit the guard.

The -1/errno 22 choice for an inaccessible out-pointer is the codebase-internal sibling-precedent convention (matching fopen_s_nid_postfix); it is not presented as measured console firmware behaviour.

Tested

  • RED (regression, fix reverted): driving vasprintf_nid_postfix with an unmapped guest destination CallVasprintf(reinterpret_cast<char**>(0x10), "value=%d", 42) faults the host — [libc] fatal SIGSEGV (code 1) at address 0x0000000000000010, exit 139; ctest -R "^guest_allocating_strings" → SEGFAULT.
  • GREEN (this commit): the same case returns -1 with errno == 22 and performs zero heap allocations (proving abort-before-format); ctest --test-dir build -R "^guest_allocating_strings" → guest_allocating_strings Passed.
  • Regression sweep (this commit): guest_allocating_strings, guest_formatting, guest_allocator_failures, guest_libc_internal_format — 4/4 passed, 0 skipped.
  • Gates: tools/check_conventions.py passes; tools/pr_overlap.py reports a feature-vs-fix false positive (file sharing with the original libc feature PRs), dismissed after hunk-level review — none of the overlapping PRs probe the vasprintf destination.

Regression test extends the existing harness core/libs/tests/GuestAllocatingStrings.cpp (no new CMake target). Changed files: core/libs/prx/libc/src/Formatting.cpp, core/libs/tests/GuestAllocatingStrings.cpp (+17/−2).

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
  • Unblocks: none
  • GPUs tested: n/a
  • AI-assisted: yes

@github-actions github-actions Bot added the libc label Nov 24, 2026

@PrivacyOnion PrivacyOnion 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.

Verified on Linux (Ubuntu 24.04, GCC 13.3, Ninja, Release) against 8bb35191d8:

  • Conventions: tools/check_conventions.py passed.
  • Build: guest_allocating_strings_tests built cleanly.
  • CTest (guest_allocating_strings):
    1/1 Test #1210: guest_allocating_strings .........   Passed    0.01 sec
    100% tests passed, 0 tests failed out of 1
    
  • Negative control: with core/libs/prx/libc/src/Formatting.cpp reverted to main and the new tests kept, the suite fails:
    1/1 Test #1210: guest_allocating_strings .........***Exception: SegFault  0.48 sec
    0% tests passed, 1 tests failed out of 1
    
    Restoring the change makes it pass again.
  • Code reading:
    • Verified vasprintf_nid_postfix destination probe uses GuestCopyOut_nid_no_patch with sizeof(nullOutput) (8 bytes / pointer width) matching the guest pointer size
    • Verified errno save and restore around GuestCopyOut_nid_no_patch to guarantee errno=22 (EINVAL) is set consistently on probe failure
    • Verified post-allocation GuestCopyOut_nid_no_patch failure path frees output via ApplicationHeapFree_nid_no_patch to prevent guest heap leakage
    • Verified input ordering: destination is probed and set to nullptr before checking format and args pointers (errno 22)
    • Verified AGENTS.md compliance: no comments added, no hardcoded title workarounds, conventional commit format in PR title
    • Verified core/libs/tests/GuestAllocatingStrings.cpp asserts return code -1, errno 22, and allocation count stability when destination is unmapped

Looks Good To Me

@github-actions

Copy link
Copy Markdown

Some comparisons could not be completed because a pull request conflicts with the base branch. Review these shared files manually before concluding that there is no overlap.

Pull request Shared files not compared
PR 9087 core/libs/prx/libc/src/Formatting.cpp
PR 9340 core/libs/prx/libc/src/Formatting.cpp
PR 11332 core/libs/prx/libc/src/Formatting.cpp

@Helldiverr

Copy link
Copy Markdown
Contributor

Works on Windows at head 8bb35191d8. On the merge, guest_allocating_strings passes, and a 13-case probe shows every unwritable destination returning -1 with errno 22, with no heap allocation and the destination bytes unchanged. With Formatting.cpp taken from main, the test crashes with a SegFault. Of six mutations, three fail the test and three pass it. The new allocation check at line 169 cannot fail, because it runs before InitializeHeap() at line 171 installs the counting hook. The two mutations that remove the up-front probe fail the test only because the allocator throws without a heap. Details below.

Existing runs. 1 review and 1 comment. No inline comments.

  • The author, kattkaries, in the PR description: the new case crashes with SIGSEGV (exit 139) with the fix reverted, and passes with it. guest_allocating_strings, guest_formatting, guest_allocator_failures and guest_libc_internal_format pass. tools/check_conventions.py passes. The host is not named. The description says that -1 with errno 22 follows fopen_s_nid_postfix, and is not measured on a console.
  • PrivacyOnion, 1 review at 8bb35191d8: Ubuntu 24.04, GCC 13.3, Ninja, Release. guest_allocating_strings passes. With Formatting.cpp reverted to main and the new test kept, it fails with a SegFault, and it passes again with the change restored. The review also lists points checked by reading the code, including that the test checks the allocation count when the destination is unmapped.
  • github-actions, 1 pr-overlap comment. fix(libc): follow snprintf_s and sscanf_s constraints as measured on a PS5 #9087, feat(libc): decode non-ASCII scanset members and non-BMP characters in the guest wide scanf #9340 and fix(libc): bound narrow formatting fields #11332 conflict with the base, so their shared core/libs/prx/libc/src/Formatting.cpp was not compared.
  • CI at 8bb35191d8:
    • pass: eligibility, conventions, library-portability, intake, labels, report, windows, and every relinker, relinker-asan, register-context, write-watch and edge-watch job;
    • skipped: linux and pipe-write.

What this run adds.

  • A local Windows run of the libc formatting tests and the public header tests, on main and on the merge.
  • A negative control and six mutations of vasprintf_nid_postfix.
  • A probe with 13 cases: unwritable destinations of several kinds, writable edge cases, null arguments, and asprintf, run on main and on the merge.

Code. Line numbers are from the head. The merge is clean.

  • vasprintf_nid_postfix (core/libs/prx/libc/src/Formatting.cpp lines 646-687):
    • line 647: a null destination returns -1 with errno 22, as before;
    • lines 648-652: GuestCopyOut_nid_no_patch writes a null pointer to the destination, with errno saved and restored around it. If the write fails, the function returns -1 with errno 22;
    • line 653: a null format or argument list returns -1 with errno 22, now after the destination has been nulled;
    • line 671: the heap allocation;
    • lines 677-681: the result is written with GuestCopyOut_nid_no_patch. If that fails, the block is freed with ApplicationHeapFree_nid_no_patch, and the function returns -1 with errno 22.
  • GuestCopyOut_nid_no_patch (core/libs/prx/libc/src/General.cpp lines 957-974 on main e68be05111) restores errno itself (line 961). On Windows, it refuses any range that VirtualQuery reports as not committed, as a guard page, or as not writable (lines 966-972).
  • asprintf_nid_postfix (core/libs/prx/libc/src/AllocatingStrings.cpp line 63 on main e68be05111) and vdprintf_nid_postfix (line 83) call vasprintf_nid_postfix.
  • The same up-front probe is in fopen_s_nid_postfix (core/libs/prx/libc/src/FileAndHeap.cpp lines 693-720 on main e68be05111), which calls the constraint handler and returns 22. readdir_r (core/libs/prx/libc/src/Directory.cpp lines 379-390 on main e68be05111) returns 14 when the same helper fails. No debt fragment records that errno 22 here is not measured on a console.
  • core/libs/tests/GuestAllocatingStrings.cpp lines 164-169 call CallVasprintf with destination 0x10. They check for -1, errno 22, and an unchanged allocations count. allocations changes only in the Allocate hook (lines 40-47). InitializeHeap() (lines 70-92) installs that hook, and it is first called at line 171, after this case. So line 169 compares 0 with 0. Without a heap, an allocation throws "application heap: process metadata is missing; relink the executable" (core/libs/prx/libc/src/ApplicationProcessParameters.cpp line 89 on main e68be05111), and the test aborts. That is how v1 and v5 below fail. With the case moved after line 171, the probe shows that v1 and v5 allocate and free one block, so line 169 would fail on the count (derived from the probe, not run as a test).

Negative control and mutation. Each row is the merge plus the probe, with one change to Formatting.cpp. Tests run: guest_allocating_strings and the 13 probe tests.

Row Change guest_allocating_strings Probe compared with the merge
n0 Formatting.cpp from main fails: SegFault (0xc0000005) the same as on main (see Probes)
v1 lines 648-652 removed fails: aborts on "application heap: process metadata is missing" zero_noheap aborts the same way. zero, readonly, execread, guard, straddle and asprintf_readonly return -1 with errno 22, with 1 allocation and 1 release. nullformat and nullargs leave the destination at 5a5a5a5a5a5a5a5a
v2 errno 14 instead of 22 at line 652 fails: aborts every unwritable-destination case reports errno 14
v3 errno = savedErrno; removed (line 651) passes the same as the merge
v4 no ApplicationHeapFree_nid_no_patch at line 678 passes the same as the merge
v5 the if (!probed) line removed (line 652) fails: aborts on "application heap: process metadata is missing" the same as v1, except that nullformat and nullargs write 0000000000000000
v6 return count; instead of return -1; at line 680 passes the same as the merge
  • 7 rows.
  • v3 survives because GuestCopyOut_nid_no_patch already restores errno (General.cpp line 961 on main e68be05111), so lines 649 and 651 have no effect that a test can see.
  • v4 and v6 change only the path at lines 677-681. That path runs only if the destination stops being writable between lines 650 and 677, for example when another thread unmaps it. Derived, not traced. No test or probe case reaches it.

Probes. One extra test executable, vasprintf_dest_probe_tests, registered in core/libs/prx/libc/CMakeLists.txt for this run only, with one ctest entry per case. It installs its own counting heap, as the test's InitializeHeap() does, except in zero_noheap. Pages come from VirtualAlloc, filled with 0x5a. Before each call errno is set to 77, except in zero_noheap, where it is set to 0. Each case prints the result, errno, and the change in allocations and releases.

Case Destination main e68be05111 Merge
zero_noheap 0x10, no heap installed SegFault -1, errno 22, +0/+0
zero 0x10 SegFault -1, errno 22, +0/+0
readonly PAGE_READONLY page + 0x100 SegFault -1, errno 22, +0/+0, bytes unchanged
execread PAGE_EXECUTE_READ page + 0x100 SegFault -1, errno 22, +0/+0, bytes unchanged
guard PAGE_READWRITE | PAGE_GUARD page + 0x100 exits nonzero, no output -1, errno 22, +0/+0, bytes unchanged, protection still 0x104
straddle 4 bytes before a PAGE_NOACCESS page SegFault -1, errno 22, +0/+0, first 4 bytes unchanged
misaligned writable page + 0x103 8, errno 77, "value=42" 8, errno 77, "value=42"
lastslot last 8 bytes before a PAGE_NOACCESS page 8, errno 77, "value=42" 8, errno 77, "value=42"
nullformat writable, null format -1, errno 22, destination zeroed -1, errno 22, destination zeroed
nullargs writable, null argument list -1, errno 22, destination zeroed -1, errno 22, destination zeroed
readonly_nullformat PAGE_READONLY, null format SegFault -1, errno 22, +0/+0
success a local char* 11, errno 77, "value=42 ok" 11, errno 77, "value=42 ok"
asprintf_readonly PAGE_READONLY, through asprintf_nid_postfix SegFault -1, errno 22, +0/+0
  • 13 rows. Measured: each cell is printed by the probe or reported by ctest.
  • A successful call leaves errno at 77 on both main and the merge.
  • On the merge, the bad-destination cases report +0 allocations even though the heap is installed, so the probe returns before formatting, as the description says.

Tests.

  • Selection: ^(guest_allocating_strings|guest_formatting|guest_allocator_failures|guest_libc_internal_format|public_headers.*|patched_libraries)$, without the probe. It has 70 tests on both main and the merge; the PR adds a case to an existing test, not a new test.
  • main e68be05111: 70/70.
  • Merge, 3 runs with -j 8: 67/70, 70/70 and 30/70. Every failure is a public_headers_compile_* timeout at 30 s; the 4 libc tests and patched_libraries passed in each run. A rerun of the 65 public_headers* tests on the merge with -j 1 passed 65/65.
  • Warnings: none in files the PR changes. The one warning, at libSceAgcDriver/Execution/src/VulkanDevice.cpp:2659, also appears on main e68be05111.
  • tools/check_conventions.py --base e68be05111: all checks passed (rc=0).
  • debt_fold --check: rc=0, no output.

Host.

  • CPU: AMD Ryzen 9 9950X3D.
  • OS: Windows 11 Pro 26300.
  • Toolchain: WinLibs GCC 15.2, Ninja, Release.
  • Commits: head 8bb35191d8 merged onto main e68be05111, tree 75ff53feb0. Every merge, negative control, mutation and probe run used that tree.

AI-assisted: yes

@oneandonlydean
oneandonlydean merged commit c14fbcd into boykopovar:main Nov 24, 2026
22 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants