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 lives in crt1.o, not libc.so, so a shared library
42// cannot take a strong link-time reference to it (#153451), and dlsym cannot
43// find it in a statically linked executable, which has no dynamic symbol
44// table to search (#158939). A weak reference covers both: it binds at link
45// time in any executable, and in a shared library the runtime linker
46// resolves it against the environ the executable exports.
47#[cfg(target_os = "freebsd")]
48pub unsafe fn environ() -> *mut *const *const c_char {
49    unsafe extern "C" {
50        #[linkage = "extern_weak"]
51        static environ: *mut *const *const c_char;
52    }
53    unsafe { environ }
54}
55
56// Use the `environ` static which is part of POSIX.
57#[cfg(not(any(target_os = "freebsd", target_vendor = "apple")))]
58pub unsafe fn environ() -> *mut *const *const c_char {
59    unsafe extern "C" {
60        static mut environ: *const *const c_char;
61    }
62    &raw mut environ
63}
64
65static ENV_LOCK: RwLock<()> = RwLock::new(());
66
67pub fn env_read_lock() -> impl Drop {
68    ENV_LOCK.read().unwrap_or_else(PoisonError::into_inner)
69}
70
71/// Returns a vector of (variable, value) byte-vector pairs for all the
72/// environment variables of the current process.
73pub fn env() -> Env {
74    unsafe {
75        let _guard = env_read_lock();
76        let mut result = Vec::new();
77        // A null return means the platform could not locate the symbol;
78        // treat it like an empty environment.
79        let environ_ptr = environ();
80        if !environ_ptr.is_null() {
81            let mut environ = *environ_ptr;
82            if !environ.is_null() {
83                while !(*environ).is_null() {
84                    if let Some(key_value) = parse(CStr::from_ptr(*environ).to_bytes()) {
85                        result.push(key_value);
86                    }
87                    environ = environ.add(1);
88                }
89            }
90        }
91        return Env::new(result);
92    }
93
94    fn parse(input: &[u8]) -> Option<(OsString, OsString)> {
95        // Strategy (copied from glibc): Variable name and value are separated
96        // by an ASCII equals sign '='. Since a variable name must not be
97        // empty, allow variable names starting with an equals sign. Skip all
98        // malformed lines.
99        if input.is_empty() {
100            return None;
101        }
102        let pos = memchr::memchr(b'=', &input[1..]).map(|p| p + 1);
103        pos.map(|p| {
104            (
105                OsStringExt::from_vec(input[..p].to_vec()),
106                OsStringExt::from_vec(input[p + 1..].to_vec()),
107            )
108        })
109    }
110}
111
112pub fn getenv(k: &OsStr) -> Option<OsString> {
113    // environment variables with a nul byte can't be set, so their value is
114    // always None as well
115    run_with_cstr(k.as_bytes(), &|k| {
116        let _guard = env_read_lock();
117        let v = unsafe { libc::getenv(k.as_ptr()) } as *const libc::c_char;
118
119        if v.is_null() {
120            Ok(None)
121        } else {
122            // SAFETY: `v` cannot be mutated while executing this line since we've a read lock
123            let bytes = unsafe { CStr::from_ptr(v) }.to_bytes().to_vec();
124
125            Ok(Some(OsStringExt::from_vec(bytes)))
126        }
127    })
128    .ok()
129    .flatten()
130}
131
132pub unsafe fn setenv(k: &OsStr, v: &OsStr) -> io::Result<()> {
133    run_with_cstr(k.as_bytes(), &|k| {
134        run_with_cstr(v.as_bytes(), &|v| {
135            let _guard = ENV_LOCK.write();
136            cvt(unsafe { libc::setenv(k.as_ptr(), v.as_ptr(), 1) }).map(drop)
137        })
138    })
139}
140
141pub unsafe fn unsetenv(n: &OsStr) -> io::Result<()> {
142    run_with_cstr(n.as_bytes(), &|nbuf| {
143        let _guard = ENV_LOCK.write();
144        cvt(unsafe { libc::unsetenv(nbuf.as_ptr()) }).map(drop)
145    })
146}