forked from rust-lang/rust
-
Notifications
You must be signed in to change notification settings - Fork 7
/
aborting-alloc.rs
40 lines (31 loc) · 1.18 KB
/
aborting-alloc.rs
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
//! Helper for 'no-allocation-before-main'.
//!
//! This also contains a meta-test to make sure that the AbortingAllocator does indeed abort.
//!
//! -Cprefer-dynamic=no is required as otherwise #[global_allocator] does nothing.
//@ run-fail
//@ compile-flags: -Cprefer-dynamic=no
use std::{sync::atomic::{AtomicBool, Ordering}, alloc::System};
static ABORT: AtomicBool = AtomicBool::new(true);
pub struct AbortingAllocator(System);
unsafe impl std::alloc::GlobalAlloc for AbortingAllocator {
unsafe fn alloc(&self, layout: std::alloc::Layout) -> *mut u8 {
if ABORT.swap(false, Ordering::SeqCst) {
println!("{}", std::backtrace::Backtrace::force_capture());
std::process::abort();
}
self.0.alloc(layout)
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: std::alloc::Layout) {
if ABORT.swap(false, Ordering::SeqCst) {
println!("{}", std::backtrace::Backtrace::force_capture());
std::process::abort();
}
self.0.dealloc(ptr, layout)
}
}
#[global_allocator]
static ALLOCATOR: AbortingAllocator = AbortingAllocator(System);
fn main() {
std::hint::black_box(String::from("An allocation"));
}