On 2026-10-19 12:01, Pali Rohár wrote:
The msvcrt/UCRT _fpreset function is not only the x87 fninit
instruction
but is doing also some other work, like setting SSE registers or
recovering
from state when the function was called from the SIGFPE signal handler
(which is begin called from SEH exception filter dispatcher).
I was curious what it does with SSE, so I tested it. It resets MXCSR to
0x1f80. But on x86_64 it doesn't touch the x87 unit at all. Only on
i686 does it also reset the x87 control word (to 0x027f). That's the
same for ucrtbase.dll and msvcrt.dll.
So change the CRT_fp10.c _fpreset function function to call also the
original msvcrt/UCRT _fpreset function and then change the x87 FPU
precision to 10 bits via _controlfp().
Unfortunately _controlfp ignores _MCW_PC on x86_64. The control word
just doesn't change, for both ucrtbase.dll and msvcrt.dll (and mingw-w64
imports _controlfp straight from them). On i686 it works.
-#ifdef __GNUC__
- __asm__ ("fninit");
-#else /* msvc: */
- __asm fninit;
-#endif
+ (* __MINGW_IMP_SYMBOL(_fpreset))();
+ _controlfp(_PC_64, _MCW_PC);
So on x86_64, nothing here resets the x87 unit any more. I built a test
program with this _fpreset linked in:
x86_64: main() starts at 0x027f (53-bit) instead of 0x037f
i686: main() starts at 0x037f, as before
That means long double on x86_64 would only get 53-bit precision, which
is what 295fafcf was fixing for winpthreads. fesetenv(FE_DFL_ENV)
would also stop resetting the x87 rounding mode and precision on
x86_64.
A simple fix is to keep the existing fninit, after calling the
Microsoft _fpreset instead of _controlfp:
(* __MINGW_IMP_SYMBOL(_fpreset))();
#ifdef __GNUC__
__asm__ ("fninit");
#else /* msvc: */
__asm fninit;
#endif
Here's the test:
#include <_mingw.h>
#include <fenv.h>
#include <float.h>
#include <stdio.h>
extern void (* __MINGW_IMP_SYMBOL(_fpreset))(void);
/* The _fpreset from your patch. */
void _fpreset(void)
{
(* __MINGW_IMP_SYMBOL(_fpreset))();
_controlfp(_PC_64, _MCW_PC);
}
static unsigned short get_cw(void)
{
unsigned short cw;
__asm__ __volatile__ ("fnstcw %0" : "=m" (cw));
return cw;
}
static void set_cw(unsigned short cw)
{
__asm__ __volatile__ ("fldcw %0" : : "m" (cw));
}
int main(void)
{
unsigned short start = get_cw();
set_cw(0x0c7f); /* round toward zero, 24-bit */
fesetenv(FE_DFL_ENV);
printf("start: %04x, after FE_DFL_ENV: %04x\n", start, get_cw());
return 0;
}
_______________________________________________
Mingw-w64-public mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/mingw-w64-public