Repository navigation
Description
Summary
printf in NuttX can hang, can read outside a buffer, and gives wrong output for valid formats. I want to fix this in small steps, with a test suite to measure each step, and without growth on small boards. This issue holds the plan and links the PRs. Comments on the plan are welcome before the larger steps.
The measurement
The suite is https://github.com/casaroli/printf-report: 45,084 tests, each tagged with the document that requires the behaviour (C99, C23, POSIX), and expected results that come from a model of the standard text, not from another C library. The published run of NuttX 13.1 on sim, with LIBC_FLOATINGPOINT, LIBC_NUMBERED_ARGS and LIBC_LOCALE:
| Measure | Result |
|---|---|
| C99 required | 61.70% |
| Correctly rounded | 57.28% |
| C23 | 1.08% |
| POSIX | 65.85% |
| XSI | 36.36% |
| Tests that crash or hang | 42 |
Findings from that report, each reproduced with a standalone program. Some code has changed since, so the first step runs the suite again on current master:
- It hangs on integer widths of 256 or more, and on
%.Newith a precision of 255 or more. %#.0xof 0 readsbuf[-1].%.0gwrites a NUL byte.%nis printed as text, and the arguments after it are then misread.%Lfreads along doubleas adouble.-0.0loses its sign.- There is no
%a, and output has only 15 significant digits.
Rules
- A correct call of
printfnever crashes or hangs, in any configuration. - The Default profile keeps every feature it has today: floating point with
!DEFAULT_SMALL && ARCH_FPU. Existing configurations do not change. - Default grows in flash only by the safety fixes, a few bytes. Each PR shows flash and stack, and any growth has a reason.
A wrong argument is outside rule 1: printf cannot detect a bad pointer for %s or an argument of the wrong type, and the documentation will say so. A legal %2147483647d prints in full, as the standard requires, so it can take a long time but it ends. Output above INT_MAX returns -1 with EOVERFLOW.
Design
The grammar of valid formats is not optional. A crash of a correct call comes from a format that is misread, not from a missing feature.
- Always on: the grammar of valid formats, and each argument read at its right size.
- A conversion that is disabled or removed still reads its argument, then prints one
?padded to the width, so the rest of the line stays correct. - An unknown conversion has no known size, so the rest of the format is printed as text and no more arguments are read. Nothing reads past the end of the format. This is always on, not an option: valid C23 formats that NuttX does not understand yet, such as
%w64d, take this path, so they stay safe.
The features are options, and a profile only sets their defaults:
| Profile | What it has |
|---|---|
| Minimal | Today's code with things removed. Each removal has a measured saving |
| Default | Today's code with the safety fixes |
| Full | Everything |
On Minimal or Default a user can add any feature one by one. LIBC_FLOATINGPOINT and LIBC_NUMBERED_ARGS keep their names.
| Option | Note |
|---|---|
| 64-bit integers on 32-bit CPUs | A candidate for Minimal. printf alone needs at most 496 bytes of division on Cortex-M0 and 48 on Cortex-M3 |
| Floating point: none, as today, exact | Exact rounding costs stack and flash |
%a |
Separate from exact rounding |
long double |
Only where it differs from double |
| Wide characters | |
| Positional arguments | LIBC_NUMBERED_ARGS |
Locale and ' grouping |
|
%n |
Off by default: it reads its pointer, stores nothing and prints ?. An option marked as dangerous really stores the count |
C23 %b and %wN |
Nothing in the tree uses them today |
What Minimal removes is measured first, so this list can change. Today, on a whole image, floating point costs 10,116 bytes on Cortex-M0, 4,084 on Cortex-M3, 2,136 on arm64 and 1,792 on rv32.
Steps
One topic in each PR:
- Safety for correct usage: all of today's features stay, no new options, a few more bytes. Each argument is read at its right size, including
%a,%nand%L. Unknown conversions and truncated formats stop cleanly - Options and profiles: Minimal, Default and Full, the existing features behind options, and what Minimal removes. No change in Default
- Output:
-0.0, then%a, and C23%band%wNwith their argument sizes, each behind its option - Exact floating point behind its option, after a discussion here
- Documentation: how
printfworks, with many examples: the conversions, what each option and profile prints,?for a disabled conversion, what is wrong usage, and the flash and stack cost
A new feature comes in off in the Default profile, so it does not grow the default configuration.
Tests: the suite on each profile with 0 crashes and hangs, a fuzz run on the host under ASan and UBSan, and a test in nuttx-apps where CI can run it.
scanf probably needs the same work after printf: it is not part of these steps.
Alternatives
- One large PR: hard to review, and it conflicts with other work in the file.
- All of it always on: it grows the small boards.
- A new library for
printf: more risk than a fix, and the small boards still need a small path.
Related
#21340 refactors the same file. The order of that PR and these steps is for its author and me to agree.
Activity
anchao commentedon Nov 5, 2026
@casaroli
Thanks for putting together such a detailed plan, and for the comprehensive test results.
Just to clarify my own intention behind #21340: my main goals were to make vsprintf_internal() easier to modularize and read through configuration, and at the same time to improve performance and reduce stack usage. Beyond that I don't have a strong attachment to a particular structure.
[One thing I'm not sure about, though, is how your plan interacts with #21340 — specifically whether it matters if your refactoring is done before or after my change is (or isn't) merged. If your ordering assumptions depend on my PR, it would be good to align on that.]
To be clear, I don't need my PR to be merged at all. The current changes were largely produced with AI assistance anyway, so there's no investment on my side to protect. If your framework/structure is better and can also address the goals I was trying to solve (modularity, readability, performance, stack usage), then I'm happy to go with your approach.
anchao commentedon Nov 5, 2026
@casaroli @xiaoxiang781216
I'd also like to share a slightly different view on the Safety part. For a foundational function like printf, making it resilient against every kind of malformed argument would require adding a lot of defensive/security-redundant code in all the boundary cases. For IoT devices that care about flash size and code footprint, that's kind of a nightmare. I think if a system crash or hang is caused by the user passing wrong arguments, then the developer who wrote that code should bear the consequences — rather than pushing that cost onto every device that links in printf.
casaroli commentedon Nov 5, 2026
@anchao Thanks for the reply. We agree: safety is a tradeoff with flash size, and small devices must not pay for it without a reason.
We do not aim to make
printfwork with wrong usage. If the caller passes an argument of the wrong type for its conversion, or a bad pointer for%s,printfcannot detect it, and that remains the developer's bug. Unknown conversions and truncated formats are wrong usage too, so they are not part of this step. They can come later, behind an option.What we want is this: if
printfis used correctly, it never crashes, in any configuration. A correct call must be safe even when the feature is disabled. For example, passing along doubleor adoubleto a minimalprintfmust read the argument at its right size and print?in the worst case, so the arguments after it stay correct. Today it does not hold:printf("%a|%s", 1.0, "x")on arm64:%areads an integer, so%sgets a wrong pointer. 27 tests of the suite crash this way on sim arm64.sprintf(buf, "%300d", 1)writes 556 bytes, not 300, past a correctly sized buffer.In our measurements so far, the first step of the plan costs at most 152 bytes of image text on Cortex-M0 and 232 on Cortex-M3, with float and numbered arguments on or off. Larger features come later, behind options that are off by default, so they do not grow the small boards.
anchao commentedon Nov 5, 2026
@casaroli
Thanks for the clarification — and I agree with "if printf is used correctly, it never crashes." My point is more about where the boundary should be drawn and how we decide what's worth fixing.
Several of the cases you cite (e.g. a %300d overrun, a width/argument mismatch, a wrong type for a given conversion) are really programmer errors — the format string and the arguments don't agree. In a language like Rust this class of bug is caught at compile time, not at runtime:
C pushed a lot of this memory burden onto the developer by design. It's no coincidence that GCC/Clang have been steadily adding compile-time checks for common libc functions over the past few releases — they're slowly catching up because they can solve these at the language level. The legacy constraints are exactly why they're moving cautiously.
My view is this: if these problems are eventually going to be solved by the compiler, then we probably shouldn't spend firmware flash budget defending against code that only an inexperienced developer would write anyway — and that AI, if anything, writes even less of.
casaroli commentedon Nov 5, 2026
@anchao i have updated the design description.
BTW are you on discord?
casaroli commentedon Nov 5, 2026
@anchao The cases we listed are not programmer errors. They are all valid C: the format and the arguments agree, as in your first Rust example.
The compiler will not solve these, because there is nothing wrong in the code. GCC 13.2 with
-Wall -Wextra -Wformat=2 -Wformat-overflow=2and Clang 22 with-Wall -Wextra -Wformat=2compile them with no warning. The bug is inprintf, and no developer, experienced or not, can avoid it without knowing the code ofprintf.We agree on the rest. A wrong type for a conversion, an unknown conversion and a truncated format are programmer errors, and the same compilers warn about them with
-Wall. We spend no flash on the wrong types, and the other two move behind an option.So this is the boundary: if the compiler accepts the call, it is correct usage and
printfmust handle it. If the compiler warns, it is wrong usage.libs/libc/stream: Take the pointer of %n and store nothing.
libs/libc/stream: Take the double of %f without floating point.
libs/libc/stream: Take the argument of %a and print a question mark.
libs/libc/stream: Record the type of each numbered argument.
libs/libc/stream: Limit the width and the precision to INT_MAX.
libs/libc/stream: Do not truncate the length of an integer conversion.
122 remaining items
libs/libc/stdio: Let vdprintf() work without a buffer.
libs/libc/stream: Read a long as an int where they have the same size.
libs/libc/stream: Print the sign of a negative zero in printf().
libs/libc/stream: Add an option for %a and %A in printf().
libs/libc/stream: Add an option for %b and %B of C23 in printf().
libs/libc/stream: Add the C23 wN and wfN lengths to printf().
libs/libc/stream: Read a long double for the L length in scanf().
libs/libc/stream: Add a dangerous option for %n in printf().
Documentation: Add a page on printf.
libs/libc/stream: Move the output of %e, %f and %g to functions.
libs/libc/stream: Print floating point on the bits with integers.
libs/libc/stream: Add an option for exact floating point in printf().
libs/libc/stream: Add an option for exact long double in printf().
Documentation: Update the page on printf for the new engine.
testing/libc/printftest: Add a test of printf() for unknown and large…