Skip to content

Commit 6f4ede4

Browse files
committed
Rollup merge of rust-lang#30801 - Amanieu:oom_print, r=alexcrichton
This adds the ability to override the default OOM behavior by setting a handler function. This is used by libstd to print a message when running out of memory instead of crashing with an obscure "illegal hardware instruction" error (at least on Linux). Fixes rust-lang#14674
2 parents 6581563 + 98bef2b commit 6f4ede4

File tree

6 files changed

+92
-17
lines changed

6 files changed

+92
-17
lines changed

src/liballoc/lib.rs

Lines changed: 3 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,7 @@
9292
#![feature(unsize)]
9393
#![feature(drop_in_place)]
9494
#![feature(fn_traits)]
95+
#![feature(const_fn)]
9596

9697
#![feature(needs_allocator)]
9798

@@ -134,15 +135,6 @@ mod boxed_test;
134135
pub mod arc;
135136
pub mod rc;
136137
pub mod raw_vec;
138+
pub mod oom;
137139

138-
/// Common out-of-memory routine
139-
#[cold]
140-
#[inline(never)]
141-
#[unstable(feature = "oom", reason = "not a scrutinized interface",
142-
issue = "27700")]
143-
pub fn oom() -> ! {
144-
// FIXME(#14674): This really needs to do something other than just abort
145-
// here, but any printing done must be *guaranteed* to not
146-
// allocate.
147-
unsafe { core::intrinsics::abort() }
148-
}
140+
pub use oom::oom;

src/liballoc/oom.rs

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
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+
}

src/libstd/panicking.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -206,7 +206,7 @@ pub fn on_panic(obj: &(Any+Send), file: &'static str, line: u32) {
206206
// debugger provides a useable stacktrace.
207207
if panics >= 3 {
208208
util::dumb_print(format_args!("thread panicked while processing \
209-
panic. aborting."));
209+
panic. aborting.\n"));
210210
unsafe { intrinsics::abort() }
211211
}
212212

@@ -232,7 +232,7 @@ pub fn on_panic(obj: &(Any+Send), file: &'static str, line: u32) {
232232
// just abort. In the future we may consider resuming
233233
// unwinding or otherwise exiting the thread cleanly.
234234
util::dumb_print(format_args!("thread panicked while panicking. \
235-
aborting."));
235+
aborting.\n"));
236236
unsafe { intrinsics::abort() }
237237
}
238238
}

src/libstd/sys/common/util.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,12 +35,12 @@ pub fn dumb_print(args: fmt::Arguments) {
3535
}
3636

3737
pub fn abort(args: fmt::Arguments) -> ! {
38-
dumb_print(format_args!("fatal runtime error: {}", args));
38+
dumb_print(format_args!("fatal runtime error: {}\n", args));
3939
unsafe { intrinsics::abort(); }
4040
}
4141

4242
#[allow(dead_code)] // stack overflow detection not enabled on all platforms
4343
pub unsafe fn report_overflow() {
44-
dumb_print(format_args!("\nthread '{}' has overflowed its stack",
44+
dumb_print(format_args!("\nthread '{}' has overflowed its stack\n",
4545
thread::current().name().unwrap_or("<unknown>")));
4646
}

src/libstd/sys/unix/mod.rs

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ use io::{self, ErrorKind};
1515
use libc;
1616
use num::One;
1717
use ops::Neg;
18+
use alloc::oom;
1819

1920
#[cfg(target_os = "android")] pub use os::android as platform;
2021
#[cfg(target_os = "bitrig")] pub use os::bitrig as platform;
@@ -45,6 +46,22 @@ pub mod thread_local;
4546
pub mod time;
4647
pub mod stdio;
4748

49+
// A nicer handler for out-of-memory situations than the default one. This one
50+
// prints a message to stderr before aborting. It is critical that this code
51+
// does not allocate any memory since we are in an OOM situation. Any errors are
52+
// ignored while printing since there's nothing we can do about them and we are
53+
// about to exit anyways.
54+
fn oom_handler() -> ! {
55+
use intrinsics;
56+
let msg = "fatal runtime error: out of memory\n";
57+
unsafe {
58+
libc::write(libc::STDERR_FILENO,
59+
msg.as_ptr() as *const libc::c_void,
60+
msg.len() as libc::size_t);
61+
intrinsics::abort();
62+
}
63+
}
64+
4865
#[cfg(not(any(target_os = "nacl", test)))]
4966
pub fn init() {
5067
use libc::signal;
@@ -58,10 +75,14 @@ pub fn init() {
5875
unsafe {
5976
assert!(signal(libc::SIGPIPE, libc::SIG_IGN) != !0);
6077
}
78+
79+
oom::set_oom_handler(oom_handler);
6180
}
6281

6382
#[cfg(all(target_os = "nacl", not(test)))]
64-
pub fn init() { }
83+
pub fn init() {
84+
oom::set_oom_handler(oom_handler);
85+
}
6586

6687
pub fn decode_error_kind(errno: i32) -> ErrorKind {
6788
match errno as libc::c_int {

src/libstd/sys/windows/mod.rs

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ use num::Zero;
2020
use os::windows::ffi::{OsStrExt, OsStringExt};
2121
use path::PathBuf;
2222
use time::Duration;
23+
use alloc::oom;
2324

2425
#[macro_use] pub mod compat;
2526

@@ -42,7 +43,26 @@ pub mod thread_local;
4243
pub mod time;
4344
pub mod stdio;
4445

45-
pub fn init() {}
46+
// See comment in sys/unix/mod.rs
47+
fn oom_handler() -> ! {
48+
use intrinsics;
49+
use ptr;
50+
let msg = "fatal runtime error: out of memory\n";
51+
unsafe {
52+
// WriteFile silently fails if it is passed an invalid handle, so there
53+
// is no need to check the result of GetStdHandle.
54+
c::WriteFile(c::GetStdHandle(c::STD_ERROR_HANDLE),
55+
msg.as_ptr() as c::LPVOID,
56+
msg.len() as c::DWORD,
57+
ptr::null_mut(),
58+
ptr::null_mut());
59+
intrinsics::abort();
60+
}
61+
}
62+
63+
pub fn init() {
64+
oom::set_oom_handler(oom_handler);
65+
}
4666

4767
pub fn decode_error_kind(errno: i32) -> ErrorKind {
4868
match errno as c::DWORD {

0 commit comments

Comments
 (0)