Skip to content

libs/libc/stream: Fix the crashes and overflows of printf() for correct calls. - #21474

Merged
xiaoxiang781216 merged 19 commits into
apache:masterfrom
casaroli:printf-safety-up
Nov 6, 2026
Merged

xiaoxiang781216 merged 19 commits into
apache:masterfrom
casaroli:printf-safety-up

Conversation

@casaroli

@casaroli casaroli commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Summary

This PR gives printf full safety for correct calls, with no current feature removed and a minimal flash increase: +68 to +128 bytes on Cortex-M0 (0.15% to 0.22% of the image) and +116 to +216 on Cortex-M3 (0.3% to 0.6%). It is the first step of #21467, one commit per defect, with no new Kconfig option. The measurement is the suite at https://github.com/casaroli/printf-report.

What is fixed

  • Each argument is read at its right size: %a and %A, %n of any length, %L as a long double, and all numbered arguments, also %x, %X, %o, %S and %n.
  • %a and %A, and %e, %f, %g with CONFIG_LIBC_FLOATINGPOINT off, read their argument and print ? padded to the width. The old text was *float*.
  • %n reads its pointer, stores nothing and prints ?, padded to the width.
  • An unknown conversion has no known size. printf prints % and the character, prints the rest of the format as text, reads no more arguments and ends. A format that ends after %, a flag, a width or a length prints %, and no read goes past the end. This is always on: valid C23 formats that NuttX does not understand yet, such as %w64d and decimal floating point, take this path, so they print as text and cannot misread a later %s.
  • A width above 255 gives the right length: %300d wrote 556 bytes. A three-digit exponent counts in the width: %12.1e of 1e100 wrote 13 bytes.
  • %.767e and %.0g no longer print a NUL byte, and %#.0x of 0 no longer reads buf[-1].
  • Width and precision stop at INT_MAX, also for * with INT_MIN and for a numbered *. Output above INT_MAX returns -1 with EOVERFLOW.
  • lib_bsprintf() no longer writes past its 64-byte conversion buffer. %pV and %pB count in the return value.

What is not fixed

  • scanf with %L.
  • A wrong argument from the caller, such as a bad pointer for %s or an argument of the wrong type: printf cannot detect it.
  • A legal %2147483647d prints in full, as the standard requires. A caller with a smaller buffer must use snprintf.
  • Output that is not correct but is safe: -0.0, a real %a, more than 15 digits, C23 %b and wN. These are later steps of [FEATURE] printf conformance: never crash, and options for flash size #21467.

Decisions

  • A numbered argument that the format does not use: its size is not known, so the place of the next arguments is not known. printf reads only the arguments before it, and a conversion with a later number ends the output, as a number above NL_ARGMAX does.
  • A width or precision with too many digits stops at INT_MAX, so %99999999999d writes INT_MAX bytes and returns INT_MAX. If the total then passes INT_MAX, the result is -1 with EOVERFLOW, and the output written before that stays. One conversion longer than INT_MAX fails before its output.
  • An integer conversion with L reads a long long, as in GNU libc.

Testing

The suite on sim arm64, master next to this PR:

C99 required Correctly rounded C23 POSIX XSI Bit-exact Crash Hang
master 61.73% 57.31% 1.08% 78.05% 36.36% 55.68% 27 0
this PR 67.81% 63.11% 1.08% 92.68% 36.36% 61.46% 0 0

No test goes from pass to fail. Six tests go from "not correctly rounded" to "fail": %.18Le, %.20Le, %.21Le and the same with E, of LDBL_EPSILON. Master printed 0 there, and this PR prints the value with 15 digits. The conversion of long double by hand gives the same output as the cast in all 45,084 tests.

The suite has no case for %2$s %1$x and it always builds with float on, so it has no case for float off with numbered on. A host harness covers both: the real sources under ASan and UBSan in 11 configurations of float, numbered arguments, locale and CONFIG_ARCH_ROMGETC, with valid, truncated, mutated and random formats, on gcc Linux arm64 and clang macOS, up to 322,000 cases per configuration. Master has about 500 to 1,150 reports per configuration in up to 4,200 cases. This PR has 0 reports. The test in nuttx-apps also covers %2$s %1$x, in ostest.

The conversion against the cast, on the target CPU: 4,126,084 values on arm64, rv32 and rv64, with 0 differences in the result bits. A NaN stays a NaN.

Runtime, a test program for these cases and ostest: qemu-armv8a:knsh (kernel), rv-virt:knsh64 (kernel), mps2-an500:knsh (protected). Flat: qemu-armv8a:nsh, and rv-virt:nsh with float and numbered arguments on and off, also float off with numbered on. Built: rv-virt:pnsh (protected).

Size

Master -> this PR:

CPU, config Float Numbered Image text vsprintf_internal stack lib_vsprintf stack
Cortex-M0, nucleo-f072rb:nsh off off 46668 -> 46736 (+68) 80 -> 88 8 -> 8
Cortex-M0, nucleo-f072rb:nsh off on 47288 -> 47392 (+104) 96 -> 96 64 -> 64
Cortex-M0, nucleo-f072rb:nsh on off 56784 -> 56888 (+104) 96 -> 96 8 -> 8
Cortex-M0, nucleo-f072rb:nsh on on 57440 -> 57568 (+128) 112 -> 112 64 -> 64
Cortex-M3, nucleo-f103rb:nsh off off 34320 -> 34476 (+156) 72 -> 72 0 -> 0
Cortex-M3, nucleo-f103rb:nsh off on 34940 -> 35056 (+116) 80 -> 80 56 -> 48
Cortex-M3, nucleo-f103rb:nsh on off 38404 -> 38620 (+216) 88 -> 88 0 -> 0
Cortex-M3, nucleo-f103rb:nsh on on 39076 -> 39212 (+136) 104 -> 104 56 -> 48
arm64, qemu-armv8a:nsh off off 357200 -> 357408 (+208) 160 -> 160 48 -> 48
arm64, qemu-armv8a:nsh off on 358228 -> 358532 (+304) 160 -> 160 160 -> 160
arm64, qemu-armv8a:nsh on off 359436 -> 359724 (+288) 176 -> 160 48 -> 48
arm64, qemu-armv8a:nsh on on 360568 -> 360984 (+416) 176 -> 176 160 -> 192
RISC-V 32, rv-virt:nsh off off 228214 -> 228374 (+160) 80 -> 80 0 -> 0
RISC-V 32, rv-virt:nsh off on 228918 -> 229110 (+192) 112 -> 112 48 -> 48
RISC-V 32, rv-virt:nsh on off 230006 -> 230450 (+444) 112 -> 144 0 -> 0
RISC-V 32, rv-virt:nsh on on 230696 -> 231342 (+646) 112 -> 144 48 -> 96
RISC-V 64, rv-virt:nsh64 off off 234712 -> 234868 (+156) 128 -> 128 0 -> 0
RISC-V 64, rv-virt:nsh64 off on 235372 -> 235524 (+152) 160 -> 160 80 -> 80
RISC-V 64, rv-virt:nsh64 on off 236400 -> 236782 (+382) 160 -> 144 0 -> 0
RISC-V 64, rv-virt:nsh64 on on 237098 -> 237512 (+414) 176 -> 176 80 -> 128

The growth is the new checks. No CPU pulls in the soft-float code of libgcc: the long double conversion is integer code, which adds 154 to 274 bytes when long double is binary128. A cast would add 854 to 1268 bytes more.

The conversion by hand applies when LDBL_MANT_DIG is 113: measured on arm64, rv32 and rv64. Cortex-M0, Cortex-M3, Cortex-A9 and Xtensa have 53, so long double is double there, and x86_64 has 64: a cast stays, with no cost on the first ones.

On rv32 the stack of vsprintf_internal goes from 112 to 144 with float on, in the two long double commits only. A long double has 16 bytes there and the ABI passes it by reference, so the function needs copies of it on its stack. With float and numbered arguments on, the stack of lib_vsprintf also grows: arm64 160 -> 192, rv32 48 -> 96, rv64 80 -> 128. On rv32 this comes with the %L commit; the reason is read from the code, because that function reads the long double for the conversion.

Impact

Only the output of formats that were wrong or undefined changes. No code in nuttx or nuttx-apps depends on *float*. This PR updates two sample outputs in the board documentation and the help text of LIBC_FLOATINGPOINT. No API and no Kconfig change.

@casaroli
casaroli force-pushed the printf-safety-up branch 2 times, most recently from 1871fa8 to 8f76445 Compare November 5, 2026 04:16
@github-actions github-actions Bot added Area: Documentation Improvements or additions to documentation Size: M The size of the change in this PR is medium labels Nov 5, 2026
anchao
anchao previously approved these changes Nov 5, 2026
@github-actions

github-actions Bot commented Nov 5, 2026 •

Copy link
Copy Markdown

MemBrowse Memory Report · Explore what changed →

arduino-mega2560

  • flash: .data -8 B, .text +158 B (+0.2%, 66,589 B / 262,144 B, total: 25% used)
  • sram: .data -8 B (-0.3%, 2,787 B / 8,192 B, total: 34% used)

esp32-devkitc

  • ROM: .flash.text +160 B (+0.1%, 129,412 B / 4,194,272 B, total: 3% used)
  • irom0_0_seg: .flash.text +160 B (+0.2%, 95,260 B / 3,342,304 B, total: 3% used)

hifive1-revb

  • flash: .text +248 B (+0.3%, 86,080 B / 4,194,304 B, total: 2% used)

mirtoo

  • kseg0_progmem: .text +8 B (+0.0%, 68,484 B / 131,072 B, total: 52% used)

qemu-armv8a

  • Code: .text.vsprintf_internal.constprop.0 +476 B, .text.vsprintf_putnum +4 B (+0.1%, 360,916 B)

qemu-intel64

  • Code: .text +640 B (+0.0%, 8,694,079 B)

rx65n-rsk2mb

  • ROM: .rodata -4 B, .text +176 B (+0.2%, 91,688 B / 2,097,152 B, total: 4% used)

s698pm-dkit

  • Code: .text +512 B (+0.1%, 389,840 B)

stm32-nucleo-f103rb

  • flash: .text +20 B (+0.1%, 34,892 B / 131,072 B, total: 27% used)

Catch memory regressions in CI with MemBrowse. Free for open source.

Comment thread libs/libc/stream/lib_libvsprintf.c Resolved
Comment thread libs/libc/stream/lib_libvsprintf.c Resolved
Comment thread libs/libc/stream/lib_libvsprintf.c Resolved
Comment thread libs/libc/stream/lib_libvsprintf.c Resolved
Comment thread libs/libc/stream/lib_libvsprintf.c Resolved
nxstyle reports "Bad left brace alignment" on this union, and the check
covers each file that a change touches.  The error is older than the
change that follows.  This commit changes only white space.

Assisted-by: Claude Code:claude-opus-5-5
Signed-off-by: Marco Casaroli <[email protected]>
printf() has no %n.  It went to the path of the unknown conversions.
This path takes an unsigned int, or with %lln a long long, and prints
the conversion as text.  The argument is a pointer.  On a 32-bit CPU
%hhn and %lln take the wrong size, and the next arguments are wrong: a
later %s then uses a value that is not a pointer.

Take the pointer for %n of any length, and print "?", padded to the
width.  Do not store through it, so a format string cannot write to
memory, and the output shows that the count is not available.

Part of apache#21467

Assisted-by: Claude Code:claude-opus-5-5
Signed-off-by: Marco Casaroli <[email protected]>
With CONFIG_LIBC_NUMBERED_ARGS on and CONFIG_LIBC_FLOATINGPOINT off,
"%f %s" did not take the double.  The %s after it then used a wrong
argument as a pointer.  The code took the double only when numbered
arguments were off, but a conversion without a number has its argument
in the va_list in both cases.

Take the double unless the conversion has an argument number.

Part of apache#21467

Assisted-by: Claude Code:claude-opus-5-5
Signed-off-by: Marco Casaroli <[email protected]>
printf() has no %a.  It went to the path of the unknown conversions,
which takes an unsigned int.  The argument is a double, and on arm64,
RISC-V and x86_64 it is in a floating point register.  The next %s used
a wrong general register as a pointer, and printf() crashed.

Take the double for %a and %A and print "?", padded to the width.  With
CONFIG_LIBC_FLOATINGPOINT off, do the same for %e, %f and %g, in place
of the text "*float*".  So a conversion that is not available has one
behavior, and the rest of the line stays correct.

Part of apache#21467

Assisted-by: Claude Code:claude-opus-5-5
Signed-off-by: Marco Casaroli <[email protected]>
lib_vsprintf() reads the numbered arguments between two passes over the
format, with the types from the first pass.  arglist.type[] had no
initial value, and the first pass had no type for %x, %X, %o, %S and %n
and for an argument number that the format does not use.  So "%2$s %1$x"
skipped an argument or read one with a size from uninitialized memory,
and the %s got a wrong pointer.  "%2$s%1$n" printed from an uninitialized
stack.

Clear arglist.type[] and record the type of these conversions.  At a
number that the format does not use, the size is not known and the
place of the next arguments is also not known: read only the arguments
before it.  A conversion with a number after that ends the output, as a
number above NL_ARGMAX does.

Part of apache#21467

Assisted-by: Claude Code:claude-opus-5-5
Signed-off-by: Marco Casaroli <[email protected]>
An unknown conversion took an unsigned int, printed the conversion as
text and went on.  Its argument can have any size, so the arguments
after it were wrong, and a later %s could use a wrong pointer.  This also
hits a valid format of a newer standard that printf() does not know yet:
%w64d %s on a 32-bit CPU, %w32d %s where int has 16 bits, %Hf %s on arm64.

A format that ends after "%", a flag, a width or a length, such as "%"
or "%5", was the same case with a NUL as the conversion.  The output got
a NUL, and the next loop read the format past its end.  The first pass
for the numbered arguments also read past the end.

Now print "%" and the character, print the rest of the format as text,
take no more arguments, and end.  At the end of the format, print only
"%".  The first pass stops at the same place.

Part of apache#21467

Assisted-by: Claude Code:claude-opus-5-5
Signed-off-by: Marco Casaroli <[email protected]>
The digits of a width or a precision had no limit: "%99999999999d" had a
signed overflow, and the width became a wrong value.  A width of INT_MIN
from "%*d" had a signed overflow when printf() negated it.

A numbered "*" did not check the value: "%2$.*1$e" with a negative value
gave a negative precision, and "%2$*1$d" did not left-justify.

Keep the value at INT_MAX in the digits and for INT_MIN.  Use one path
for the value of "*", with or without a number, and for the digits, so
all later code gets a width and a precision from 0 to INT_MAX.  The one
path also makes the code smaller.

Part of apache#21467

Assisted-by: Claude Code:claude-opus-5-5
Signed-off-by: Marco Casaroli <[email protected]>
vsprintf_internal() kept the length of an integer conversion in an
unsigned char.  A width above 255 is truncated, but the padding uses the
full width: "%300d" wrote 556 bytes and "%4095d" wrote 7935 bytes.  A
sprintf() into a buffer that has the size of the width overflows.

Use an unsigned int.  It holds a width of INT_MAX and the prefix.

Part of apache#21467

Assisted-by: Claude Code:claude-opus-5-5
Signed-off-by: Marco Casaroli <[email protected]>
The C standard takes a precision of 0 as 1 for %g.  printf() asked
__dtoa_engine() for 0 digits, and "%.0g" of 1.5 printed a NUL byte and
"e+00".

Ask for 1 digit.

Part of apache#21467

Assisted-by: Claude Code:claude-opus-5-5
Signed-off-by: Marco Casaroli <[email protected]>
vsprintf_internal() kept the number of digits in a uint8_t, and set it
from the precision before it applied the limit.  "%.255e" and "%.767e"
asked for 0 digits, so the output began with a NUL byte.  "%.256f" asked
for no limit of decimals and "%.257f" for 1 decimal.

Apply the limit first, and use an unsigned int.

Part of apache#21467

Assisted-by: Claude Code:claude-opus-5-5
Signed-off-by: Marco Casaroli <[email protected]>
…sion.

A float conversion had signed overflows with a precision near INT_MAX: in
the length of the conversion, and in exp - n, which is the digit index.

Use an unsigned int for the length.  Use unsigned arithmetic for the
index: a value below 0 becomes large, so one compare has the job of two.

Part of apache#21467

Assisted-by: Claude Code:claude-opus-5-5
Signed-off-by: Marco Casaroli <[email protected]>
A float conversion in the exponent form took the exponent as two digits
for the padding.  "%12.1e" of 1e100 wrote 13 bytes.  A sprintf() into a
buffer that has the size of the width overflows by one byte.

Add one for an exponent with three digits.

Part of apache#21467

Assisted-by: Claude Code:claude-opus-5-5
Signed-off-by: Marco Casaroli <[email protected]>
printf() added each part of the output to an int, without a limit.
"%*d%*d" with two large widths had a signed overflow and returned a
negative value that is not -1.  A caller of vasprintf() or of snprintf()
then uses a wrong size.

Keep the total in a size_t.  Stop when it passes INT_MAX, and then return
-1 with errno set to EOVERFLOW, as POSIX specifies.  A conversion with a
length above INT_MAX fails before its output, so one conversion adds at
most INT_MAX and the total does not wrap.

Part of apache#21467

Assisted-by: Claude Code:claude-opus-5-5
Signed-off-by: Marco Casaroli <[email protected]>
A value of 0 with a precision of 0 has no digits, so c is 0, and the check
for a first digit of 0 read buf[-1].  The result was the prefix or none,
from the value of that byte.  %p with a precision and a NULL has the same
problem.

With no digits, drop the 0x prefix.  %#.0o keeps its "0": the C standard
requires it.

Part of apache#21467

Assisted-by: Claude Code:claude-opus-5-5
Signed-off-by: Marco Casaroli <[email protected]>
lib_bsprintf() copies a conversion to a buffer of 64 bytes, without a
limit, and each "*" adds the digits of an int.  "%" and 100 digits wrote
past the buffer on the stack.

End the output at a conversion that does not fit.

Part of apache#21467

Assisted-by: Claude Code:claude-opus-5-5
Signed-off-by: Marco Casaroli <[email protected]>
%pV and %pB did not add their output to the return value.  vasprintf() has
an assertion that the return value is the same as the count of the null
stream, so asprintf() with %pV crashes when the assertions are on.  The
return value of the other functions was too small.

Add the output of these conversions to the total.

Part of apache#21467

Assisted-by: Claude Code:claude-opus-5-5
Signed-off-by: Marco Casaroli <[email protected]>
printf() took %Lf, %Le, %Lg and %La as double conversions: the L modifier
set the same flag as l, and the conversion read the argument with
va_arg(ap, double).  A long double has a different size and is passed in
a different place on arm64, RISC-V and x86_64.  The output was wrong, and
the arguments after it were also wrong.  On arm64 and RISC-V the low 64
bits of a binary128 value, taken as a double, can have more than 300
digits, and a buffer of the correct size for the number then overflows.

Now L sets the flags of ll.  A floating point conversion with these flags
takes a long double, also in a numbered argument.  An integer conversion
with L takes a long long, as in GNU libc: it was a long, which is smaller
on a 32-bit CPU.

The conversion to double means that the output has the precision and the
range of a double.  If CONFIG_HAVE_LONG_DOUBLE is not defined, nothing
changes for a floating point conversion.

Part of apache#21467

Assisted-by: Claude Code:claude-opus-5-5
Signed-off-by: Marco Casaroli <[email protected]>
The cast from a binary128 long double to double calls __trunctfdf2() in
libgcc.  It adds more than 1 KiB to each image with floating point in
printf(), also when no format uses %Lf.

Convert it with integer code when long double is binary128: on arm64 and
RISC-V.  It rounds to nearest with ties to even, as the cast does, and it
does not set the floating point exception flags.  A long double of any
other format still uses a cast.

With floating point on, this saves 916 bytes of image text on arm64, 1268
on rv32 and 854 on rv64.

Part of apache#21467

Assisted-by: Claude Code:claude-opus-5-5
Signed-off-by: Marco Casaroli <[email protected]>
The hx711 example output of two boards has the text that printf() printed
for a floating point conversion with CONFIG_LIBC_FLOATINGPOINT off.  This
text is now "?".

Assisted-by: Claude Code:claude-opus-5-5
Signed-off-by: Marco Casaroli <[email protected]>
@github-actions github-actions Bot added Size: L The size of the change in this PR is large and removed Size: M The size of the change in this PR is medium labels Nov 5, 2026
@xiaoxiang781216

Copy link
Copy Markdown
Contributor

@casaroli @anchao which pr should we merge first? this one or #21340.

@anchao

anchao commented Nov 6, 2026

Copy link
Copy Markdown
Contributor

@xiaoxiang781216 @casaroli Please merge this first. thanks for the fix.

@xiaoxiang781216
xiaoxiang781216 merged commit 3e04c33 into apache:master Nov 6, 2026
54 checks passed
xiaoxiang781216 pushed a commit that referenced this pull request Nov 9, 2026
…off.

Since #21474, printf() takes the pointer of %n, stores nothing and prints
"?" when LIBC_PRINTF_PERCENT_N is off.  But the correct output of %n is
empty, so "?" changes the text and the return value of the call.  The
safety comes from the missing store, not from the "?".

Now %n prints nothing also with the option off.  It still reads its pointer
and stores nothing.  With the option on nothing changes: %n stores the count
and prints nothing.  A width or flags on %n have no effect, as C leaves
them undefined.

Update the help of the option.

Part of #21467

Assisted-by: Claude Code:claude-opus-5-5
Signed-off-by: Marco Casaroli <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Area: Documentation Improvements or additions to documentation Size: L The size of the change in this PR is large

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants