From a3a6ed358288f6be39afcc34b3013b6dfa3413a9 Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Fri, 27 Feb 2026 12:40:58 -1000 Subject: [PATCH] Extract common buffer write + overflow check into helper --- esphome/components/esp32/printf_stubs.cpp | 35 +++++++++++------------ 1 file changed, 16 insertions(+), 19 deletions(-) diff --git a/esphome/components/esp32/printf_stubs.cpp b/esphome/components/esp32/printf_stubs.cpp index d85e92aacd..8fc303cfe9 100644 --- a/esphome/components/esp32/printf_stubs.cpp +++ b/esphome/components/esp32/printf_stubs.cpp @@ -33,22 +33,26 @@ namespace esphome::esp32 {} static constexpr size_t PRINTF_BUFFER_SIZE = 512; +// Write formatted buffer to stream, aborting on overflow. +static int write_printf_buffer_(FILE *stream, char *buf, int len) { + if (len < 0) { + return len; + } + if (static_cast(len) >= PRINTF_BUFFER_SIZE) { + // Output was truncated — this should not happen in normal operation. + // Abort to make the issue visible rather than silently losing output. + esp_system_abort("printf buffer overflow; set enable_full_printf: true in esp32 advanced config"); + } + fwrite(buf, 1, len, stream); + return len; +} + // NOLINTBEGIN(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp,readability-identifier-naming) extern "C" { int __wrap_vprintf(const char *fmt, va_list ap) { char buf[PRINTF_BUFFER_SIZE]; - int len = vsnprintf(buf, sizeof(buf), fmt, ap); - if (len < 0) { - return len; - } - if (static_cast(len) >= sizeof(buf)) { - // Output was truncated — this should not happen in normal operation. - // Abort to make the issue visible rather than silently losing output. - esp_system_abort("printf buffer overflow; set enable_full_printf: true in esp32 advanced config"); - } - fwrite(buf, 1, len, stdout); - return len; + return write_printf_buffer_(stdout, buf, vsnprintf(buf, sizeof(buf), fmt, ap)); } int __wrap_printf(const char *fmt, ...) { @@ -63,15 +67,8 @@ int __wrap_fprintf(FILE *stream, const char *fmt, ...) { va_list ap; va_start(ap, fmt); char buf[PRINTF_BUFFER_SIZE]; - int len = vsnprintf(buf, sizeof(buf), fmt, ap); + int len = write_printf_buffer_(stream, buf, vsnprintf(buf, sizeof(buf), fmt, ap)); va_end(ap); - if (len < 0) { - return len; - } - if (static_cast(len) >= sizeof(buf)) { - esp_system_abort("fprintf buffer overflow; set enable_full_printf: true in esp32 advanced config"); - } - fwrite(buf, 1, len, stream); return len; }