Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix potential overflows in utils::aligned_div, utils::rounded_div #9801

Merged
merged 1 commit into from
Feb 19, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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