Extract common buffer write + overflow check into helper

This commit is contained in:
J. Nick Koston
2026-02-27 12:40:58 -10:00
parent 9f11dc736f
commit a3a6ed3582
+16 -19
View File
@@ -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<size_t>(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<size_t>(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<size_t>(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;
}