]> git.lizzy.rs Git - rust.git/blob - src/liballoc/oom.rs
Rollup merge of #31295 - steveklabnik:gh31266, r=alexcrichton
[rust.git] / src / liballoc / oom.rs
1 // Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use core::sync::atomic::{AtomicPtr, Ordering};
12 use core::mem;
13 use core::intrinsics;
14
15 static OOM_HANDLER: AtomicPtr<()> = AtomicPtr::new(default_oom_handler as *mut ());
16
17 fn default_oom_handler() -> ! {
18     // The default handler can't do much more since we can't assume the presence
19     // of libc or any way of printing an error message.
20     unsafe { intrinsics::abort() }
21 }
22
23 /// Common out-of-memory routine
24 #[cold]
25 #[inline(never)]
26 #[unstable(feature = "oom", reason = "not a scrutinized interface",
27            issue = "27700")]
28 pub fn oom() -> ! {
29     let value = OOM_HANDLER.load(Ordering::SeqCst);
30     let handler: fn() -> ! = unsafe { mem::transmute(value) };
31     handler();
32 }
33
34 /// Set a custom handler for out-of-memory conditions
35 ///
36 /// To avoid recursive OOM failures, it is critical that the OOM handler does
37 /// not allocate any memory itself.
38 #[unstable(feature = "oom", reason = "not a scrutinized interface",
39            issue = "27700")]
40 pub fn set_oom_handler(handler: fn() -> !) {
41     OOM_HANDLER.store(handler as *mut (), Ordering::SeqCst);
42 }