Skip to content

Commit ff3fd6a

Browse files
committed
std::thread update freensd stack guard handling.
up to now, it had been assumed the stack guard setting default is not touched in the field but some user might just want to disable it or increase it. checking it once at runtime should be enough.
1 parent 8c0b4f6 commit ff3fd6a

File tree

1 file changed

+34
-5
lines changed

1 file changed

+34
-5
lines changed

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

+34-5
Original file line numberDiff line numberDiff line change
@@ -847,11 +847,40 @@ pub mod guard {
847847
let stackptr = get_stack_start_aligned()?;
848848
let guardaddr = stackptr.addr();
849849
// Technically the number of guard pages is tunable and controlled
850-
// by the security.bsd.stack_guard_page sysctl, but there are
851-
// few reasons to change it from the default. The default value has
852-
// been 1 ever since FreeBSD 11.1 and 10.4.
853-
const GUARD_PAGES: usize = 1;
854-
let guard = guardaddr..guardaddr + GUARD_PAGES * page_size;
850+
// by the security.bsd.stack_guard_page sysctl.
851+
// By default it is 1, checking once is enough since it is
852+
// a boot time config value.
853+
static LOCK: crate::sync::OnceLock<usize> = crate::sync::OnceLock::new();
854+
let guard = guardaddr
855+
..guardaddr
856+
+ *LOCK.get_or_init(|| {
857+
extern "C" {
858+
pub fn sysctlbyname(
859+
oid: *const libc::c_char,
860+
ov: *mut libc::c_void,
861+
osize: *mut libc::size_t,
862+
nv: *const libc::c_void,
863+
nsize: libc::size_t,
864+
) -> libc::c_int;
865+
}
866+
let mut guard: usize = 0;
867+
let mut size = crate::mem::size_of_val(&guard);
868+
let oid = crate::ffi::CStr::from_bytes_with_nul(
869+
b"security.bsd.stack_guard_page\0",
870+
)
871+
.unwrap();
872+
let res = sysctlbyname(
873+
oid.as_ptr(),
874+
&mut guard as *mut _ as *mut _,
875+
&mut size as *mut _ as *mut _,
876+
crate::ptr::null_mut(),
877+
0,
878+
);
879+
if res == 0 {
880+
return guard;
881+
}
882+
1
883+
}) * page_size;
855884
Some(guard)
856885
} else if cfg!(target_os = "openbsd") {
857886
// OpenBSD stack already includes a guard page, and stack is

0 commit comments

Comments
 (0)