Skip to content

Commit

Permalink
Fix potential overflows in utils::aligned_div, utils::rounded_div
Browse files Browse the repository at this point in the history
  • Loading branch information
elad335 authored and Nekotekina committed Feb 19, 2021
1 parent 20eb435 commit b86ec2f
Showing 1 changed file with 5 additions and 5 deletions.
10 changes: 5 additions & 5 deletions rpcs3/util/asm.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -374,21 +374,21 @@ namespace utils

// General purpose aligned division, the result is rounded up not truncated
template <typename T, typename = std::enable_if_t<std::is_integral<T>::value && std::is_unsigned<T>::value>>
constexpr T aligned_div(T value, ullong align)
constexpr T aligned_div(T value, std::type_identity_t<T> align)
{
return static_cast<T>((value + align - 1) / align);
return static_cast<T>(value / align + T{!!(value % align)});
}

// General purpose aligned division, the result is rounded to nearest
template <typename T, typename = std::enable_if_t<std::is_integral<T>::value>>
constexpr T rounded_div(T value, std::conditional_t<std::is_signed<T>::value, llong, ullong> align)
constexpr T rounded_div(T value, std::type_identity_t<T> align)
{
if constexpr (std::is_unsigned<T>::value)
{
return static_cast<T>((value + (align / 2)) / align);
return static_cast<T>(value / align + T{(value % align) > (align / 2)});
}

return static_cast<T>((value + (value < 0 ? 0 - align : align) / 2) / align);
return static_cast<T>(value / align + (value > 0 ? T{(value % align) > (align / 2)} : 0 - T{(value % align) < (align / 2)}));
}
} // namespace utils

Expand Down

0 comments on commit b86ec2f

Please sign in to comment.