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(
386                io::const_error!(io::ErrorKind::Uncategorized, "no current exe available",),
387            );
388        }
389        let argv0 = CStr::from_ptr(argv[0]).to_bytes();
390        if argv0[0] == b'.' || argv0.iter().any(|b| *b == b'/') {
391            crate::fs::canonicalize(OsStr::from_bytes(argv0))
392        } else {
393            Ok(PathBuf::from(OsStr::from_bytes(argv0)))
394        }
395    }
396}
397
398#[cfg(any(
399    target_os = "linux",
400    target_os = "hurd",
401    target_os = "android",
402    target_os = "nuttx",
403    target_os = "emscripten"
404))]
405pub fn current_exe() -> io::Result<PathBuf> {
406    match crate::fs::read_link("/proc/self/exe") {
407        Err(ref e) if e.kind() == io::ErrorKind::NotFound => Err(io::const_error!(
408            io::ErrorKind::Uncategorized,
409            "no /proc/self/exe available. Is /proc mounted?",
410        )),
411        other => other,
412    }
413}
414
415#[cfg(target_os = "nto")]
416pub fn current_exe() -> io::Result<PathBuf> {
417    let mut e = crate::fs::read("/proc/self/exefile")?;
418    // Current versions of QNX Neutrino provide a null-terminated path.
419    // Ensure the trailing null byte is not returned here.
420    if let Some(0) = e.last() {
421        e.pop();
422    }
423    Ok(PathBuf::from(OsString::from_vec(e)))
424}
425
426#[cfg(target_vendor = "apple")]
427pub fn current_exe() -> io::Result<PathBuf> {
428    unsafe {
429        let mut sz: u32 = 0;
430        #[expect(deprecated)]
431        libc::_NSGetExecutablePath(ptr::null_mut(), &mut sz);
432        if sz == 0 {
433            return Err(io::Error::last_os_error());
434        }
435        let mut v: Vec<u8> = Vec::with_capacity(sz as usize);
436        #[expect(deprecated)]
437        let err = libc::_NSGetExecutablePath(v.as_mut_ptr() as *mut i8, &mut sz);
438        if err != 0 {
439            return Err(io::Error::last_os_error());
440        }
441        v.set_len(sz as usize - 1); // chop off trailing NUL
442        Ok(PathBuf::from(OsString::from_vec(v)))
443    }
444}
445
446#[cfg(any(target_os = "solaris", target_os = "illumos"))]
447pub fn current_exe() -> io::Result<PathBuf> {
448    if let Ok(path) = crate::fs::read_link("/proc/self/path/a.out") {
449        Ok(path)
450    } else {
451        unsafe {
452            let path = libc::getexecname();
453            if path.is_null() {
454                Err(io::Error::last_os_error())
455            } else {
456                let filename = CStr::from_ptr(path).to_bytes();
457                let path = PathBuf::from(<OsStr as OsStrExt>::from_bytes(filename));
458
459                // Prepend a current working directory to the path if
460                // it doesn't contain an absolute pathname.
461                if filename[0] == b'/' { Ok(path) } else { getcwd().map(|cwd| cwd.join(path)) }
462            }
463        }
464    }
465}
466
467#[cfg(target_os = "haiku")]
468pub fn current_exe() -> io::Result<PathBuf> {
469    let mut name = vec![0; libc::PATH_MAX as usize];
470    unsafe {
471        let result = libc::find_path(
472            crate::ptr::null_mut(),
473            libc::path_base_directory::B_FIND_PATH_IMAGE_PATH,
474            crate::ptr::null_mut(),
475            name.as_mut_ptr(),
476            name.len(),
477        );
478        if result != libc::B_OK {
479            use crate::io::ErrorKind;
480            Err(io::const_error!(ErrorKind::Uncategorized, "Error getting executable path"))
481        } else {
482            // find_path adds the null terminator.
483            let name = CStr::from_ptr(name.as_ptr()).to_bytes();
484            Ok(PathBuf::from(OsStr::from_bytes(name)))
485        }
486    }
487}
488
489#[cfg(any(target_os = "redox", target_os = "rtems"))]
490pub fn current_exe() -> io::Result<PathBuf> {
491    crate::fs::read_to_string("sys:exe").map(PathBuf::from)
492}
493
494#[cfg(target_os = "l4re")]
495pub fn current_exe() -> io::Result<PathBuf> {
496    use crate::io::ErrorKind;
497    Err(io::const_error!(ErrorKind::Unsupported, "Not yet implemented!"))
498}
499
500#[cfg(target_os = "vxworks")]
501pub fn current_exe() -> io::Result<PathBuf> {
502    #[cfg(test)]
503    use realstd::env;
504
505    #[cfg(not(test))]
506    use crate::env;
507
508    let exe_path = env::args().next().unwrap();
509    let path = path::Path::new(&exe_path);
510    path.canonicalize()
511}
512
513#[cfg(any(target_os = "espidf", target_os = "horizon", target_os = "vita"))]
514pub fn current_exe() -> io::Result<PathBuf> {
515    super::unsupported::unsupported()
516}
517
518#[cfg(target_os = "fuchsia")]
519pub fn current_exe() -> io::Result<PathBuf> {
520    #[cfg(test)]
521    use realstd::env;
522
523    #[cfg(not(test))]
524    use crate::env;
525    use crate::io::ErrorKind;
526
527    let exe_path = env::args().next().ok_or(io::const_error!(
528        ErrorKind::Uncategorized,
529        "an executable path was not found because no arguments were provided through argv"
530    ))?;
531    let path = PathBuf::from(exe_path);
532
533    // Prepend the current working directory to the path if it's not absolute.
534    if !path.is_absolute() { getcwd().map(|cwd| cwd.join(path)) } else { Ok(path) }
535}
536
537pub struct Env {
538    iter: vec::IntoIter<(OsString, OsString)>,
539}
540
541// FIXME(https://github.com/rust-lang/rust/issues/114583): Remove this when <OsStr as Debug>::fmt matches <str as Debug>::fmt.
542pub struct EnvStrDebug<'a> {
543    slice: &'a [(OsString, OsString)],
544}
545
546impl fmt::Debug for EnvStrDebug<'_> {
547    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
548        let Self { slice } = self;
549        f.debug_list()
550            .entries(slice.iter().map(|(a, b)| (a.to_str().unwrap(), b.to_str().unwrap())))
551            .finish()
552    }
553}
554
555impl Env {
556    pub fn str_debug(&self) -> impl fmt::Debug + '_ {
557        let Self { iter } = self;
558        EnvStrDebug { slice: iter.as_slice() }
559    }
560}
561
562impl fmt::Debug for Env {
563    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
564        let Self { iter } = self;
565        f.debug_list().entries(iter.as_slice()).finish()
566    }
567}
568
569impl !Send for Env {}
570impl !Sync for Env {}
571
572impl Iterator for Env {
573    type Item = (OsString, OsString);
574    fn next(&mut self) -> Option<(OsString, OsString)> {
575        self.iter.next()
576    }
577    fn size_hint(&self) -> (usize, Option<usize>) {
578        self.iter.size_hint()
579    }
580}
581
582// Use `_NSGetEnviron` on Apple platforms.
583//
584// `_NSGetEnviron` is the documented alternative (see `man environ`), and has
585// been available since the first versions of both macOS and iOS.
586//
587// Nowadays, specifically since macOS 10.8, `environ` has been exposed through
588// `libdyld.dylib`, which is linked via. `libSystem.dylib`:
589// <https://github.com/apple-oss-distributions/dyld/blob/dyld-1160.6/libdyld/libdyldGlue.cpp#L913>
590//
591// So in the end, it likely doesn't really matter which option we use, but the
592// performance cost of using `_NSGetEnviron` is extremely miniscule, and it
593// might be ever so slightly more supported, so let's just use that.
594//
595// NOTE: The header where this is defined (`crt_externs.h`) was added to the
596// iOS 13.0 SDK, which has been the source of a great deal of confusion in the
597// past about the availability of this API.
598//
599// NOTE(madsmtm): Neither this nor using `environ` has been verified to not
600// cause App Store rejections; if this is found to be the case, an alternative
601// implementation of this is possible using `[NSProcessInfo environment]`
602// - which internally uses `_NSGetEnviron` and a system-wide lock on the
603// environment variables to protect against `setenv`, so using that might be
604// desirable anyhow? Though it also means that we have to link to Foundation.
605#[cfg(target_vendor = "apple")]
606pub unsafe fn environ() -> *mut *const *const c_char {
607    libc::_NSGetEnviron() as *mut *const *const c_char
608}
609
610// Use the `environ` static which is part of POSIX.
611#[cfg(not(target_vendor = "apple"))]
612pub unsafe fn environ() -> *mut *const *const c_char {
613    unsafe extern "C" {
614        static mut environ: *const *const c_char;
615    }
616    &raw mut environ
617}
618
619static ENV_LOCK: RwLock<()> = RwLock::new(());
620
621pub fn env_read_lock() -> impl Drop {
622    ENV_LOCK.read().unwrap_or_else(PoisonError::into_inner)
623}
624
625/// Returns a vector of (variable, value) byte-vector pairs for all the
626/// environment variables of the current process.
627pub fn env() -> Env {
628    unsafe {
629        let _guard = env_read_lock();
630        let mut environ = *environ();
631        let mut result = Vec::new();
632        if !environ.is_null() {
633            while !(*environ).is_null() {
634                if let Some(key_value) = parse(CStr::from_ptr(*environ).to_bytes()) {
635                    result.push(key_value);
636                }
637                environ = environ.add(1);
638            }
639        }
640        return Env { iter: result.into_iter() };
641    }
642
643    fn parse(input: &[u8]) -> Option<(OsString, OsString)> {
644        // Strategy (copied from glibc): Variable name and value are separated
645        // by an ASCII equals sign '='. Since a variable name must not be
646        // empty, allow variable names starting with an equals sign. Skip all
647        // malformed lines.
648        if input.is_empty() {
649            return None;
650        }
651        let pos = memchr::memchr(b'=', &input[1..]).map(|p| p + 1);
652        pos.map(|p| {
653            (
654                OsStringExt::from_vec(input[..p].to_vec()),
655                OsStringExt::from_vec(input[p + 1..].to_vec()),
656            )
657        })
658    }
659}
660
661pub fn getenv(k: &OsStr) -> Option<OsString> {
662    // environment variables with a nul byte can't be set, so their value is
663    // always None as well
664    run_with_cstr(k.as_bytes(), &|k| {
665        let _guard = env_read_lock();
666        let v = unsafe { libc::getenv(k.as_ptr()) } as *const libc::c_char;
667
668        if v.is_null() {
669            Ok(None)
670        } else {
671            // SAFETY: `v` cannot be mutated while executing this line since we've a read lock
672            let bytes = unsafe { CStr::from_ptr(v) }.to_bytes().to_vec();
673
674            Ok(Some(OsStringExt::from_vec(bytes)))
675        }
676    })
677    .ok()
678    .flatten()
679}
680
681pub unsafe fn setenv(k: &OsStr, v: &OsStr) -> io::Result<()> {
682    run_with_cstr(k.as_bytes(), &|k| {
683        run_with_cstr(v.as_bytes(), &|v| {
684            let _guard = ENV_LOCK.write();
685            cvt(libc::setenv(k.as_ptr(), v.as_ptr(), 1)).map(drop)
686        })
687    })
688}
689
690pub unsafe fn unsetenv(n: &OsStr) -> io::Result<()> {
691    run_with_cstr(n.as_bytes(), &|nbuf| {
692        let _guard = ENV_LOCK.write();
693        cvt(libc::unsetenv(nbuf.as_ptr())).map(drop)
694    })
695}
696
697#[cfg(not(target_os = "espidf"))]
698pub fn page_size() -> usize {
699    unsafe { libc::sysconf(libc::_SC_PAGESIZE) as usize }
700}
701
702// Returns the value for [`confstr(key, ...)`][posix_confstr]. Currently only
703// used on Darwin, but should work on any unix (in case we need to get
704// `_CS_PATH` or `_CS_V[67]_ENV` in the future).
705//
706// [posix_confstr]:
707//     https://pubs.opengroup.org/onlinepubs/9699919799/functions/confstr.html
708//
709// FIXME: Support `confstr` in Miri.
710#[cfg(all(target_vendor = "apple", not(miri)))]
711fn confstr(key: c_int, size_hint: Option<usize>) -> io::Result<OsString> {
712    let mut buf: Vec<u8> = Vec::with_capacity(0);
713    let mut bytes_needed_including_nul = size_hint
714        .unwrap_or_else(|| {
715            // Treat "None" as "do an extra call to get the length". In theory
716            // we could move this into the loop below, but it's hard to do given
717            // that it isn't 100% clear if it's legal to pass 0 for `len` when
718            // the buffer isn't null.
719            unsafe { libc::confstr(key, core::ptr::null_mut(), 0) }
720        })
721        .max(1);
722    // If the value returned by `confstr` is greater than the len passed into
723    // it, then the value was truncated, meaning we need to retry. Note that
724    // while `confstr` results don't seem to change for a process, it's unclear
725    // if this is guaranteed anywhere, so looping does seem required.
726    while bytes_needed_including_nul > buf.capacity() {
727        // We write into the spare capacity of `buf`. This lets us avoid
728        // changing buf's `len`, which both simplifies `reserve` computation,
729        // allows working with `Vec<u8>` instead of `Vec<MaybeUninit<u8>>`, and
730        // may avoid a copy, since the Vec knows that none of the bytes are needed
731        // when reallocating (well, in theory anyway).
732        buf.reserve(bytes_needed_including_nul);
733        // `confstr` returns
734        // - 0 in the case of errors: we break and return an error.
735        // - The number of bytes written, iff the provided buffer is enough to
736        //   hold the entire value: we break and return the data in `buf`.
737        // - Otherwise, the number of bytes needed (including nul): we go
738        //   through the loop again.
739        bytes_needed_including_nul =
740            unsafe { libc::confstr(key, buf.as_mut_ptr().cast::<c_char>(), buf.capacity()) };
741    }
742    // `confstr` returns 0 in the case of an error.
743    if bytes_needed_including_nul == 0 {
744        return Err(io::Error::last_os_error());
745    }
746    // Safety: `confstr(..., buf.as_mut_ptr(), buf.capacity())` returned a
747    // non-zero value, meaning `bytes_needed_including_nul` bytes were
748    // initialized.
749    unsafe {
750        buf.set_len(bytes_needed_including_nul);
751        // Remove the NUL-terminator.
752        let last_byte = buf.pop();
753        // ... and smoke-check that it *was* a NUL-terminator.
754        assert_eq!(last_byte, Some(0), "`confstr` provided a string which wasn't nul-terminated");
755    };
756    Ok(OsString::from_vec(buf))
757}
758
759#[cfg(all(target_vendor = "apple", not(miri)))]
760fn darwin_temp_dir() -> PathBuf {
761    confstr(libc::_CS_DARWIN_USER_TEMP_DIR, Some(64)).map(PathBuf::from).unwrap_or_else(|_| {
762        // It failed for whatever reason (there are several possible reasons),
763        // so return the global one.
764        PathBuf::from("/tmp")
765    })
766}
767
768pub fn temp_dir() -> PathBuf {
769    crate::env::var_os("TMPDIR").map(PathBuf::from).unwrap_or_else(|| {
770        cfg_if::cfg_if! {
771            if #[cfg(all(target_vendor = "apple", not(miri)))] {
772                darwin_temp_dir()
773            } else if #[cfg(target_os = "android")] {
774                PathBuf::from("/data/local/tmp")
775            } else {
776                PathBuf::from("/tmp")
777            }
778        }
779    })
780}
781
782pub fn home_dir() -> Option<PathBuf> {
783    return crate::env::var_os("HOME").or_else(|| unsafe { fallback() }).map(PathBuf::from);
784
785    #[cfg(any(
786        target_os = "android",
787        target_os = "emscripten",
788        target_os = "redox",
789        target_os = "vxworks",
790        target_os = "espidf",
791        target_os = "horizon",
792        target_os = "vita",
793        target_os = "nuttx",
794        all(target_vendor = "apple", not(target_os = "macos")),
795    ))]
796    unsafe fn fallback() -> Option<OsString> {
797        None
798    }
799    #[cfg(not(any(
800        target_os = "android",
801        target_os = "emscripten",
802        target_os = "redox",
803        target_os = "vxworks",
804        target_os = "espidf",
805        target_os = "horizon",
806        target_os = "vita",
807        target_os = "nuttx",
808        all(target_vendor = "apple", not(target_os = "macos")),
809    )))]
810    unsafe fn fallback() -> Option<OsString> {
811        let amt = match libc::sysconf(libc::_SC_GETPW_R_SIZE_MAX) {
812            n if n < 0 => 512 as usize,
813            n => n as usize,
814        };
815        let mut buf = Vec::with_capacity(amt);
816        let mut p = mem::MaybeUninit::<libc::passwd>::uninit();
817        let mut result = ptr::null_mut();
818        match libc::getpwuid_r(
819            libc::getuid(),
820            p.as_mut_ptr(),
821            buf.as_mut_ptr(),
822            buf.capacity(),
823            &mut result,
824        ) {
825            0 if !result.is_null() => {
826                let ptr = (*result).pw_dir as *const _;
827                let bytes = CStr::from_ptr(ptr).to_bytes().to_vec();
828                Some(OsStringExt::from_vec(bytes))
829            }
830            _ => None,
831        }
832    }
833}
834
835pub fn exit(code: i32) -> ! {
836    crate::sys::exit_guard::unique_thread_exit();
837    unsafe { libc::exit(code as c_int) }
838}
839
840pub fn getpid() -> u32 {
841    unsafe { libc::getpid() as u32 }
842}
843
844pub fn getppid() -> u32 {
845    unsafe { libc::getppid() as u32 }
846}
847
848#[cfg(all(target_os = "linux", target_env = "gnu"))]
849pub fn glibc_version() -> Option<(usize, usize)> {
850    unsafe extern "C" {
851        fn gnu_get_libc_version() -> *const libc::c_char;
852    }
853    let version_cstr = unsafe { CStr::from_ptr(gnu_get_libc_version()) };
854    if let Ok(version_str) = version_cstr.to_str() {
855        parse_glibc_version(version_str)
856    } else {
857        None
858    }
859}
860
861// Returns Some((major, minor)) if the string is a valid "x.y" version,
862// ignoring any extra dot-separated parts. Otherwise return None.
863#[cfg(all(target_os = "linux", target_env = "gnu"))]
864fn parse_glibc_version(version: &str) -> Option<(usize, usize)> {
865    let mut parsed_ints = version.split('.').map(str::parse::<usize>).fuse();
866    match (parsed_ints.next(), parsed_ints.next()) {
867        (Some(Ok(major)), Some(Ok(minor))) => Some((major, minor)),
868        _ => None,
869    }
870}