From cc02dc0a55a95bdd13a3856ba930c9ef923b3b67 Mon Sep 17 00:00:00 2001 From: Abdullah Ahmed <92085834+abd-770@users.noreply.github.com> Date: Wed, 4 Sep 2024 05:45:04 +0530 Subject: [PATCH] fix: Handle Input/Output Errors in vsnprintf and snprintf (#35898) Fix for Issue: #35897 --- internal/core/src/log/Log.cpp | 32 ++++++++++++++++++++++++++------ 1 file changed, 26 insertions(+), 6 deletions(-) diff --git a/internal/core/src/log/Log.cpp b/internal/core/src/log/Log.cpp index 68ac1b21cc827..64192107e1328 100644 --- a/internal/core/src/log/Log.cpp +++ b/internal/core/src/log/Log.cpp @@ -46,9 +46,20 @@ LogOut(const char* pattern, ...) { va_list vl; va_start(vl, pattern); - vsnprintf(str_p.get(), len, pattern, vl); // NOLINT + int result = vsnprintf(str_p.get(), len, pattern, vl); // NOLINT va_end(vl); + if (result < 0) { + std::cerr << "Error: vsnprintf failed to format the string." + << std::endl; + return "Formatting Error"; + } else if (static_cast(result) >= len) { + std::cerr + << "Warning: Output was truncated. Buffer size was insufficient." + << std::endl; + return "Truncated Output"; + } + return {str_p.get()}; } @@ -98,11 +109,20 @@ get_thread_starttime() { int64_t pid = getpid(); char filename[256]; - snprintf(filename, - sizeof(filename), - "/proc/%lld/task/%lld/stat", - (long long)pid, // NOLINT, TODO: How to solve this? - (long long)tid); // NOLINT + int ret_snprintf = + snprintf(filename, + sizeof(filename), + "/proc/%lld/task/%lld/stat", + (long long)pid, // NOLINT, TODO: How to solve this? + (long long)tid); // NOLINT + + if (ret_snprintf < 0 || + static_cast(ret_snprintf) >= sizeof(filename)) { + std::cerr << "Error: snprintf failed or output was truncated when " + "creating filename." + << std::endl; + throw std::runtime_error("Failed to format filename string."); + } int64_t val = 0; char comm[16], state;