Repository navigation
libs/libc/stream: Fix the crashes and overflows of printf() for correct calls. - #21474
Merged
Merged
Conversation
casaroli
requested review from
acassis,
anchao,
linguini1,
raiden00pl,
rcsim and
xiaoxiang781216
as code owners
November 5, 2026 04:06
casaroli
force-pushed
the
printf-safety-up
branch
2 times, most recently
from
November 5, 2026 04:16
1871fa8 to
8f76445
Compare
5 tasks done
anchao
previously approved these changes
Nov 5, 2026
|
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]>
casaroli
force-pushed
the
printf-safety-up
branch
from
November 5, 2026 06:12
8f76445 to
f4044a0
Compare
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]>
casaroli
force-pushed
the
printf-safety-up
branch
from
November 5, 2026 20:20
f4044a0 to
e472b5f
Compare
Contributor
Contributor
|
@xiaoxiang781216 @casaroli Please merge this first. thanks for the fix. |
anchao
approved these changes
Nov 6, 2026
xiaoxiang781216
approved these changes
Nov 6, 2026
This was referenced Nov 6, 2026
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]>
1 task done
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
This PR gives
printffull 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
%aand%A,%nof any length,%Las along double, and all numbered arguments, also%x,%X,%o,%Sand%n.%aand%A, and%e,%f,%gwithCONFIG_LIBC_FLOATINGPOINToff, read their argument and print?padded to the width. The old text was*float*.%nreads its pointer, stores nothing and prints?, padded to the width.printfprints%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%w64dand decimal floating point, take this path, so they print as text and cannot misread a later%s.%300dwrote 556 bytes. A three-digit exponent counts in the width:%12.1eof 1e100 wrote 13 bytes.%.767eand%.0gno longer print a NUL byte, and%#.0xof 0 no longer readsbuf[-1].INT_MAX, also for*withINT_MINand for a numbered*. Output aboveINT_MAXreturns -1 withEOVERFLOW.lib_bsprintf()no longer writes past its 64-byte conversion buffer.%pVand%pBcount in the return value.What is not fixed
scanfwith%L.%sor an argument of the wrong type:printfcannot detect it.%2147483647dprints in full, as the standard requires. A caller with a smaller buffer must usesnprintf.-0.0, a real%a, more than 15 digits, C23%bandwN. These are later steps of [FEATURE] printf conformance: never crash, and options for flash size #21467.Decisions
printfreads only the arguments before it, and a conversion with a later number ends the output, as a number aboveNL_ARGMAXdoes.INT_MAX, so%99999999999dwritesINT_MAXbytes and returnsINT_MAX. If the total then passesINT_MAX, the result is -1 withEOVERFLOW, and the output written before that stays. One conversion longer thanINT_MAXfails before its output.Lreads along long, as in GNU libc.Testing
The suite on sim arm64, master next to this PR:
No test goes from pass to fail. Six tests go from "not correctly rounded" to "fail":
%.18Le,%.20Le,%.21Leand the same withE, ofLDBL_EPSILON. Master printed 0 there, and this PR prints the value with 15 digits. The conversion oflong doubleby hand gives the same output as the cast in all 45,084 tests.The suite has no case for
%2$s %1$xand 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 andCONFIG_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:
vsprintf_internalstacklib_vsprintfstackThe growth is the new checks. No CPU pulls in the soft-float code of libgcc: the
long doubleconversion is integer code, which adds 154 to 274 bytes whenlong doubleis binary128. A cast would add 854 to 1268 bytes more.The conversion by hand applies when
LDBL_MANT_DIGis 113: measured on arm64, rv32 and rv64. Cortex-M0, Cortex-M3, Cortex-A9 and Xtensa have 53, solong doubleisdoublethere, and x86_64 has 64: a cast stays, with no cost on the first ones.On rv32 the stack of
vsprintf_internalgoes from 112 to 144 with float on, in the twolong doublecommits only. Along doublehas 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 oflib_vsprintfalso grows: arm64 160 -> 192, rv32 48 -> 96, rv64 80 -> 128. On rv32 this comes with the%Lcommit; the reason is read from the code, because that function reads thelong doublefor 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 ofLIBC_FLOATINGPOINT. No API and no Kconfig change.