Skip to content

Commit e457b77

Browse files
committed
Avoid panicking unnecessarily on startup
1 parent 029cb1b commit e457b77

File tree

3 files changed

+10
-30
lines changed

3 files changed

+10
-30
lines changed

library/std/src/sys/pal/windows/stack_overflow.rs

+7-19
Original file line numberDiff line numberDiff line change
@@ -3,21 +3,10 @@
33
use crate::sys::c;
44
use crate::thread;
55

6-
use super::api;
7-
8-
pub struct Handler;
9-
10-
impl Handler {
11-
pub unsafe fn new() -> Handler {
12-
// This API isn't available on XP, so don't panic in that case and just
13-
// pray it works out ok.
14-
if c::SetThreadStackGuarantee(&mut 0x5000) == 0
15-
&& api::get_last_error().code != c::ERROR_CALL_NOT_IMPLEMENTED
16-
{
17-
panic!("failed to reserve stack space for exception handling");
18-
}
19-
Handler
20-
}
6+
/// Reserve stack space for use in stack overflow exceptions.
7+
pub unsafe fn reserve_stack() {
8+
let result = c::SetThreadStackGuarantee(&mut 0x5000);
9+
debug_assert_ne!(result, 0, "failed to reserve stack space for exception handling");
2110
}
2211

2312
unsafe extern "system" fn vectored_handler(ExceptionInfo: *mut c::EXCEPTION_POINTERS) -> c::LONG {
@@ -36,9 +25,8 @@ unsafe extern "system" fn vectored_handler(ExceptionInfo: *mut c::EXCEPTION_POIN
3625
}
3726

3827
pub unsafe fn init() {
39-
if c::AddVectoredExceptionHandler(0, Some(vectored_handler)).is_null() {
40-
panic!("failed to install exception handler");
41-
}
28+
let result = c::AddVectoredExceptionHandler(0, Some(vectored_handler));
29+
debug_assert!(!result.is_null(), "failed to install exception handler");
4230
// Set the thread stack guarantee for the main thread.
43-
let _h = Handler::new();
31+
reserve_stack();
4432
}
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,4 @@
11
#![cfg_attr(test, allow(dead_code))]
22

3-
pub struct Handler;
4-
5-
impl Handler {
6-
pub fn new() -> Handler {
7-
Handler
8-
}
9-
}
10-
3+
pub unsafe fn reserve_stack() {}
114
pub unsafe fn init() {}

library/std/src/sys/pal/windows/thread.rs

+2-3
Original file line numberDiff line numberDiff line change
@@ -48,9 +48,8 @@ impl Thread {
4848

4949
extern "system" fn thread_start(main: *mut c_void) -> c::DWORD {
5050
unsafe {
51-
// Next, set up our stack overflow handler which may get triggered if we run
52-
// out of stack.
53-
let _handler = stack_overflow::Handler::new();
51+
// Next, reserve some stack space for if we otherwise run out of stack.
52+
stack_overflow::reserve_stack();
5453
// Finally, let's run some code.
5554
Box::from_raw(main as *mut Box<dyn FnOnce()>)();
5655
}

0 commit comments

Comments
 (0)