Skip to content

Commit 2bad604

Browse files
committed
request at least ptr-size alignment from posix_memalign
1 parent 6ea4036 commit 2bad604

File tree

1 file changed

+11
-1
lines changed

1 file changed

+11
-1
lines changed

src/libstd/sys/unix/alloc.rs

+11-1
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,15 @@
11
use crate::ptr;
22
use crate::sys_common::alloc::{MIN_ALIGN, realloc_fallback};
33
use crate::alloc::{GlobalAlloc, Layout, System};
4+
use crate::mem;
45

56
#[stable(feature = "alloc_system_type", since = "1.28.0")]
67
unsafe impl GlobalAlloc for System {
78
#[inline]
89
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
10+
// jemalloc provides alignment less than MIN_ALIGN for small allocations.
11+
// So only rely on MIN_ALIGN if size >= align.
12+
// Also see <https://github.com/rust-lang/rust/issues/45955>.
913
if layout.align() <= MIN_ALIGN && layout.align() <= layout.size() {
1014
libc::malloc(layout.size()) as *mut u8
1115
} else {
@@ -21,6 +25,9 @@ unsafe impl GlobalAlloc for System {
2125

2226
#[inline]
2327
unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
28+
// jemalloc provides alignment less than MIN_ALIGN for small allocations.
29+
// So only rely on MIN_ALIGN if size >= align.
30+
// Also see <https://github.com/rust-lang/rust/issues/45955>.
2431
if layout.align() <= MIN_ALIGN && layout.align() <= layout.size() {
2532
libc::calloc(layout.size(), 1) as *mut u8
2633
} else {
@@ -80,7 +87,10 @@ unsafe fn aligned_malloc(layout: &Layout) -> *mut u8 {
8087
#[inline]
8188
unsafe fn aligned_malloc(layout: &Layout) -> *mut u8 {
8289
let mut out = ptr::null_mut();
83-
let ret = libc::posix_memalign(&mut out, layout.align(), layout.size());
90+
// posix_memalign requires that the alignment be a multiple of `sizeof(void*)`.
91+
// Since these are all powers of 2, we can just use max.
92+
let align = layout.align().max(mem::size_of::<usize>());
93+
let ret = libc::posix_memalign(&mut out, align, layout.size());
8494
if ret != 0 {
8595
ptr::null_mut()
8696
} else {

0 commit comments

Comments
 (0)