From b8a0863c1bb2a0e1b3d226679e4a7bd31d14c2b4 Mon Sep 17 00:00:00 2001 From: David Tolnay Date: Thu, 14 Dec 2023 10:59:28 -0800 Subject: [PATCH] Fix insufficient alignment of malloc's return value on 32-bit --- src/lib.rs | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index e083433..0b5cf1f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -60,11 +60,23 @@ mod externs { use core::ptr; use core::slice; - const HEADER: usize = mem::size_of::(); + const HEADER: usize = { + let need_len = mem::size_of::(); + // Round up to multiple of MALLOC_ALIGN. + (need_len + MALLOC_ALIGN - 1) & !(MALLOC_ALIGN - 1) + }; // `max_align_t` may be bigger than this, but libyaml does not use `long // double` or u128. - const MALLOC_ALIGN: usize = mem::align_of::(); + const MALLOC_ALIGN: usize = { + let int_align = mem::align_of::(); + let ptr_align = mem::align_of::(); + if int_align >= ptr_align { + int_align + } else { + ptr_align + } + }; pub unsafe fn malloc(size: libc::c_ulong) -> *mut libc::c_void { let size = HEADER.force_add(size.force_into());