hardened_malloc_sys/lib.rs
1//
2// hardened-malloc-sys: Rust bindings for GrapheneOS allocator
3// src/lib.rs: Extern definitions for allocator functions
4//
5// Copyright (c) 2025 Ali Polatel <alip@chesswob.org>
6// Based in part upon hardened_malloc-rs/src/bindings.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
12pub mod hardened_malloc_sys {
13 use core::ffi::{c_int, c_void};
14
15 // ideally we would use c_size_t but it's unstable
16
17 #[allow(dead_code)]
18 extern "C" {
19 /* C standard */
20 pub fn malloc(size: usize) -> *mut c_void;
21 pub fn calloc(nmemb: usize, size: usize) -> *mut c_void;
22 pub fn realloc(ptr: *mut c_void, size: usize) -> *mut c_void;
23 pub fn aligned_alloc(alignment: usize, size: usize) -> *mut c_void;
24 pub fn free(ptr: *mut c_void);
25
26 /* POSIX */
27 pub fn posix_memalign(memptr: *mut *mut c_void, alignment: usize, size: usize) -> c_int;
28
29 /* hardened_malloc extensions */
30 /// return an upper bound on object size for any pointer based on malloc
31 /// metadata
32 pub fn malloc_object_size(ptr: *const c_void) -> usize;
33
34 /// similar to malloc_object_size, but avoiding locking so the results are
35 /// much more limited
36 pub fn malloc_object_size_fast(ptr: *const c_void) -> usize;
37
38 /// The free function with an extra parameter for passing the size requested
39 /// at allocation time.
40 ///
41 /// This offers the same functionality as C++14 sized deallocation and can
42 /// be used to implement it.
43 ///
44 /// A performance-oriented allocator would use this as a performance
45 /// enhancement with undefined behavior on a mismatch. Instead, this
46 /// hardened allocator implementation uses it to improve security by
47 /// checking that the passed size matches the allocated size.
48 pub fn free_sized(ptr: *mut c_void, expected_size: usize) -> c_void;
49 }
50}