diff options
author | Johannes Stoelp <johannes.stoelp@gmail.com> | 2023-10-18 18:47:10 +0200 |
---|---|---|
committer | Johannes Stoelp <johannes.stoelp@gmail.com> | 2023-10-18 18:47:10 +0200 |
commit | bce90f172699c8094668fbedafcd11fc743588b5 (patch) | |
tree | cb2e4ae2bb432ff898b39ce5677f088dba0cf2c6 | |
parent | 5d27fb85fc3d482f10aa7b5fab900beb1d4a0e92 (diff) | |
download | cpp-utils-bce90f172699c8094668fbedafcd11fc743588b5.tar.gz cpp-utils-bce90f172699c8094668fbedafcd11fc743588b5.zip |
log: fix -Wformat-security lint and remove lint excuse
-rw-r--r-- | log.h | 32 | ||||
-rw-r--r-- | test/log.cc | 1 |
2 files changed, 26 insertions, 7 deletions
@@ -75,6 +75,25 @@ constexpr inline Arg sanitize_fmt_args(Arg arg) { return arg; } +template <std::size_t N> +struct formatter { + template <typename... Args> + 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 <int UtcOffset = 0> @@ -112,7 +131,7 @@ struct time_stamp { // -- LOGGER ------------------------------------------------------------------- -template <bool WithTimestamp = true, size_t BufSize = 128> +template <bool WithTimestamp = true, std::size_t BufSize = 128> struct logger { constexpr logger() = default; constexpr logger(log_level lvl) : m_lvl{lvl} {} @@ -134,11 +153,11 @@ struct logger { // -- LOGGER IMPLEMENTATION ---------------------------------------------------- -template <bool WithTimestamp, size_t BufSize> +template <bool WithTimestamp, std::size_t BufSize> template <log_level L, typename... Args> constexpr void logger<WithTimestamp, BufSize>::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<WithTimestamp, BufSize>::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<sizeof...(Args)> 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); |