RFR: 8371637: allocateNativeInternal sometimes return incorrectly aligned memory

Jorn Vernee jvernee at openjdk.org
Thu Nov 13 15:02:42 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

I think what Maurizio is suggesting is probably the most flexible. We can assume that e.g. a 4 byte allocation is at least 4 byte aligned, and an 8 byte allocation is also at least 8 bytes aligned (which implies 4 byte alignment as well), up to a value equal to `alignof(max_align_t)`, which we currently assume to be 16 (though, we could have a native method that actually returns `alignof(max_align_t)`).

> Doesn't this assume that all malloc implementations follow power of 2 pattern of arena sizes: 8, 16, 32, 64 and pointer alignments between min and max? malloc could also be implemented skipping some of those intermediate sizes. e.g. 16, 64, 256.

If an 8 byte value is allocated in a 16 byte arena, I assume it is 16 byte aligned, which implies 8 byte alignment.

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

PR Comment: https://git.openjdk.org/jdk/pull/28235#issuecomment-3528212611


More information about the core-libs-dev mailing list