RFR: 8318127: align_up has potential overflow [v3]

Casper Norrbin cnorrbin at openjdk.org
Wed Oct 2 09:51:37 UTC 2024


On Tue, 1 Oct 2024 14:39:10 GMT, Casper Norrbin <cnorrbin at openjdk.org> wrote:

>> Hi everyone,
>> 
>> The `align_up` function contained code which could potentially overflow and produce an incorrect result. This PR adds an assert to check for such.
>> 
>> Additionally, two test case that previously caused an overflow have been updated to use the highest possible values that do not trigger an overflow.
>
> Casper Norrbin has refreshed the contents of this pull request, and previous commits have been removed. Incremental views are not available. The pull request now contains two commits:
> 
>  - change reserve_memory test
>  - align overflow check

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);
}

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

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


More information about the hotspot-dev mailing list