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