RFR: 8371637: allocateNativeInternal sometimes return incorrectly aligned memory
Maurizio Cimadamore
mcimadamore at openjdk.org
Wed Nov 12 11:24:09 UTC 2025
On Tue, 11 Nov 2025 14:11:28 GMT, Harald Eilertsen <haraldei at openjdk.org> wrote:
> `jdk.internal.foreign.SegmentFactories::allocateNativeInternal` assumes that the underlying implementation of malloc aligns allocations on 16 byte boundaries for 64 bit platforms, and 8 byte boundaries on 32 bit platforms. So for any allocation where the requested alignment is less than or equal to this default alignment it makes no adjustment.
>
> However, this assumption does not hold for all allocators. Specifically jemallc, used by libc on FreeBSD will align small allocations on 8 or 4 byte boundaries, respectively. This causes allocateNativeInternal to sometimes return memory that is not properly aligned when the requested alignment is exactly 16 bytes.
>
> To make sure we honour the requested alignment when it exaclty matches the quantum as defined by MAX_MALLOC_ALIGN, this patch ensures that we adjust the alignment also in this case.
>
> This should make no difference for platforms where malloc allready aligns on the quantum, except for a few unnecessary trivial calculations.
>
> This work was sponsored by: The FreeBSD Foundation
>From a logical point of view, what we'd need would be a couple of extra constants:
* `MIN_ALIGN`, this is the minimum alignment provided by the allocator/OS/platform combo
* `MAX_ALIGN`, this is the maximum alignment provided by the allocator/OS/platform combo
Then, we have three cases:
* if the requested alignment `A` is `A <= MIN_ALIGN`, we can just allocate and don't adjust for alignment
* if the requested alignment `A` is `MIN_ALIGN < A <= MAX_ALIGN` and the requested size is a multiple of the alignment, also just allocate and don't adjust for alignment
* otherwise, allocate a bigger segment and manually align the result
The problem is: how do we discover these constants?
> Having something like os::posix_memalign() could eliminate the problem completely, and probably simplify the code in allocateNativeInternal quite a bit.
Yeah, that would be nice -- but I noticed that `posix_memalign` is currently not allowed in hotspot code:
https://github.com/openjdk/jdk/blob/400a83da893f5fc285a175b63a266de21e93683c/src/hotspot/os/posix/forbiddenFunctions_posix.hpp#L45
So, allowing this would require some discussion. Also, going down this path will likely require its own `Unsafe` primitive, and intrinsics, plus potential tweaks to support NMT. So, not straightforward to pull off.
-------------
PR Comment: https://git.openjdk.org/jdk/pull/28235#issuecomment-3521432776
More information about the core-libs-dev
mailing list