Skip to content

Commit bf323ba

Browse files
Rollup merge of #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 472c820 + 6686ca0 commit bf323ba

File tree

1 file changed

+25
-5
lines changed

1 file changed

+25
-5
lines changed

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

+25-5
Original file line numberDiff line numberDiff line change
@@ -847,11 +847,31 @@ 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+
use crate::sys::weak::dlsym;
858+
dlsym!(fn sysctlbyname(*const libc::c_char, *mut libc::c_void, *mut libc::size_t, *const libc::c_void, libc::size_t) -> libc::c_int);
859+
let mut guard: usize = 0;
860+
let mut size = crate::mem::size_of_val(&guard);
861+
let oid = crate::ffi::CStr::from_bytes_with_nul(
862+
b"security.bsd.stack_guard_page\0",
863+
)
864+
.unwrap();
865+
match sysctlbyname.get() {
866+
Some(fcn) => {
867+
if fcn(oid.as_ptr(), &mut guard as *mut _ as *mut _, &mut size as *mut _ as *mut _, crate::ptr::null_mut(), 0) == 0 {
868+
return guard;
869+
}
870+
return 1;
871+
},
872+
_ => { return 1; }
873+
}
874+
}) * page_size;
855875
Some(guard)
856876
} else if cfg!(target_os = "openbsd") {
857877
// OpenBSD stack already includes a guard page, and stack is

0 commit comments

Comments
 (0)