1 //! Implementation of `std::os` functionality for unix systems
3 #![allow(unused_imports)] // lots of cfg code here
8 use crate::os::unix::prelude::*;
10 use crate::error::Error as StdError;
11 use crate::ffi::{CStr, CString, OsStr, OsString};
16 use crate::path::{self, PathBuf};
20 use crate::sync::{PoisonError, RwLock};
23 use crate::sys::memchr;
26 #[cfg(all(target_env = "gnu", not(target_os = "vxworks")))]
27 use crate::sys::weak::weak;
29 use libc::{c_char, c_int, c_void};
31 const TMPBUF_SZ: usize = 128;
34 if #[cfg(target_os = "redox")] {
35 const PATH_SEPARATOR: u8 = b';';
37 const PATH_SEPARATOR: u8 = b':';
42 #[cfg(not(any(target_os = "dragonfly", target_os = "vxworks")))]
46 target_os = "emscripten",
47 target_os = "fuchsia",
50 link_name = "__errno_location"
55 target_os = "openbsd",
56 target_os = "android",
62 #[cfg_attr(any(target_os = "solaris", target_os = "illumos"), link_name = "___errno")]
64 any(target_os = "macos", target_os = "ios", target_os = "freebsd", target_os = "watchos"),
67 #[cfg_attr(target_os = "haiku", link_name = "_errnop")]
68 fn errno_location() -> *mut c_int;
71 /// Returns the platform-specific value of errno
72 #[cfg(not(any(target_os = "dragonfly", target_os = "vxworks")))]
73 pub fn errno() -> i32 {
74 unsafe { (*errno_location()) as i32 }
77 /// Sets the platform-specific value of errno
78 #[cfg(all(not(target_os = "dragonfly"), not(target_os = "vxworks")))] // needed for readdir and syscall!
79 #[allow(dead_code)] // but not all target cfgs actually end up using it
80 pub fn set_errno(e: i32) {
81 unsafe { *errno_location() = e as c_int }
84 #[cfg(target_os = "vxworks")]
85 pub fn errno() -> i32 {
86 unsafe { libc::errnoGet() }
89 #[cfg(target_os = "dragonfly")]
90 pub fn errno() -> i32 {
96 unsafe { errno as i32 }
99 #[cfg(target_os = "dragonfly")]
101 pub fn set_errno(e: i32) {
104 static mut errno: c_int;
112 /// Gets a detailed string description for the given error number.
113 pub fn error_string(errno: i32) -> String {
115 #[cfg_attr(any(target_os = "linux", target_env = "newlib"), link_name = "__xpg_strerror_r")]
116 fn strerror_r(errnum: c_int, buf: *mut c_char, buflen: libc::size_t) -> c_int;
119 let mut buf = [0 as c_char; TMPBUF_SZ];
121 let p = buf.as_mut_ptr();
123 if strerror_r(errno as c_int, p, buf.len()) < 0 {
124 panic!("strerror_r failure");
127 let p = p as *const _;
128 // We can't always expect a UTF-8 environment. When we don't get that luxury,
129 // it's better to give a low-quality error message than none at all.
130 String::from_utf8_lossy(CStr::from_ptr(p).to_bytes()).into()
134 #[cfg(target_os = "espidf")]
135 pub fn getcwd() -> io::Result<PathBuf> {
136 Ok(PathBuf::from("/"))
139 #[cfg(not(target_os = "espidf"))]
140 pub fn getcwd() -> io::Result<PathBuf> {
141 let mut buf = Vec::with_capacity(512);
144 let ptr = buf.as_mut_ptr() as *mut libc::c_char;
145 if !libc::getcwd(ptr, buf.capacity()).is_null() {
146 let len = CStr::from_ptr(buf.as_ptr() as *const libc::c_char).to_bytes().len();
149 return Ok(PathBuf::from(OsString::from_vec(buf)));
151 let error = io::Error::last_os_error();
152 if error.raw_os_error() != Some(libc::ERANGE) {
157 // Trigger the internal buffer resizing logic of `Vec` by requiring
158 // more space than the current capacity.
159 let cap = buf.capacity();
166 #[cfg(target_os = "espidf")]
167 pub fn chdir(p: &path::Path) -> io::Result<()> {
168 super::unsupported::unsupported()
171 #[cfg(not(target_os = "espidf"))]
172 pub fn chdir(p: &path::Path) -> io::Result<()> {
173 let p: &OsStr = p.as_ref();
174 let p = CString::new(p.as_bytes())?;
175 if unsafe { libc::chdir(p.as_ptr()) } != 0 {
176 return Err(io::Error::last_os_error());
181 pub struct SplitPaths<'a> {
182 iter: iter::Map<slice::Split<'a, u8, fn(&u8) -> bool>, fn(&'a [u8]) -> PathBuf>,
185 pub fn split_paths(unparsed: &OsStr) -> SplitPaths<'_> {
186 fn bytes_to_path(b: &[u8]) -> PathBuf {
187 PathBuf::from(<OsStr as OsStrExt>::from_bytes(b))
189 fn is_separator(b: &u8) -> bool {
192 let unparsed = unparsed.as_bytes();
195 .split(is_separator as fn(&u8) -> bool)
196 .map(bytes_to_path as fn(&[u8]) -> PathBuf),
200 impl<'a> Iterator for SplitPaths<'a> {
202 fn next(&mut self) -> Option<PathBuf> {
205 fn size_hint(&self) -> (usize, Option<usize>) {
206 self.iter.size_hint()
211 pub struct JoinPathsError;
213 pub fn join_paths<I, T>(paths: I) -> Result<OsString, JoinPathsError>
215 I: Iterator<Item = T>,
218 let mut joined = Vec::new();
220 for (i, path) in paths.enumerate() {
221 let path = path.as_ref().as_bytes();
223 joined.push(PATH_SEPARATOR)
225 if path.contains(&PATH_SEPARATOR) {
226 return Err(JoinPathsError);
228 joined.extend_from_slice(path);
230 Ok(OsStringExt::from_vec(joined))
233 impl fmt::Display for JoinPathsError {
234 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
235 write!(f, "path segment contains separator `{}`", char::from(PATH_SEPARATOR))
239 impl StdError for JoinPathsError {
241 fn description(&self) -> &str {
242 "failed to join paths"
246 #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))]
247 pub fn current_exe() -> io::Result<PathBuf> {
250 libc::CTL_KERN as c_int,
251 libc::KERN_PROC as c_int,
252 libc::KERN_PROC_PATHNAME as c_int,
258 mib.len() as libc::c_uint,
265 return Err(io::Error::last_os_error());
267 let mut v: Vec<u8> = Vec::with_capacity(sz);
270 mib.len() as libc::c_uint,
271 v.as_mut_ptr() as *mut libc::c_void,
277 return Err(io::Error::last_os_error());
279 v.set_len(sz - 1); // chop off trailing NUL
280 Ok(PathBuf::from(OsString::from_vec(v)))
284 #[cfg(target_os = "netbsd")]
285 pub fn current_exe() -> io::Result<PathBuf> {
286 fn sysctl() -> io::Result<PathBuf> {
288 let mib = [libc::CTL_KERN, libc::KERN_PROC_ARGS, -1, libc::KERN_PROC_PATHNAME];
289 let mut path_len: usize = 0;
292 mib.len() as libc::c_uint,
299 return Err(io::const_io_error!(
300 io::ErrorKind::Uncategorized,
301 "KERN_PROC_PATHNAME sysctl returned zero-length string",
304 let mut path: Vec<u8> = Vec::with_capacity(path_len);
307 mib.len() as libc::c_uint,
308 path.as_ptr() as *mut libc::c_void,
313 path.set_len(path_len - 1); // chop off NUL
314 Ok(PathBuf::from(OsString::from_vec(path)))
317 fn procfs() -> io::Result<PathBuf> {
318 let curproc_exe = path::Path::new("/proc/curproc/exe");
319 if curproc_exe.is_file() {
320 return crate::fs::read_link(curproc_exe);
322 Err(io::const_io_error!(
323 io::ErrorKind::Uncategorized,
324 "/proc/curproc/exe doesn't point to regular file.",
327 sysctl().or_else(|_| procfs())
330 #[cfg(target_os = "openbsd")]
331 pub fn current_exe() -> io::Result<PathBuf> {
333 let mut mib = [libc::CTL_KERN, libc::KERN_PROC_ARGS, libc::getpid(), libc::KERN_PROC_ARGV];
334 let mib = mib.as_mut_ptr();
335 let mut argv_len = 0;
336 cvt(libc::sysctl(mib, 4, ptr::null_mut(), &mut argv_len, ptr::null_mut(), 0))?;
337 let mut argv = Vec::<*const libc::c_char>::with_capacity(argv_len as usize);
338 cvt(libc::sysctl(mib, 4, argv.as_mut_ptr() as *mut _, &mut argv_len, ptr::null_mut(), 0))?;
339 argv.set_len(argv_len as usize);
340 if argv[0].is_null() {
341 return Err(io::const_io_error!(
342 io::ErrorKind::Uncategorized,
343 "no current exe available",
346 let argv0 = CStr::from_ptr(argv[0]).to_bytes();
347 if argv0[0] == b'.' || argv0.iter().any(|b| *b == b'/') {
348 crate::fs::canonicalize(OsStr::from_bytes(argv0))
350 Ok(PathBuf::from(OsStr::from_bytes(argv0)))
355 #[cfg(any(target_os = "linux", target_os = "android", target_os = "emscripten"))]
356 pub fn current_exe() -> io::Result<PathBuf> {
357 match crate::fs::read_link("/proc/self/exe") {
358 Err(ref e) if e.kind() == io::ErrorKind::NotFound => Err(io::const_io_error!(
359 io::ErrorKind::Uncategorized,
360 "no /proc/self/exe available. Is /proc mounted?",
366 #[cfg(any(target_os = "macos", target_os = "ios", target_os = "watchos"))]
367 pub fn current_exe() -> io::Result<PathBuf> {
370 libc::_NSGetExecutablePath(ptr::null_mut(), &mut sz);
372 return Err(io::Error::last_os_error());
374 let mut v: Vec<u8> = Vec::with_capacity(sz as usize);
375 let err = libc::_NSGetExecutablePath(v.as_mut_ptr() as *mut i8, &mut sz);
377 return Err(io::Error::last_os_error());
379 v.set_len(sz as usize - 1); // chop off trailing NUL
380 Ok(PathBuf::from(OsString::from_vec(v)))
384 #[cfg(any(target_os = "solaris", target_os = "illumos"))]
385 pub fn current_exe() -> io::Result<PathBuf> {
386 if let Ok(path) = crate::fs::read_link("/proc/self/path/a.out") {
390 let path = libc::getexecname();
392 Err(io::Error::last_os_error())
394 let filename = CStr::from_ptr(path).to_bytes();
395 let path = PathBuf::from(<OsStr as OsStrExt>::from_bytes(filename));
397 // Prepend a current working directory to the path if
398 // it doesn't contain an absolute pathname.
399 if filename[0] == b'/' { Ok(path) } else { getcwd().map(|cwd| cwd.join(path)) }
405 #[cfg(target_os = "haiku")]
406 pub fn current_exe() -> io::Result<PathBuf> {
408 let mut info: mem::MaybeUninit<libc::image_info> = mem::MaybeUninit::uninit();
409 let mut cookie: i32 = 0;
410 // the executable can be found at team id 0
411 let result = libc::_get_next_image_info(
415 mem::size_of::<libc::image_info>(),
418 use crate::io::ErrorKind;
419 Err(io::const_io_error!(ErrorKind::Uncategorized, "Error getting executable path"))
421 let name = CStr::from_ptr((*info.as_ptr()).name.as_ptr()).to_bytes();
422 Ok(PathBuf::from(OsStr::from_bytes(name)))
427 #[cfg(target_os = "redox")]
428 pub fn current_exe() -> io::Result<PathBuf> {
429 crate::fs::read_to_string("sys:exe").map(PathBuf::from)
432 #[cfg(target_os = "l4re")]
433 pub fn current_exe() -> io::Result<PathBuf> {
434 use crate::io::ErrorKind;
435 Err(io::const_io_error!(ErrorKind::Unsupported, "Not yet implemented!"))
438 #[cfg(target_os = "vxworks")]
439 pub fn current_exe() -> io::Result<PathBuf> {
446 let exe_path = env::args().next().unwrap();
447 let path = path::Path::new(&exe_path);
451 #[cfg(any(target_os = "espidf", target_os = "horizon"))]
452 pub fn current_exe() -> io::Result<PathBuf> {
453 super::unsupported::unsupported()
456 #[cfg(target_os = "fuchsia")]
457 pub fn current_exe() -> io::Result<PathBuf> {
458 use crate::io::ErrorKind;
466 let exe_path = env::args().next().ok_or(io::const_io_error!(
467 ErrorKind::Uncategorized,
468 "an executable path was not found because no arguments were provided through argv"
470 let path = PathBuf::from(exe_path);
472 // Prepend the current working directory to the path if it's not absolute.
473 if !path.is_absolute() { getcwd().map(|cwd| cwd.join(path)) } else { Ok(path) }
477 iter: vec::IntoIter<(OsString, OsString)>,
480 impl !Send for Env {}
481 impl !Sync for Env {}
483 impl Iterator for Env {
484 type Item = (OsString, OsString);
485 fn next(&mut self) -> Option<(OsString, OsString)> {
488 fn size_hint(&self) -> (usize, Option<usize>) {
489 self.iter.size_hint()
493 #[cfg(target_os = "macos")]
494 pub unsafe fn environ() -> *mut *const *const c_char {
495 libc::_NSGetEnviron() as *mut *const *const c_char
498 #[cfg(not(target_os = "macos"))]
499 pub unsafe fn environ() -> *mut *const *const c_char {
501 static mut environ: *const *const c_char;
503 ptr::addr_of_mut!(environ)
506 static ENV_LOCK: RwLock<()> = RwLock::new(());
508 pub fn env_read_lock() -> impl Drop {
509 ENV_LOCK.read().unwrap_or_else(PoisonError::into_inner)
512 /// Returns a vector of (variable, value) byte-vector pairs for all the
513 /// environment variables of the current process.
514 pub fn env() -> Env {
516 let _guard = env_read_lock();
517 let mut environ = *environ();
518 let mut result = Vec::new();
519 if !environ.is_null() {
520 while !(*environ).is_null() {
521 if let Some(key_value) = parse(CStr::from_ptr(*environ).to_bytes()) {
522 result.push(key_value);
524 environ = environ.add(1);
527 return Env { iter: result.into_iter() };
530 fn parse(input: &[u8]) -> Option<(OsString, OsString)> {
531 // Strategy (copied from glibc): Variable name and value are separated
532 // by an ASCII equals sign '='. Since a variable name must not be
533 // empty, allow variable names starting with an equals sign. Skip all
535 if input.is_empty() {
538 let pos = memchr::memchr(b'=', &input[1..]).map(|p| p + 1);
541 OsStringExt::from_vec(input[..p].to_vec()),
542 OsStringExt::from_vec(input[p + 1..].to_vec()),
548 pub fn getenv(k: &OsStr) -> Option<OsString> {
549 // environment variables with a nul byte can't be set, so their value is
550 // always None as well
551 let k = CString::new(k.as_bytes()).ok()?;
553 let _guard = env_read_lock();
554 let s = libc::getenv(k.as_ptr()) as *const libc::c_char;
558 Some(OsStringExt::from_vec(CStr::from_ptr(s).to_bytes().to_vec()))
563 pub fn setenv(k: &OsStr, v: &OsStr) -> io::Result<()> {
564 let k = CString::new(k.as_bytes())?;
565 let v = CString::new(v.as_bytes())?;
568 let _guard = ENV_LOCK.write();
569 cvt(libc::setenv(k.as_ptr(), v.as_ptr(), 1)).map(drop)
573 pub fn unsetenv(n: &OsStr) -> io::Result<()> {
574 let nbuf = CString::new(n.as_bytes())?;
577 let _guard = ENV_LOCK.write();
578 cvt(libc::unsetenv(nbuf.as_ptr())).map(drop)
582 #[cfg(not(target_os = "espidf"))]
583 pub fn page_size() -> usize {
584 unsafe { libc::sysconf(libc::_SC_PAGESIZE) as usize }
587 pub fn temp_dir() -> PathBuf {
588 crate::env::var_os("TMPDIR").map(PathBuf::from).unwrap_or_else(|| {
589 if cfg!(target_os = "android") {
590 PathBuf::from("/data/local/tmp")
592 PathBuf::from("/tmp")
597 pub fn home_dir() -> Option<PathBuf> {
598 return crate::env::var_os("HOME").or_else(|| unsafe { fallback() }).map(PathBuf::from);
601 target_os = "android",
603 target_os = "watchos",
604 target_os = "emscripten",
606 target_os = "vxworks",
607 target_os = "espidf",
608 target_os = "horizon"
610 unsafe fn fallback() -> Option<OsString> {
614 target_os = "android",
616 target_os = "watchos",
617 target_os = "emscripten",
619 target_os = "vxworks",
620 target_os = "espidf",
621 target_os = "horizon"
623 unsafe fn fallback() -> Option<OsString> {
624 let amt = match libc::sysconf(libc::_SC_GETPW_R_SIZE_MAX) {
625 n if n < 0 => 512 as usize,
628 let mut buf = Vec::with_capacity(amt);
629 let mut passwd: libc::passwd = mem::zeroed();
630 let mut result = ptr::null_mut();
631 match libc::getpwuid_r(
638 0 if !result.is_null() => {
639 let ptr = passwd.pw_dir as *const _;
640 let bytes = CStr::from_ptr(ptr).to_bytes().to_vec();
641 Some(OsStringExt::from_vec(bytes))
648 pub fn exit(code: i32) -> ! {
649 unsafe { libc::exit(code as c_int) }
652 pub fn getpid() -> u32 {
653 unsafe { libc::getpid() as u32 }
656 pub fn getppid() -> u32 {
657 unsafe { libc::getppid() as u32 }
660 #[cfg(all(target_os = "linux", target_env = "gnu"))]
661 pub fn glibc_version() -> Option<(usize, usize)> {
663 fn gnu_get_libc_version() -> *const libc::c_char;
665 let version_cstr = unsafe { CStr::from_ptr(gnu_get_libc_version()) };
666 if let Ok(version_str) = version_cstr.to_str() {
667 parse_glibc_version(version_str)
673 // Returns Some((major, minor)) if the string is a valid "x.y" version,
674 // ignoring any extra dot-separated parts. Otherwise return None.
675 #[cfg(all(target_os = "linux", target_env = "gnu"))]
676 fn parse_glibc_version(version: &str) -> Option<(usize, usize)> {
677 let mut parsed_ints = version.split('.').map(str::parse::<usize>).fuse();
678 match (parsed_ints.next(), parsed_ints.next()) {
679 (Some(Ok(major)), Some(Ok(minor))) => Some((major, minor)),