latexml/alloc_hook.rs
1//! The binaries' global allocator: an allocator that ends the process through the binary's allocation-failure hook
2//! (`latexml_core::watchdog::alloc_failed`) when an allocation returns null. It replaces the nightly-only
3//! `std::alloc::set_alloc_error_hook` (issue #143): the hook's `Fatal:oom:alloc_failed` line and exit 137 are kept
4//! for every allocation, and a fallible one (`try_reserve`, std's `fs::read`) now ends the same way instead of
5//! returning an error. `cortex_worker`'s address-space cap (`--child-mem-limit-mb`) reaches the hook through it.
6
7use std::alloc::{GlobalAlloc, Layout};
8
9/// `A` with every null result ending in the allocation-failure hook (see the module docs).
10pub struct HookedAlloc<A>(A);
11
12impl<A> HookedAlloc<A> {
13 /// Wraps `inner`, for a `#[global_allocator]` static.
14 pub const fn new(inner: A) -> Self { HookedAlloc(inner) }
15
16 /// The wrapped allocator, whose null results return to the caller.
17 pub fn inner(&self) -> &A { &self.0 }
18}
19
20// SAFETY: each method forwards to `A` under the caller's contract unchanged, and returns `A`'s pointer; a null one
21// never returns (the hook ends the process). The forwarding calls are the only unsafe operations, hence the allow.
22#[allow(unsafe_op_in_unsafe_fn)]
23unsafe impl<A: GlobalAlloc> GlobalAlloc for HookedAlloc<A> {
24 #[inline]
25 unsafe fn alloc(&self, layout: Layout) -> *mut u8 { non_null(self.0.alloc(layout), layout) }
26
27 #[inline]
28 unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
29 non_null(self.0.alloc_zeroed(layout), layout)
30 }
31
32 #[inline]
33 unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { self.0.dealloc(ptr, layout) }
34
35 #[inline]
36 unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
37 let grown = self.0.realloc(ptr, layout, new_size);
38 if grown.is_null() {
39 // The failed request, as `handle_alloc_error` receives it from a growing `Vec`.
40 failed(Layout::from_size_align(new_size, layout.align()).unwrap_or(layout));
41 }
42 grown
43 }
44}
45
46#[inline(always)]
47fn non_null(ptr: *mut u8, layout: Layout) -> *mut u8 {
48 if ptr.is_null() {
49 failed(layout);
50 }
51 ptr
52}
53
54#[cold]
55#[inline(never)]
56fn failed(layout: Layout) -> ! { latexml_core::watchdog::alloc_failed(layout) }