Skip to content

Commit b65f8ec

Browse files
authored
Rollup merge of rust-lang#120672 - devnexen:update_thread_stack_guardpages_fbsd, r=m-ou-se
std::thread update freebsd 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.
2 parents 330b494 + ff3fd6a commit b65f8ec

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
@@ -836,11 +836,40 @@ pub mod guard {
836836
let stackptr = get_stack_start_aligned()?;
837837
let guardaddr = stackptr.addr();
838838
// Technically the number of guard pages is tunable and controlled
839-
// by the security.bsd.stack_guard_page sysctl, but there are
840-
// few reasons to change it from the default. The default value has
841-
// been 1 ever since FreeBSD 11.1 and 10.4.
842-
const GUARD_PAGES: usize = 1;
843-
let guard = guardaddr..guardaddr + GUARD_PAGES * page_size;
839+
// by the security.bsd.stack_guard_page sysctl.
840+
// By default it is 1, checking once is enough since it is
841+
// a boot time config value.
842+
static LOCK: crate::sync::OnceLock<usize> = crate::sync::OnceLock::new();
843+
let guard = guardaddr
844+
..guardaddr
845+
+ *LOCK.get_or_init(|| {
846+
extern "C" {
847+
pub fn sysctlbyname(
848+
oid: *const libc::c_char,
849+
ov: *mut libc::c_void,
850+
osize: *mut libc::size_t,
851+
nv: *const libc::c_void,
852+
nsize: libc::size_t,
853+
) -> libc::c_int;
854+
}
855+
let mut guard: usize = 0;
856+
let mut size = crate::mem::size_of_val(&guard);
857+
let oid = crate::ffi::CStr::from_bytes_with_nul(
858+
b"security.bsd.stack_guard_page\0",
859+
)
860+
.unwrap();
861+
let res = sysctlbyname(
862+
oid.as_ptr(),
863+
&mut guard as *mut _ as *mut _,
864+
&mut size as *mut _ as *mut _,
865+
crate::ptr::null_mut(),
866+
0,
867+
);
868+
if res == 0 {
869+
return guard;
870+
}
871+
1
872+
}) * page_size;
844873
Some(guard)
845874
} else if cfg!(target_os = "openbsd") {
846875
// OpenBSD stack already includes a guard page, and stack is

0 commit comments

Comments
 (0)