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