]> git.lizzy.rs Git - rust.git/blob - src/liballoc/oom.rs
Auto merge of #42976 - ids1024:redoxfix, r=sfackler
[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 #[cfg(target_has_atomic = "ptr")]
12 pub use self::imp::set_oom_handler;
13 use core::intrinsics;
14
15 fn default_oom_handler() -> ! {
16     // The default handler can't do much more since we can't assume the presence
17     // of libc or any way of printing an error message.
18     unsafe { intrinsics::abort() }
19 }
20
21 /// Common out-of-memory routine
22 #[cold]
23 #[inline(never)]
24 #[unstable(feature = "oom", reason = "not a scrutinized interface",
25            issue = "27700")]
26 pub fn oom() -> ! {
27     self::imp::oom()
28 }
29
30 #[cfg(target_has_atomic = "ptr")]
31 mod imp {
32     use core::mem;
33     use core::sync::atomic::{AtomicPtr, Ordering};
34
35     static OOM_HANDLER: AtomicPtr<()> = AtomicPtr::new(super::default_oom_handler as *mut ());
36
37     #[inline(always)]
38     pub fn oom() -> ! {
39         let value = OOM_HANDLER.load(Ordering::SeqCst);
40         let handler: fn() -> ! = unsafe { mem::transmute(value) };
41         handler();
42     }
43
44     /// Set a custom handler for out-of-memory conditions
45     ///
46     /// To avoid recursive OOM failures, it is critical that the OOM handler does
47     /// not allocate any memory itself.
48     #[unstable(feature = "oom", reason = "not a scrutinized interface",
49                issue = "27700")]
50     pub fn set_oom_handler(handler: fn() -> !) {
51         OOM_HANDLER.store(handler as *mut (), Ordering::SeqCst);
52     }
53 }
54
55 #[cfg(not(target_has_atomic = "ptr"))]
56 mod imp {
57     #[inline(always)]
58     pub fn oom() -> ! {
59         super::default_oom_handler()
60     }
61 }