feat(fiber): execute contextless fibers on the caller stack #10047

Merged
atharvjairath merged 1 commit from upstream-pr/10047 into main 2026-10-26 05:26:25 +00:00
atharvjairath commented 2026-10-23 06:15:26 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by atharvjairath on 2026-10-23T06:15:26Z.


What

Contextless-execution follow-up to #9072. After that PR, running or switching to a fiber initialized with a null context and size zero still throws. This change executes it on the original calling thread's stack and restarts its entry after each yield. A context can subsequently be attached, after which the fiber retains its continuation normally.

Contextless switches restore the calling thread's Windows stack bounds, preserve the caller's nonvolatile registers and FPU state, and honor #9072's 0x100 FPU initialization flag. Contextless sceFiberGetInfo reports no context or size-check margin.

#9072 merged on 2026-10-24 as d962e7b9b43b474da1e2a3af31d2ec37f38fb655. This branch now contains only the contextless follow-up, 676a0e007250a92f8f768e95cb4cbf713abc57cc, directly on main 933c0e4f1d502fc9702b990f2d6009179da3a40b. The redundant dependency commit has been dropped. The implementation, fixture, CMake registration and debt entry are byte-for-byte unchanged from the reviewed follow-up; the new tree has been rebuilt and retested.

Semantics follow shadPS4 commit f68923fe807f657348e6719ce658bcbd0a2b1c72: run, switch, and return. Not measured on a PS5; recorded in the existing debt entry.

Overlap check: the refreshed scan and manual inspection found no competing contextless implementation. #6044 relocates and labels the fiber fixture; #7149 changes Windows host-stack allocation. Both peers conflict with main, so their shared-file diffs were inspected directly. The pre-push self-comparison with this PR's previous head is not competing work.

Tested

All current results below were rerun on exact head 676a0e007250a92f8f768e95cb4cbf713abc57cc, tree 69dfc7ff3228dd9726c56612512cd5332066ded3, after rebasing onto main 933c0e4f1d502fc9702b990f2d6009179da3a40b. Author and committer are atharvjairath <[email protected]>.

  • Linux, Ubuntu 24.04 / GCC 13.3, Release: rebuilt the complete real libc and libSceFiber libraries and fiber_tests. Both focused modes pass under native ARM QEMU 11.0.3: 2/2, 0.13 s total (fiber 0.06 s, fiber_contextless 0.04 s).
  • Windows x64 PE, WinLibs GCC 15.2 / UCRT, Release: rebuilt the same complete libraries and fixture, then executed both modes under Wine 9 / QEMU 11.0.3 with WINELOADERNOEXEC=1: 2/2, 6.72 s total (fiber 3.34 s, fiber_contextless 3.36 s). No assertions or write-watch behavior were disabled for these tests.
  • Linux Release with UBSan and -fno-sanitize-recover=all, instrumenting libSceFiber and its fixture and linking the rebuilt, uninstrumented real libc: 2/2, 0.12 s total (fiber 0.05 s, fiber_contextless 0.04 s).
  • Historical regression control: the new contextless fixture failed against #9072's unsupported caller-stack path. That control was not repeated for this patch-equivalent rebase.
  • New coverage includes caller-stack placement, restart after return/switch, 1,024 switches without stack growth, attached/contextless transitions, attachment after execution, migration to another thread, 64-bit arguments, caller frame pointer and nonvolatile registers, Windows stack bounds, and inherited/default/restored FPU controls.
  • Conventions against origin/main, git diff --check, and the refreshed overlap scan/manual review pass.

These are focused runtime builds. Native x86 hardware, native Windows, whole-project builds, PS5 hardware and commercial titles remain untested. QEMU 11 is required in this Apple Silicon setup because the default x86 translation masks MXCSR DAZ; the FPU assertions remain intact.

Standalone focused build recipe

Run from the PR checkout in a Linux x86-64 build environment with GCC, CMake and Ninja. This writes the driver/build outside the repository and initializes the two pinned submodules (zstd f8745da6, ZArchive 965b66c8).

fiber_source=$(git -c core.commitGraph=false rev-parse --show-toplevel)
test "$(git -c core.commitGraph=false -C "$fiber_source" rev-parse HEAD)" = 676a0e007250a92f8f768e95cb4cbf713abc57cc
git -c core.commitGraph=false -C "$fiber_source" submodule update --init --recursive --depth 1 -- 3rdparty/zstd 3rdparty/ZArchive
fiber_verify=$(mktemp -d)
ln -s "$fiber_source/3rdparty" "$fiber_verify/3rdparty"
cat > "$fiber_verify/CMakeLists.txt" <<'CMAKE'
cmake_minimum_required(VERSION 3.20)
project(FiberValidation LANGUAGES CXX)
enable_testing()
set(CMAKE_CXX_STANDARD 20)
set(BUILD_TESTING ON)
set(ANYPS5_SOURCE_ROOT /src CACHE PATH "AnyPS5 source checkout")
set(LIBS_INCLUDE_DIR ${ANYPS5_SOURCE_ROOT}/core/libs)
set(ANYPS5_TEST_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/tests)
set(ANYPS5_WINDOWS_TEST_EXIT ${ANYPS5_SOURCE_ROOT}/cmake/WindowsTestExit.cpp)
add_compile_options(-ffunction-sections -fdata-sections)
add_link_options(-Wl,--gc-sections)
function(add_test_executable target)
    add_executable(${target} ${ARGN})
    set_target_properties(${target} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "$<1:${ANYPS5_TEST_OUTPUT_DIRECTORY}>")
    if(MINGW)
        target_sources(${target} PRIVATE "${ANYPS5_WINDOWS_TEST_EXIT}")
        target_link_options(${target} PRIVATE LINKER:--wrap=main)
    endif()
endfunction()
function(add_asan_test_options test options)
    if(ANYPS5_ENABLE_ASAN)
        set_property(TEST ${test} APPEND PROPERTY ENVIRONMENT_MODIFICATION "ASAN_OPTIONS=string_append::${options}")
    endif()
endfunction()
function(configure_windows_unwind target)
    if(MINGW)
        if(NOT EXISTS "${CMAKE_OBJCOPY}")
            message(FATAL_ERROR "Windows DWARF unwinding requires objcopy")
        endif()
        add_custom_command(TARGET ${target} POST_BUILD
                COMMAND "${CMAKE_OBJCOPY}" --rename-section .eh_frame=.ehfram --rename-section .eh_fram=.ehfram "$<TARGET_FILE:${target}>"
                VERBATIM
        )
    endif()
endfunction()
if(MINGW)
    add_compile_options(-fno-asynchronous-unwind-tables)
endif()
include(${ANYPS5_SOURCE_ROOT}/cmake/ZArchive.cmake)
set(BUILD_TESTING OFF)
add_library(libc SHARED)
add_subdirectory(${ANYPS5_SOURCE_ROOT}/core/libs/prx/libc libc)
configure_windows_unwind(libc)
if(WIN32)
    target_compile_options(libc PRIVATE "SHELL:-include ${LIBS_INCLUDE_DIR}/prx/libc/include/HostStandardStreams.hpp")
endif()
if(CMAKE_SYSTEM_NAME STREQUAL "Linux")
    target_link_options(libc PRIVATE LINKER:-z,now)
    target_link_options(libc INTERFACE LINKER:--no-as-needed)
endif()
set(BUILD_TESTING ON)
add_subdirectory(${ANYPS5_SOURCE_ROOT}/core/libs/prx/libSceFiber fiber)
target_link_libraries(libSceFiber PUBLIC libc)
if(WIN32)
    target_compile_options(libSceFiber PRIVATE "SHELL:-include ${LIBS_INCLUDE_DIR}/prx/libc/include/HostStandardStreams.hpp")
endif()
CMAKE
cmake -S "$fiber_verify" -B "$fiber_verify/build" -G Ninja \
  -DCMAKE_BUILD_TYPE=Release -DANYPS5_SOURCE_ROOT="$fiber_source"
cmake --build "$fiber_verify/build" --target fiber_tests --parallel 3
ctest --test-dir "$fiber_verify/build" -R '^fiber' --timeout 30 --output-on-failure

On my Apple Silicon host, the x86-64 container build additionally uses -DCMAKE_CROSSCOMPILING_EMULATOR=/path/to/native-arm-qemu-x86_64 with QEMU 11.0.3. Omit that option on a native x86-64 Linux host. The reported run used QEMU; native hardware and the whole-project build remain untested.

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 (#9072 merged and is included in the base)
  • Fixes: none
  • Unblocks: none
  • GPUs tested: n/a
  • AI-assisted: yes
<!-- greyfinch-sync:boykopovar/AnyPS5:issue:4978686460 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/10047). Originally posted by [atharvjairath](https://github.com/atharvjairath) on 2026-10-23T06:15:26Z. --- ### What Contextless-execution follow-up to #9072. After that PR, running or switching to a fiber initialized with a null context and size zero still throws. This change executes it on the original calling thread's stack and restarts its entry after each yield. A context can subsequently be attached, after which the fiber retains its continuation normally. Contextless switches restore the calling thread's Windows stack bounds, preserve the caller's nonvolatile registers and FPU state, and honor #9072's `0x100` FPU initialization flag. Contextless `sceFiberGetInfo` reports no context or size-check margin. #9072 merged on 2026-10-24 as `d962e7b9b43b474da1e2a3af31d2ec37f38fb655`. This branch now contains only the contextless follow-up, `676a0e007250a92f8f768e95cb4cbf713abc57cc`, directly on main `933c0e4f1d502fc9702b990f2d6009179da3a40b`. The redundant dependency commit has been dropped. The implementation, fixture, CMake registration and debt entry are byte-for-byte unchanged from the reviewed follow-up; the new tree has been rebuilt and retested. Semantics follow shadPS4 commit `f68923fe807f657348e6719ce658bcbd0a2b1c72`: [run](https://github.com/shadps4-emu/shadPS4/blob/f68923fe807f657348e6719ce658bcbd0a2b1c72/src/core/libraries/fiber/fiber.cpp#L238-L307), [switch](https://github.com/shadps4-emu/shadPS4/blob/f68923fe807f657348e6719ce658bcbd0a2b1c72/src/core/libraries/fiber/fiber.cpp#L309-L360), and [return](https://github.com/shadps4-emu/shadPS4/blob/f68923fe807f657348e6719ce658bcbd0a2b1c72/src/core/libraries/fiber/fiber.cpp#L376-L401). Not measured on a PS5; recorded in the existing debt entry. Overlap check: the refreshed scan and manual inspection found no competing contextless implementation. #6044 relocates and labels the fiber fixture; #7149 changes Windows host-stack allocation. Both peers conflict with main, so their shared-file diffs were inspected directly. The pre-push self-comparison with this PR's previous head is not competing work. ### Tested <!-- OS, title or homebrew, what was checked. "Not tested" is a valid answer. A performance change: the summary lines of main and of this PR from the same machine and scene, with the traces attached, captured as the Performance report issue form describes. --> All current results below were rerun on exact head `676a0e007250a92f8f768e95cb4cbf713abc57cc`, tree `69dfc7ff3228dd9726c56612512cd5332066ded3`, after rebasing onto main `933c0e4f1d502fc9702b990f2d6009179da3a40b`. Author and committer are `atharvjairath <54663702+[email protected]>`. - Linux, Ubuntu 24.04 / GCC 13.3, Release: rebuilt the complete real `libc` and `libSceFiber` libraries and `fiber_tests`. Both focused modes pass under native ARM QEMU 11.0.3: **2/2**, 0.13 s total (`fiber` 0.06 s, `fiber_contextless` 0.04 s). - Windows x64 PE, WinLibs GCC 15.2 / UCRT, Release: rebuilt the same complete libraries and fixture, then executed both modes under Wine 9 / QEMU 11.0.3 with `WINELOADERNOEXEC=1`: **2/2**, 6.72 s total (`fiber` 3.34 s, `fiber_contextless` 3.36 s). No assertions or write-watch behavior were disabled for these tests. - Linux Release with UBSan and `-fno-sanitize-recover=all`, instrumenting `libSceFiber` and its fixture and linking the rebuilt, uninstrumented real `libc`: **2/2**, 0.12 s total (`fiber` 0.05 s, `fiber_contextless` 0.04 s). - Historical regression control: the new contextless fixture failed against #9072's unsupported caller-stack path. That control was not repeated for this patch-equivalent rebase. - New coverage includes caller-stack placement, restart after return/switch, 1,024 switches without stack growth, attached/contextless transitions, attachment after execution, migration to another thread, 64-bit arguments, caller frame pointer and nonvolatile registers, Windows stack bounds, and inherited/default/restored FPU controls. - Conventions against `origin/main`, `git diff --check`, and the refreshed overlap scan/manual review pass. These are focused runtime builds. Native x86 hardware, native Windows, whole-project builds, PS5 hardware and commercial titles remain untested. QEMU 11 is required in this Apple Silicon setup because the default x86 translation masks MXCSR DAZ; the FPU assertions remain intact. <details> <summary>Standalone focused build recipe</summary> Run from the PR checkout in a Linux x86-64 build environment with GCC, CMake and Ninja. This writes the driver/build outside the repository and initializes the two pinned submodules (`zstd f8745da6`, `ZArchive 965b66c8`). ```sh fiber_source=$(git -c core.commitGraph=false rev-parse --show-toplevel) test "$(git -c core.commitGraph=false -C "$fiber_source" rev-parse HEAD)" = 676a0e007250a92f8f768e95cb4cbf713abc57cc git -c core.commitGraph=false -C "$fiber_source" submodule update --init --recursive --depth 1 -- 3rdparty/zstd 3rdparty/ZArchive fiber_verify=$(mktemp -d) ln -s "$fiber_source/3rdparty" "$fiber_verify/3rdparty" cat > "$fiber_verify/CMakeLists.txt" <<'CMAKE' cmake_minimum_required(VERSION 3.20) project(FiberValidation LANGUAGES CXX) enable_testing() set(CMAKE_CXX_STANDARD 20) set(BUILD_TESTING ON) set(ANYPS5_SOURCE_ROOT /src CACHE PATH "AnyPS5 source checkout") set(LIBS_INCLUDE_DIR ${ANYPS5_SOURCE_ROOT}/core/libs) set(ANYPS5_TEST_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/tests) set(ANYPS5_WINDOWS_TEST_EXIT ${ANYPS5_SOURCE_ROOT}/cmake/WindowsTestExit.cpp) add_compile_options(-ffunction-sections -fdata-sections) add_link_options(-Wl,--gc-sections) function(add_test_executable target) add_executable(${target} ${ARGN}) set_target_properties(${target} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "$<1:${ANYPS5_TEST_OUTPUT_DIRECTORY}>") if(MINGW) target_sources(${target} PRIVATE "${ANYPS5_WINDOWS_TEST_EXIT}") target_link_options(${target} PRIVATE LINKER:--wrap=main) endif() endfunction() function(add_asan_test_options test options) if(ANYPS5_ENABLE_ASAN) set_property(TEST ${test} APPEND PROPERTY ENVIRONMENT_MODIFICATION "ASAN_OPTIONS=string_append::${options}") endif() endfunction() function(configure_windows_unwind target) if(MINGW) if(NOT EXISTS "${CMAKE_OBJCOPY}") message(FATAL_ERROR "Windows DWARF unwinding requires objcopy") endif() add_custom_command(TARGET ${target} POST_BUILD COMMAND "${CMAKE_OBJCOPY}" --rename-section .eh_frame=.ehfram --rename-section .eh_fram=.ehfram "$<TARGET_FILE:${target}>" VERBATIM ) endif() endfunction() if(MINGW) add_compile_options(-fno-asynchronous-unwind-tables) endif() include(${ANYPS5_SOURCE_ROOT}/cmake/ZArchive.cmake) set(BUILD_TESTING OFF) add_library(libc SHARED) add_subdirectory(${ANYPS5_SOURCE_ROOT}/core/libs/prx/libc libc) configure_windows_unwind(libc) if(WIN32) target_compile_options(libc PRIVATE "SHELL:-include ${LIBS_INCLUDE_DIR}/prx/libc/include/HostStandardStreams.hpp") endif() if(CMAKE_SYSTEM_NAME STREQUAL "Linux") target_link_options(libc PRIVATE LINKER:-z,now) target_link_options(libc INTERFACE LINKER:--no-as-needed) endif() set(BUILD_TESTING ON) add_subdirectory(${ANYPS5_SOURCE_ROOT}/core/libs/prx/libSceFiber fiber) target_link_libraries(libSceFiber PUBLIC libc) if(WIN32) target_compile_options(libSceFiber PRIVATE "SHELL:-include ${LIBS_INCLUDE_DIR}/prx/libc/include/HostStandardStreams.hpp") endif() CMAKE cmake -S "$fiber_verify" -B "$fiber_verify/build" -G Ninja \ -DCMAKE_BUILD_TYPE=Release -DANYPS5_SOURCE_ROOT="$fiber_source" cmake --build "$fiber_verify/build" --target fiber_tests --parallel 3 ctest --test-dir "$fiber_verify/build" -R '^fiber' --timeout 30 --output-on-failure ``` On my Apple Silicon host, the x86-64 container build additionally uses `-DCMAKE_CROSSCOMPILING_EMULATOR=/path/to/native-arm-qemu-x86_64` with QEMU 11.0.3. Omit that option on a native x86-64 Linux host. The reported run used QEMU; native hardware and the whole-project build remain untested. </details> ### 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 (#9072 merged and is included in the base) - [x] Fixes: none - [x] Unblocks: none - [x] GPUs tested: n/a - [x] AI-assisted: yes
MarcZX10 commented 2026-10-23 06:25:57 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-23T06:25:57Z.

Review: COMMENTED


I reviewed the explicitly scoped follow-up range f1612d73ede97701b24d293876540c7a7fdcad8f...9ba4da78f2afc1b0ff5a4815478ecad23559bd25, not the dependency implementation. In that range, the contextless switch path saves/restores the caller thread stack and bounds, starts the fiber trampoline with the target fiber, then clears the contextless saved stack when it yields. The tests cover restart after yield, repeated switches without stack growth, attached/contextless transitions, thread migration, nonvolatile registers, frame pointer, Windows stack bounds, and the 0x100 FPU behavior. The new debt entry clearly marks the semantics as inferred from shadPS4 rather than measured on hardware.

The declared dependency #9072 is still open at 43d4eebe518da686d89629e6e7a386644f899214; the PR body correctly says to merge it first and drop that unchanged implementation commit when rebasing. So this review is limited to the follow-up range and does not treat the complete branch as independently mergeable.

The focused Linux/Windows/Wine and UBSan runs in the description are detailed and consistent with the added coverage. Hosted eligibility, conventions, intake, labels, and progress-report checks pass; hosted product build jobs are skipped. I tried configuring a local focused build, but the fetched snapshot has uninitialized submodules (including SDL2), and ANYPS5_RELINKER_ONLY=ON excludes core/libs, so fiber_tests is not generated. No local fiber test ran. Please retain the matched current-main/dependency context when refreshing after #9072 lands, and rerun the focused tests on the resulting tree.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5624701344 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/10047#pullrequestreview-5624701344). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-23T06:25:57Z. **Review:** COMMENTED --- I reviewed the explicitly scoped follow-up range `f1612d73ede97701b24d293876540c7a7fdcad8f...9ba4da78f2afc1b0ff5a4815478ecad23559bd25`, not the dependency implementation. In that range, the contextless switch path saves/restores the caller thread stack and bounds, starts the fiber trampoline with the target fiber, then clears the contextless saved stack when it yields. The tests cover restart after yield, repeated switches without stack growth, attached/contextless transitions, thread migration, nonvolatile registers, frame pointer, Windows stack bounds, and the `0x100` FPU behavior. The new debt entry clearly marks the semantics as inferred from shadPS4 rather than measured on hardware. The declared dependency #9072 is still open at `43d4eebe518da686d89629e6e7a386644f899214`; the PR body correctly says to merge it first and drop that unchanged implementation commit when rebasing. So this review is limited to the follow-up range and does not treat the complete branch as independently mergeable. The focused Linux/Windows/Wine and UBSan runs in the description are detailed and consistent with the added coverage. Hosted eligibility, conventions, intake, labels, and progress-report checks pass; hosted product build jobs are skipped. I tried configuring a local focused build, but the fetched snapshot has uninitialized submodules (including SDL2), and `ANYPS5_RELINKER_ONLY=ON` excludes `core/libs`, so `fiber_tests` is not generated. No local fiber test ran. Please retain the matched current-main/dependency context when refreshing after #9072 lands, and rerun the focused tests on the resulting tree.
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!10047
No description provided.