RFR: 8371637: allocateNativeInternal sometimes return incorrectly aligned memory [v2]
Maurizio Cimadamore
mcimadamore at openjdk.org
Fri Nov 14 10:22:06 UTC 2025
On Thu, 13 Nov 2025 19:12:41 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
>
> Harald Eilertsen has updated the pull request incrementally with two additional commits since the last revision:
>
> - Second try to fix alignment for native segments
>
> Introducing a helper function as suggested by JornVernee to decide on
> the proper alignment based on the segment size.
>
> This work was sponsored by: The FreeBSD Foundation
>
> Co-authored-by: JornVernee
> - Test that native segments don't overlap
>
> This work was sponsored by: The FreeBSD Foundation
The fix is simple and pragmatic. The main difference between this and what I described is that by singling out FreeBSD, we won't be able to support cases where e.g. a developer runs on Linux, but using LD_PRELOAD to use a different allocator like jemalloc? It's a cornery case, but one I've seen from time to time to take advantage of some of the "hardening" features provided by jemalloc (and diagnose memory issues). Of course, we can also keep this PR as is, and then address other (more cornery cases) in separate PRs.
-------------
PR Comment: https://git.openjdk.org/jdk/pull/28235#issuecomment-3532013857
More information about the core-libs-dev
mailing list