Skip to content

Commit 485f882

Browse files
committed
Check conversion from Duration to timespec in futex_wait.
1 parent 2cf0f64 commit 485f882

File tree

1 file changed

+11
-12
lines changed

1 file changed

+11
-12
lines changed

library/std/src/sys/unix/futex.rs

+11-12
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,26 @@
11
#![cfg(any(target_os = "linux", target_os = "android"))]
22

3+
use crate::convert::TryInto;
4+
use crate::ptr::null;
35
use crate::sync::atomic::AtomicI32;
46
use crate::time::Duration;
57

68
pub fn futex_wait(futex: &AtomicI32, expected: i32, timeout: Option<Duration>) {
7-
let timespec;
8-
let timespec_ptr = match timeout {
9-
Some(timeout) => {
10-
timespec = libc::timespec {
11-
tv_sec: timeout.as_secs() as _,
12-
tv_nsec: timeout.subsec_nanos() as _,
13-
};
14-
&timespec as *const libc::timespec
15-
}
16-
None => crate::ptr::null(),
17-
};
9+
let timespec = timeout.and_then(|d| {
10+
Some(libc::timespec {
11+
// Sleep forever if the timeout is longer than fits in a timespec.
12+
tv_sec: d.as_secs().try_into().ok()?,
13+
// This conversion never truncates, as subsec_nanos is always <1e9.
14+
tv_nsec: d.subsec_nanos() as _,
15+
})
16+
});
1817
unsafe {
1918
libc::syscall(
2019
libc::SYS_futex,
2120
futex as *const AtomicI32,
2221
libc::FUTEX_WAIT | libc::FUTEX_PRIVATE_FLAG,
2322
expected,
24-
timespec_ptr,
23+
timespec.as_ref().map_or(null(), |d| d as *const libc::timespec),
2524
);
2625
}
2726
}

0 commit comments

Comments
 (0)