1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
//! Memory allocation error.

use std::alloc::Layout;
use std::collections::TryReserveError;
use std::error::Error;
use std::fmt;
use std::panic::{PanicInfo, UnwindSafe};
use std::sync::atomic::{AtomicBool, Ordering};

/// The error type for allocation failure.
#[derive(Copy, Clone)]
#[repr(transparent)]
pub struct AllocError(Layout);

impl AllocError {
    /// Creates a new `AllocError`.
    #[must_use]
    #[inline]
    pub const fn new(layout: Layout) -> Self {
        AllocError(layout)
    }

    /// Returns the memory layout of the `AllocError`.
    #[must_use]
    #[inline]
    pub const fn layout(self) -> Layout {
        self.0
    }
}

impl fmt::Debug for AllocError {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("AllocError")
            .field("size", &self.0.size())
            .field("align", &self.0.align())
            .finish()
    }
}

impl fmt::Display for AllocError {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "failed to allocate memory by required layout {{size: {}, align: {}}}",
            self.0.size(),
            self.0.align()
        )
    }
}

impl Error for AllocError {}

impl From<TryReserveError> for AllocError {
    #[inline]
    fn from(e: TryReserveError) -> Self {
        use std::collections::TryReserveErrorKind;
        match e.kind() {
            TryReserveErrorKind::AllocError { layout, .. } => AllocError::new(layout),
            TryReserveErrorKind::CapacityOverflow => {
                unreachable!("unexpected capacity overflow")
            }
        }
    }
}

fn alloc_error_hook(layout: Layout) {
    std::panic::panic_any(AllocError(layout))
}

type PanicHook = Box<dyn Fn(&PanicInfo<'_>) + 'static + Sync + Send>;

fn panic_hook(panic_info: &PanicInfo<'_>) {
    // panic abort except alloc error
    if !panic_info.payload().is::<AllocError>() {
        std::process::abort();
    }
}

/// Invokes a closure, capturing the panic of memory allocation error if one occurs.
///
/// This function will return `Ok` with the closure's result if the closure
/// does not panic, and will return `AllocError` if allocation error occurs. The
/// process will abort if other panics occur.
///
/// Notes that this function will set panic hook and alloc error hook.
#[inline]
pub fn catch_alloc_error<F: FnOnce() -> R + UnwindSafe, R>(f: F) -> Result<R, AllocError> {
    static SET_HOOK: AtomicBool = AtomicBool::new(false);
    if !SET_HOOK.load(Ordering::Acquire) {
        let hook: PanicHook =
            Box::try_new(panic_hook).map_err(|_| AllocError::new(Layout::new::<PanicHook>()))?;
        std::panic::set_hook(hook);
        std::alloc::set_alloc_error_hook(alloc_error_hook);
        SET_HOOK.store(true, Ordering::Release);
    }

    #[cfg(feature = "global-allocator")]
    allocator::ThreadPanic::try_reserve_mem()?;

    let result = std::panic::catch_unwind(f);
    match result {
        Ok(r) => Ok(r),
        Err(e) => match e.downcast_ref::<AllocError>() {
            None => unreachable!(),
            Some(e) => Err(*e),
        },
    }
}

#[cfg(feature = "global-allocator")]
mod allocator {
    use crate::AllocError;
    use std::alloc::{GlobalAlloc, Layout, System};
    use std::cell::RefCell;
    use std::ptr::NonNull;

    #[global_allocator]
    static GLOBAL: Alloc = Alloc;

    struct Alloc;

    unsafe impl GlobalAlloc for Alloc {
        #[inline]
        unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
            let ptr = System.alloc(layout);

            if ptr.is_null() && std::thread::panicking() {
                if let Some(p) = ThreadPanic::take_mem(layout) {
                    return p.as_ptr();
                }
            }

            ptr
        }

        #[inline]
        unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
            System.dealloc(ptr, layout)
        }
    }

    struct PanicMem {
        // See core::panic::BoxMeUp
        box_me_up: Option<NonNull<u8>>,

        // Panic handler doesn't alloc memory for Exception in Windows.
        #[cfg(not(target_os = "windows"))]
        exception: Option<NonNull<u8>>,
    }

    impl PanicMem {
        const BOX_ME_UP_LAYOUT: Layout = unsafe { Layout::from_size_align_unchecked(16, 8) };

        #[cfg(not(target_os = "windows"))]
        const EXCEPTION_LAYOUT: Layout = unsafe { Layout::from_size_align_unchecked(80, 8) };

        #[inline]
        const fn new() -> Self {
            PanicMem {
                box_me_up: None,

                #[cfg(not(target_os = "windows"))]
                exception: None,
            }
        }

        #[inline]
        fn try_reserve(&mut self) -> Result<(), AllocError> {
            if self.box_me_up.is_none() {
                let ptr = unsafe { System.alloc(PanicMem::BOX_ME_UP_LAYOUT) };
                if ptr.is_null() {
                    return Err(AllocError::new(PanicMem::BOX_ME_UP_LAYOUT));
                } else {
                    self.box_me_up = unsafe { Some(NonNull::new_unchecked(ptr)) };
                }
            }

            #[cfg(not(target_os = "windows"))]
            if self.exception.is_none() {
                let ptr = unsafe { System.alloc(PanicMem::EXCEPTION_LAYOUT) };
                if ptr.is_null() {
                    return Err(AllocError::new(PanicMem::EXCEPTION_LAYOUT));
                } else {
                    self.exception = unsafe { Some(NonNull::new_unchecked(ptr)) };
                }
            }

            Ok(())
        }

        #[inline]
        fn take_mem(&mut self, layout: Layout) -> Option<NonNull<u8>> {
            if layout == PanicMem::BOX_ME_UP_LAYOUT {
                return self.box_me_up.take();
            }

            #[cfg(not(target_os = "windows"))]
            if layout == PanicMem::EXCEPTION_LAYOUT {
                return self.exception.take();
            }

            None
        }
    }

    impl Drop for PanicMem {
        #[inline]
        fn drop(&mut self) {
            if let Some(mut ptr) = self.box_me_up.take() {
                unsafe { System.dealloc(ptr.as_mut(), PanicMem::BOX_ME_UP_LAYOUT) };
            }

            #[cfg(not(target_os = "windows"))]
            if let Some(mut ptr) = self.exception.take() {
                unsafe { System.dealloc(ptr.as_mut(), PanicMem::EXCEPTION_LAYOUT) };
            }
        }
    }

    thread_local! {
        static THREAD_PANIC_MEM: RefCell<PanicMem> = RefCell::new(PanicMem::new());
    }

    pub struct ThreadPanic;

    impl ThreadPanic {
        #[inline]
        pub fn try_reserve_mem() -> Result<(), AllocError> {
            THREAD_PANIC_MEM.with(|panic_mem| panic_mem.borrow_mut().try_reserve())
        }

        #[inline]
        pub fn take_mem(layout: Layout) -> Option<NonNull<u8>> {
            THREAD_PANIC_MEM.with(|panic_mem| panic_mem.borrow_mut().take_mem(layout))
        }
    }
}

#[cfg(test)]
mod tests {
    use super::catch_alloc_error;
    use std::alloc::{AllocError as StdAllocError, Allocator, Layout};
    use std::ptr::NonNull;

    struct NoMem;

    unsafe impl Allocator for NoMem {
        #[inline]
        fn allocate(&self, _layout: Layout) -> Result<NonNull<[u8]>, StdAllocError> {
            Err(StdAllocError)
        }

        #[inline]
        unsafe fn deallocate(&self, _ptr: NonNull<u8>, _layout: Layout) {
            unreachable!()
        }
    }

    #[test]
    fn test_catch_alloc_error() {
        let result = catch_alloc_error(|| Vec::<u8, _>::with_capacity_in(10, NoMem));
        assert_eq!(
            result.unwrap_err().layout(),
            Layout::from_size_align(10, 1).unwrap()
        );
    }
}