RFR: 8318127: align_up has potential overflow [v3]

Kim Barrett kbarrett at openjdk.org
Wed Oct 2 10:20:35 UTC 2024


On Wed, 2 Oct 2024 09:48:59 GMT, Casper Norrbin <cnorrbin at openjdk.org> wrote:

> To find a middle ground, maybe a solution like this would be good, avoiding the assert when called with unsigned types. This does however have the consequence that the function behaves a bit differently depending on from where it is called.
> 
> ```c++
> template<typename T, typename A, ENABLE_IF(std::is_integral<T>::value)>
> constexpr T align_up(T size, A alignment) {
>   T mask = checked_cast<T>(alignment_mask(alignment));
>   if (!std::is_unsigned<T>()) {
>     assert(size <= std::numeric_limits<T>::max() - mask, "overflow");
>   }
>   T adjusted = size + mask;
>   return align_down(adjusted, alignment);
> }
> ```

That's more or less the modular variant that I mentioned earlier.  Find a use-case for modular behavior, and we
can add a new function that provides that behavior.  But I think align_up should have the post-condition that
size <= result.  (I don't think it's worth making that post-condition explicit in code though.  That's what the
pre-condition is providing, and the check needs to be pre, else UB for some types comes into play.)

-------------

PR Comment: https://git.openjdk.org/jdk/pull/20808#issuecomment-2388274861


More information about the hotspot-dev mailing list