Skip to content

fix(libc): preserve partial wcsftime output on overflow - #10895

Merged
oneandonlydean merged 7 commits into
boykopovar:mainfrom
StoneDC:fix/wcsftime-partial-output
Nov 1, 2026
Merged

oneandonlydean merged 7 commits into
boykopovar:mainfrom
StoneDC:fix/wcsftime-partial-output

Conversation

@StoneDC

@StoneDC StoneDC commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor

What

Align wide time-formatting overflow with the reported native-PC run of firmware 13.42 libSceLibcInternal.sprx, following the requested review changes.

A conversion writes as many 16-bit units as fit, but advances the logical position only when the complete conversion fits. Otherwise later format pieces reuse that position, and final termination may return a shorter nonzero prefix while retaining partial units beyond the terminator. A literal that does not fit still stops and returns zero. Expand compound conversions as complete pieces; retain the separate narrow strftime stop-on-overflow behavior.

Add 22 explicit boundary vectors derived from the reported rule and examples, including %Y-%m-%d at each boundary, partial compound conversions, later literals, modifiers, unknown conversions, surrogate units, zero capacity, empty format, errno and untouched guards. Retain complete-output/reference cases and capacity safety checks, replacing the superseded flat-prefix overflow expectation. Set and restore the guest TZ explicitly so the existing %Z comparison does not depend on the host's localized default zone name.

Update the existing libc debt entry. The reference report is a firmware-module execution on a PC, not a physical-console measurement. I have not independently run its private loader, reproduced its 895-case reference campaign or verified %Z/%z, conversion failures, null-argument differences or the large-count restriction. The last two remain unchanged gaps. The agreed test-integration order remains #10895 before #10987.

Maintainer confirmation on 2026-11-01: firmware libSceLibcInternal.sprx is the intended target, and the reviewed head matches the reported 13.42 model. This closes the earlier target question. Source head remains 3d9db7dad635e0290f9e0a2808c593048ecb964d; no additional code or independent console/firmware run is claimed by this documentation update.

Tested

Exact tested head: 3d9db7dad635e0290f9e0a2808c593048ecb964d; observed main snapshot: ba5b5330b37724bca4b99f30faab504653635a04. Upstream may advance after that recorded snapshot.

Windows 11 / MinGW GCC 15.2 / CMake 4.3.1 and WSL Ubuntu 26.04 / GCC 15.2 / CMake 4.2.3, Release. Configure the actual full project with the existing dependency cache and supported FFMPEG_PREBUILT_DIR option, then build its real shared libc and the repository's guest_wide_formatting_tests, guest_strftime_tests, guest_time_conversion_tests and guest_time_extras_tests targets. No repository build-file bypass is introduced.

  • Actual shared-libc CTests ^guest_(wide_formatting|strftime|time_conversion|time_extras)$: 4/4 passed on each OS, no skips. The first Windows run exposed the existing default-zone-name assumption; the final exact tests set and restore guest TZ and pass on that same localized host.
  • Independently compile the actual Time.cpp, TimeExtras.cpp, Environment.cpp, Multibyte.cpp and FormattingWide.cpp plus the four actual repository tests in the external focused harness with ASan+UBSan, recovery disabled: 4/4 passed. Its adapter supplies errno, failure reporting and an aborting unused stream-read boundary; it is supplementary coverage, not the shared-library integration result above.
  • Restore only the pre-change Time.cpp while retaining current tests and sanitizer flags: the real wide test fails at wcsftime firmware piece units, rather than an import or link failure. The new explicit cases execute on both real shared-library builds.
  • Public-header audit: 373 libraries / 13467 exports verified; unknown-NID checker regressions: 10/10 passed.
  • Runtime dependencies come from the existing prepared cache. Three changed, unrelated SPIRV/vorbis dependency roots are absent from the selected libc target's Ninja input graph. This is a selected shared-library build, not a fresh all-product build; patched_libraries, the remaining libraries/tests, macOS, PS5 hardware, game execution and a new firmware-loader campaign were not run.

Current-main conventions with this complete description and whitespace checks pass. Python 3.9 grammar checks pass for changed Python files. Recorded main and the original published PR head are ancestors of this tested branch. Hosted follow-up verified on 2026-10-29 for this same final head 3d9db7dad635e0290f9e0a2808c593048ecb964d: Build run 40867077680 completed with every executed job successful, including full Windows, Linux/Windows/macOS arm64/macOS x86_64 relinker jobs and Linux ASan. The full Linux job was skipped and is not counted as passed. Conventions and the remaining reported checks also pass.

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

Write wide literals and conversion results directly while sharing the current time-format rules. Cover truncated output and retain documented argument-handling gaps.

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

The direct wide-character formatter preserves literal UTF-16 units, the established conversion behavior, and the tested partial-write boundary semantics. I reviewed the changed path and test cases; the author reports a focused ASan/UBSan harness, and the repository policy checks pass. Product build jobs are skipped by repository policy, so this approval does not claim an independent full integration build.

@oneandonlydean

Copy link
Copy Markdown
Collaborator

@StoneDC Please trim the wcsftime debt entry to the remaining gaps. CONTRIBUTING.md asks that a fixed gap be cut from the entry, rather than replaced with a description of the corrected behavior. Drop the direct-write/prefix introduction and keep the strftime gaps, null argument and oversized-count differences; the production change and tests can stay as they are.

Remove the corrected direct-write and partial-output description, keeping the outstanding formatting, null-argument and oversized-count gaps.
@github-actions

github-actions Bot commented Oct 25, 2026 •

Copy link
Copy Markdown

Other open pull requests touch the same code. Merging one will break the other, or both implement the same thing. If this one builds on them, list them in Depends on.

Pull request Conflicting files (lines on main) Same exports Same new files
PR 12841 docs/dev/debt/libc.md L226-227

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/Time.cpp
docs/dev/debt/libc.md
PR 7081 docs/dev/debt/libc.md
PR 7386 docs/dev/debt/libc.md
PR 7447 docs/dev/debt/libc.md
PR 7715 docs/dev/debt/libc.md
PR 8150 docs/dev/debt/libc.md
PR 8965 docs/dev/debt/libc.md
PR 9340 docs/dev/debt/libc.md
PR 9371 docs/dev/debt/libc.md
PR 9447 core/libs/prx/libc/src/Time.cpp
docs/dev/debt/libc.md
PR 9526 docs/dev/debt/libc.md
PR 9929 docs/dev/debt/libc.md
PR 10113 docs/dev/debt/libc.md
PR 10349 docs/dev/debt/libc.md
PR 10405 docs/dev/debt/libc.md
PR 11332 docs/dev/debt/libc.md
PR 11661 docs/dev/debt/libc.md
PR 11689 docs/dev/debt/libc.md
PR 11698 docs/dev/debt/libc.md
PR 11831 docs/dev/debt/libc.md
PR 12560 docs/dev/debt/libc.md
PR 12682 docs/dev/debt/libc.md
PR 12688 docs/dev/debt/libc.md
PR 12700 docs/dev/debt/libc.md
PR 12920 docs/dev/debt/libc.md
PR 12965 docs/dev/debt/libc.md
PR 14212 docs/dev/debt/libc.md

@StoneDC

StoneDC commented Oct 25, 2026

Copy link
Copy Markdown
Contributor Author

@oneandonlydean Addressed in 920903d. The wcsftime debt entry now contains only the remaining strftime gaps, null-argument behavior and oversized-count restriction. The direct-write/prefix introduction has been removed; production code and tests are byte-identical to 0ce70b4. Conventions and whitespace checks pass. No runtime tests were rerun for this documentation-only follow-up; the previously reported integration-build limitations still apply.

I also investigated the progress bot's "went back to stubs" classification without changing the formatter or the reporting tool. tools/progress.py propagates NotImplemented_nid_no_patch through ordinary helper calls, and now sees:

wcsftime -> formatTime -> addConversion -> isoWeek -> NotImplemented_nid_no_patch

The three ISO-week guards already exist on the base branch and are documented in the strftime debt entry. Previously wcsftime called the exported strftime path, across which the helper analysis did not propagate that classification. I reproduced the baseline's empty stub-match list and the candidate's formatTime match. This is newly visible reporting of an existing unsupported-input path, not a replacement of the formatter with a stub; the necessary guards are retained.

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

Independent native Windows validation of exact head 920903db939cef0943f4f381f1cc0a9df3e3f055. No blocking finding in the formatter change. Confirmed that its production/test blobs are unchanged from 0ce70b465; the latest commit only trims the debt entry.

Windows 11 build 26200, MSYS2 UCRT64 GCC 16.2.0-6 (SEH), CMake 4.3.1, Ninja 1.13.2:

  • An out-of-tree harness compiles the actual Time.cpp, Environment.cpp, Multibyte.cpp, FormattingWide.cpp, and complete repository GuestWideFormatting.cpp / GuestStrftime.cpp. Both CTest cases pass, including three consecutive repeats of each. This exercises the UTF-16 literals/surrogates, capacity/guard checks, modifiers/composites, errno and oversized-count boundaries in the submitted tests, alongside the existing narrow formatter checks.
  • Negative control: replace only wcsftime with main's prior implementation, restoring its required <memory> / <new> includes. The wide test fails at wcsftime written prefix (0.06 s), while guest_strftime still passes.
  • Support supplies guest errno as Process.cpp does, a throwing unimplemented entry, and Windows abort-UI suppression. Two additional stream symbols are link-only placeholders: fgetwc aborts if called, and __stdoutp is null. The submitted tests do not exercise stream I/O. A GDB hardware read watchpoint on __stdoutp, set at main, lets each complete test exit normally without a read; the aborting input placeholder is not called. Neither placeholder implements or changes time/conversion/memory-formatting logic. Full replay files are below.
  • Conventions and whitespace checks pass. Merge-tree against main 2742004ed28f765c7147db0e0269ff5868e9eb6f is clean.

This adds focused native Windows evidence to the author's Linux results. It is not a full shared-libc/runtime integration build, stream-I/O test, sanitizer run, console measurement, game run or cross-PR composition test. No maintainer-triggered upstream native CI is claimed. AI-assisted testing and review: yes (OpenAI Codex).

Out-of-tree replay files

CMakeLists.txt:

cmake_minimum_required(VERSION 3.20)
project(AnyPS5WideTimeReview LANGUAGES CXX)
enable_testing()
set(REPO "${CMAKE_CURRENT_LIST_DIR}/../review-10895" CACHE PATH "Exact PR checkout")
set(TIME_SOURCE "${REPO}/core/libs/prx/libc/src/Time.cpp" CACHE FILEPATH "Time source under test")
add_library(time_sources OBJECT
    "${TIME_SOURCE}"
    "${REPO}/core/libs/prx/libc/src/Environment.cpp"
    "${REPO}/core/libs/prx/libc/src/Multibyte.cpp"
    "${REPO}/core/libs/prx/libc/src/FormattingWide.cpp"
    IoPoison.cpp
    Support.cpp)
target_compile_features(time_sources PUBLIC cxx_std_20)
target_include_directories(time_sources PUBLIC "${REPO}/core/libs")
target_compile_options(time_sources PUBLIC -O1 -g -Wall -Wextra -ffunction-sections -fdata-sections)
foreach(pair IN ITEMS "guest_wide_formatting|GuestWideFormatting" "guest_strftime|GuestStrftime")
    string(REPLACE "|" ";" parts "${pair}")
    list(GET parts 0 name)
    list(GET parts 1 source)
    add_executable(${name} "${REPO}/core/libs/tests/${source}.cpp")
    target_link_libraries(${name} PRIVATE time_sources)
    target_link_options(${name} PRIVATE -Wl,--gc-sections)
    add_test(NAME ${name} COMMAND ${name})
    set_tests_properties(${name} PROPERTIES TIMEOUT 30)
endforeach()

Support.cpp:

#include "prx/libc/include/Api.hpp"
#include "prx/libc/include/General.hpp"
#include <cerrno>
#include <cstdlib>
#include <stdexcept>

[[maybe_unused]] const unsigned int abortFlags = _set_abort_behavior(0, _CALL_REPORTFAULT);

extern "C" int* APS5_VABI __error_nid_postfix() {
    return &errno;
}

extern "C" [[noreturn]] void NotImplemented_nid_no_patch(const char* name) {
    throw std::runtime_error(name);
}

IoPoison.cpp:

#include "prx/libc/include/Api.hpp"
#include <cstdio>
#include <cstdlib>

extern "C" {
FileStream* __stdoutp_nid_postfix = nullptr;

std::int32_t APS5_VABI fgetwc_nid_postfix(FileStream*) {
    std::fputs("Unexpected stream I/O in memory-formatting harness\n", stderr);
    std::abort();
}
}

Use GCC 16.2 UCRT64 bin first on PATH, followed by CMake/Ninja. Configure with cmake -S native-wide-time-review -B native-wide-time-review/build16 -G Ninja -DREPO=<exact-PR-checkout> -DCMAKE_CXX_COMPILER=<GCC16-bin>/g++.exe -DCMAKE_BUILD_TYPE=Release, build, then run ctest --test-dir native-wide-time-review/build16 --output-on-failure. The negative control uses a separate build directory and -DTIME_SOURCE=<copy-with-only-old-wcsftime-and-required-includes>. For each executable, gdb --batch --nx -ex "set auto-load python-scripts off" -ex start -ex "rwatch __stdoutp_nid_postfix" -ex continue --args <exe> exits normally without a watchpoint hit after setup.

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

Reviewed exact head 920903db939cef0943f4f381f1cc0a9df3e3f055.

The wide formatter now writes each formatted piece directly into the caller buffer, retaining the prefix when capacity is exhausted and writing a terminator only for a complete result. The new tests cover capacities around each result length, zero capacity, empty output, multibyte UTF-16 units, surrogate code units, composite/modified/unknown conversions, errno, and the oversized-count boundary. The diff also exercises narrow strftime through the shared formatter; the author’s target-level harness ran both wide and narrow formatting tests under ASan/UBSan, with repeated runs and a negative control using the baseline wcsftime implementation.

The author updated the debt entry to retain only the remaining differences requested in review. I found no new overlap implementing partial wide output; #8855 is the merged predecessor. Hosted macOS and Ubuntu Debug/Release register-context, relinker, ASan, conventions, labels, and report checks pass; Windows product jobs are skipped by path policy. Local diff/convention checks pass. The PR explicitly discloses that the target-level harness is not a full product/shared-libc build and that native Windows/macOS, title, and console validation were not run; I did not independently run the harness.

No blocking issue found in the scoped partial-output change.

AI-assisted: yes.

@MarcZX10

Copy link
Copy Markdown
Contributor

The overlap check for my #10987 flags Time.cpp and the GuestWideFormatting.cpp assertions because #10987 converts Windows CRT zone names from CP_ACP to UTF-8 and fixes the UTF-8-to-UTF-16 test comparison. This is separate from the partial-output behavior in this PR, but your Time.cpp refactor and added wide-formatting cases touch the same hunks.

I propose #10895 goes first, then I rebase #10987 onto the merged result, resolve any overlap, and declare Depends on: #10895 until then. Does that sequencing work for you?

@StoneDC

StoneDC commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor Author

@MarcZX10 Thanks, that sequencing works for me. Please proceed with #10895 first, then rebase #10987 onto the merged result and resolve the overlap. Rerunning the wide-formatting and time-conversion tests after rebasing would help verify the combined changes.

@MarcZX10

Copy link
Copy Markdown
Contributor

The overlap check now flags #10987 on GuestWideFormatting.cpp; I verified that merging the current heads produces a content conflict in that file. The changes cover separate cases: this PR adds partial-output/capacity checks, while #10987 updates the expected UTF-8-to-UTF-16 behavior. Since #10895 predates #10987, I suggest this PR go first and I will rebase #10987 afterward, but I am happy to follow another order you prefer. Once we agree, I will record the dependency on #10987's checklist as required by CONTRIBUTING.md.

@StoneDC

StoneDC commented Oct 25, 2026

Copy link
Copy Markdown
Contributor Author

@MarcZX10 Agreed—#10895 first, followed by rebasing #10987. Please go ahead and record Depends on: #10895 in your checklist. Thanks for checking the conflict.

@MarcZX10

Copy link
Copy Markdown
Contributor

I manually compared the exact current heads of #10895 and my #10987. The three-way merge reports a conflict in GuestWideFormatting.cpp; Time.cpp auto-merges. The reported behavior changes are separate, but both branches extend the wide-formatting tests, so the merged test file needs to retain both regression sets. Which order do you prefer? I can rebase and add the agreed Depends on entry if one PR needs to land first.

@StoneDC

StoneDC commented Oct 26, 2026

Copy link
Copy Markdown
Contributor Author

@MarcZX10 Thanks for checking the current heads so carefully! I'm happy to keep the agreed order: #10895 first, then #10987 rebased onto the merged result. I also see you've already recorded Depends on: #10895—thank you.

When resolving the test conflict, please retain both the partial-output/capacity cases and the UTF-8-to-UTF-16 comparison changes, then rerun the wide-formatting and time-conversion tests. Thanks again for coordinating this!

@oneandonlydean oneandonlydean self-assigned this Oct 26, 2026
@github-actions github-actions Bot added the needs rebase Conflicts with main, rebase needed label Oct 26, 2026
@verusferro

verusferro commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

@StoneDC sorry: #11004 was merged before this PR, so the order we agreed did not hold, and the conflicts are now on your side. I merged current main (74acfad65b) into this branch locally to check the resolution. In both files, each PR changed a different line:

  • core/libs/prx/libc/src/Time.cpp: drop isLeapYearSum, because main no longer calls it, and keep your template<typename TChar> before struct FormatBuffer.
  • docs/dev/debt/libc.md: keep main's strftime and asctime entry and this PR's wcsftime entry.

With that, guest_strftime, guest_wide_formatting, guest_time_conversion, guest_time_extras, patched_libraries and conventions_unknown_nids pass (6/6, WSL2 Ubuntu 24.04, GCC 13.3, Release), and check_conventions.py --base origin/main passes. If it helps, I can push that merge commit to a branch on my fork for you to pull.

AI-assisted: yes

@oneandonlydean

Copy link
Copy Markdown
Collaborator

@StoneDC Sorry, #11004 went in ahead of this PR even though we'd agreed this one first. @verusferro's resolution above looks right: main no longer has isLeapYearSum, so drop it and keep your FormatBuffer template and both debt entries. Once the branch has main merged in, we'll check the new head. #10987 still goes after this one.

@StoneDC

StoneDC commented Oct 27, 2026

Copy link
Copy Markdown
Contributor Author

@oneandonlydean @verusferro Resolved and pushed 5be64730a23cb09a9ce5ed0136f4ec074a13f3a7 by merging main cb45ae2ddf6e113a4619e8fed91fe7b9333c5c0f into the existing branch.

  • Dropped isLeapYearSum and kept template<typename TChar> immediately before FormatBuffer.
  • Kept main's week-number implementation and strftime and asctime debt entry verbatim, this PR's remaining wcsftime debt entry, and both branches' regression cases.
  • On the exact new head, the four real repository time/wide-formatting tests plus an out-of-tree wide composition probe pass 5/5 in both WSL Release and ASan/UBSan. The probe exercises current main's reference cases, including out-of-range ISO week fields, at every capacity. Restoring only the old wcsftime makes the sanitized regression fail at the intended prefix assertion.
  • Current conventions, whitespace, unknown-NID tests (10/10), and the public-header declaration audit pass. The overlap scan still reports fix(libc): convert Windows time zone names to UTF-8 #10987's coordinated test conflict: fix(libc): preserve partial wcsftime output on overflow #10895 first, then fix(libc): convert Windows time zone names to UTF-8 #10987 rebased with both regression sets retained.

The PR description now records these exact-head results and the remaining limits. Local full product configuration is still blocked by missing dependencies; native Windows focused validation did not complete because the available toolchain's ABI/exception support failed to compile/link. No full shared-libc, patched_libraries, macOS, title or new console validation is claimed. Please recheck the new head and run the maintainer-triggered full product CI when available.

AI-assisted: yes.

@github-actions github-actions Bot removed the needs rebase Conflicts with main, rebase needed label Oct 27, 2026
@BunnyFl

BunnyFl commented Oct 27, 2026

Copy link
Copy Markdown
Contributor

A Windows run of 5be64730a2 as it is (it already contains main cb45ae2ddf): Windows 11 (10.0.26200), WinLibs GCC 15.2.0 r7 (MinGW-w64 UCRT), Release, BUILD_TESTING=ON, each test run three times with ctest -V.

  • guest_wide_formatting passes in all three runs, with this PR and on main 74acfad65b (each with its own test). 74acfad65b..cb45ae2ddf only changes the windows_crash_stack_words regex in libc/CMakeLists.txt.
  • Control: with only libc/src/Time.cpp put back to main's version (the same in 74acfad65b and cb45ae2ddf; this PR's test kept), it fails in all three runs with snwprintf_s: wcsftime written prefix (exit 0xc0000409).

@JJenkx

JJenkx commented Oct 27, 2026

Copy link
Copy Markdown
Contributor

Data on overflow behaviour from the libc.prx that titles ship, for comparison with this PR. These are not requested changes; it's a reference for deciding which behaviour to match.

Setup: a scratch loader runs the decrypted libc.prx of PPSA07923 and PPSA13934 natively on Windows, calling wcsftime and strftime by NID. The other columns are the libc.prx DLL built from this PR's exact head 5be64730a2 and from main 3fea2a937b. The tm is 2026-03-04 07:05:34, a Wednesday. Each buffer is pre-filled with ., and 0 marks the written terminator. The two titles give identical output in every row.

format, size titles' wcsftime titles' strftime this PR's wcsftime main wcsftime
%e|%F|%S|, 1 0 | 0 . 0 0 .
%e|%F|%S|, 4 0 4|| 0 4| 0 4|2 0 .
%e|%F|%S|, 8 7 4||34|0 0 4|2026- 0 4|2026- 0 .
%e|%F|%S|, 12 7 4||34|003-0 0 4|2026-03- 0 4|2026-03-0 0 .
ab%Ycd, 3 0 abc 0 ab 0 ab2 0 .
ab%Ycd, 5 4 abcd0 0 ab 0 ab202 0 .
%A %B, 2 1 0 0 . 0 We 0 .
%A %B, 7 6 March0 0 . 0 Wednesd 0 .
%A %B, 11 10 Wednesday 0 0 Wednesday 0 Wednesday M 0 .

All 21 sizes from 0 to 20 for these three formats fit one rule for the titles' wcsftime:

  • Each literal character and each conversion's output is a piece.
  • A piece is written until the buffer is full. If it doesn't fit, the write position returns to the piece's start, and the characters already written stay in the buffer.
  • Formatting then continues with the next pieces.
  • At the end, if there is room, a terminator is written and the position is returned. Otherwise the result is 0.

So a too-small buffer can return a nonzero count for a string with conversions missing, and characters from an abandoned piece can follow the terminator (003-0 above). The titles' narrow strftime instead stops at the first piece that doesn't fit and returns 0. Its prefix never contains part of a conversion ( 4| at size 4, not 4|2), and main's narrow strftime already matches that.

Random formats: 200,000 formats of 1 to 3 conversions with E/O modifiers, one in eight with a buffer of 0 to 11 units. With a buffer large enough for the output there are no differences, for main or for this PR. With small buffers, main differs from the titles in 16,525 cases and this PR in 10,057.

This is the titles' bundled libc.prx, not the firmware's libSceLibcInternal.sprx that the debt entry describes. I have not checked whether the two differ. This PR's guest_wide_formatting passes on Windows at the exact head (one run).

AI-assisted: yes (Claude Code).

@StoneDC

StoneDC commented Oct 27, 2026

Copy link
Copy Markdown
Contributor Author

@JJenkx Thanks for the measurements and for distinguishing the titles' bundled libc.prx from firmware libSceLibcInternal.sprx.

@oneandonlydean @MarcZX10 Could you confirm which reference this PR's wcsftime should match: the titles' bundled libc.prx, or firmware libSceLibcInternal.sprx? The original scope followed the console observations recorded for #8855, but those observations do not establish the piece rollback/continuation behavior in this new report. We should not assume the two modules behave identically, or that the current implementation already matches firmware in these cases.

I checked the code at the unchanged PR head 5be64730a23cb09a9ce5ed0136f4ec074a13f3a7. Its wide conversion path writes into the remaining buffer, can leave part of a conversion, and stops processing further format pieces once the buffer is full. It then returns 0 without adding a final terminator. It does not rewind to the overflowing piece's start and continue with later pieces.

That differs from the bundled modules in your report, which rewind the logical write position after an overflowing piece while retaining the written bytes, continue formatting, and can terminate and return a nonzero count with conversions omitted. For example, using your tm and buffer initialization (0 below denotes the written terminator):

Format / capacity Current PR, as reported Bundled libc.prx, as reported
ab%Ycd / 5 returns 0, buffer ab202 returns 4, buffer abcd0
%A %B / 7 returns 0, buffer Wednesd returns 6, buffer March0
%e|%F|%S| / 8 returns 0, buffer 4|2026- returns 7, buffer 4||34|0

The narrow strftime distinction also matters: your report says it stops at the first piece that does not fit, without retaining part of that conversion, and current main already matches that behavior. Any change to wide overflow handling should preserve that separate narrow behavior.

These module results are your measurements; I have not independently rerun the loader or measured firmware libc. The existing passing regression tests check the PR's current prefix-preservation expectations, so they do not resolve this compatibility question. If firmware libc is the intended reference, do we have measurements for these same small-buffer cases to compare? Once the target is confirmed, I can adjust the wide implementation and regression expectations to the supported behavior. No code has been changed for this clarification.

AI-assisted: yes.

@JJenkx

JJenkx commented Oct 28, 2026

Copy link
Copy Markdown
Contributor

@StoneDC a native comparison of this head (5be64730a2, merged locally onto main 319621ba2e) against the libc.prx that titles ship (PPSA07923), in case it helps.

Method: a scratch loader calls the titles' wcsftime and strftime by NID next to this build's. For every conversion (%a to %Y, %%, and the E/O forms) it makes 3,000 calls with random dates, a quarter of the fields out of range (from -20 to 59), and a buffer of 1 to 40 characters. It compares the return value and every buffer element. %Z and %z are left out.

main this PR
wcsftime, calls that differ 23,541 15,913
of those, with a nonzero return on either side 0 0
strftime, calls that differ 0 0

Every remaining difference is a call that fails (both sides return 0), and in all 15,913 the only differing element is the first one. When the output doesn't fit, the titles write as much as fits, as this PR now does, and then store L'\0' at str[0]:

%A, buffer of 5 (Friday):  titles 0 72 69 64 61  ("\0rida")
                           this PR 46 72 69 64 61  ("Frida")
                           main    1 1 1 1 1        (untouched)

The narrow strftime does not do this. It leaves the partial output alone, and main already matches the titles there on every call. So the change would be wcsftime only: when buffer.full || buffer.remaining == 0, set *str = 0 before returning 0.

Not covered:

  • the buffer.failed (conversion error) path;
  • a zero count;
  • errno.

The probe is a native harness (a title's decrypted libc.prx run next to the build's DLL), so it isn't in the repository; I can run it again on a later head.

AI-assisted: yes (Claude Code).

@MarcZX10

Copy link
Copy Markdown
Contributor

Reference target

Given the scope recorded in #8855, I would treat firmware libSceLibcInternal.sprx as the authoritative target for this emulator behavior. That PR explicitly derives its console C-locale measurements from the firmware module; title-bundled libc.prx measurements are valuable cross-checks, but they should not establish firmware behavior where the two modules may differ.

For the newly reported multi-piece overflow and error boundaries, I agree we need a firmware measurement before changing the implementation or claiming a match. Until then, keeping the current tested behavior and documenting the remaining difference is the evidence-backed choice. This clarifies the intended reference, but it does not independently resolve the unmeasured cases or replace maintainer confirmation.

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

Re-checked — approved

I clarified the reference question in my follow-up: for the console behavior scoped by #8855, firmware libSceLibcInternal.sprx is authoritative; title-bundled libc.prx results are cross-checks and cannot establish firmware behavior when they differ. The current description now explicitly keeps the multi-piece/error boundary behavior unclaimed and unchanged pending a firmware measurement, and retains the remaining gaps in debt.

The exact head 5be64730a23cb09a9ce5ed0136f4ec074a13f3a7 preserves the previously reviewed formatter and tests while merging current main; the author reports the repository test suites plus ASan/UBSan harness passing, with a negative control. The documented full product/integration limitations are clear. Hosted relinker and policy checks pass; Linux and Windows product jobs are skipped by workflow policy. I did not rerun the harness locally.

@BunnyFl

BunnyFl commented Oct 29, 2026

Copy link
Copy Markdown
Contributor

@MarcZX10 @PrivacyOnion a firmware 13.42 measurement of the open cases.

Setup. I ran the decrypted firmware 13.42 libSceLibcInternal.sprx wcsftime natively on a PC, not on a console, next to AnyPS5's wcsftime_nid_postfix:

  • 19 formats: literal-only, single and multi-piece conversions, %c, %x %X, %%, an unknown %Q, E/O modifiers, a surrogate-pair literal on either side of a conversion, the empty format and a lone %.
  • 3 dates, every capacity from 0 to the full length + 2 (to 42 for the empty format), 16-bit output pre-filled with 0xA5A5, and errno set before each call.

That is 895 cases, two byte-identical runs. %Z and %z are left out, because the module reads time-zone state that isn't set up outside a process.

What the module does. This model reproduces every case, return value and every output unit:

  • Walk the format with an output position pos.
  • A literal unit when pos has reached the capacity returns 0. Otherwise it is written and pos advances.
  • A conversion's text is copied for as many units as fit. pos advances only if the whole text fits (the terminator not counted). A conversion that doesn't fit is skipped, and the rest of the format is still processed from the same position.
  • At the end, if pos is below the capacity, a terminator goes at pos and pos is returned; otherwise 0.

So when a conversion doesn't fit:

  • The module returns the non-zero length of what came before it. Example: %Y-%m-%d at capacity 9 returns 8, "2024-02-".
  • Later pieces are written over the skipped conversion's partial text. Example: %Y-%m-%d at capacity 1 returns 0 with - in the first unit.
  • The terminator lands on the skipped conversion's first unit. That is the first-unit clearing in the earlier bundled-module comparison, and its other partial units stay past the terminator: %A %B at capacity 9 gives "Friday \0e".

A literal that doesn't fit always returns 0 with everything before it in place. No case changed errno. Capacity 0 writes nothing and returns 0. The empty format at capacity 1 or more writes only the terminator and returns 0.

Against this head (5be64730a2). 368 of the 895 cases differ, all from the skip rule:

  • 199 where the module returns the shorter non-zero length and this head returns 0;
  • 169 where both return 0 but the module has gone on writing later pieces at the same position.

The other 527 match, including the literal-only overflow, the empty format and errno. For comparison, main (aaccd0ba39) differs in 730.

Not covered: %Z/%z, conversion failures inside a single conversion, and anything a title's own libc.prx does differently. This is the firmware library only.

AI-assisted: yes (Claude Code)

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

Re-checked — changes requested

The new firmware 13.42 measurement materially changes the evidence behind my earlier approval. The reported native comparison covers 895 cases twice and finds 368 differences on this head: 199 cases where the firmware returns the written prefix but this code returns 0, and 169 where it continues writing later format pieces after a conversion does not fit. The earlier review explicitly left those multi-piece/error boundaries unclaimed pending firmware evidence; that evidence is now available and contradicts the current behavior.

Please add focused regressions for the measured cases and align the implementation and debt description with the firmware results, or narrow the PR so it no longer claims the unverified multi-piece behavior. I am changing the review to request changes because the current tests do not cover the newly measured cases. The report is a firmware-module run on a PC, not a physical-console result, so please retain that limitation in the description.

@rooklz rooklz mentioned this pull request Oct 29, 2026
12 tasks done
@StoneDC

StoneDC commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor Author

Follow-up on the review fixes at head 3d9db7dad635e0290f9e0a2808c593048ecb964d.

Implemented the reported firmware-style wide-formatting overflow behavior: a conversion advances the logical position only when its whole result fits, while later pieces can overwrite an abandoned partial conversion. Literal overflow still stops. Added 22 boundary vectors and retained the complete-output tests; the timezone fixture now sets and restores guest TZ explicitly.

Validation at this exact head: the real shared-libc wide-formatting/time CTests pass 4/4 on both Windows and Linux; the supplementary actual-source ASan+UBSan harness also passes 4/4. Restoring only the old formatter makes the current regression fail at the firmware-piece assertion. The reference evidence is the reported firmware 13.42 module run on a PC; I have not independently rerun its private loader/895-case campaign or tested PS5 hardware. Remaining unverified cases are listed in the PR/debt entry.

Build run 40867077680 completed successfully for every executed job, including full Windows and the relinker/ASan jobs. Full Linux was skipped.

Hosted-check snapshot checked on 2026-10-30 UTC+08:00 (2026-10-29 UTC) for this head: 16 passed, 1 skipped; no failures. Current checks. Pending and skipped checks are not counted as passes.

The PR description contains the detailed validation scope and limitations. Please re-review the updated head when convenient.

AI-assisted: yes.

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

Re-checked — new head, looks good

The firmware-piece overflow finding is now covered by boundary cases, and all four focused formatting/time tests pass locally.

What I ran

  • Reviewed head 3d9db7d against current main bb04a4f.
  • Current-main merge preview completed cleanly (tree 8dbddde8864d20874b5042b1a6cfd434b61b86c0).
  • Debian Linux 6.1.190, x86_64, GCC 12.2.0, CMake/Ninja.
  • Built the actual shared-libc targets and ran four focused CTests.
  • Replaced only Time.cpp with current-main source while retaining the PR regression test, then restored the PR source and reran the suite.
  • Ran conventions and whitespace checks. Hosted checks are reported separately below.
cmake --build /dev/shm/AnyPS5-build-12915-full --target guest_wide_formatting_tests guest_strftime_tests guest_time_conversion_tests guest_time_extras_tests -j 2
ctest --test-dir /dev/shm/AnyPS5-build-12915-full -R '^guest_(wide_formatting|strftime|time_conversion|time_extras)$' --output-on-failure
git show upstream/main:core/libs/prx/libc/src/Time.cpp > core/libs/prx/libc/src/Time.cpp
cmake --build /dev/shm/AnyPS5-build-12915-full --target guest_wide_formatting_tests -j 2
ctest --test-dir /dev/shm/AnyPS5-build-12915-full -R '^guest_wide_formatting$' --output-on-failure
git checkout -- core/libs/prx/libc/src/Time.cpp
python3 tools/check_conventions.py --base upstream/main
git diff --check upstream/main...HEAD

Results

Check Result
Current-main merge preview Clean; tree 8dbddde8864d20874b5042b1a6cfd434b61b86c0
Shared-libc/test build Passed
Four focused formatting/time CTests 4/4 passed
Baseline formatter negative control Failed at the expected firmware-piece assertion
Restored PR formatter 4/4 passed
Conventions and diff check Passed
Hosted checks Executed jobs pass; full Linux job skipped
Unedited local test output
Internal ctest changing into directory: /dev/shm/AnyPS5-build-12915-full
Test project /dev/shm/AnyPS5-build-12915-full
    Start 514: guest_time_conversion
1/4 Test #514: guest_time_conversion ............   Passed    0.34 sec
    Start 517: guest_time_extras
2/4 Test #517: guest_time_extras ................   Passed    0.08 sec
    Start 522: guest_wide_formatting
3/4 Test #522: guest_wide_formatting ............   Passed    0.02 sec
    Start 596: guest_strftime
4/4 Test #596: guest_strftime ...................   Passed    0.03 sec

100% tests passed, 0 tests failed out of 4

Total Test time (real) =   0.74 sec
Unedited negative-control output
Internal ctest changing into directory: /dev/shm/AnyPS5-build-12915-full
Test project /dev/shm/AnyPS5-build-12915-full
    Start 522: guest_wide_formatting
1/1 Test #522: guest_wide_formatting ............Subprocess aborted***Exception:   0.06 sec
snwprintf_s: wcsftime firmware piece units

0% tests passed, 1 tests failed out of 1

Total Test time (real) =   0.35 sec

The following tests FAILED:
	522 - guest_wide_formatting (Subprocess aborted)
baseline_formatter_control_exit=8
Unedited restored-test and conventions output
Internal ctest changing into directory: /dev/shm/AnyPS5-build-12915-full
Test project /dev/shm/AnyPS5-build-12915-full
    Start 514: guest_time_conversion
1/4 Test #514: guest_time_conversion ............   Passed    0.33 sec
    Start 517: guest_time_extras
2/4 Test #517: guest_time_extras ................   Passed    0.09 sec
    Start 522: guest_wide_formatting
3/4 Test #522: guest_wide_formatting ............   Passed    0.02 sec
    Start 596: guest_strftime
4/4 Test #596: guest_strftime ...................   Passed    0.01 sec

100% tests passed, 0 tests failed out of 4

Total Test time (real) =   0.98 sec
restored_pr_test_exit=0
All conventions checks passed.
diff_check_exit=0

Negative control

Assertion Mutation Result
Conversion overflow continuation Replaced only Time.cpp with current-main source while retaining the PR tests guest_wide_formatting failed at the expected firmware-piece assertion (exit 8)
Restored PR source Restored the reviewed Time.cpp All four CTests passed

Findings

Blocking

None found in the reviewed head.

Non-blocking

The follow-up comment 6502794473, created on October 29, says its hosted-check snapshot was checked on October 30. The current hosted checks are available and executed jobs pass; please correct or remove that future-dated snapshot line so the report timeline remains accurate.

Sources

Not verified

  • I did not reproduce the firmware module run/private 895-case campaign or run on PS5 hardware.
  • The CTests ran on the exact PR head; I computed a clean current-main merge preview but did not run CTests on a synthetic merged working tree.
  • Game-level behavior, %Z/%z differences, and unmeasured conversion-failure cases remain unverified.

@StoneDC

StoneDC commented Oct 30, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the re-check and approval. I clarified the original follow-up comment: its snapshot used the local date 2026-10-30 in UTC+08:00, corresponding to 2026-10-29 UTC. The line now explicitly states both dates, so its timeline agrees with GitHub's UTC creation date.

The reviewed head remains 3d9db7dad635e0290f9e0a2808c593048ecb964d; the correction is to the report's time-zone notation. The latest check snapshot still shows 16 passed and the full Linux job skipped, as reported separately from local validation.

AI-assisted: yes.

@oneandonlydean

Copy link
Copy Markdown
Collaborator

@StoneDC to close the question you asked us: yes, firmware libSceLibcInternal.sprx is the target, as MarcZX10 said. We checked 3d9db7dad6 against BunnyFl's 13.42 model: a literal at the capacity returns 0, a conversion that doesn't fit is skipped while later pieces continue from the same position, the terminator goes at that position when there is room, and capacity 0, the empty format and errno match. strftime keeps its stop-on-overflow behaviour. Thanks, and thanks to @BunnyFl and @JJenkx for the measurements. Nothing further from us on this head.

@StoneDC

StoneDC commented Nov 1, 2026

Copy link
Copy Markdown
Contributor Author

@oneandonlydean Thanks for closing the target question and checking 3d9db7dad635e0290f9e0a2808c593048ecb964d against BunnyFl's 13.42 model. I updated the description to record that firmware libSceLibcInternal.sprx is the intended target.

The reviewed wide-formatting behavior and separate narrow strftime stop-on-overflow behavior remain unchanged. Source head is still 3d9db7dad635e0290f9e0a2808c593048ecb964d; no further code push or new local firmware/console run is claimed. Existing debt and limits on independently verified cases remain as recorded. Current-main merge preview, description conventions and whitespace pass; hosted snapshot before this documentation edit: {"pass": 16, "skipping": 1}.

Current-head checks. AI-assisted: yes.

@oneandonlydean
oneandonlydean merged commit c50acd1 into boykopovar:main Nov 1, 2026
23 of 25 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants