Skip to main content

hardened_malloc/
lib.rs

1//
2// hardened-malloc: Global allocator using GrapheneOS allocator
3// src/lib.rs: Global allocator definition
4//
5// Copyright (c) 2025, 2026 Ali Polatel <alip@chesswob.org>
6// Based in part upon hardened_malloc-rs/src/lib.rs which is
7//   Copyright (c) strawberry <strawberry@puppygock.gay>
8//   SPDX-License-Identifier: Apache-2.0 OR MIT
9//
10// SPDX-License-Identifier: MIT
11
12#![no_std]
13
14use core::{
15    alloc::{GlobalAlloc, Layout},
16    ffi::c_void,
17};
18
19// POSIX
20pub use hardened_malloc_sys::posix_memalign;
21// C standard
22pub use hardened_malloc_sys::{aligned_alloc, calloc, free, malloc, realloc};
23// hardened_malloc extensions
24pub use hardened_malloc_sys::{free_sized, malloc_object_size, malloc_object_size_fast};
25
26pub struct HardenedMalloc;
27
28unsafe impl GlobalAlloc for HardenedMalloc {
29    #[inline]
30    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
31        malloc(layout.size()) as *mut u8
32    }
33
34    #[inline]
35    unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
36        calloc(layout.size(), 1) as *mut u8
37    }
38
39    #[inline]
40    unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
41        // Deallocate memory using free_sized.
42        // Pass the size of the allocation to ensure proper sized deallocation.
43        free_sized(ptr as *mut c_void, layout.size());
44    }
45
46    #[inline]
47    unsafe fn realloc(&self, ptr: *mut u8, _layout: Layout, size: usize) -> *mut u8 {
48        realloc(ptr as *mut c_void, size) as *mut u8
49    }
50}