Skip to content

Commit

Permalink
use posix_memalign on all Unix targets
Browse files Browse the repository at this point in the history
  • Loading branch information
RalfJung committed May 19, 2024
1 parent 6579ed8 commit ab53b48
Showing 1 changed file with 13 additions and 29 deletions.
42 changes: 13 additions & 29 deletions library/std/src/sys/pal/unix/alloc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,33 +58,17 @@ unsafe impl GlobalAlloc for System {
}
}

cfg_if::cfg_if! {
// We use posix_memalign wherever possible, but not all targets have that function.
if #[cfg(any(
target_os = "redox",
target_os = "espidf",
target_os = "horizon",
target_os = "vita",
))] {
#[inline]
unsafe fn aligned_malloc(layout: &Layout) -> *mut u8 {
libc::memalign(layout.align(), layout.size()) as *mut u8
}
} else {
#[inline]
unsafe fn aligned_malloc(layout: &Layout) -> *mut u8 {
let mut out = ptr::null_mut();
// We prefer posix_memalign over aligned_malloc since with aligned_malloc,
// implementations are making almost arbitrary choices for which alignments are
// "supported", making it hard to use. For instance, some implementations require the
// size to be a multiple of the alignment (wasi emmalloc), while others require the
// alignment to be at least the pointer size (Illumos, macOS) -- which may or may not be
// standards-compliant, but that does not help us.
// posix_memalign only has one, clear requirement: that the alignment be a multiple of
// `sizeof(void*)`. Since these are all powers of 2, we can just use max.
let align = layout.align().max(crate::mem::size_of::<usize>());
let ret = libc::posix_memalign(&mut out, align, layout.size());
if ret != 0 { ptr::null_mut() } else { out as *mut u8 }
}
}
unsafe fn aligned_malloc(layout: &Layout) -> *mut u8 {
let mut out = ptr::null_mut();
// We prefer posix_memalign over aligned_malloc since it is more widely available, and since
// with aligned_malloc, implementations are making almost arbitrary choices for which alignments
// are "supported", making it hard to use. For instance, some implementations require the size
// to be a multiple of the alignment (wasi emmalloc), while others require the alignment to be
// at least the pointer size (Illumos, macOS) -- which may or may not be standards-compliant,
// but that does not help us.
// posix_memalign only has one, clear requirement: that the alignment be a multiple of
// `sizeof(void*)`. Since these are all powers of 2, we can just use max.
let align = layout.align().max(crate::mem::size_of::<usize>());
let ret = libc::posix_memalign(&mut out, align, layout.size());
if ret != 0 { ptr::null_mut() } else { out as *mut u8 }
}

0 comments on commit ab53b48

Please sign in to comment.