Skip to content

Commit

Permalink
Check value is in range before casting from double to uint32_t, to av…
Browse files Browse the repository at this point in the history
…oid undefined behavior.
  • Loading branch information
kevinbackhouse committed Aug 2, 2021
1 parent db527f4 commit 1455cc8
Showing 1 changed file with 13 additions and 3 deletions.
16 changes: 13 additions & 3 deletions src/tags_int.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2585,12 +2585,22 @@ namespace Exiv2 {
URational exposureTime(float shutterSpeedValue)
{
URational ur(1, 1);
double tmp = std::exp(std::log(2.0) * static_cast<double>(shutterSpeedValue));
const double tmp = std::exp(std::log(2.0) * static_cast<double>(shutterSpeedValue));
if (tmp > 1) {
ur.second = static_cast<long>(tmp + 0.5);
// Add 0.5 for rounding.
const double x = tmp + 0.5;
// Check that x is within the range of a uint32_t before casting.
if (0 <= x && x <= std::numeric_limits<uint32_t>::max()) {
ur.second = static_cast<uint32_t>(x);
}
}
else {
ur.first = static_cast<long>(1/tmp + 0.5);
// Add 0.5 for rounding.
const double x = 1/tmp + 0.5;
// Check that x is within the range of a uint32_t before casting.
if (0 <= x && x <= std::numeric_limits<uint32_t>::max()) {
ur.first = static_cast<uint32_t>(x);
}
}
return ur;
}
Expand Down

0 comments on commit 1455cc8

Please sign in to comment.