Skip to content

[FEATURE] printf conformance: never crash, and options for flash size #21467

Closed

Description

@casaroli

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 %.Ne with a precision of 255 or more.
  • %#.0x of 0 reads buf[-1].
  • %.0g writes a NUL byte.
  • %n is printed as text, and the arguments after it are then misread.
  • %Lf reads a long double as a double.
  • -0.0 loses its sign.
  • There is no %a, and output has only 15 significant digits.

Rules

  1. A correct call of printf never crashes or hangs, in any configuration.
  2. The Default profile keeps every feature it has today: floating point with !DEFAULT_SMALL && ARCH_FPU. Existing configurations do not change.
  3. 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, %n and %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 %b and %wN with their argument sizes, each behind its option
  • Exact floating point behind its option, after a discussion here
  • Documentation: how printf works, 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

  1. added
    Type: Enhancement
    on Nov 5, 2026
  2. anchao commented on Nov 5, 2026

    @anchao
    Contributor

    @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.

  3. anchao commented on Nov 5, 2026

    @anchao
    Contributor

    @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.

  4. casaroli commented on Nov 5, 2026

    @casaroli
    ContributorAuthor

    @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 printf work with wrong usage. If the caller passes an argument of the wrong type for its conversion, or a bad pointer for %s, printf cannot 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 printf is used correctly, it never crashes, in any configuration. A correct call must be safe even when the feature is disabled. For example, passing a long double or a double to a minimal printf must 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: %a reads an integer, so %s gets 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.

  5. anchao commented on Nov 5, 2026

    @anchao
    Contributor

    @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:

          println!("{:?}|{}", 1.0, "x");   // OK                                                                                                                                            
          println!("{:x}|{}", 1.0, "x");   // error: `{x}` (LowerHex) is not implemented for `{float}`                                                                                      
          println!("{}|{}", 1.0);          // error: 2 positional arguments in format string, but there is 1 argument                                                                       
          println!("{}", 1.0, "x");        // error: argument never used                                                                                                                    
    

    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.

  6. casaroli commented on Nov 5, 2026

    @casaroli
    ContributorAuthor

    @anchao i have updated the design description.

    BTW are you on discord?

  7. casaroli commented on Nov 5, 2026

    @casaroli
    ContributorAuthor

    @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.

    char buf[301];
    
    sprintf(buf, "%300d", 1);             /* the width fits the buffer, and 556 bytes are written */
    printf("%a|%s\n", 1.0, "x");          /* %a is in C99 and takes a double; %s gets a wrong pointer on arm64 */
    printf("%Lf|%s\n", 1.5L, "x");        /* %Lf takes a long double, and it is read as a double */

    The compiler will not solve these, because there is nothing wrong in the code. GCC 13.2 with -Wall -Wextra -Wformat=2 -Wformat-overflow=2 and Clang 22 with -Wall -Wextra -Wformat=2 compile them with no warning. The bug is in printf, and no developer, experienced or not, can avoid it without knowing the code of printf.

    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 printf must handle it. If the compiler warns, it is wrong usage.

  8. 122 remaining items

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

Type: Enhancement

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions