Skip to main content

std/sys/env/
unix.rs

1use core::slice::memchr;
2
3use libc::c_char;
4
5pub use super::common::Env;
6use crate::ffi::{CStr, OsStr, OsString};
7use crate::io;
8use crate::os::unix::prelude::*;
9use crate::sync::{PoisonError, RwLock};
10use crate::sys::cvt;
11use crate::sys::helpers::run_with_cstr;
12
13// Use `_NSGetEnviron` on Apple platforms.
14//
15// `_NSGetEnviron` is the documented alternative (see `man environ`), and has
16// been available since the first versions of both macOS and iOS.
17//
18// Nowadays, specifically since macOS 10.8, `environ` has been exposed through
19// `libdyld.dylib`, which is linked via. `libSystem.dylib`:
20// <https://github.com/apple-oss-distributions/dyld/blob/dyld-1160.6/libdyld/libdyldGlue.cpp#L913>
21//
22// So in the end, it likely doesn't really matter which option we use, but the
23// performance cost of using `_NSGetEnviron` is extremely miniscule, and it
24// might be ever so slightly more supported, so let's just use that.
25//
26// NOTE: The header where this is defined (`crt_externs.h`) was added to the
27// iOS 13.0 SDK, which has been the source of a great deal of confusion in the
28// past about the availability of this API.
29//
30// NOTE(madsmtm): Neither this nor using `environ` has been verified to not
31// cause App Store rejections; if this is found to be the case, an alternative
32// implementation of this is possible using `[NSProcessInfo environment]`
33// - which internally uses `_NSGetEnviron` and a system-wide lock on the
34// environment variables to protect against `setenv`, so using that might be
35// desirable anyhow? Though it also means that we have to link to Foundation.
36#[cfg(target_vendor = "apple")]
37pub unsafe fn environ() -> *mut *const *const c_char {
38    unsafe { libc::_NSGetEnviron() as *mut *const *const c_char }
39}
40
41// On FreeBSD, environ comes from CRT rather than libc
42#[cfg(target_os = "freebsd")]
43pub unsafe fn environ() -> *mut *const *const c_char {
44    use crate::sync::LazyLock;
45
46    struct Environ(*mut *const *const c_char);
47    unsafe impl Send for Environ {}
48    unsafe impl Sync for Environ {}
49
50    static ENVIRON: LazyLock<Environ> = LazyLock::new(|| {
51        Environ(unsafe {
52            libc::dlsym(libc::RTLD_DEFAULT, c"environ".as_ptr()) as *mut *const *const c_char
53        })
54    });
55    ENVIRON.0
56}
57
58// Use the `environ` static which is part of POSIX.
59#[cfg(not(any(target_os = "freebsd", target_vendor = "apple")))]
60pub unsafe fn environ() -> *mut *const *const c_char {
61    unsafe extern "C" {
62        static mut environ: *const *const c_char;
63    }
64    &raw mut environ
65}
66
67static ENV_LOCK: RwLock<()> = RwLock::new(());
68
69pub fn env_read_lock() -> impl Drop {
70    ENV_LOCK.read().unwrap_or_else(PoisonError::into_inner)
71}
72
73/// Returns a vector of (variable, value) byte-vector pairs for all the
74/// environment variables of the current process.
75pub fn env() -> Env {
76    unsafe {
77        let _guard = env_read_lock();
78        let mut environ = *environ();
79        let mut result = Vec::new();
80        if !environ.is_null() {
81            while !(*environ).is_null() {
82                if let Some(key_value) = parse(CStr::from_ptr(*environ).to_bytes()) {
83                    result.push(key_value);
84                }
85                environ = environ.add(1);
86            }
87        }
88        return Env::new(result);
89    }
90
91    fn parse(input: &[u8]) -> Option<(OsString, OsString)> {
92        // Strategy (copied from glibc): Variable name and value are separated
93        // by an ASCII equals sign '='. Since a variable name must not be
94        // empty, allow variable names starting with an equals sign. Skip all
95        // malformed lines.
96        if input.is_empty() {
97            return None;
98        }
99        let pos = memchr::memchr(b'=', &input[1..]).map(|p| p + 1);
100        pos.map(|p| {
101            (
102                OsStringExt::from_vec(input[..p].to_vec()),
103                OsStringExt::from_vec(input[p + 1..].to_vec()),
104            )
105        })
106    }
107}
108
109pub fn getenv(k: &OsStr) -> Option<OsString> {
110    // environment variables with a nul byte can't be set, so their value is
111    // always None as well
112    run_with_cstr(k.as_bytes(), &|k| {
113        let _guard = env_read_lock();
114        let v = unsafe { libc::getenv(k.as_ptr()) } as *const libc::c_char;
115
116        if v.is_null() {
117            Ok(None)
118        } else {
119            // SAFETY: `v` cannot be mutated while executing this line since we've a read lock
120            let bytes = unsafe { CStr::from_ptr(v) }.to_bytes().to_vec();
121
122            Ok(Some(OsStringExt::from_vec(bytes)))
123        }
124    })
125    .ok()
126    .flatten()
127}
128
129pub unsafe fn setenv(k: &OsStr, v: &OsStr) -> io::Result<()> {
130    run_with_cstr(k.as_bytes(), &|k| {
131        run_with_cstr(v.as_bytes(), &|v| {
132            let _guard = ENV_LOCK.write();
133            cvt(unsafe { libc::setenv(k.as_ptr(), v.as_ptr(), 1) }).map(drop)
134        })
135    })
136}
137
138pub unsafe fn unsetenv(n: &OsStr) -> io::Result<()> {
139    run_with_cstr(n.as_bytes(), &|nbuf| {
140        let _guard = ENV_LOCK.write();
141        cvt(unsafe { libc::unsetenv(nbuf.as_ptr()) }).map(drop)
142    })
143}