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 // https://github.com/apple-oss-distributions/Libc/blob/63976b830a836a22649b806fe62e8614fe3e5555/stdlib/FreeBSD/getenv.c#L118
12 // https://github.com/apple-oss-distributions/Libc/blob/63976b830a836a22649b806fe62e8614fe3e5555/stdlib/FreeBSD/setenv.c#L446
13 // https://blog.rust-lang.org/2023/09/25/Increasing-Apple-Version-Requirements/
14 | b"macos"
15 => true,
16 _ => false,
17};
18
19/// Update time zone information from the system.
20///
21/// For safety documentation, see [`time::util::refresh_tz`].
22#[inline]
23pub(super) unsafe fn refresh_tz_unchecked() {
24 extern "C" {
25 #[cfg_attr(target_os = "netbsd", link_name = "__tzset50")]
26 fn tzset();
27 }
28
29 // Safety: The caller must uphold the safety requirements.
30 unsafe { tzset() };
31}
32
33/// Attempt to update time zone information from the system. Returns `None` if the call is not known
34/// to be sound.
35#[inline]
36pub(super) fn refresh_tz() -> Option<()> {
37 // Refresh $TZ if and only if the call is known to be sound.
38 //
39 // Soundness can be guaranteed either by knowledge of the operating system or knowledge that the
40 // process is single-threaded. If the process is single-threaded, then the environment cannot
41 // be mutated by a different thread in the process while execution of this function is taking
42 // place, which can cause a segmentation fault by dereferencing a dangling pointer.
43 //
44 // If the `num_threads` crate is incapable of determining the number of running threads, then
45 // we conservatively return `None` to avoid a soundness bug.
46
47 if OS_HAS_THREAD_SAFE_ENVIRONMENT || num_threads::is_single_threaded() == Some(true) {
48 // Safety: The caller must uphold the safety requirements.
49 unsafe { refresh_tz_unchecked() };
50 Some(())
51 } else {
52 None
53 }
54}