Skip to content

Commit

Permalink
fix UB on signed int overflow in chrono_formatter constructor
Browse files Browse the repository at this point in the history
see #1179
  • Loading branch information
pauldreik committed May 30, 2019
1 parent b6a5927 commit a77a5fc
Showing 1 changed file with 10 additions and 2 deletions.
12 changes: 10 additions & 2 deletions include/fmt/chrono.h
Original file line number Diff line number Diff line change
Expand Up @@ -497,8 +497,16 @@ struct chrono_formatter {
explicit chrono_formatter(FormatContext& ctx, OutputIt o,
std::chrono::duration<Rep, Period> 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<Rep>;
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.
Expand Down

0 comments on commit a77a5fc

Please sign in to comment.