time/sys/refresh_tz/unix.rs
1/// Whether the operating system has a thread-safe environment. This allows bypassing the check for
2/// if the process is multi-threaded.
3// This is the same value as `cfg!(target_os = "x")`.
4// Use byte-strings to work around current limitations of const eval.
5const OS_HAS_THREAD_SAFE_ENVIRONMENT: bool = match std::env::consts::OS.as_bytes() {
6 // https://github.com/illumos/illumos-gate/blob/0fb96ba1f1ce26ff8b286f8f928769a6afcb00a6/usr/src/lib/libc/port/gen/getenv.c
7 b"illumos"
8 // https://github.com/NetBSD/src/blob/f45028636a44111bc4af44d460924958a4460844/lib/libc/stdlib/getenv.c
9 // https://github.com/NetBSD/src/blob/f45028636a44111bc4af44d460924958a4460844/lib/libc/stdlib/setenv.c
10 | b"netbsd"
11 => true,
12 _ => false,
13};
14
15/// Update time zone information from the system.
16///
17/// For safety documentation, see [`time::util::refresh_tz`].
18pub(super) unsafe fn refresh_tz_unchecked() {
19 extern "C" {
20 #[cfg_attr(target_os = "netbsd", link_name = "__tzset50")]
21 fn tzset();
22 }
23
24 // Safety: The caller must uphold the safety requirements.
25 unsafe { tzset() };
26}
27
28/// Attempt to update time zone information from the system. Returns `None` if the call is not known
29/// to be sound.
30pub(super) fn refresh_tz() -> Option<()> {
31 // Refresh $TZ if and only if the call is known to be sound.
32 //
33 // Soundness can be guaranteed either by knowledge of the operating system or knowledge that the
34 // process is single-threaded. If the process is single-threaded, then the environment cannot
35 // be mutated by a different thread in the process while execution of this function is taking
36 // place, which can cause a segmentation fault by dereferencing a dangling pointer.
37 //
38 // If the `num_threads` crate is incapable of determining the number of running threads, then
39 // we conservatively return `None` to avoid a soundness bug.
40
41 if OS_HAS_THREAD_SAFE_ENVIRONMENT || num_threads::is_single_threaded() == Some(true) {
42 // Safety: The caller must uphold the safety requirements.
43 unsafe { refresh_tz_unchecked() };
44 Some(())
45 } else {
46 None
47 }
48}