Skip to main content

relibc/header/malloc/
mod.rs

1//! `malloc.h` implementation.
2//!
3//! Non-POSIX, see <https://man7.org/linux/man-pages/man3/posix_memalign.3.html>.
4
5use crate::{
6    header::errno::ENOMEM,
7    platform::{
8        self, Pal, Sys,
9        types::{c_void, size_t},
10    },
11};
12use core::ptr;
13
14/// See <https://man7.org/linux/man-pages/man3/posix_memalign.3.html>.
15#[deprecated]
16#[unsafe(no_mangle)]
17pub unsafe extern "C" fn pvalloc(size: size_t) -> *mut c_void {
18    let page_size = Sys::getpagesize();
19    // Find the smallest multiple of the page size in which the requested size
20    // will fit. The result of the division will always be less than or equal
21    // to size_t::MAX - 1, and the num_pages calculation will therefore never
22    // overflow.
23    let num_pages = if size != 0 {
24        (size - 1) / page_size + 1
25    } else {
26        0
27    };
28
29    match num_pages.checked_mul(page_size) {
30        Some(alloc_size) => {
31            let ptr = unsafe { platform::alloc_align(alloc_size, page_size) };
32            if ptr.is_null() {
33                platform::ERRNO.set(ENOMEM);
34            }
35            ptr
36        }
37        None => {
38            platform::ERRNO.set(ENOMEM);
39            ptr::null_mut()
40        }
41    }
42}
43
44/// See <https://man7.org/linux/man-pages/man3/malloc_usable_size.3.html>.
45#[unsafe(no_mangle)]
46pub unsafe extern "C" fn malloc_usable_size(ptr: *mut c_void) -> size_t {
47    unsafe { platform::alloc_usable_size(ptr) }
48}