Skip to content

Commit 490be60

Browse files
authored
Fix undefined behavior when initializing cpu_set_t
While working on implementing a safe abstraction around `cpu_set_t` for the `rsix` crate I've find you're usage of `cpu_set_t`. However you're usage of it is instant UB because you initialize them when `MaybeUninit::uninit().assume_init()` which is UB by definition. Comment from bjorn3: > With UB anything is allowed including compiling it correctly. A future compiler version may replace MaybeUninit::uninit().assume_init() with intrinsics::unreachable(), which makes the syscall trivially unreachable. Replace their usage with `std::mem::zeroed` witch is the same as using `CPU_ZERO` after initilization.
1 parent 03b0d5a commit 490be60

File tree

1 file changed

+3
-7
lines changed

1 file changed

+3
-7
lines changed

src/linux.rs

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,10 @@
11
use crate::Result;
22
use ::libc::*;
3-
use std::mem::{size_of, MaybeUninit};
3+
use std::mem::{zeroed, size_of, MaybeUninit};
44

55
pub fn set_thread_affinity(core_ids: &[usize]) -> Result<()> {
6-
#[allow(clippy::uninit_assumed_init)]
7-
let mut set: cpu_set_t = unsafe { MaybeUninit::uninit().assume_init() };
6+
let mut set: cpu_set_t = unsafe { zeroed() };
87
unsafe {
9-
CPU_ZERO(&mut set);
108
for core_id in core_ids {
119
CPU_SET(*core_id, &mut set);
1210
}
@@ -23,9 +21,7 @@ pub fn set_thread_affinity(core_ids: &[usize]) -> Result<()> {
2321

2422
pub fn get_thread_affinity() -> Result<Vec<usize>> {
2523
let mut affinity = Vec::new();
26-
#[allow(clippy::uninit_assumed_init)]
27-
let mut set: cpu_set_t = unsafe { MaybeUninit::uninit().assume_init() };
28-
unsafe { CPU_ZERO(&mut set) };
24+
let mut set: cpu_set_t = unsafe { zeroed() };
2925

3026
if let Err(e) = _sched_getaffinity(0, size_of::<cpu_set_t>(), &mut set) {
3127
return Err(From::from(format!(

0 commit comments

Comments
 (0)