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