On 11/19/26 14:47, Jonathan Yong wrote:
On 10/26/26 17:08, jmarrec via Sourceware Forge wrote:
From: Julien Marrec <[email protected]>

On targets without POSIX 2008 locales (e.g. MinGW-w64), formatted I/O saves the pointer returned by setlocale (LC_NUMERIC, NULL) and restores through it after setlocale (LC_NUMERIC, "C"). C11 allows that second call to overwrite the string, and both Windows C runtimes invalidate it. msvcrt overwrites its static buffer with "C", so a non-"C" LC_NUMERIC set by the program is reset to "C" by the first formatted I/O statement. UCRT frees the buffer, so the restore reads freed memory and leaves the process in an arbitrary locale or fails, and formatted I/O becomes several times slower.

Save a copy of the name instead, and skip the switch entirely when LC_NUMERIC is already "C", which avoids two setlocale calls per data transfer statement in the common case.

    PR libfortran/128183

libgfortran/ChangeLog:

    * io/transfer.c (data_transfer_init_worker): Save a copy of the
    LC_NUMERIC name, and only switch to "C" if it is not already "C".
    (finalize_transfer): Only restore if a name was saved, and free it.
    * io/unit.c (old_locale): Update comment.

gcc/testsuite/ChangeLog:

    * gfortran.dg/pr128183.f90: New test.
    * gfortran.dg/pr128183_aux.c: New file.

Signed-off-by: Julien Marrec <[email protected]>
---
Testing:

- x86_64-pc-linux-gnu, non-bootstrap C/Fortran build, with libgfortran configured with `ac_cv_func_uselocale=no` so that it uses the setlocale fallback. `make check-fortran` with and without the fix: no new failures. - The new test fails without the fix on that build (glibc frees the old name too; valgrind reports an invalid read in finalize_transfer) and passes with it. - x86_64-w64-mingw32: transfer.c and unit.c rebuilt with the fix and swapped into the libgfortran.a of a GCC 16.2.0 UCRT toolchain. The reproducer passes (it fails with the stock library), and an internal WRITE goes from 6.8 us to 1.8 us. I have not run the testsuite on MinGW-w64.

Bug and reproducers: https://gcc.gnu.org/PR128183, https://github.com/ jmarrec/libgfortran-ucrt-setlocale

I don't have write access, so please push it for me if approved. Ok for trunk?

I don't mind helping to push if at least one Fortran maintainer okays it.


Re-adding all the other participants.

Reply via email to