std/sys/pal/unix/
os.rs

1//! Implementation of `std::os` functionality for unix systems
2
3#![allow(unused_imports)] // lots of cfg code here
4
5#[cfg(test)]
6mod tests;
7
8use core::slice::memchr;
9
10use libc::{c_char, c_int, c_void};
11
12use crate::error::Error as StdError;
13use crate::ffi::{CStr, CString, OsStr, OsString};
14use crate::os::unix::prelude::*;
15use crate::path::{self, PathBuf};
16use crate::sync::{PoisonError, RwLock};
17use crate::sys::common::small_c_string::{run_path_with_cstr, run_with_cstr};
18#[cfg(all(target_env = "gnu", not(target_os = "vxworks")))]
19use crate::sys::weak::weak;
20use crate::sys::{cvt, fd};
21use crate::{fmt, io, iter, mem, ptr, slice, str, vec};
22
23const TMPBUF_SZ: usize = 128;
24
25cfg_if::cfg_if! {
26    if #[cfg(target_os = "redox")] {
27        const PATH_SEPARATOR: u8 = b';';
28    } else {
29        const PATH_SEPARATOR: u8 = b':';
30    }
31}
32
33unsafe extern "C" {
34    #[cfg(not(any(target_os = "dragonfly", target_os = "vxworks", target_os = "rtems")))]
35    #[cfg_attr(
36        any(
37            target_os = "linux",
38            target_os = "emscripten",
39            target_os = "fuchsia",
40            target_os = "l4re",
41            target_os = "hurd",
42        ),
43        link_name = "__errno_location"
44    )]
45    #[cfg_attr(
46        any(
47            target_os = "netbsd",
48            target_os = "openbsd",
49            target_os = "android",
50            target_os = "redox",
51            target_os = "nuttx",
52            target_env = "newlib"
53        ),
54        link_name = "__errno"
55    )]
56    #[cfg_attr(any(target_os = "solaris", target_os = "illumos"), link_name = "___errno")]
57    #[cfg_attr(target_os = "nto", link_name = "__get_errno_ptr")]
58    #[cfg_attr(any(target_os = "freebsd", target_vendor = "apple"), link_name = "__error")]
59    #[cfg_attr(target_os = "haiku", link_name = "_errnop")]
60    #[cfg_attr(target_os = "aix", link_name = "_Errno")]
61    fn errno_location() -> *mut c_int;
62}
63
64/// Returns the platform-specific value of errno
65#[cfg(not(any(target_os = "dragonfly", target_os = "vxworks", target_os = "rtems")))]
66pub fn errno() -> i32 {
67    unsafe { (*errno_location()) as i32 }
68}
69
70/// Sets the platform-specific value of errno
71// needed for readdir and syscall!
72#[cfg(all(not(target_os = "dragonfly"), not(target_os = "vxworks"), not(target_os = "rtems")))]
73#[allow(dead_code)] // but not all target cfgs actually end up using it
74pub fn set_errno(e: i32) {
75    unsafe { *errno_location() = e as c_int }
76}
77
78#[cfg(target_os = "vxworks")]
79pub fn errno() -> i32 {
80    unsafe { libc::errnoGet() }
81}
82
83#[cfg(target_os = "rtems")]
84pub fn errno() -> i32 {
85    unsafe extern "C" {
86        #[thread_local]
87        static _tls_errno: c_int;
88    }
89
90    unsafe { _tls_errno as i32 }
91}
92
93#[cfg(target_os = "dragonfly")]
94pub fn errno() -> i32 {
95    unsafe extern "C" {
96        #[thread_local]
97        static errno: c_int;
98    }
99
100    unsafe { errno as i32 }
101}
102
103#[cfg(target_os = "dragonfly")]
104#[allow(dead_code)]
105pub fn set_errno(e: i32) {
106    unsafe extern "C" {
107        #[thread_local]
108        static mut errno: c_int;
109    }
110
111    unsafe {
112        errno = e;
113    }
114}
115
116/// Gets a detailed string description for the given error number.
117pub fn error_string(errno: i32) -> String {
118    unsafe extern "C" {
119        #[cfg_attr(
120            all(
121                any(target_os = "linux", target_os = "hurd", target_env = "newlib"),
122                not(target_env = "ohos")
123            ),
124            link_name = "__xpg_strerror_r"
125        )]
126        fn strerror_r(errnum: c_int, buf: *mut c_char, buflen: libc::size_t) -> c_int;
127    }
128
129    let mut buf = [0 as c_char; TMPBUF_SZ];
130
131    let p = buf.as_mut_ptr();
132    unsafe {
133        if strerror_r(errno as c_int, p, buf.len()) < 0 {
134            panic!("strerror_r failure");
135        }
136
137        let p = p as *const _;
138        // We can't always expect a UTF-8 environment. When we don't get that luxury,
139        // it's better to give a low-quality error message than none at all.
140        String::from_utf8_lossy(CStr::from_ptr(p).to_bytes()).into()
141    }
142}
143
144#[cfg(target_os = "espidf")]
145pub fn getcwd() -> io::Result<PathBuf> {
146    Ok(PathBuf::from("/"))
147}
148
149#[cfg(not(target_os = "espidf"))]
150pub fn getcwd() -> io::Result<PathBuf> {
151    let mut buf = Vec::with_capacity(512);
152    loop {
153        unsafe {
154            let ptr = buf.as_mut_ptr() as *mut libc::c_char;
155            if !libc::getcwd(ptr, buf.capacity()).is_null() {
156                let len = CStr::from_ptr(buf.as_ptr() as *const libc::c_char).to_bytes().len();
157                buf.set_len(len);
158                buf.shrink_to_fit();
159                return Ok(PathBuf::from(OsString::from_vec(buf)));
160            } else {
161                let error = io::Error::last_os_error();
162                if error.raw_os_error() != Some(libc::ERANGE) {
163                    return Err(error);
164                }
165            }
166
167            // Trigger the internal buffer resizing logic of `Vec` by requiring
168            // more space than the current capacity.
169            let cap = buf.capacity();
170            buf.set_len(cap);
171            buf.reserve(1);
172        }
173    }
174}
175
176#[cfg(target_os = "espidf")]
177pub fn chdir(_p: &path::Path) -> io::Result<()> {
178    super::unsupported::unsupported()
179}
180
181#[cfg(not(target_os = "espidf"))]
182pub fn chdir(p: &path::Path) -> io::Result<()> {
183    let result = run_path_with_cstr(p, &|p| unsafe { Ok(libc::chdir(p.as_ptr())) })?;
184    if result == 0 { Ok(()) } else { Err(io::Error::last_os_error()) }
185}
186
187pub struct SplitPaths<'a> {
188    iter: iter::Map<slice::Split<'a, u8, fn(&u8) -> bool>, fn(&'a [u8]) -> PathBuf>,
189}
190
191pub fn split_paths(unparsed: &OsStr) -> SplitPaths<'_> {
192    fn bytes_to_path(b: &[u8]) -> PathBuf {
193        PathBuf::from(<OsStr as OsStrExt>::from_bytes(b))
194    }
195    fn is_separator(b: &u8) -> bool {
196        *b == PATH_SEPARATOR
197    }
198    let unparsed = unparsed.as_bytes();
199    SplitPaths {
200        iter: unparsed
201            .split(is_separator as fn(&u8) -> bool)
202            .map(bytes_to_path as fn(&[u8]) -> PathBuf),
203    }
204}
205
206impl<'a> Iterator for SplitPaths<'a> {
207    type Item = PathBuf;
208    fn next(&mut self) -> Option<PathBuf> {
209        self.iter.next()
210    }
211    fn size_hint(&self) -> (usize, Option<usize>) {
212        self.iter.size_hint()
213    }
214}
215
216#[derive(Debug)]
217pub struct JoinPathsError;
218
219pub fn join_paths<I, T>(paths: I) -> Result<OsString, JoinPathsError>
220where
221    I: Iterator<Item = T>,
222    T: AsRef<OsStr>,
223{
224    let mut joined = Vec::new();
225
226    for (i, path) in paths.enumerate() {
227        let path = path.as_ref().as_bytes();
228        if i > 0 {
229            joined.push(PATH_SEPARATOR)
230        }
231        if path.contains(&PATH_SEPARATOR) {
232            return Err(JoinPathsError);
233        }
234        joined.extend_from_slice(path);
235    }
236    Ok(OsStringExt::from_vec(joined))
237}
238
239impl fmt::Display for JoinPathsError {
240    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
241        write!(f, "path segment contains separator `{}`", char::from(PATH_SEPARATOR))
242    }
243}
244
245impl StdError for JoinPathsError {
246    #[allow(deprecated)]
247    fn description(&self) -> &str {
248        "failed to join paths"
249    }
250}
251
252#[cfg(target_os = "aix")]
253pub fn current_exe() -> io::Result<PathBuf> {
254    #[cfg(test)]
255    use realstd::env;
256
257    #[cfg(not(test))]
258    use crate::env;
259    use crate::io::ErrorKind;
260
261    let exe_path = env::args().next().ok_or(io::const_error!(
262        ErrorKind::NotFound,
263        "an executable path was not found because no arguments were provided through argv",
264    ))?;
265    let path = PathBuf::from(exe_path);
266    if path.is_absolute() {
267        return path.canonicalize();
268    }
269    // Search PWD to infer current_exe.
270    if let Some(pstr) = path.to_str()
271        && pstr.contains("/")
272    {
273        return getcwd().map(|cwd| cwd.join(path))?.canonicalize();
274    }
275    // Search PATH to infer current_exe.
276    if let Some(p) = getenv(OsStr::from_bytes("PATH".as_bytes())) {
277        for search_path in split_paths(&p) {
278            let pb = search_path.join(&path);
279            if pb.is_file()
280                && let Ok(metadata) = crate::fs::metadata(&pb)
281                && metadata.permissions().mode() & 0o111 != 0
282            {
283                return pb.canonicalize();
284            }
285        }
286    }
287    Err(io::const_error!(ErrorKind::NotFound, "an executable path was not found"))
288}
289
290#[cfg(any(target_os = "freebsd", target_os = "dragonfly"))]
291pub fn current_exe() -> io::Result<PathBuf> {
292    unsafe {
293        let mut mib = [
294            libc::CTL_KERN as c_int,
295            libc::KERN_PROC as c_int,
296            libc::KERN_PROC_PATHNAME as c_int,
297            -1 as c_int,
298        ];
299        let mut sz = 0;
300        cvt(libc::sysctl(
301            mib.as_mut_ptr(),
302            mib.len() as libc::c_uint,
303            ptr::null_mut(),
304            &mut sz,
305            ptr::null_mut(),
306            0,
307        ))?;
308        if sz == 0 {
309            return Err(io::Error::last_os_error());
310        }
311        let mut v: Vec<u8> = Vec::with_capacity(sz);
312        cvt(libc::sysctl(
313            mib.as_mut_ptr(),
314            mib.len() as libc::c_uint,
315            v.as_mut_ptr() as *mut libc::c_void,
316            &mut sz,
317            ptr::null_mut(),
318            0,
319        ))?;
320        if sz == 0 {
321            return Err(io::Error::last_os_error());
322        }
323        v.set_len(sz - 1); // chop off trailing NUL
324        Ok(PathBuf::from(OsString::from_vec(v)))
325    }
326}
327
328#[cfg(target_os = "netbsd")]
329pub fn current_exe() -> io::Result<PathBuf> {
330    fn sysctl() -> io::Result<PathBuf> {
331        unsafe {
332            let mib = [libc::CTL_KERN, libc::KERN_PROC_ARGS, -1, libc::KERN_PROC_PATHNAME];
333            let mut path_len: usize = 0;
334            cvt(libc::sysctl(
335                mib.as_ptr(),
336                mib.len() as libc::c_uint,
337                ptr::null_mut(),
338                &mut path_len,
339                ptr::null(),
340                0,
341            ))?;
342            if path_len <= 1 {
343                return Err(io::const_error!(
344                    io::ErrorKind::Uncategorized,
345                    "KERN_PROC_PATHNAME sysctl returned zero-length string",
346                ));
347            }
348            let mut path: Vec<u8> = Vec::with_capacity(path_len);
349            cvt(libc::sysctl(
350                mib.as_ptr(),
351                mib.len() as libc::c_uint,
352                path.as_ptr() as *mut libc::c_void,
353                &mut path_len,
354                ptr::null(),
355                0,
356            ))?;
357            path.set_len(path_len - 1); // chop off NUL
358            Ok(PathBuf::from(OsString::from_vec(path)))
359        }
360    }
361    fn procfs() -> io::Result<PathBuf> {
362        let curproc_exe = path::Path::new("/proc/curproc/exe");
363        if curproc_exe.is_file() {
364            return crate::fs::read_link(curproc_exe);
365        }
366        Err(io::const_error!(
367            io::ErrorKind::Uncategorized,
368            "/proc/curproc/exe doesn't point to regular file.",
369        ))
370    }
371    sysctl().or_else(|_| procfs())
372}
373
374#[cfg(target_os = "openbsd")]
375pub fn current_exe() -> io::Result<PathBuf> {
376    unsafe {
377        let mut mib = [libc::CTL_KERN, libc::KERN_PROC_ARGS, libc::getpid(), libc::KERN_PROC_ARGV];
378        let mib = mib.as_mut_ptr();
379        let mut argv_len = 0;
380        cvt(libc::sysctl(mib, 4, ptr::null_mut(), &mut argv_len, ptr::null_mut(), 0))?;
381        let mut argv = Vec::<*const libc::c_char>::with_capacity(argv_len as usize);
382        cvt(libc::sysctl(mib, 4, argv.as_mut_ptr() as *mut _, &mut argv_len, ptr::null_mut(), 0))?;
383        argv.set_len(argv_len as usize);
384        if argv[0].is_null() {
385            return Err(io::const_error!(io::ErrorKind::Uncategorized, "no current exe available"));
386        }
387        let argv0 = CStr::from_ptr(argv[0]).to_bytes();
388        if argv0[0] == b'.' || argv0.iter().any(|b| *b == b'/') {
389            crate::fs::canonicalize(OsStr::from_bytes(argv0))
390        } else {
391            Ok(PathBuf::from(OsStr::from_bytes(argv0)))
392        }
393    }
394}
395
396#[cfg(any(
397    target_os = "linux",
398    target_os = "hurd",
399    target_os = "android",
400    target_os = "nuttx",
401    target_os = "emscripten"
402))]
403pub fn current_exe() -> io::Result<PathBuf> {
404    match crate::fs::read_link("/proc/self/exe") {
405        Err(ref e) if e.kind() == io::ErrorKind::NotFound => Err(io::const_error!(
406            io::ErrorKind::Uncategorized,
407            "no /proc/self/exe available. Is /proc mounted?",
408        )),
409        other => other,
410    }
411}
412
413#[cfg(target_os = "nto")]
414pub fn current_exe() -> io::Result<PathBuf> {
415    let mut e = crate::fs::read("/proc/self/exefile")?;
416    // Current versions of QNX Neutrino provide a null-terminated path.
417    // Ensure the trailing null byte is not returned here.
418    if let Some(0) = e.last() {
419        e.pop();
420    }
421    Ok(PathBuf::from(OsString::from_vec(e)))
422}
423
424#[cfg(target_vendor = "apple")]
425pub fn current_exe() -> io::Result<PathBuf> {
426    unsafe {
427        let mut sz: u32 = 0;
428        #[expect(deprecated)]
429        libc::_NSGetExecutablePath(ptr::null_mut(), &mut sz);
430        if sz == 0 {
431            return Err(io::Error::last_os_error());
432        }
433        let mut v: Vec<u8> = Vec::with_capacity(sz as usize);
434        #[expect(deprecated)]
435        let err = libc::_NSGetExecutablePath(v.as_mut_ptr() as *mut i8, &mut sz);
436        if err != 0 {
437            return Err(io::Error::last_os_error());
438        }
439        v.set_len(sz as usize - 1); // chop off trailing NUL
440        Ok(PathBuf::from(OsString::from_vec(v)))
441    }
442}
443
444#[cfg(any(target_os = "solaris", target_os = "illumos"))]
445pub fn current_exe() -> io::Result<PathBuf> {
446    if let Ok(path) = crate::fs::read_link("/proc/self/path/a.out") {
447        Ok(path)
448    } else {
449        unsafe {
450            let path = libc::getexecname();
451            if path.is_null() {
452                Err(io::Error::last_os_error())
453            } else {
454                let filename = CStr::from_ptr(path).to_bytes();
455                let path = PathBuf::from(<OsStr as OsStrExt>::from_bytes(filename));
456
457                // Prepend a current working directory to the path if
458                // it doesn't contain an absolute pathname.
459                if filename[0] == b'/' { Ok(path) } else { getcwd().map(|cwd| cwd.join(path)) }
460            }
461        }
462    }
463}
464
465#[cfg(target_os = "haiku")]
466pub fn current_exe() -> io::Result<PathBuf> {
467    let mut name = vec![0; libc::PATH_MAX as usize];
468    unsafe {
469        let result = libc::find_path(
470            crate::ptr::null_mut(),
471            libc::path_base_directory::B_FIND_PATH_IMAGE_PATH,
472            crate::ptr::null_mut(),
473            name.as_mut_ptr(),
474            name.len(),
475        );
476        if result != libc::B_OK {
477            use crate::io::ErrorKind;
478            Err(io::const_error!(ErrorKind::Uncategorized, "Error getting executable path"))
479        } else {
480            // find_path adds the null terminator.
481            let name = CStr::from_ptr(name.as_ptr()).to_bytes();
482            Ok(PathBuf::from(OsStr::from_bytes(name)))
483        }
484    }
485}
486
487#[cfg(any(target_os = "redox", target_os = "rtems"))]
488pub fn current_exe() -> io::Result<PathBuf> {
489    crate::fs::read_to_string("sys:exe").map(PathBuf::from)
490}
491
492#[cfg(target_os = "l4re")]
493pub fn current_exe() -> io::Result<PathBuf> {
494    use crate::io::ErrorKind;
495    Err(io::const_error!(ErrorKind::Unsupported, "Not yet implemented!"))
496}
497
498#[cfg(target_os = "vxworks")]
499pub fn current_exe() -> io::Result<PathBuf> {
500    #[cfg(test)]
501    use realstd::env;
502
503    #[cfg(not(test))]
504    use crate::env;
505
506    let exe_path = env::args().next().unwrap();
507    let path = path::Path::new(&exe_path);
508    path.canonicalize()
509}
510
511#[cfg(any(target_os = "espidf", target_os = "horizon", target_os = "vita"))]
512pub fn current_exe() -> io::Result<PathBuf> {
513    super::unsupported::unsupported()
514}
515
516#[cfg(target_os = "fuchsia")]
517pub fn current_exe() -> io::Result<PathBuf> {
518    #[cfg(test)]
519    use realstd::env;
520
521    #[cfg(not(test))]
522    use crate::env;
523    use crate::io::ErrorKind;
524
525    let exe_path = env::args().next().ok_or(io::const_error!(
526        ErrorKind::Uncategorized,
527        "an executable path was not found because no arguments were provided through argv",
528    ))?;
529    let path = PathBuf::from(exe_path);
530
531    // Prepend the current working directory to the path if it's not absolute.
532    if !path.is_absolute() { getcwd().map(|cwd| cwd.join(path)) } else { Ok(path) }
533}
534
535pub struct Env {
536    iter: vec::IntoIter<(OsString, OsString)>,
537}
538
539// FIXME(https://github.com/rust-lang/rust/issues/114583): Remove this when <OsStr as Debug>::fmt matches <str as Debug>::fmt.
540pub struct EnvStrDebug<'a> {
541    slice: &'a [(OsString, OsString)],
542}
543
544impl fmt::Debug for EnvStrDebug<'_> {
545    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
546        let Self { slice } = self;
547        f.debug_list()
548            .entries(slice.iter().map(|(a, b)| (a.to_str().unwrap(), b.to_str().unwrap())))
549            .finish()
550    }
551}
552
553impl Env {
554    pub fn str_debug(&self) -> impl fmt::Debug + '_ {
555        let Self { iter } = self;
556        EnvStrDebug { slice: iter.as_slice() }
557    }
558}
559
560impl fmt::Debug for Env {
561    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
562        let Self { iter } = self;
563        f.debug_list().entries(iter.as_slice()).finish()
564    }
565}
566
567impl !Send for Env {}
568impl !Sync for Env {}
569
570impl Iterator for Env {
571    type Item = (OsString, OsString);
572    fn next(&mut self) -> Option<(OsString, OsString)> {
573        self.iter.next()
574    }
575    fn size_hint(&self) -> (usize, Option<usize>) {
576        self.iter.size_hint()
577    }
578}
579
580// Use `_NSGetEnviron` on Apple platforms.
581//
582// `_NSGetEnviron` is the documented alternative (see `man environ`), and has
583// been available since the first versions of both macOS and iOS.
584//
585// Nowadays, specifically since macOS 10.8, `environ` has been exposed through
586// `libdyld.dylib`, which is linked via. `libSystem.dylib`:
587// <https://github.com/apple-oss-distributions/dyld/blob/dyld-1160.6/libdyld/libdyldGlue.cpp#L913>
588//
589// So in the end, it likely doesn't really matter which option we use, but the
590// performance cost of using `_NSGetEnviron` is extremely miniscule, and it
591// might be ever so slightly more supported, so let's just use that.
592//
593// NOTE: The header where this is defined (`crt_externs.h`) was added to the
594// iOS 13.0 SDK, which has been the source of a great deal of confusion in the
595// past about the availability of this API.
596//
597// NOTE(madsmtm): Neither this nor using `environ` has been verified to not
598// cause App Store rejections; if this is found to be the case, an alternative
599// implementation of this is possible using `[NSProcessInfo environment]`
600// - which internally uses `_NSGetEnviron` and a system-wide lock on the
601// environment variables to protect against `setenv`, so using that might be
602// desirable anyhow? Though it also means that we have to link to Foundation.
603#[cfg(target_vendor = "apple")]
604pub unsafe fn environ() -> *mut *const *const c_char {
605    libc::_NSGetEnviron() as *mut *const *const c_char
606}
607
608// Use the `environ` static which is part of POSIX.
609#[cfg(not(target_vendor = "apple"))]
610pub unsafe fn environ() -> *mut *const *const c_char {
611    unsafe extern "C" {
612        static mut environ: *const *const c_char;
613    }
614    &raw mut environ
615}
616
617static ENV_LOCK: RwLock<()> = RwLock::new(());
618
619pub fn env_read_lock() -> impl Drop {
620    ENV_LOCK.read().unwrap_or_else(PoisonError::into_inner)
621}
622
623/// Returns a vector of (variable, value) byte-vector pairs for all the
624/// environment variables of the current process.
625pub fn env() -> Env {
626    unsafe {
627        let _guard = env_read_lock();
628        let mut environ = *environ();
629        let mut result = Vec::new();
630        if !environ.is_null() {
631            while !(*environ).is_null() {
632                if let Some(key_value) = parse(CStr::from_ptr(*environ).to_bytes()) {
633                    result.push(key_value);
634                }
635                environ = environ.add(1);
636            }
637        }
638        return Env { iter: result.into_iter() };
639    }
640
641    fn parse(input: &[u8]) -> Option<(OsString, OsString)> {
642        // Strategy (copied from glibc): Variable name and value are separated
643        // by an ASCII equals sign '='. Since a variable name must not be
644        // empty, allow variable names starting with an equals sign. Skip all
645        // malformed lines.
646        if input.is_empty() {
647            return None;
648        }
649        let pos = memchr::memchr(b'=', &input[1..]).map(|p| p + 1);
650        pos.map(|p| {
651            (
652                OsStringExt::from_vec(input[..p].to_vec()),
653                OsStringExt::from_vec(input[p + 1..].to_vec()),
654            )
655        })
656    }
657}
658
659pub fn getenv(k: &OsStr) -> Option<OsString> {
660    // environment variables with a nul byte can't be set, so their value is
661    // always None as well
662    run_with_cstr(k.as_bytes(), &|k| {
663        let _guard = env_read_lock();
664        let v = unsafe { libc::getenv(k.as_ptr()) } as *const libc::c_char;
665
666        if v.is_null() {
667            Ok(None)
668        } else {
669            // SAFETY: `v` cannot be mutated while executing this line since we've a read lock
670            let bytes = unsafe { CStr::from_ptr(v) }.to_bytes().to_vec();
671
672            Ok(Some(OsStringExt::from_vec(bytes)))
673        }
674    })
675    .ok()
676    .flatten()
677}
678
679pub unsafe fn setenv(k: &OsStr, v: &OsStr) -> io::Result<()> {
680    run_with_cstr(k.as_bytes(), &|k| {
681        run_with_cstr(v.as_bytes(), &|v| {
682            let _guard = ENV_LOCK.write();
683            cvt(libc::setenv(k.as_ptr(), v.as_ptr(), 1)).map(drop)
684        })
685    })
686}
687
688pub unsafe fn unsetenv(n: &OsStr) -> io::Result<()> {
689    run_with_cstr(n.as_bytes(), &|nbuf| {
690        let _guard = ENV_LOCK.write();
691        cvt(libc::unsetenv(nbuf.as_ptr())).map(drop)
692    })
693}
694
695#[cfg(not(target_os = "espidf"))]
696pub fn page_size() -> usize {
697    unsafe { libc::sysconf(libc::_SC_PAGESIZE) as usize }
698}
699
700// Returns the value for [`confstr(key, ...)`][posix_confstr]. Currently only
701// used on Darwin, but should work on any unix (in case we need to get
702// `_CS_PATH` or `_CS_V[67]_ENV` in the future).
703//
704// [posix_confstr]:
705//     https://pubs.opengroup.org/onlinepubs/9699919799/functions/confstr.html
706//
707// FIXME: Support `confstr` in Miri.
708#[cfg(all(target_vendor = "apple", not(miri)))]
709fn confstr(key: c_int, size_hint: Option<usize>) -> io::Result<OsString> {
710    let mut buf: Vec<u8> = Vec::with_capacity(0);
711    let mut bytes_needed_including_nul = size_hint
712        .unwrap_or_else(|| {
713            // Treat "None" as "do an extra call to get the length". In theory
714            // we could move this into the loop below, but it's hard to do given
715            // that it isn't 100% clear if it's legal to pass 0 for `len` when
716            // the buffer isn't null.
717            unsafe { libc::confstr(key, core::ptr::null_mut(), 0) }
718        })
719        .max(1);
720    // If the value returned by `confstr` is greater than the len passed into
721    // it, then the value was truncated, meaning we need to retry. Note that
722    // while `confstr` results don't seem to change for a process, it's unclear
723    // if this is guaranteed anywhere, so looping does seem required.
724    while bytes_needed_including_nul > buf.capacity() {
725        // We write into the spare capacity of `buf`. This lets us avoid
726        // changing buf's `len`, which both simplifies `reserve` computation,
727        // allows working with `Vec<u8>` instead of `Vec<MaybeUninit<u8>>`, and
728        // may avoid a copy, since the Vec knows that none of the bytes are needed
729        // when reallocating (well, in theory anyway).
730        buf.reserve(bytes_needed_including_nul);
731        // `confstr` returns
732        // - 0 in the case of errors: we break and return an error.
733        // - The number of bytes written, iff the provided buffer is enough to
734        //   hold the entire value: we break and return the data in `buf`.
735        // - Otherwise, the number of bytes needed (including nul): we go
736        //   through the loop again.
737        bytes_needed_including_nul =
738            unsafe { libc::confstr(key, buf.as_mut_ptr().cast::<c_char>(), buf.capacity()) };
739    }
740    // `confstr` returns 0 in the case of an error.
741    if bytes_needed_including_nul == 0 {
742        return Err(io::Error::last_os_error());
743    }
744    // Safety: `confstr(..., buf.as_mut_ptr(), buf.capacity())` returned a
745    // non-zero value, meaning `bytes_needed_including_nul` bytes were
746    // initialized.
747    unsafe {
748        buf.set_len(bytes_needed_including_nul);
749        // Remove the NUL-terminator.
750        let last_byte = buf.pop();
751        // ... and smoke-check that it *was* a NUL-terminator.
752        assert_eq!(last_byte, Some(0), "`confstr` provided a string which wasn't nul-terminated");
753    };
754    Ok(OsString::from_vec(buf))
755}
756
757#[cfg(all(target_vendor = "apple", not(miri)))]
758fn darwin_temp_dir() -> PathBuf {
759    confstr(libc::_CS_DARWIN_USER_TEMP_DIR, Some(64)).map(PathBuf::from).unwrap_or_else(|_| {
760        // It failed for whatever reason (there are several possible reasons),
761        // so return the global one.
762        PathBuf::from("/tmp")
763    })
764}
765
766pub fn temp_dir() -> PathBuf {
767    crate::env::var_os("TMPDIR").map(PathBuf::from).unwrap_or_else(|| {
768        cfg_if::cfg_if! {
769            if #[cfg(all(target_vendor = "apple", not(miri)))] {
770                darwin_temp_dir()
771            } else if #[cfg(target_os = "android")] {
772                PathBuf::from("/data/local/tmp")
773            } else {
774                PathBuf::from("/tmp")
775            }
776        }
777    })
778}
779
780pub fn home_dir() -> Option<PathBuf> {
781    return crate::env::var_os("HOME").or_else(|| unsafe { fallback() }).map(PathBuf::from);
782
783    #[cfg(any(
784        target_os = "android",
785        target_os = "emscripten",
786        target_os = "redox",
787        target_os = "vxworks",
788        target_os = "espidf",
789        target_os = "horizon",
790        target_os = "vita",
791        target_os = "nuttx",
792        all(target_vendor = "apple", not(target_os = "macos")),
793    ))]
794    unsafe fn fallback() -> Option<OsString> {
795        None
796    }
797    #[cfg(not(any(
798        target_os = "android",
799        target_os = "emscripten",
800        target_os = "redox",
801        target_os = "vxworks",
802        target_os = "espidf",
803        target_os = "horizon",
804        target_os = "vita",
805        target_os = "nuttx",
806        all(target_vendor = "apple", not(target_os = "macos")),
807    )))]
808    unsafe fn fallback() -> Option<OsString> {
809        let amt = match libc::sysconf(libc::_SC_GETPW_R_SIZE_MAX) {
810            n if n < 0 => 512 as usize,
811            n => n as usize,
812        };
813        let mut buf = Vec::with_capacity(amt);
814        let mut p = mem::MaybeUninit::<libc::passwd>::uninit();
815        let mut result = ptr::null_mut();
816        match libc::getpwuid_r(
817            libc::getuid(),
818            p.as_mut_ptr(),
819            buf.as_mut_ptr(),
820            buf.capacity(),
821            &mut result,
822        ) {
823            0 if !result.is_null() => {
824                let ptr = (*result).pw_dir as *const _;
825                let bytes = CStr::from_ptr(ptr).to_bytes().to_vec();
826                Some(OsStringExt::from_vec(bytes))
827            }
828            _ => None,
829        }
830    }
831}
832
833pub fn exit(code: i32) -> ! {
834    crate::sys::exit_guard::unique_thread_exit();
835    unsafe { libc::exit(code as c_int) }
836}
837
838pub fn getpid() -> u32 {
839    unsafe { libc::getpid() as u32 }
840}
841
842pub fn getppid() -> u32 {
843    unsafe { libc::getppid() as u32 }
844}
845
846#[cfg(all(target_os = "linux", target_env = "gnu"))]
847pub fn glibc_version() -> Option<(usize, usize)> {
848    unsafe extern "C" {
849        fn gnu_get_libc_version() -> *const libc::c_char;
850    }
851    let version_cstr = unsafe { CStr::from_ptr(gnu_get_libc_version()) };
852    if let Ok(version_str) = version_cstr.to_str() {
853        parse_glibc_version(version_str)
854    } else {
855        None
856    }
857}
858
859// Returns Some((major, minor)) if the string is a valid "x.y" version,
860// ignoring any extra dot-separated parts. Otherwise return None.
861#[cfg(all(target_os = "linux", target_env = "gnu"))]
862fn parse_glibc_version(version: &str) -> Option<(usize, usize)> {
863    let mut parsed_ints = version.split('.').map(str::parse::<usize>).fuse();
864    match (parsed_ints.next(), parsed_ints.next()) {
865        (Some(Ok(major)), Some(Ok(minor))) => Some((major, minor)),
866        _ => None,
867    }
868}