Skip to content

feat(libc): implement overlap-safe bcopy - #6532

Merged
adriadam10 merged 1 commit into
boykopovar:mainfrom
ArjenS-LA:feat/guest-bcopy
Oct 19, 2026
Merged

adriadam10 merged 1 commit into
boykopovar:mainfrom
ArjenS-LA:feat/guest-bcopy

Conversation

@ArjenS-LA

Copy link
Copy Markdown
Contributor

What

A PS5 ABI conformance homebrew importing bcopy stops at startup because its NID is absent. Implement source-first, overlap-safe copying and a zero-length no-op. The regression checks both overlap directions, identical pointers, separate buffers and copy boundaries.

Contract: FreeBSD bcopy(3). The signature/export is also present in the open PS5 payload SDK. This is general library behavior; no title-specific workaround.

Tested

Windows 11 Pro 10.0.26200 x64, Intel Core i7-10700K, supported WinLibs MinGW-w64 GCC 15.2.0 r7, Ninja, Release, BUILD_TESTING=ON, Python 3.13.7. The full suite's Vulkan tests select an NVIDIA GeForce RTX 4070 SUPER, Windows driver 32.0.16.1088. Baseline b7cedd900d67a94453b8a45eec9b5623532a0441; branch feat/guest-bcopy; tested head af691b717ad068bb93ac50bfc428af63ab259613.

Executed purpose-built PS5 ABI homebrew: identical ELF input is relinked and launched against baseline and rebuilt patched libraries. Baseline stops at the expected unresolved bcopy import (exit 0xC0000139). Fixed reaches the ELF entry point, executes the behavioral checks and exits 0. The input is compiled with clang 23 targeting x86_64-sie-ps5, with NID imports/SCE module metadata and a freestanding entry. Link-time stubs are not deployed; no trap or implementation substitution is used. This establishes module load, entry and conformance completion for this probe, not shipped-title, physical-console or gameplay compatibility.

FAIL: unresolved ELF import RMo7j0iTPfA from libSceLibcInternal.prx
Transferring control to ELF entry point
PS5 ABI bcopy probe: PASS (overlap, identity, boundaries, zero length)

The full build was attempted on baseline and both fixes. All three hit the same unrelated upstream MinGW error in GpuIndirectArgumentsMisalignedWriterAhead.cpp:25: requested alignment 65536 exceeds the object-file maximum 8192. Continuing Ninja with -k 0 built the remaining available targets; the separate libs target and focused regression tests passed. The same new regression test cannot link on baseline specifically because bcopy_nid_postfix is absent. Conventions and git diff --check pass. A clean full build is not claimed.

Full CTest results (unrelated failures/skips are disclosed):

Build Total Passed Failed Unavailable executable Skipped
Main 1298 1279 2 1 16
This PR 1298 1280 1 1 16

Failed on both: windows_trace_imports. Baseline-only failures: agc_driver_store_over_untracked. Fixed-only failures: none. Skipped on this PR: agc_host_import_sparse, agc_driver_sparse_dma_buf_import, agc_driver_stencil_ref_export, guest_video_out_high_frame_rate, video_out_flip_labels, video_out_flip_labels_main, video_out_flip_lifetime, video_out_flip_reopen, video_out_flip_controls, video_out_flip_overlay, video_out_flip_unopened, video_out_flip_eop, video_out_flip_eop_main, video_out_flip_eop_aftergpu, guest_video_out_wqhd_detection_no_vulkan, long_paths. Native Linux/macOS were not tested locally. GitHub full builds require a collaborator-triggered run under current contribution rules.

Unavailable on this PR: agc_driver_gpu_indirect_arguments_misaligned_writer_ahead. The alignment build error above explains the unavailable AGC executable. Baseline windows_trace_imports fails with WinError 225 because Defender blocks its separate generated fixture; no protection settings were changed. Neither unavailable nor skipped tests are execution evidence.

Reproducer, input/build hashes and library artifacts

Save the C source below as bcopy.c and the Python recipe as build_probe.py. Set LLVM_BIN to the bin directory of LLVM MinGW 20261006, then run python build_probe.py bcopy bcopy puts. The generated input layout is probes/bcopy/probe.elf with an empty sce_module/; system-link stubs remain outside that module directory. The script preserves the input after construction.

typedef __SIZE_TYPE__ size_t;
extern void bcopy(const void *, void *, size_t) IMPORT(bcopy);
extern int puts(const char *) IMPORT(puts);
int _start(void) {
    unsigned char original[12] = {0, 17, 34, 51, 68, 85, 102, 119, 136, 153, 170, 187};
    for (size_t source = 0; source < 12; ++source) {
        for (size_t destination = 0; destination < 12; ++destination) {
            size_t maximum = source > destination ? source : destination;
            for (size_t count = 0; count <= 12 - maximum; ++count) {
                unsigned char actual[12], expected[12];
                for (size_t i = 0; i < 12; ++i) actual[i] = expected[i] = original[i];
                for (size_t i = 0; i < count; ++i) expected[destination + i] = original[source + i];
                bcopy(actual + source, actual + destination, count);
                for (size_t i = 0; i < 12; ++i) if (actual[i] != expected[i]) return 1;
            }
        }
    }
    bcopy((void *)0, (void *)0, 0);
    puts("PS5 ABI bcopy probe: PASS (overlap, identity, boundaries, zero length)");
    return 0;
}
import base64
import hashlib
import os
import pathlib
import struct
import subprocess
import sys

root = pathlib.Path(__file__).parent
llvm = pathlib.Path(os.environ.get('LLVM_BIN', str(root / 'cross-toolchain/llvm-mingw-20261006-ucrt-x86_64/bin')))
name = sys.argv[1]
folder = root / 'probes' / name
folder.mkdir(parents=True, exist_ok=True)
(folder / 'sce_module').mkdir(exist_ok=True)
source = (root / (name + '.c')).read_text()
symbols = sys.argv[2:]
aliases = {}
for symbol in symbols:
    digest = hashlib.sha1(symbol.encode() + bytes.fromhex('518d64a635ded8c1e6b039b1c3e55230')).digest()
    aliases[symbol] = base64.b64encode(digest[:8][::-1], altchars=b'+-').decode().rstrip('=') + '#A#B'
for symbol, alias in aliases.items():
    source = source.replace('IMPORT(' + symbol + ')', '__asm__("' + alias + '")')
(folder / 'probe.c').write_text(source)
assembly = '\n'.join(('.data\n.global "{0}"\n.type "{0}",@object\n.size "{0}",8\n"{0}":\n.quad 0' if symbol.startswith('opt') else '.text\n.global "{0}"\n.type "{0}",@function\n"{0}":\nret').format(alias) for symbol, alias in aliases.items())
(folder / 'stubs.s').write_text(assembly)
def run(args):
    print(subprocess.list2cmdline([str(a) for a in args]), flush=True)
    subprocess.run([str(a) for a in args], check=True, cwd=folder)
run([llvm/'clang-23.exe', '-target', 'x86_64-sie-ps5', '-c', '-ffreestanding', '-fno-builtin', '-fno-stack-protector', '-fno-plt', '-fPIC', '-O1', 'probe.c', '-o', 'probe.o'])
run([llvm/'clang-23.exe', '-target', 'x86_64-sie-ps5', '-c', 'stubs.s', '-o', 'stubs.o'])
run([llvm/'ld.lld.exe', '-m', 'elf_x86_64', '-shared', '-soname', 'libSceLibcInternal.prx', 'stubs.o', '-o', 'libSceLibcInternal.so'])
run([llvm/'ld.lld.exe', '-m', 'elf_x86_64', '-pie', '-e', '_start', '-z', 'max-page-size=0x4000', '--hash-style=sysv', 'probe.o', 'libSceLibcInternal.so', '-o', 'probe.elf'])
path = folder/'probe.elf'
image = bytearray(path.read_bytes())
phoff = struct.unpack_from('<Q', image, 32)[0]
phnum = struct.unpack_from('<H', image, 56)[0]
for i in range(phnum):
    ph = phoff + i*56
    if struct.unpack_from('<I', image, ph)[0] != 2:
        continue
    offset, size = struct.unpack_from('<Q', image, ph+8)[0], struct.unpack_from('<Q', image, ph+32)[0]
    tags = [(at, *struct.unpack_from('<qQ', image, at)) for at in range(offset, offset+size, 16)]
    needed = next(value for at, tag, value in tags if tag == 1)
    debug = next(at for at, tag, value in tags if tag == 21)
    struct.pack_into('<qQ', image, debug, 0x61000045, (1 << 48) | needed)
path.write_bytes(image)
print('ELF SHA256', hashlib.sha256(image).hexdigest())

Build each checkout with:

cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release -DCMAKE_C_COMPILER=gcc -DCMAKE_CXX_COMPILER=g++ -DBUILD_TESTING=ON -DPython3_EXECUTABLE=<working-python>
cmake --build build --parallel 4
cmake --build build --parallel 4 -- -k 0
cmake --build build --target libs --parallel 4
ctest --test-dir build --output-on-failure -j 4

Place the toolchain's libgcc_s_seh-1.dll, libstdc++-6.dll and libwinpthread-1.dll beside the patched PRXs. Convert each variant with the baseline relinker:

relinker.exe --windows --windows-diagnostics --trace-imports --rpath <variant-build>/core/libs/libs probes/bcopy/probe.elf probes/bcopy/<variant>.exe
probes/bcopy/<variant>.exe

Startup diagnostics recorded the selected library paths. --trace-imports was present but the optional APS5_TRACE_CALLS ring was not enabled; no per-call trace capture is claimed. Execution is demonstrated by the probe's checks and successful return through the converted entry.

Input ELF SHA256: cde94935738d5ac7d35665cdf27509098d5c48f46bd665dfc6dd64ed3b3200d0. Relinker SHA256: a4babf4b9154c44b64676011724911b6fa38451b96923d7d596f48eaaf191f1a.

Artifact Baseline SHA256 Fixed SHA256
libc.prx 59a0ec0a34c68c0c547d8a3e825abee36e0fe1165c6ed9a17a7620128c3daaa8 f43a0d316fc29b762e025a396e86322212d8d26ef6d1f3a36a7e18f3bc6469a2
libSceLibcInternal.prx d56fba282a0e9f2a85af9ee1db7037611b2dcc8f35e176aadd1696cd9c845b5b fa82ac6bb55c0ca1016b8e225fcc332cbd861242d8e64b5aafa52386d22c6afe
libkernel.prx 9b799f8d27051476ebfdc91f92461374fd4526eac142168af3ff30023d34dad1 25a4c4f628de4f5e83c0c4dd4ac31dac5566fc411bd31e8463251d28f4c997f2
Open-PR overlap check

Complete paginated inventory: 630 open PRs. Main checked: 44df21632125dbe3113a19173e7ebb879da53003. Exact changed-file lists and every shared-file implementation were inspected; Git tree-only previews normalize both sides to that main as the explicit merge base. 1 reliable clean shared-file comparisons; 19 inconclusive because those peers already conflict with main. No duplicate implementation or reliable pairwise conflict found. The two proposed topics also merge cleanly together; this does not claim combined runtime testing.

The tested base is b7cedd900d67a94453b8a45eec9b5623532a0441. Main advanced during validation; the newer main above was checked for integration conflicts, not claimed as the runtime-tested baseline.

PR Checked head Result
#6144 c33036b1629c16fcd304b12225cd37f6897688a9 clean normalized merge
#5021 01f2073d06385ca2adb537d4996ad61e8255bd2e peer already conflicts with main; inconclusive
#4813 2d6b8ef4341e21d78686bfba9da9a5c6bb14d629 peer already conflicts with main; inconclusive
#4760 1263d7065489fd6b7a15ebbecb1fcf0ee72d21f9 peer already conflicts with main; inconclusive
#4749 07713af3078fcb4e24a15c96bf15c3df4e2b071a peer already conflicts with main; inconclusive
#4740 beb1ba79f2b3a2fc3882bf9d65553e4e754fc03d peer already conflicts with main; inconclusive
#4718 e4b37aa2e22c15e0e07341a7d8c18100cbae55c2 peer already conflicts with main; inconclusive
#4599 8c49e6d6960021ef72e1382d78b9b83914cc7f31 peer already conflicts with main; inconclusive
#4566 16b602cbfb29dcf3fc89b4ed67f228d65a27b20b peer already conflicts with main; inconclusive
#4523 66c8f11a47d64c2db6f514e409e94e91f5ac5309 peer already conflicts with main; inconclusive
#4522 92b12559c64489b556179b651ab4d966c29314ec peer already conflicts with main; inconclusive
#4521 67f9e72d1c663dbc8811cdb6c85753844be02381 peer already conflicts with main; inconclusive
#4520 b339b4f6ca25b1b274555394e73a26f8c8d98347 peer already conflicts with main; inconclusive
#4424 b447062d71dc1748d60edfdc0ec437aa597a5b7d peer already conflicts with main; inconclusive
#4423 bad53434ecca2bf92ee67c43952598c6a108941e peer already conflicts with main; inconclusive
#4422 f9b136024e27d1463a70edee4952553628e5f289 peer already conflicts with main; inconclusive
#4397 5e296b79d94a6312c385890352d7f76e9a0d4380 peer already conflicts with main; inconclusive
#4396 eb34b754de4b65b11c1f7d9beafe58a0d057c45d peer already conflicts with main; inconclusive
#4156 a6cb0cb5f277da258a661bb11792e04941f4c790 peer already conflicts with main; inconclusive
#3891 67f94df827623df9210738a5ba3275b9a59f1c8b peer already conflicts with main; inconclusive

Checklist

  • Based on main snapshot b7cedd900d67a94453b8a45eec9b5623532a0441; refreshed current-main merge check above; 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; no silent stubs added
  • No notes, investigation files or images added to the repository
  • New third-party code is a submodule built from source (no new dependency)
  • Generic behaviour, not specific to one title
  • Depends on: none
  • Unblocks: none — purpose-built ABI probe only
  • GPUs tested: NVIDIA GeForce RTX 4070 SUPER, Windows driver 32.0.16.1088, Windows 11 x64 (full-suite regression run; this change is CPU-only)
  • AI-assisted: yes, Codex

@github-actions

Copy link
Copy Markdown

Progress report (44df216 → af691b7)

➖ System libraries: 88.8% (+0.0%, +1 implemented functions)

✅ 1 implemented
Library Name
libc bcopy_nid_postfix

@github-actions

github-actions Bot commented Oct 15, 2026 •

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 5021 core/libs/prx/libc/src/Strings.cpp
PR 6044 core/libs/tests/GuestStrings.cpp
PR 6879 core/libs/prx/libc/src/Strings.cpp
PR 7201 core/libs/prx/libc/src/Strings.cpp
PR 7332 core/libs/prx/libc/src/Strings.cpp

@github-actions github-actions Bot added the libc label Oct 16, 2026

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

Windows check of head af691b717 (together with #6533, which merges cleanly with it), on main 5d9dcc42d. Windows 11 Pro (26300), WinLibs GCC 15.2.0 r7, Ninja Release.

  • guest_strings passes, with the exhaustive source/destination/count overlap check.
  • Code: memmove gives bcopy(3)'s overlap-safe copy with the arguments swapped, and the count != 0 guard keeps bcopy(NULL, NULL, 0) well defined. That matches FreeBSD's bcopy, which does nothing for a zero length. No issues.

Evidence: both descriptions use a purpose-built probe. In earlier rounds maintainers held back functions that no shipped title or released homebrew imports yet, so a real importer would help. I checked the two released websrv payloads built with the same ps5-payload-dev SDK. Neither Mari0 (Mari0.zip from websrv v0.34, SHA-256 e0331ed5…2ce3, the bundle in #6239) nor the Quake homebrew (#6698) imports bcopy or getopt_long_only, in love.elf/quake.elf or in their libOSMesa.so.8. If a released title or homebrew does, naming it would make the case.

Build note: with the same WinLibs GCC 15.2.0 r7, a full build of main 5d9dcc42d plus this PR (and #6532/#6533 together) completes here without the GpuIndirectArgumentsMisalignedWriterAhead.cpp:25 alignment error, so that error looks specific to your tree or setup.

AI-assisted: yes. I ran the build and tests above and read the import tables of the two bundles.

@adriadam10 adriadam10 self-assigned this Oct 19, 2026
@adriadam10
adriadam10 merged commit 676d423 into boykopovar:main Oct 19, 2026
15 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.

3 participants