• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //! Implementation of `std::os` functionality for unix systems
2 
3 #![allow(unused_imports)] // lots of cfg code here
4 
5 #[cfg(test)]
6 mod tests;
7 
8 use crate::os::unix::prelude::*;
9 
10 use crate::error::Error as StdError;
11 use crate::ffi::{CStr, CString, OsStr, OsString};
12 use crate::fmt;
13 use crate::io;
14 use crate::iter;
15 use crate::mem;
16 use crate::path::{self, PathBuf};
17 use crate::ptr;
18 use crate::slice;
19 use crate::str;
20 use crate::sync::{PoisonError, RwLock};
21 use crate::sys::common::small_c_string::{run_path_with_cstr, run_with_cstr};
22 use crate::sys::cvt;
23 use crate::sys::fd;
24 use crate::sys::memchr;
25 use crate::vec;
26 
27 #[cfg(all(target_env = "gnu", not(target_os = "vxworks")))]
28 use crate::sys::weak::weak;
29 
30 use libc::{c_char, c_int, c_void};
31 
32 const TMPBUF_SZ: usize = 128;
33 
34 cfg_if::cfg_if! {
35     if #[cfg(target_os = "redox")] {
36         const PATH_SEPARATOR: u8 = b';';
37     } else {
38         const PATH_SEPARATOR: u8 = b':';
39     }
40 }
41 
42 extern "C" {
43     #[cfg(not(any(target_os = "dragonfly", target_os = "vxworks")))]
44     #[cfg_attr(
45         any(
46             target_os = "linux",
47             target_os = "emscripten",
48             target_os = "fuchsia",
49             target_os = "l4re"
50         ),
51         link_name = "__errno_location"
52     )]
53     #[cfg_attr(
54         any(
55             target_os = "netbsd",
56             target_os = "openbsd",
57             target_os = "android",
58             target_os = "redox",
59             target_env = "newlib"
60         ),
61         link_name = "__errno"
62     )]
63     #[cfg_attr(any(target_os = "solaris", target_os = "illumos"), link_name = "___errno")]
64     #[cfg_attr(target_os = "nto", link_name = "__get_errno_ptr")]
65     #[cfg_attr(
66         any(
67             target_os = "macos",
68             target_os = "ios",
69             target_os = "tvos",
70             target_os = "freebsd",
71             target_os = "watchos"
72         ),
73         link_name = "__error"
74     )]
75     #[cfg_attr(target_os = "haiku", link_name = "_errnop")]
errno_location() -> *mut c_int76     fn errno_location() -> *mut c_int;
77 }
78 
79 /// Returns the platform-specific value of errno
80 #[cfg(not(any(target_os = "dragonfly", target_os = "vxworks")))]
errno() -> i3281 pub fn errno() -> i32 {
82     unsafe { (*errno_location()) as i32 }
83 }
84 
85 /// Sets the platform-specific value of errno
86 #[cfg(all(not(target_os = "dragonfly"), not(target_os = "vxworks")))] // needed for readdir and syscall!
87 #[allow(dead_code)] // but not all target cfgs actually end up using it
set_errno(e: i32)88 pub fn set_errno(e: i32) {
89     unsafe { *errno_location() = e as c_int }
90 }
91 
92 #[cfg(target_os = "vxworks")]
errno() -> i3293 pub fn errno() -> i32 {
94     unsafe { libc::errnoGet() }
95 }
96 
97 #[cfg(target_os = "dragonfly")]
errno() -> i3298 pub fn errno() -> i32 {
99     extern "C" {
100         #[thread_local]
101         static errno: c_int;
102     }
103 
104     unsafe { errno as i32 }
105 }
106 
107 #[cfg(target_os = "dragonfly")]
108 #[allow(dead_code)]
set_errno(e: i32)109 pub fn set_errno(e: i32) {
110     extern "C" {
111         #[thread_local]
112         static mut errno: c_int;
113     }
114 
115     unsafe {
116         errno = e;
117     }
118 }
119 
120 /// Gets a detailed string description for the given error number.
error_string(errno: i32) -> String121 pub fn error_string(errno: i32) -> String {
122     extern "C" {
123         #[cfg_attr(
124             all(any(target_os = "linux", target_env = "newlib"), not(target_env = "ohos")),
125             link_name = "__xpg_strerror_r"
126         )]
127         fn strerror_r(errnum: c_int, buf: *mut c_char, buflen: libc::size_t) -> c_int;
128     }
129 
130     let mut buf = [0 as c_char; TMPBUF_SZ];
131 
132     let p = buf.as_mut_ptr();
133     unsafe {
134         if strerror_r(errno as c_int, p, buf.len()) < 0 {
135             panic!("strerror_r failure");
136         }
137 
138         let p = p as *const _;
139         // We can't always expect a UTF-8 environment. When we don't get that luxury,
140         // it's better to give a low-quality error message than none at all.
141         String::from_utf8_lossy(CStr::from_ptr(p).to_bytes()).into()
142     }
143 }
144 
145 #[cfg(target_os = "espidf")]
getcwd() -> io::Result<PathBuf>146 pub fn getcwd() -> io::Result<PathBuf> {
147     Ok(PathBuf::from("/"))
148 }
149 
150 #[cfg(not(target_os = "espidf"))]
getcwd() -> io::Result<PathBuf>151 pub fn getcwd() -> io::Result<PathBuf> {
152     let mut buf = Vec::with_capacity(512);
153     loop {
154         unsafe {
155             let ptr = buf.as_mut_ptr() as *mut libc::c_char;
156             if !libc::getcwd(ptr, buf.capacity()).is_null() {
157                 let len = CStr::from_ptr(buf.as_ptr() as *const libc::c_char).to_bytes().len();
158                 buf.set_len(len);
159                 buf.shrink_to_fit();
160                 return Ok(PathBuf::from(OsString::from_vec(buf)));
161             } else {
162                 let error = io::Error::last_os_error();
163                 if error.raw_os_error() != Some(libc::ERANGE) {
164                     return Err(error);
165                 }
166             }
167 
168             // Trigger the internal buffer resizing logic of `Vec` by requiring
169             // more space than the current capacity.
170             let cap = buf.capacity();
171             buf.set_len(cap);
172             buf.reserve(1);
173         }
174     }
175 }
176 
177 #[cfg(target_os = "espidf")]
chdir(p: &path::Path) -> io::Result<()>178 pub fn chdir(p: &path::Path) -> io::Result<()> {
179     super::unsupported::unsupported()
180 }
181 
182 #[cfg(not(target_os = "espidf"))]
chdir(p: &path::Path) -> io::Result<()>183 pub fn chdir(p: &path::Path) -> io::Result<()> {
184     let result = run_path_with_cstr(p, |p| unsafe { Ok(libc::chdir(p.as_ptr())) })?;
185     if result == 0 { Ok(()) } else { Err(io::Error::last_os_error()) }
186 }
187 
188 pub struct SplitPaths<'a> {
189     iter: iter::Map<slice::Split<'a, u8, fn(&u8) -> bool>, fn(&'a [u8]) -> PathBuf>,
190 }
191 
split_paths(unparsed: &OsStr) -> SplitPaths<'_>192 pub fn split_paths(unparsed: &OsStr) -> SplitPaths<'_> {
193     fn bytes_to_path(b: &[u8]) -> PathBuf {
194         PathBuf::from(<OsStr as OsStrExt>::from_bytes(b))
195     }
196     fn is_separator(b: &u8) -> bool {
197         *b == PATH_SEPARATOR
198     }
199     let unparsed = unparsed.as_bytes();
200     SplitPaths {
201         iter: unparsed
202             .split(is_separator as fn(&u8) -> bool)
203             .map(bytes_to_path as fn(&[u8]) -> PathBuf),
204     }
205 }
206 
207 impl<'a> Iterator for SplitPaths<'a> {
208     type Item = PathBuf;
next(&mut self) -> Option<PathBuf>209     fn next(&mut self) -> Option<PathBuf> {
210         self.iter.next()
211     }
size_hint(&self) -> (usize, Option<usize>)212     fn size_hint(&self) -> (usize, Option<usize>) {
213         self.iter.size_hint()
214     }
215 }
216 
217 #[derive(Debug)]
218 pub struct JoinPathsError;
219 
join_paths<I, T>(paths: I) -> Result<OsString, JoinPathsError> where I: Iterator<Item = T>, T: AsRef<OsStr>,220 pub fn join_paths<I, T>(paths: I) -> Result<OsString, JoinPathsError>
221 where
222     I: Iterator<Item = T>,
223     T: AsRef<OsStr>,
224 {
225     let mut joined = Vec::new();
226 
227     for (i, path) in paths.enumerate() {
228         let path = path.as_ref().as_bytes();
229         if i > 0 {
230             joined.push(PATH_SEPARATOR)
231         }
232         if path.contains(&PATH_SEPARATOR) {
233             return Err(JoinPathsError);
234         }
235         joined.extend_from_slice(path);
236     }
237     Ok(OsStringExt::from_vec(joined))
238 }
239 
240 impl fmt::Display for JoinPathsError {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result241     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
242         write!(f, "path segment contains separator `{}`", char::from(PATH_SEPARATOR))
243     }
244 }
245 
246 impl StdError for JoinPathsError {
247     #[allow(deprecated)]
description(&self) -> &str248     fn description(&self) -> &str {
249         "failed to join paths"
250     }
251 }
252 
253 #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))]
current_exe() -> io::Result<PathBuf>254 pub fn current_exe() -> io::Result<PathBuf> {
255     unsafe {
256         let mut mib = [
257             libc::CTL_KERN as c_int,
258             libc::KERN_PROC as c_int,
259             libc::KERN_PROC_PATHNAME as c_int,
260             -1 as c_int,
261         ];
262         let mut sz = 0;
263         cvt(libc::sysctl(
264             mib.as_mut_ptr(),
265             mib.len() as libc::c_uint,
266             ptr::null_mut(),
267             &mut sz,
268             ptr::null_mut(),
269             0,
270         ))?;
271         if sz == 0 {
272             return Err(io::Error::last_os_error());
273         }
274         let mut v: Vec<u8> = Vec::with_capacity(sz);
275         cvt(libc::sysctl(
276             mib.as_mut_ptr(),
277             mib.len() as libc::c_uint,
278             v.as_mut_ptr() as *mut libc::c_void,
279             &mut sz,
280             ptr::null_mut(),
281             0,
282         ))?;
283         if sz == 0 {
284             return Err(io::Error::last_os_error());
285         }
286         v.set_len(sz - 1); // chop off trailing NUL
287         Ok(PathBuf::from(OsString::from_vec(v)))
288     }
289 }
290 
291 #[cfg(target_os = "netbsd")]
current_exe() -> io::Result<PathBuf>292 pub fn current_exe() -> io::Result<PathBuf> {
293     fn sysctl() -> io::Result<PathBuf> {
294         unsafe {
295             let mib = [libc::CTL_KERN, libc::KERN_PROC_ARGS, -1, libc::KERN_PROC_PATHNAME];
296             let mut path_len: usize = 0;
297             cvt(libc::sysctl(
298                 mib.as_ptr(),
299                 mib.len() as libc::c_uint,
300                 ptr::null_mut(),
301                 &mut path_len,
302                 ptr::null(),
303                 0,
304             ))?;
305             if path_len <= 1 {
306                 return Err(io::const_io_error!(
307                     io::ErrorKind::Uncategorized,
308                     "KERN_PROC_PATHNAME sysctl returned zero-length string",
309                 ));
310             }
311             let mut path: Vec<u8> = Vec::with_capacity(path_len);
312             cvt(libc::sysctl(
313                 mib.as_ptr(),
314                 mib.len() as libc::c_uint,
315                 path.as_ptr() as *mut libc::c_void,
316                 &mut path_len,
317                 ptr::null(),
318                 0,
319             ))?;
320             path.set_len(path_len - 1); // chop off NUL
321             Ok(PathBuf::from(OsString::from_vec(path)))
322         }
323     }
324     fn procfs() -> io::Result<PathBuf> {
325         let curproc_exe = path::Path::new("/proc/curproc/exe");
326         if curproc_exe.is_file() {
327             return crate::fs::read_link(curproc_exe);
328         }
329         Err(io::const_io_error!(
330             io::ErrorKind::Uncategorized,
331             "/proc/curproc/exe doesn't point to regular file.",
332         ))
333     }
334     sysctl().or_else(|_| procfs())
335 }
336 
337 #[cfg(target_os = "openbsd")]
current_exe() -> io::Result<PathBuf>338 pub fn current_exe() -> io::Result<PathBuf> {
339     unsafe {
340         let mut mib = [libc::CTL_KERN, libc::KERN_PROC_ARGS, libc::getpid(), libc::KERN_PROC_ARGV];
341         let mib = mib.as_mut_ptr();
342         let mut argv_len = 0;
343         cvt(libc::sysctl(mib, 4, ptr::null_mut(), &mut argv_len, ptr::null_mut(), 0))?;
344         let mut argv = Vec::<*const libc::c_char>::with_capacity(argv_len as usize);
345         cvt(libc::sysctl(mib, 4, argv.as_mut_ptr() as *mut _, &mut argv_len, ptr::null_mut(), 0))?;
346         argv.set_len(argv_len as usize);
347         if argv[0].is_null() {
348             return Err(io::const_io_error!(
349                 io::ErrorKind::Uncategorized,
350                 "no current exe available",
351             ));
352         }
353         let argv0 = CStr::from_ptr(argv[0]).to_bytes();
354         if argv0[0] == b'.' || argv0.iter().any(|b| *b == b'/') {
355             crate::fs::canonicalize(OsStr::from_bytes(argv0))
356         } else {
357             Ok(PathBuf::from(OsStr::from_bytes(argv0)))
358         }
359     }
360 }
361 
362 #[cfg(any(target_os = "linux", target_os = "android", target_os = "emscripten"))]
current_exe() -> io::Result<PathBuf>363 pub fn current_exe() -> io::Result<PathBuf> {
364     match crate::fs::read_link("/proc/self/exe") {
365         Err(ref e) if e.kind() == io::ErrorKind::NotFound => Err(io::const_io_error!(
366             io::ErrorKind::Uncategorized,
367             "no /proc/self/exe available. Is /proc mounted?",
368         )),
369         other => other,
370     }
371 }
372 
373 #[cfg(target_os = "nto")]
current_exe() -> io::Result<PathBuf>374 pub fn current_exe() -> io::Result<PathBuf> {
375     let mut e = crate::fs::read("/proc/self/exefile")?;
376     // Current versions of QNX Neutrino provide a null-terminated path.
377     // Ensure the trailing null byte is not returned here.
378     if let Some(0) = e.last() {
379         e.pop();
380     }
381     Ok(PathBuf::from(OsString::from_vec(e)))
382 }
383 
384 #[cfg(any(target_os = "macos", target_os = "ios", target_os = "tvos", target_os = "watchos"))]
current_exe() -> io::Result<PathBuf>385 pub fn current_exe() -> io::Result<PathBuf> {
386     unsafe {
387         let mut sz: u32 = 0;
388         libc::_NSGetExecutablePath(ptr::null_mut(), &mut sz);
389         if sz == 0 {
390             return Err(io::Error::last_os_error());
391         }
392         let mut v: Vec<u8> = Vec::with_capacity(sz as usize);
393         let err = libc::_NSGetExecutablePath(v.as_mut_ptr() as *mut i8, &mut sz);
394         if err != 0 {
395             return Err(io::Error::last_os_error());
396         }
397         v.set_len(sz as usize - 1); // chop off trailing NUL
398         Ok(PathBuf::from(OsString::from_vec(v)))
399     }
400 }
401 
402 #[cfg(any(target_os = "solaris", target_os = "illumos"))]
current_exe() -> io::Result<PathBuf>403 pub fn current_exe() -> io::Result<PathBuf> {
404     if let Ok(path) = crate::fs::read_link("/proc/self/path/a.out") {
405         Ok(path)
406     } else {
407         unsafe {
408             let path = libc::getexecname();
409             if path.is_null() {
410                 Err(io::Error::last_os_error())
411             } else {
412                 let filename = CStr::from_ptr(path).to_bytes();
413                 let path = PathBuf::from(<OsStr as OsStrExt>::from_bytes(filename));
414 
415                 // Prepend a current working directory to the path if
416                 // it doesn't contain an absolute pathname.
417                 if filename[0] == b'/' { Ok(path) } else { getcwd().map(|cwd| cwd.join(path)) }
418             }
419         }
420     }
421 }
422 
423 #[cfg(target_os = "haiku")]
current_exe() -> io::Result<PathBuf>424 pub fn current_exe() -> io::Result<PathBuf> {
425     unsafe {
426         let mut info: mem::MaybeUninit<libc::image_info> = mem::MaybeUninit::uninit();
427         let mut cookie: i32 = 0;
428         // the executable can be found at team id 0
429         let result = libc::_get_next_image_info(
430             0,
431             &mut cookie,
432             info.as_mut_ptr(),
433             mem::size_of::<libc::image_info>(),
434         );
435         if result != 0 {
436             use crate::io::ErrorKind;
437             Err(io::const_io_error!(ErrorKind::Uncategorized, "Error getting executable path"))
438         } else {
439             let name = CStr::from_ptr((*info.as_ptr()).name.as_ptr()).to_bytes();
440             Ok(PathBuf::from(OsStr::from_bytes(name)))
441         }
442     }
443 }
444 
445 #[cfg(target_os = "redox")]
current_exe() -> io::Result<PathBuf>446 pub fn current_exe() -> io::Result<PathBuf> {
447     crate::fs::read_to_string("sys:exe").map(PathBuf::from)
448 }
449 
450 #[cfg(target_os = "l4re")]
current_exe() -> io::Result<PathBuf>451 pub fn current_exe() -> io::Result<PathBuf> {
452     use crate::io::ErrorKind;
453     Err(io::const_io_error!(ErrorKind::Unsupported, "Not yet implemented!"))
454 }
455 
456 #[cfg(target_os = "vxworks")]
current_exe() -> io::Result<PathBuf>457 pub fn current_exe() -> io::Result<PathBuf> {
458     #[cfg(test)]
459     use realstd::env;
460 
461     #[cfg(not(test))]
462     use crate::env;
463 
464     let exe_path = env::args().next().unwrap();
465     let path = path::Path::new(&exe_path);
466     path.canonicalize()
467 }
468 
469 #[cfg(any(target_os = "espidf", target_os = "horizon", target_os = "vita"))]
current_exe() -> io::Result<PathBuf>470 pub fn current_exe() -> io::Result<PathBuf> {
471     super::unsupported::unsupported()
472 }
473 
474 #[cfg(target_os = "fuchsia")]
current_exe() -> io::Result<PathBuf>475 pub fn current_exe() -> io::Result<PathBuf> {
476     use crate::io::ErrorKind;
477 
478     #[cfg(test)]
479     use realstd::env;
480 
481     #[cfg(not(test))]
482     use crate::env;
483 
484     let exe_path = env::args().next().ok_or(io::const_io_error!(
485         ErrorKind::Uncategorized,
486         "an executable path was not found because no arguments were provided through argv"
487     ))?;
488     let path = PathBuf::from(exe_path);
489 
490     // Prepend the current working directory to the path if it's not absolute.
491     if !path.is_absolute() { getcwd().map(|cwd| cwd.join(path)) } else { Ok(path) }
492 }
493 
494 pub struct Env {
495     iter: vec::IntoIter<(OsString, OsString)>,
496 }
497 
498 impl !Send for Env {}
499 impl !Sync for Env {}
500 
501 impl Iterator for Env {
502     type Item = (OsString, OsString);
next(&mut self) -> Option<(OsString, OsString)>503     fn next(&mut self) -> Option<(OsString, OsString)> {
504         self.iter.next()
505     }
size_hint(&self) -> (usize, Option<usize>)506     fn size_hint(&self) -> (usize, Option<usize>) {
507         self.iter.size_hint()
508     }
509 }
510 
511 #[cfg(target_os = "macos")]
environ() -> *mut *const *const c_char512 pub unsafe fn environ() -> *mut *const *const c_char {
513     libc::_NSGetEnviron() as *mut *const *const c_char
514 }
515 
516 #[cfg(not(target_os = "macos"))]
environ() -> *mut *const *const c_char517 pub unsafe fn environ() -> *mut *const *const c_char {
518     extern "C" {
519         static mut environ: *const *const c_char;
520     }
521     ptr::addr_of_mut!(environ)
522 }
523 
524 static ENV_LOCK: RwLock<()> = RwLock::new(());
525 
env_read_lock() -> impl Drop526 pub fn env_read_lock() -> impl Drop {
527     ENV_LOCK.read().unwrap_or_else(PoisonError::into_inner)
528 }
529 
530 /// Returns a vector of (variable, value) byte-vector pairs for all the
531 /// environment variables of the current process.
env() -> Env532 pub fn env() -> Env {
533     unsafe {
534         let _guard = env_read_lock();
535         let mut environ = *environ();
536         let mut result = Vec::new();
537         if !environ.is_null() {
538             while !(*environ).is_null() {
539                 if let Some(key_value) = parse(CStr::from_ptr(*environ).to_bytes()) {
540                     result.push(key_value);
541                 }
542                 environ = environ.add(1);
543             }
544         }
545         return Env { iter: result.into_iter() };
546     }
547 
548     fn parse(input: &[u8]) -> Option<(OsString, OsString)> {
549         // Strategy (copied from glibc): Variable name and value are separated
550         // by an ASCII equals sign '='. Since a variable name must not be
551         // empty, allow variable names starting with an equals sign. Skip all
552         // malformed lines.
553         if input.is_empty() {
554             return None;
555         }
556         let pos = memchr::memchr(b'=', &input[1..]).map(|p| p + 1);
557         pos.map(|p| {
558             (
559                 OsStringExt::from_vec(input[..p].to_vec()),
560                 OsStringExt::from_vec(input[p + 1..].to_vec()),
561             )
562         })
563     }
564 }
565 
getenv(k: &OsStr) -> Option<OsString>566 pub fn getenv(k: &OsStr) -> Option<OsString> {
567     // environment variables with a nul byte can't be set, so their value is
568     // always None as well
569     let s = run_with_cstr(k.as_bytes(), |k| {
570         let _guard = env_read_lock();
571         Ok(unsafe { libc::getenv(k.as_ptr()) } as *const libc::c_char)
572     })
573     .ok()?;
574     if s.is_null() {
575         None
576     } else {
577         Some(OsStringExt::from_vec(unsafe { CStr::from_ptr(s) }.to_bytes().to_vec()))
578     }
579 }
580 
setenv(k: &OsStr, v: &OsStr) -> io::Result<()>581 pub fn setenv(k: &OsStr, v: &OsStr) -> io::Result<()> {
582     run_with_cstr(k.as_bytes(), |k| {
583         run_with_cstr(v.as_bytes(), |v| {
584             let _guard = ENV_LOCK.write();
585             cvt(unsafe { libc::setenv(k.as_ptr(), v.as_ptr(), 1) }).map(drop)
586         })
587     })
588 }
589 
unsetenv(n: &OsStr) -> io::Result<()>590 pub fn unsetenv(n: &OsStr) -> io::Result<()> {
591     run_with_cstr(n.as_bytes(), |nbuf| {
592         let _guard = ENV_LOCK.write();
593         cvt(unsafe { libc::unsetenv(nbuf.as_ptr()) }).map(drop)
594     })
595 }
596 
597 #[cfg(not(target_os = "espidf"))]
page_size() -> usize598 pub fn page_size() -> usize {
599     unsafe { libc::sysconf(libc::_SC_PAGESIZE) as usize }
600 }
601 
temp_dir() -> PathBuf602 pub fn temp_dir() -> PathBuf {
603     crate::env::var_os("TMPDIR").map(PathBuf::from).unwrap_or_else(|| {
604         if cfg!(target_os = "android") {
605             PathBuf::from("/data/local/tmp")
606         } else {
607             PathBuf::from("/tmp")
608         }
609     })
610 }
611 
home_dir() -> Option<PathBuf>612 pub fn home_dir() -> Option<PathBuf> {
613     return crate::env::var_os("HOME").or_else(|| unsafe { fallback() }).map(PathBuf::from);
614 
615     #[cfg(any(
616         target_os = "android",
617         target_os = "ios",
618         target_os = "tvos",
619         target_os = "watchos",
620         target_os = "emscripten",
621         target_os = "redox",
622         target_os = "vxworks",
623         target_os = "espidf",
624         target_os = "horizon",
625         target_os = "vita",
626     ))]
627     unsafe fn fallback() -> Option<OsString> {
628         None
629     }
630     #[cfg(not(any(
631         target_os = "android",
632         target_os = "ios",
633         target_os = "tvos",
634         target_os = "watchos",
635         target_os = "emscripten",
636         target_os = "redox",
637         target_os = "vxworks",
638         target_os = "espidf",
639         target_os = "horizon",
640         target_os = "vita",
641     )))]
642     unsafe fn fallback() -> Option<OsString> {
643         let amt = match libc::sysconf(libc::_SC_GETPW_R_SIZE_MAX) {
644             n if n < 0 => 512 as usize,
645             n => n as usize,
646         };
647         let mut buf = Vec::with_capacity(amt);
648         let mut passwd: libc::passwd = mem::zeroed();
649         let mut result = ptr::null_mut();
650         match libc::getpwuid_r(
651             libc::getuid(),
652             &mut passwd,
653             buf.as_mut_ptr(),
654             buf.capacity(),
655             &mut result,
656         ) {
657             0 if !result.is_null() => {
658                 let ptr = passwd.pw_dir as *const _;
659                 let bytes = CStr::from_ptr(ptr).to_bytes().to_vec();
660                 Some(OsStringExt::from_vec(bytes))
661             }
662             _ => None,
663         }
664     }
665 }
666 
exit(code: i32) -> !667 pub fn exit(code: i32) -> ! {
668     unsafe { libc::exit(code as c_int) }
669 }
670 
getpid() -> u32671 pub fn getpid() -> u32 {
672     unsafe { libc::getpid() as u32 }
673 }
674 
getppid() -> u32675 pub fn getppid() -> u32 {
676     unsafe { libc::getppid() as u32 }
677 }
678 
679 #[cfg(all(target_os = "linux", target_env = "gnu"))]
glibc_version() -> Option<(usize, usize)>680 pub fn glibc_version() -> Option<(usize, usize)> {
681     extern "C" {
682         fn gnu_get_libc_version() -> *const libc::c_char;
683     }
684     let version_cstr = unsafe { CStr::from_ptr(gnu_get_libc_version()) };
685     if let Ok(version_str) = version_cstr.to_str() {
686         parse_glibc_version(version_str)
687     } else {
688         None
689     }
690 }
691 
692 // Returns Some((major, minor)) if the string is a valid "x.y" version,
693 // ignoring any extra dot-separated parts. Otherwise return None.
694 #[cfg(all(target_os = "linux", target_env = "gnu"))]
parse_glibc_version(version: &str) -> Option<(usize, usize)>695 fn parse_glibc_version(version: &str) -> Option<(usize, usize)> {
696     let mut parsed_ints = version.split('.').map(str::parse::<usize>).fuse();
697     match (parsed_ints.next(), parsed_ints.next()) {
698         (Some(Ok(major)), Some(Ok(minor))) => Some((major, minor)),
699         _ => None,
700     }
701 }
702