fix(libc): convert Windows time zone names to UTF-8 #10987

Merged
MarcZX10 merged 5 commits from upstream-pr/10987 into main 2026-11-08 05:28:06 +00:00
MarcZX10 commented 2026-10-25 12:26:28 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-10-25T12:26:28Z.


What

Windows exposes CRT time-zone names in the active ANSI code page, while the guest expects UTF-8. Convert the names returned through tzname and tm_zone to UTF-8, retaining the original name if conversion fails. This fixes non-ASCII Windows zone names in %Z and wide time formatting.

The wide formatting regression test now decodes the narrow UTF-8 result to UTF-16 before comparing it with wcsftime; its prior byte-for-code-unit comparison failed for multi-byte UTF-8. The time conversion test covers a fixed CP1252 name and the host CRT names.

Tested

  • Linux GCC 12.2: -fsyntax-only passed for Time.cpp, GuestTimeConversion.cpp, and GuestWideFormatting.cpp.
  • MinGW-w64: standalone compilation of the Windows code-page conversion helper passed. A syntax check of the full Windows translation units is blocked by the environment's missing _fflush_nolock declaration in FileStream.hpp.
  • Full CMake test configuration did not complete because this checkout has no 3rdparty/SDL2/CMakeLists.txt and the environment reports missing XRandR support. Runtime tests were not run here.
  • tools/check_conventions.py --base upstream/main --head HEAD: passed. tools/pr_overlap.py --branch marc/fix-windows-timezone-name-utf8: no overlap with open PRs.

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
  • New third-party code is a submodule built from source
  • Generic behaviour, not specific to one title
  • Depends on: #10895 (merge order: #10895 first; rebase this PR afterward, as agreed with its author)
  • Fixes: #10981
  • Unblocks: none
  • GPUs tested: n/a
  • AI-assisted: yes
<!-- greyfinch-sync:boykopovar/AnyPS5:issue:5004711238 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/10987). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-10-25T12:26:28Z. --- ### What Windows exposes CRT time-zone names in the active ANSI code page, while the guest expects UTF-8. Convert the names returned through `tzname` and `tm_zone` to UTF-8, retaining the original name if conversion fails. This fixes non-ASCII Windows zone names in `%Z` and wide time formatting. The wide formatting regression test now decodes the narrow UTF-8 result to UTF-16 before comparing it with `wcsftime`; its prior byte-for-code-unit comparison failed for multi-byte UTF-8. The time conversion test covers a fixed CP1252 name and the host CRT names. ### Tested - Linux GCC 12.2: `-fsyntax-only` passed for `Time.cpp`, `GuestTimeConversion.cpp`, and `GuestWideFormatting.cpp`. - MinGW-w64: standalone compilation of the Windows code-page conversion helper passed. A syntax check of the full Windows translation units is blocked by the environment's missing `_fflush_nolock` declaration in `FileStream.hpp`. - Full CMake test configuration did not complete because this checkout has no `3rdparty/SDL2/CMakeLists.txt` and the environment reports missing XRandR support. Runtime tests were not run here. - `tools/check_conventions.py --base upstream/main --head HEAD`: passed. `tools/pr_overlap.py --branch marc/fix-windows-timezone-name-utf8`: no overlap with open PRs. ### Checklist - [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 - [x] Unimplemented paths throw (`NotImplemented_nid_no_patch`); silent stubs are listed under Silent stubs in their library's technical debt file - [x] No notes, investigation `.md` files or images added to the repository - [x] New third-party code is a submodule built from source - [x] Generic behaviour, not specific to one title - [x] Depends on: #10895 (merge order: #10895 first; rebase this PR afterward, as agreed with its author) - [x] Fixes: #10981 - [x] Unblocks: none - [x] GPUs tested: n/a - [x] AI-assisted: yes
thepoppfish commented 2026-10-25 12:42:36 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by thepoppfish on 2026-10-25T12:42:36Z.

Review: CHANGES_REQUESTED


I built and ran the actual changed sources at 445ecdef58fc53f3498d09a2e232f7ba37384471 on Windows and found the two blocking issues below.

Windows 11 build26200; MSYS2 UCRT64 GCC16.2.0-6; CMake4.3.1; Ninja1.13.2; Release with explicit -O1 -g, no LTO. Observed OS name is ASCII Jerusalem Standard Time (23 bytes), ACP1252, so the lifetime finding does not require a German/non-ASCII host.

Built complete, unmodified Time.cpp, Environment.cpp, Multibyte.cpp and FormattingWide.cpp, plus the complete submitted GuestTimeConversion.cpp, GuestWideFormatting.cpp and existing GuestStrftime.cpp. The standalone harness supplies errno, the existing NotImplemented throw, and a fail-fast stream-I/O adapter; it does not replace time/formatting/conversion logic. This is an isolated native executable build, not the whole shared libc/runtime or NID-patched product.

Test PR sources Only Time.cpp restored to main 29ce6d87eb
Complete guest_time_conversion FAIL: new tzname comparison (0.42s) Same failure (0.06s)
Complete guest_wide_formatting Pass on final run (0.03s); first unchanged-binary run failed its length comparison Pass (0.03s)
Complete guest_strftime Pass (0.03s) Pass (0.03s)
Additional timezone_lifetime FAIL: tzname[0] names released storage (0.06s) Pass, four calls retain storage (0.06s)
Additional timezone_no_dst Pass: CRT empty, guest three spaces (0.02s) Same pass (0.03s)

Final full harness: 3/5 pass on the PR, 4/5 on the baseline control; the remaining baseline failure is the newly introduced incorrect test expectation. A passing wide-formatting run does not disprove the independently observed lifetime issue. Earlier runs also caught the published name being freed by the very next localtime call rather than during tzset itself.

The lifetime diagnostic statically links libstdc++/libgcc so its ordinary malloc/free-backed global new/delete hooks can observe the string library's deallocations. It records freed addresses, clears them on reuse and never reads the freed name. The same hooks/flags are used for the baseline control. The other three submitted fixtures use the normal dynamic C++ runtime. No OS time-zone/locale settings changed, only each test process's TZ.

Conventions and whitespace pass against main 29ce6d87eb5b3050b4f08f60ed9ee52195979d14. Both builds show the existing __dstbias dllimport redeclaration warning in GuestTimeConversion.cpp. No full product/shared-library build, sanitizer, Linux/macOS, PS5, game or hosted-CI result claimed. AI-assisted review and harness: yes, OpenAI Codex.

Complete standalone reproduction harness and commands

Check out this PR at 445ecdef58fc53f3498d09a2e232f7ba37384471, and a separate baseline checkout at 29ce6d87eb5b3050b4f08f60ed9ee52195979d14. Put these four files in a new harness folder. Put the GCC16/UCRT64 bin directory and CMake/Ninja bin directory on PATH, then use absolute forward-slash paths for the placeholders:

cmake -S <harness> -B <build> -G Ninja -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_COMPILER=g++ -DREPO=<PR-checkout>
cmake --build <build> -j 2
ctest --test-dir <build> -V

cmake -S <harness> -B <baseline-build> -G Ninja -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_COMPILER=g++ -DREPO=<PR-checkout> -DTIME_SOURCE=<baseline-checkout>/core/libs/prx/libc/src/Time.cpp
cmake --build <baseline-build> -j 2
ctest --test-dir <baseline-build> -V

The baseline command intentionally retains all PR headers and tests and changes only the production Time.cpp. On a system whose OS zone name fits the string's inline capacity (15 bytes here), the lifetime probe returns77 rather than claiming a reproduction. The observed host here needs no such adjustment.

CMakeLists.txt

cmake_minimum_required(VERSION 3.20)
project(AnyPS5TimeZoneReview LANGUAGES CXX)
enable_testing()
set(REPO "${CMAKE_CURRENT_LIST_DIR}/../review-10987" 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_time_conversion|GuestTimeConversion" "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_custom_command(TARGET ${name} POST_BUILD
        COMMAND "${CMAKE_OBJCOPY}" --rename-section .eh_frame=.ehfram --rename-section .eh_fram=.ehfram "$<TARGET_FILE:${name}>" VERBATIM)
    add_test(NAME ${name} COMMAND ${name})
    set_tests_properties(${name} PROPERTIES TIMEOUT 30)
endforeach()
add_executable(timezone_lifetime TimeZoneLifetime.cpp)
target_link_libraries(timezone_lifetime PRIVATE time_sources)
target_link_options(timezone_lifetime PRIVATE -Wl,--gc-sections -static-libstdc++ -static-libgcc)
add_custom_command(TARGET timezone_lifetime POST_BUILD
    COMMAND "${CMAKE_OBJCOPY}" --rename-section .eh_frame=.ehfram --rename-section .eh_fram=.ehfram "$<TARGET_FILE:timezone_lifetime>" VERBATIM)
add_test(NAME timezone_lifetime COMMAND timezone_lifetime)
set_tests_properties(timezone_lifetime PROPERTIES TIMEOUT 30)
add_test(NAME timezone_no_dst COMMAND timezone_lifetime --no-dst)
set_tests_properties(timezone_no_dst PROPERTIES TIMEOUT 30)

Support.cpp

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

[[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(std::string(name) + " not implemented");
}

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();
}
}

TimeZoneLifetime.cpp

#include "prx/libc/include/Api.hpp"
#include "prx/libc/include/GuestTime.hpp"
#include "prx/libc/include/GuestTimeZoneName.hpp"
#include "prx/libc/include/SonyCrt.hpp"
#include <atomic>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <new>
#include <string>
#include <windows.h>

extern "C" char* tzname_nid_postfix[2];

static std::atomic<void*> watched{nullptr};
static std::atomic<unsigned> frees{0};
static void* released[4096]{};
static unsigned releaseIndex = 0;

void* operator new(std::size_t size) {
    if (void* memory = std::malloc(size == 0 ? 1 : size)) {
        for (void*& entry : released) if (entry == memory) entry = nullptr;
        return memory;
    }
    throw std::bad_alloc();
}

void operator delete(void* memory) noexcept {
    if (memory != nullptr) released[releaseIndex++ % 4096] = memory;
    if (memory != nullptr && memory == watched.load()) ++frees;
    std::free(memory);
}

void operator delete(void* memory, std::size_t) noexcept {
    ::operator delete(memory);
}

int main(int argc, char** argv) {
    if (argc == 2 && std::strcmp(argv[1], "--no-dst") == 0) {
        if (setenv_nid_postfix("TZ", "UTC-2", 1) != 0) return 2;
        tzset_nid_postfix();
        std::printf("TZ=UTC-2 _daylight=%d CRT-daylight-name=[%s] guest-daylight-name=[%s]\n",
            _daylight, _tzname[1], tzname_nid_postfix[1]);
        return _daylight == 0 && std::strcmp(_tzname[1], "") == 0
            && std::strcmp(tzname_nid_postfix[1], "   ") == 0 ? 0 : 1;
    }
    unsetenv_nid_postfix("TZ");
    const std::int64_t instant = 172800;
    GuestTm first{};
    if (localtime_s_nid_postfix(&instant, &first) != &first) return 2;
    const std::string expected = GuestTimeZoneNameToUtf8(_tzname[0], CP_ACP);
    std::printf("ACP=%u host-name-bytes=%zu host=%s\n", GetACP(), expected.size(), expected.c_str());
    if (expected.size() <= 15) {
        std::puts("Need a non-SSO system zone name for this lifetime probe");
        return 77;
    }
    tzset_nid_postfix();
    char* published = tzname_nid_postfix[0];
    for (const void* entry : released) {
        if (entry == published) {
            std::puts("FAIL: tzset returned with tzname[0] pointing at already released storage");
            return 1;
        }
    }
    watched.store(published);
    for (int index = 0; index < 4; ++index) {
        GuestTm local{};
        if (localtime_s_nid_postfix(&instant, &local) != &local) return 2;
        const unsigned released = frees.load();
        std::printf("call=%d published=%p tm_zone=%p frees=%u\n", index + 1,
            static_cast<void*>(published), static_cast<const void*>(local.tm_zone), released);
        if (released != 0 && tzname_nid_postfix[0] == published && local.tm_zone != published) {
            watched.store(nullptr);
            std::puts("FAIL: unchanged tzname[0] points at storage released during localtime_s");
            return 1;
        }
    }
    watched.store(nullptr);
    std::puts("Published zone-name storage was not released");
}
<!-- greyfinch-sync:boykopovar/AnyPS5:review:5643242113 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/10987#pullrequestreview-5643242113). Originally posted by [thepoppfish](https://github.com/thepoppfish) on 2026-10-25T12:42:36Z. **Review:** CHANGES_REQUESTED --- I built and ran the actual changed sources at `445ecdef58fc53f3498d09a2e232f7ba37384471` on Windows and found the two blocking issues below. Windows 11 build26200; MSYS2 UCRT64 GCC16.2.0-6; CMake4.3.1; Ninja1.13.2; Release with explicit `-O1 -g`, no LTO. Observed OS name is ASCII `Jerusalem Standard Time` (23 bytes), ACP1252, so the lifetime finding does not require a German/non-ASCII host. Built complete, unmodified `Time.cpp`, `Environment.cpp`, `Multibyte.cpp` and `FormattingWide.cpp`, plus the complete submitted `GuestTimeConversion.cpp`, `GuestWideFormatting.cpp` and existing `GuestStrftime.cpp`. The standalone harness supplies errno, the existing NotImplemented throw, and a fail-fast stream-I/O adapter; it does not replace time/formatting/conversion logic. This is an isolated native executable build, not the whole shared libc/runtime or NID-patched product. | Test | PR sources | Only Time.cpp restored to main `29ce6d87eb` | |---|---|---| | Complete guest_time_conversion | FAIL: new tzname comparison (0.42s) | Same failure (0.06s) | | Complete guest_wide_formatting | Pass on final run (0.03s); first unchanged-binary run failed its length comparison | Pass (0.03s) | | Complete guest_strftime | Pass (0.03s) | Pass (0.03s) | | Additional timezone_lifetime | FAIL: tzname[0] names released storage (0.06s) | Pass, four calls retain storage (0.06s) | | Additional timezone_no_dst | Pass: CRT empty, guest three spaces (0.02s) | Same pass (0.03s) | Final full harness: 3/5 pass on the PR, 4/5 on the baseline control; the remaining baseline failure is the newly introduced incorrect test expectation. A passing wide-formatting run does not disprove the independently observed lifetime issue. Earlier runs also caught the published name being freed by the very next localtime call rather than during tzset itself. The lifetime diagnostic statically links libstdc++/libgcc so its ordinary malloc/free-backed global new/delete hooks can observe the string library's deallocations. It records freed addresses, clears them on reuse and never reads the freed name. The same hooks/flags are used for the baseline control. The other three submitted fixtures use the normal dynamic C++ runtime. No OS time-zone/locale settings changed, only each test process's TZ. Conventions and whitespace pass against main `29ce6d87eb5b3050b4f08f60ed9ee52195979d14`. Both builds show the existing `__dstbias` dllimport redeclaration warning in GuestTimeConversion.cpp. No full product/shared-library build, sanitizer, Linux/macOS, PS5, game or hosted-CI result claimed. AI-assisted review and harness: yes, OpenAI Codex. <details> <summary>Complete standalone reproduction harness and commands</summary> Check out this PR at `445ecdef58fc53f3498d09a2e232f7ba37384471`, and a separate baseline checkout at `29ce6d87eb5b3050b4f08f60ed9ee52195979d14`. Put these four files in a new harness folder. Put the GCC16/UCRT64 bin directory and CMake/Ninja bin directory on PATH, then use absolute forward-slash paths for the placeholders: ```text cmake -S <harness> -B <build> -G Ninja -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_COMPILER=g++ -DREPO=<PR-checkout> cmake --build <build> -j 2 ctest --test-dir <build> -V cmake -S <harness> -B <baseline-build> -G Ninja -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_COMPILER=g++ -DREPO=<PR-checkout> -DTIME_SOURCE=<baseline-checkout>/core/libs/prx/libc/src/Time.cpp cmake --build <baseline-build> -j 2 ctest --test-dir <baseline-build> -V ``` The baseline command intentionally retains all PR headers and tests and changes only the production Time.cpp. On a system whose OS zone name fits the string's inline capacity (15 bytes here), the lifetime probe returns77 rather than claiming a reproduction. The observed host here needs no such adjustment. **CMakeLists.txt** ```cmake cmake_minimum_required(VERSION 3.20) project(AnyPS5TimeZoneReview LANGUAGES CXX) enable_testing() set(REPO "${CMAKE_CURRENT_LIST_DIR}/../review-10987" 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_time_conversion|GuestTimeConversion" "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_custom_command(TARGET ${name} POST_BUILD COMMAND "${CMAKE_OBJCOPY}" --rename-section .eh_frame=.ehfram --rename-section .eh_fram=.ehfram "$<TARGET_FILE:${name}>" VERBATIM) add_test(NAME ${name} COMMAND ${name}) set_tests_properties(${name} PROPERTIES TIMEOUT 30) endforeach() add_executable(timezone_lifetime TimeZoneLifetime.cpp) target_link_libraries(timezone_lifetime PRIVATE time_sources) target_link_options(timezone_lifetime PRIVATE -Wl,--gc-sections -static-libstdc++ -static-libgcc) add_custom_command(TARGET timezone_lifetime POST_BUILD COMMAND "${CMAKE_OBJCOPY}" --rename-section .eh_frame=.ehfram --rename-section .eh_fram=.ehfram "$<TARGET_FILE:timezone_lifetime>" VERBATIM) add_test(NAME timezone_lifetime COMMAND timezone_lifetime) set_tests_properties(timezone_lifetime PROPERTIES TIMEOUT 30) add_test(NAME timezone_no_dst COMMAND timezone_lifetime --no-dst) set_tests_properties(timezone_no_dst PROPERTIES TIMEOUT 30) ``` **Support.cpp** ```cpp #include "prx/libc/include/Api.hpp" #include "prx/libc/include/General.hpp" #include <cerrno> #include <cstdlib> #include <stdexcept> #include <string> [[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(std::string(name) + " not implemented"); } ``` **IoPoison.cpp** ```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(); } } ``` **TimeZoneLifetime.cpp** ```cpp #include "prx/libc/include/Api.hpp" #include "prx/libc/include/GuestTime.hpp" #include "prx/libc/include/GuestTimeZoneName.hpp" #include "prx/libc/include/SonyCrt.hpp" #include <atomic> #include <cstddef> #include <cstdint> #include <cstdio> #include <cstdlib> #include <cstring> #include <new> #include <string> #include <windows.h> extern "C" char* tzname_nid_postfix[2]; static std::atomic<void*> watched{nullptr}; static std::atomic<unsigned> frees{0}; static void* released[4096]{}; static unsigned releaseIndex = 0; void* operator new(std::size_t size) { if (void* memory = std::malloc(size == 0 ? 1 : size)) { for (void*& entry : released) if (entry == memory) entry = nullptr; return memory; } throw std::bad_alloc(); } void operator delete(void* memory) noexcept { if (memory != nullptr) released[releaseIndex++ % 4096] = memory; if (memory != nullptr && memory == watched.load()) ++frees; std::free(memory); } void operator delete(void* memory, std::size_t) noexcept { ::operator delete(memory); } int main(int argc, char** argv) { if (argc == 2 && std::strcmp(argv[1], "--no-dst") == 0) { if (setenv_nid_postfix("TZ", "UTC-2", 1) != 0) return 2; tzset_nid_postfix(); std::printf("TZ=UTC-2 _daylight=%d CRT-daylight-name=[%s] guest-daylight-name=[%s]\n", _daylight, _tzname[1], tzname_nid_postfix[1]); return _daylight == 0 && std::strcmp(_tzname[1], "") == 0 && std::strcmp(tzname_nid_postfix[1], " ") == 0 ? 0 : 1; } unsetenv_nid_postfix("TZ"); const std::int64_t instant = 172800; GuestTm first{}; if (localtime_s_nid_postfix(&instant, &first) != &first) return 2; const std::string expected = GuestTimeZoneNameToUtf8(_tzname[0], CP_ACP); std::printf("ACP=%u host-name-bytes=%zu host=%s\n", GetACP(), expected.size(), expected.c_str()); if (expected.size() <= 15) { std::puts("Need a non-SSO system zone name for this lifetime probe"); return 77; } tzset_nid_postfix(); char* published = tzname_nid_postfix[0]; for (const void* entry : released) { if (entry == published) { std::puts("FAIL: tzset returned with tzname[0] pointing at already released storage"); return 1; } } watched.store(published); for (int index = 0; index < 4; ++index) { GuestTm local{}; if (localtime_s_nid_postfix(&instant, &local) != &local) return 2; const unsigned released = frees.load(); std::printf("call=%d published=%p tm_zone=%p frees=%u\n", index + 1, static_cast<void*>(published), static_cast<const void*>(local.tm_zone), released); if (released != 0 && tzname_nid_postfix[0] == published && local.tm_zone != published) { watched.store(nullptr); std::puts("FAIL: unchanged tzname[0] points at storage released during localtime_s"); return 1; } } watched.store(nullptr); std::puts("Published zone-name storage was not released"); } ``` </details>
thepoppfish commented 2026-10-25 13:31:11 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by thepoppfish on 2026-10-25T13:31:11Z.

Review: DISMISSED


Reran the complete native Windows harness against 7c8eb3b531b1c6481398af4d162d754e8e6ef2f8 as requested. All five checks from my original review now pass (1.87s): the three complete repository time-conversion/wide-formatting/strftime fixtures, the direct-localtime allocation probe, and the no-DST probe. That verifies the two originally reproduced sequences are corrected.

There is one remaining lifetime path. After localtime_s returns a caller-owned GuestTm, calling strftime or wcsftime on that same struct causes another tzset refresh and frees its tm_zone buffer under an unchanged time zone. The exported tzname is refreshed; the existing GuestTm still contains the old address. Reading that field afterward accesses released storage.

Same environment: Windows11 build26200, GCC16.2.0-6/UCRT64, CMake4.3.1, Ninja1.13.2, Release with explicit O1-g/noLTO. The actual OS name is ASCII Jerusalem Standard Time (23 bytes), ACP1252. No German-host or PS5 measurement claimed by me.

Additional allocation-observer check Exact 7c8eb3b Only Time.cpp restored to main29ce6d87eb Scratch unchanged-name guard
localtime_s -> strftime(%Z) FAIL, 0.05s; length23/free1/different published buffer Pass0.09s; length23/free0/same buffer Pass0.05s
localtime_s -> wcsftime(%Z) FAIL, 0.02s; length23/free1/different published buffer Pass0.02s; length23/free0/same buffer Pass0.02s

The minimal diagnostic change below also passes the five original checks (5/5,1.87s), retaining the revised fixture's timezone changes, restoration and blank-daylight coverage. I changed only a scratch copy of Time.cpp; your checkout is unmodified.

    for (std::size_t index = 0; index < utf8Names.size(); ++index) {
        const auto converted = GuestTimeZoneNameToUtf8(names[index], CP_ACP);
        if (utf8Names[index] != converted) utf8Names[index] = converted;
    }

This is also consistent with the pinned FreeBSD implementation reusing its active state for an unchanged TZ, with tm_zone referring into that state. I am reporting a native regression against main, not asserting console lifetime measurements.

The extra harness builds complete, unmodified Time.cpp/Environment.cpp/Multibyte.cpp and uses the same errno/NotImplemented support adapter as before. The only allocation hooks are ordinary malloc/free-backed global new/delete, statically linking libstdc++/libgcc so deallocations are observable. The probe watches a live returned pointer and never reads it after release. No time-zone, decoder or formatter implementation is replaced. Its baseline/guard controls change only TIME_SOURCE, retaining all other sources, headers, code, flags and API calls.

Conventions and whitespace pass against local origin/main4017310678; checkout remains clean. The five-check harness still shows the existing __dstbias dllimport warning. No full shared-libc/runtime/product build, sanitizer, Linux/macOS, title, GPU, PS5 or hosted-CI validation claimed. AI-assisted: yes.

Complete additional probe and replay

Save these three files in a separate harness folder and place the same GCC16 UCRT64 and CMake/Ninja bin directories on PATH. Use absolute forward-slash paths for the placeholders. The PR checkout must be at 7c8eb3b531b1c6481398af4d162d754e8e6ef2f8; use a separate baseline checkout at29ce6d87eb5b3050b4f08f60ed9ee52195979d14.

cmake -S <harness> -B <build> -G Ninja -DCMAKE_CXX_COMPILER=g++ -DCMAKE_BUILD_TYPE=Release -DREPO=<PR-checkout>
cmake --build <build> -j 2
ctest --test-dir <build> -V

cmake -S <harness> -B <baseline-build> -G Ninja -DCMAKE_CXX_COMPILER=g++ -DCMAKE_BUILD_TYPE=Release -DREPO=<PR-checkout> -DTIME_SOURCE=<baseline-checkout>/core/libs/prx/libc/src/Time.cpp
cmake --build <baseline-build> -j 2
ctest --test-dir <baseline-build> -V

For the guard control, copy the exact PR Time.cpp outside the checkout, replace only the unconditional refresh loop with the guarded loop above, and use that file as TIME_SOURCE in another build directory. Both new checks pass. The original five-check harness also passes with REPO pointing at this PR checkout, both with the unmodified Time.cpp and with the guard-control TIME_SOURCE. No previous source/binary was overwritten. On a host whose name fits the observed GCC string's 15-byte inline capacity, this additional probe returns77 instead of claiming a reproduction.

CMakeLists.txt

cmake_minimum_required(VERSION 3.20)
project(AnyPS5TimeZoneFormatLifetime LANGUAGES CXX)
enable_testing()
set(REPO "${CMAKE_CURRENT_LIST_DIR}/../review-10987-followup" CACHE PATH "Exact PR checkout")
set(TIME_SOURCE "${REPO}/core/libs/prx/libc/src/Time.cpp" CACHE FILEPATH "Time source under test")
add_executable(format_lifetime
    "${TIME_SOURCE}"
    "${REPO}/core/libs/prx/libc/src/Environment.cpp"
    "${REPO}/core/libs/prx/libc/src/Multibyte.cpp"
    FormatLifetime.cpp Support.cpp)
target_compile_features(format_lifetime PRIVATE cxx_std_20)
target_include_directories(format_lifetime PRIVATE "${REPO}/core/libs")
target_compile_options(format_lifetime PRIVATE -O1 -g -Wall -Wextra -ffunction-sections -fdata-sections)
target_link_options(format_lifetime PRIVATE -Wl,--gc-sections -static-libstdc++ -static-libgcc)
add_custom_command(TARGET format_lifetime POST_BUILD
    COMMAND "${CMAKE_OBJCOPY}" --rename-section .eh_frame=.ehfram --rename-section .eh_fram=.ehfram "$<TARGET_FILE:format_lifetime>" VERBATIM)
add_test(NAME strftime_zone_lifetime COMMAND format_lifetime)
add_test(NAME wcsftime_zone_lifetime COMMAND format_lifetime --wide)
set_tests_properties(strftime_zone_lifetime wcsftime_zone_lifetime PROPERTIES TIMEOUT 30)

Support.cpp

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

[[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(std::string(name) + " not implemented");
}

FormatLifetime.cpp

#include "prx/libc/include/Api.hpp"
#include "prx/libc/include/GuestTime.hpp"
#include "prx/libc/include/GuestTimeZoneName.hpp"
#include "prx/libc/include/SonyCrt.hpp"
#include <atomic>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <new>
#include <string>
#include <windows.h>

extern "C" char* tzname_nid_postfix[2];

static std::atomic<void*> watched{nullptr};
static std::atomic<unsigned> frees{0};

void* operator new(std::size_t size) {
    if (void* memory = std::malloc(size == 0 ? 1 : size)) return memory;
    throw std::bad_alloc();
}

void operator delete(void* memory) noexcept {
    if (memory != nullptr && memory == watched.load()) ++frees;
    std::free(memory);
}

void operator delete(void* memory, std::size_t) noexcept {
    ::operator delete(memory);
}

int main(int argc, char** argv) {
    const bool wide = argc == 2 && std::strcmp(argv[1], "--wide") == 0;
    unsetenv_nid_postfix("TZ");
    tzset_nid_postfix();
    const std::int64_t instant = 172800;
    GuestTm local{};
    if (localtime_s_nid_postfix(&instant, &local) != &local) return 2;
    const std::string expected = GuestTimeZoneNameToUtf8(_tzname[local.tm_isdst > 0 ? 1 : 0], CP_ACP);
    std::printf("ACP=%u host-name-bytes=%zu host=%s\n", GetACP(), expected.size(), expected.c_str());
    if (expected.size() <= 15) return 77;
    const char* saved = local.tm_zone;
    watched.store(const_cast<char*>(saved));
    std::size_t length = 0;
    if (wide) {
        std::uint16_t output[256]{};
        length = wcsftime_nid_postfix(output, 256, reinterpret_cast<const std::uint16_t*>(u"%Z"), &local);
    } else {
        char output[256]{};
        length = strftime_nid_postfix(output, sizeof(output), "%Z", &local);
    }
    const unsigned released = frees.load();
    watched.store(nullptr);
    const char* published = tzname_nid_postfix[local.tm_isdst > 0 ? 1 : 0];
    std::printf("%s length=%zu saved-tm-zone=%p current-tzname=%p frees=%u\n", wide ? "wcsftime" : "strftime",
        length, static_cast<const void*>(saved), static_cast<const void*>(published), released);
    if (length == 0) return 2;
    if (released != 0 && local.tm_zone == saved && saved != published) {
        std::puts("FAIL: formatting freed the unchanged input tm_zone storage");
        return 1;
    }
    std::puts("Formatting retained the input tm_zone storage");
}
<!-- greyfinch-sync:boykopovar/AnyPS5:review:5643396501 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/10987#pullrequestreview-5643396501). Originally posted by [thepoppfish](https://github.com/thepoppfish) on 2026-10-25T13:31:11Z. **Review:** DISMISSED --- Reran the complete native Windows harness against `7c8eb3b531b1c6481398af4d162d754e8e6ef2f8` as requested. **All five checks from my original review now pass** (1.87s): the three complete repository time-conversion/wide-formatting/strftime fixtures, the direct-localtime allocation probe, and the no-DST probe. That verifies the two originally reproduced sequences are corrected. There is one remaining lifetime path. After `localtime_s` returns a caller-owned GuestTm, calling `strftime` or `wcsftime` on that same struct causes another tzset refresh and frees its tm_zone buffer under an **unchanged time zone**. The exported tzname is refreshed; the existing GuestTm still contains the old address. Reading that field afterward accesses released storage. Same environment: Windows11 build26200, GCC16.2.0-6/UCRT64, CMake4.3.1, Ninja1.13.2, Release with explicit O1-g/noLTO. The actual OS name is ASCII `Jerusalem Standard Time` (23 bytes), ACP1252. No German-host or PS5 measurement claimed by me. | Additional allocation-observer check | Exact 7c8eb3b | Only Time.cpp restored to main29ce6d87eb | Scratch unchanged-name guard | |---|---|---|---| | localtime_s -> strftime(`%Z`) | FAIL, 0.05s; length23/free1/different published buffer | Pass0.09s; length23/free0/same buffer | Pass0.05s | | localtime_s -> wcsftime(`%Z`) | FAIL, 0.02s; length23/free1/different published buffer | Pass0.02s; length23/free0/same buffer | Pass0.02s | The minimal diagnostic change below also passes the five original checks (5/5,1.87s), retaining the revised fixture's timezone changes, restoration and blank-daylight coverage. I changed only a scratch copy of Time.cpp; your checkout is unmodified. ```cpp for (std::size_t index = 0; index < utf8Names.size(); ++index) { const auto converted = GuestTimeZoneNameToUtf8(names[index], CP_ACP); if (utf8Names[index] != converted) utf8Names[index] = converted; } ``` This is also consistent with the pinned [FreeBSD implementation](https://github.com/freebsd/freebsd-src/blob/8c639945a44588f6cfdddfb057bb5aad88735da0/contrib/tzcode/stdtime/localtime.c#L1168-L1225) reusing its active state for an unchanged TZ, with tm_zone referring into that state. I am reporting a native regression against main, not asserting console lifetime measurements. The extra harness builds complete, unmodified Time.cpp/Environment.cpp/Multibyte.cpp and uses the same errno/NotImplemented support adapter as before. The only allocation hooks are ordinary malloc/free-backed global new/delete, statically linking libstdc++/libgcc so deallocations are observable. The probe watches a live returned pointer and never reads it after release. No time-zone, decoder or formatter implementation is replaced. Its baseline/guard controls change only TIME_SOURCE, retaining all other sources, headers, code, flags and API calls. Conventions and whitespace pass against local origin/main4017310678; checkout remains clean. The five-check harness still shows the existing __dstbias dllimport warning. No full shared-libc/runtime/product build, sanitizer, Linux/macOS, title, GPU, PS5 or hosted-CI validation claimed. AI-assisted: yes. <details> <summary>Complete additional probe and replay</summary> Save these three files in a separate harness folder and place the same GCC16 UCRT64 and CMake/Ninja bin directories on PATH. Use absolute forward-slash paths for the placeholders. The PR checkout must be at `7c8eb3b531b1c6481398af4d162d754e8e6ef2f8`; use a separate baseline checkout at29ce6d87eb5b3050b4f08f60ed9ee52195979d14. ```text cmake -S <harness> -B <build> -G Ninja -DCMAKE_CXX_COMPILER=g++ -DCMAKE_BUILD_TYPE=Release -DREPO=<PR-checkout> cmake --build <build> -j 2 ctest --test-dir <build> -V cmake -S <harness> -B <baseline-build> -G Ninja -DCMAKE_CXX_COMPILER=g++ -DCMAKE_BUILD_TYPE=Release -DREPO=<PR-checkout> -DTIME_SOURCE=<baseline-checkout>/core/libs/prx/libc/src/Time.cpp cmake --build <baseline-build> -j 2 ctest --test-dir <baseline-build> -V ``` For the guard control, copy the exact PR Time.cpp outside the checkout, replace only the unconditional refresh loop with the guarded loop above, and use that file as TIME_SOURCE in another build directory. Both new checks pass. The [original five-check harness](https://github.com/boykopovar/AnyPS5/pull/10987#pullrequestreview-5643242113) also passes with REPO pointing at this PR checkout, both with the unmodified Time.cpp and with the guard-control TIME_SOURCE. No previous source/binary was overwritten. On a host whose name fits the observed GCC string's 15-byte inline capacity, this additional probe returns77 instead of claiming a reproduction. **CMakeLists.txt** ```cmake cmake_minimum_required(VERSION 3.20) project(AnyPS5TimeZoneFormatLifetime LANGUAGES CXX) enable_testing() set(REPO "${CMAKE_CURRENT_LIST_DIR}/../review-10987-followup" CACHE PATH "Exact PR checkout") set(TIME_SOURCE "${REPO}/core/libs/prx/libc/src/Time.cpp" CACHE FILEPATH "Time source under test") add_executable(format_lifetime "${TIME_SOURCE}" "${REPO}/core/libs/prx/libc/src/Environment.cpp" "${REPO}/core/libs/prx/libc/src/Multibyte.cpp" FormatLifetime.cpp Support.cpp) target_compile_features(format_lifetime PRIVATE cxx_std_20) target_include_directories(format_lifetime PRIVATE "${REPO}/core/libs") target_compile_options(format_lifetime PRIVATE -O1 -g -Wall -Wextra -ffunction-sections -fdata-sections) target_link_options(format_lifetime PRIVATE -Wl,--gc-sections -static-libstdc++ -static-libgcc) add_custom_command(TARGET format_lifetime POST_BUILD COMMAND "${CMAKE_OBJCOPY}" --rename-section .eh_frame=.ehfram --rename-section .eh_fram=.ehfram "$<TARGET_FILE:format_lifetime>" VERBATIM) add_test(NAME strftime_zone_lifetime COMMAND format_lifetime) add_test(NAME wcsftime_zone_lifetime COMMAND format_lifetime --wide) set_tests_properties(strftime_zone_lifetime wcsftime_zone_lifetime PROPERTIES TIMEOUT 30) ``` **Support.cpp** ```cpp #include "prx/libc/include/Api.hpp" #include "prx/libc/include/General.hpp" #include <cerrno> #include <cstdlib> #include <stdexcept> #include <string> [[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(std::string(name) + " not implemented"); } ``` **FormatLifetime.cpp** ```cpp #include "prx/libc/include/Api.hpp" #include "prx/libc/include/GuestTime.hpp" #include "prx/libc/include/GuestTimeZoneName.hpp" #include "prx/libc/include/SonyCrt.hpp" #include <atomic> #include <cstddef> #include <cstdint> #include <cstdio> #include <cstdlib> #include <cstring> #include <new> #include <string> #include <windows.h> extern "C" char* tzname_nid_postfix[2]; static std::atomic<void*> watched{nullptr}; static std::atomic<unsigned> frees{0}; void* operator new(std::size_t size) { if (void* memory = std::malloc(size == 0 ? 1 : size)) return memory; throw std::bad_alloc(); } void operator delete(void* memory) noexcept { if (memory != nullptr && memory == watched.load()) ++frees; std::free(memory); } void operator delete(void* memory, std::size_t) noexcept { ::operator delete(memory); } int main(int argc, char** argv) { const bool wide = argc == 2 && std::strcmp(argv[1], "--wide") == 0; unsetenv_nid_postfix("TZ"); tzset_nid_postfix(); const std::int64_t instant = 172800; GuestTm local{}; if (localtime_s_nid_postfix(&instant, &local) != &local) return 2; const std::string expected = GuestTimeZoneNameToUtf8(_tzname[local.tm_isdst > 0 ? 1 : 0], CP_ACP); std::printf("ACP=%u host-name-bytes=%zu host=%s\n", GetACP(), expected.size(), expected.c_str()); if (expected.size() <= 15) return 77; const char* saved = local.tm_zone; watched.store(const_cast<char*>(saved)); std::size_t length = 0; if (wide) { std::uint16_t output[256]{}; length = wcsftime_nid_postfix(output, 256, reinterpret_cast<const std::uint16_t*>(u"%Z"), &local); } else { char output[256]{}; length = strftime_nid_postfix(output, sizeof(output), "%Z", &local); } const unsigned released = frees.load(); watched.store(nullptr); const char* published = tzname_nid_postfix[local.tm_isdst > 0 ? 1 : 0]; std::printf("%s length=%zu saved-tm-zone=%p current-tzname=%p frees=%u\n", wide ? "wcsftime" : "strftime", length, static_cast<const void*>(saved), static_cast<const void*>(published), released); if (length == 0) return 2; if (released != 0 && local.tm_zone == saved && saved != published) { std::puts("FAIL: formatting freed the unchanged input tm_zone storage"); return 1; } std::puts("Formatting retained the input tm_zone storage"); } ``` </details>
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!10987
No description provided.