From a77a5fc505bbeab1cfa36be16d40f7799689317a Mon Sep 17 00:00:00 2001 From: Paul Dreik Date: Thu, 30 May 2019 05:45:55 +0200 Subject: [PATCH] fix UB on signed int overflow in chrono_formatter constructor see https://github.com/fmtlib/fmt/issues/1179 --- include/fmt/chrono.h | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/include/fmt/chrono.h b/include/fmt/chrono.h index 6ec420f44bda..3f7c3f4ed1c2 100644 --- a/include/fmt/chrono.h +++ b/include/fmt/chrono.h @@ -497,8 +497,16 @@ struct chrono_formatter { explicit chrono_formatter(FormatContext& ctx, OutputIt o, std::chrono::duration d) : context(ctx), out(o), val(d.count()) { - // hmm, what happens if this is INT_MIN? - if (d.count() < 0) d = -d; + if (d.count() < 0) { + //protect against signed integer overflow + using TT=std::numeric_limits; + if(TT::is_integer && TT::is_signed) { + if(d.count()==TT::min()) { + FMT_THROW(format_error("value would cause UB")); + } + } + d = -d; + } // this may overflow and/or the result may not fit in the // target type.