https://gcc.gnu.org/bugzilla/show_bug.cgi?id=129092

            Bug ID: 129092
           Summary: [14/15/16/17 Regression] wrong code at -O2: return
                    value range of "%.*g" with a constant argument and a
                    precision range has too high a minimum
           Product: gcc
           Version: 14.2.1
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: tree-optimization
          Assignee: unassigned at gcc dot gnu.org
          Reporter: dev at pmgroup dot ch
  Target Milestone: ---

Created attachment 66306
  --> https://gcc.gnu.org/bugzilla/attachment.cgi?id=66306&action=edit
gcc -v -save-temps -O2 t.c -o a2

/* -fprintf-return-value, constant float with a variable precision: the call
 * returns 4, gcc records [18, 25] and folds n >= 8 to true. */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
__attribute__((noipa)) static void check(int i)
{
    char buf[32];
    int prec = i >= 15 && i <= 17 ? i : 17;
    int n = snprintf(buf, sizeof buf, "%.*g", prec, -0.9);

    if (n >= 8 && strlen(buf) < 8)
        abort();
}
int main(void)
{
    check(15);
    return 0;
}

gcc -O2 t.c && ./a.out    aborts.
Exit status 0 with -O0 or -fno-printf-return-value.

Attached: t.c (code above) and gcc-v.txt (local 14.2.1,
x86_64-unknown-linux-gnu), from: gcc -v -save-temps -O2 t.c -o a2   (no
diagnostics).

snprintf returns 4 ("-0.9"). With -fdump-tree-strlen-details (14.2.1, and the
same on trunk):

  Directive 1 at offset 0: "%.*g", precision in range [1517]
    Result: 18, 20, 20, 25 (18, 20, 20, 25)
  Directive 2 at offset 4: "", length = 1
  Setting in-bounds return value range [18, 25].

so n >= 8 is folded to true.

>From reading format_floating (dir, arg) in gimple-ssa-sprintf.cc: for a
constant argument the minimum is formatted only at prec[0] with MPFR_RNDD
(-0.900000000000001 at 15 digits) and the maximum only at prec[1] with
MPFR_RNDU. With a precision range, the shortest %g output need not be either,
since trailing zeros are trimmed.

The same range can also make an inlined memcpy of n bytes overrun: a second
program segfaults at -O2 with 14.2.1, 14.4 and 15.3 (not with 16.2 or trunk). I
can attach it.

Tested on x86_64, locally with 14.2.1 and otherwise on Compiler Explorer.
Aborts at -O2 with 8.5, 9.5, 10.5, 11.1-11.5, 12.5, 13.4, 14.4, 15.3, 16.2 and
trunk 17.0.0 20261126 (50cd76914e6e). 7.1 and 7.5 abort too, using
noinline,noclone and a volatile argument in place of noipa; 6.3 exits 0 with
that variant.

Reply via email to