From bce90f172699c8094668fbedafcd11fc743588b5 Mon Sep 17 00:00:00 2001 From: Johannes Stoelp Date: Wed, 18 Oct 2023 18:47:10 +0200 Subject: log: fix -Wformat-security lint and remove lint excuse --- log.h | 32 +++++++++++++++++++++++++------- test/log.cc | 1 + 2 files changed, 26 insertions(+), 7 deletions(-) diff --git a/log.h b/log.h index 6aca9ea..3e26501 100644 --- a/log.h +++ b/log.h @@ -75,6 +75,25 @@ constexpr inline Arg sanitize_fmt_args(Arg arg) { return arg; } +template +struct formatter { + template + std::size_t operator()(char* str, + std::size_t size, + const char* fmt, + Args... args) { + static_assert(sizeof...(Args) == N, ""); + return std::snprintf(str, size, fmt, args...); + } +}; + +template <> +struct formatter<0> { + std::size_t operator()(char* str, std::size_t size, const char* fmt) { + return std::snprintf(str, size, "%s", fmt); + } +}; + // -- TIME STAMP HELPER -------------------------------------------------------- template @@ -112,7 +131,7 @@ struct time_stamp { // -- LOGGER ------------------------------------------------------------------- -template +template struct logger { constexpr logger() = default; constexpr logger(log_level lvl) : m_lvl{lvl} {} @@ -134,11 +153,11 @@ struct logger { // -- LOGGER IMPLEMENTATION ---------------------------------------------------- -template +template template constexpr void logger::log(const char* fmt, Args... args) { - size_t pos{0}; + std::size_t pos{0}; // Add timestamp if enabled. if (WithTimestamp) { @@ -160,10 +179,9 @@ constexpr void logger::log(const char* fmt, // string literal as fmt string and hence the user controls the fmt string. // Additionally, we sanitize the arguments to only allow explicitly specified // argument types. - // - // NOLINTNEXTLINE - pos += std::snprintf(m_buf + pos, BufSize - pos, fmt, - detail::sanitize_fmt_args(args)...); + detail::formatter formatter; + pos += formatter(m_buf + pos, BufSize - pos, fmt, + detail::sanitize_fmt_args(args)...); assert(pos < BufSize); // Ensure terminated with new line and null terminator. diff --git a/test/log.cc b/test/log.cc index c059ba8..7d8305d 100644 --- a/test/log.cc +++ b/test/log.cc @@ -4,6 +4,7 @@ int main() { logging::logger<> mlog; mlog.set_level(logging::kDbg0); + INFO(&mlog, "Hallo nofmt"); INFO(&mlog, "Hallo %d", 42); WARN(&mlog, "Hallo %x", 0x1337); FAIL(&mlog, "Hallo %u", 666); -- cgit v1.2.3