1 //! Implementation of `std::os` functionality for unix systems
3 #![allow(unused_imports)] // lots of cfg code here
5 #[cfg(all(test, target_env = "gnu"))]
8 use crate::os::unix::prelude::*;
10 use crate::error::Error as StdError;
11 use crate::ffi::{CStr, CString, OsStr, OsString};
17 use crate::path::{self, PathBuf};
23 use crate::sys::rwlock::{RWLockReadGuard, StaticRWLock};
24 use crate::sys_common::mutex::{StaticMutex, StaticMutexGuard};
27 use libc::{c_char, c_int, c_void};
29 const TMPBUF_SZ: usize = 128;
32 if #[cfg(target_os = "redox")] {
33 const PATH_SEPARATOR: u8 = b';';
35 const PATH_SEPARATOR: u8 = b':';
40 #[cfg(not(any(target_os = "dragonfly", target_os = "vxworks")))]
44 target_os = "emscripten",
45 target_os = "fuchsia",
48 link_name = "__errno_location"
53 target_os = "openbsd",
54 target_os = "android",
60 #[cfg_attr(any(target_os = "solaris", target_os = "illumos"), link_name = "___errno")]
62 any(target_os = "macos", target_os = "ios", target_os = "freebsd"),
65 #[cfg_attr(target_os = "haiku", link_name = "_errnop")]
66 fn errno_location() -> *mut c_int;
69 /// Returns the platform-specific value of errno
70 #[cfg(not(any(target_os = "dragonfly", target_os = "vxworks")))]
71 pub fn errno() -> i32 {
72 unsafe { (*errno_location()) as i32 }
75 /// Sets the platform-specific value of errno
76 #[cfg(all(not(target_os = "linux"), not(target_os = "dragonfly"), not(target_os = "vxworks")))] // needed for readdir and syscall!
77 #[allow(dead_code)] // but not all target cfgs actually end up using it
78 pub fn set_errno(e: i32) {
79 unsafe { *errno_location() = e as c_int }
82 #[cfg(target_os = "vxworks")]
83 pub fn errno() -> i32 {
84 unsafe { libc::errnoGet() }
87 #[cfg(target_os = "dragonfly")]
88 pub fn errno() -> i32 {
94 unsafe { errno as i32 }
97 #[cfg(target_os = "dragonfly")]
98 pub fn set_errno(e: i32) {
101 static mut errno: c_int;
109 /// Gets a detailed string description for the given error number.
110 pub fn error_string(errno: i32) -> String {
112 #[cfg_attr(any(target_os = "linux", target_env = "newlib"), link_name = "__xpg_strerror_r")]
113 fn strerror_r(errnum: c_int, buf: *mut c_char, buflen: libc::size_t) -> c_int;
116 let mut buf = [0 as c_char; TMPBUF_SZ];
118 let p = buf.as_mut_ptr();
120 if strerror_r(errno as c_int, p, buf.len()) < 0 {
121 panic!("strerror_r failure");
124 let p = p as *const _;
125 str::from_utf8(CStr::from_ptr(p).to_bytes()).unwrap().to_owned()
129 pub fn getcwd() -> io::Result<PathBuf> {
130 let mut buf = Vec::with_capacity(512);
133 let ptr = buf.as_mut_ptr() as *mut libc::c_char;
134 if !libc::getcwd(ptr, buf.capacity()).is_null() {
135 let len = CStr::from_ptr(buf.as_ptr() as *const libc::c_char).to_bytes().len();
138 return Ok(PathBuf::from(OsString::from_vec(buf)));
140 let error = io::Error::last_os_error();
141 if error.raw_os_error() != Some(libc::ERANGE) {
146 // Trigger the internal buffer resizing logic of `Vec` by requiring
147 // more space than the current capacity.
148 let cap = buf.capacity();
155 pub fn chdir(p: &path::Path) -> io::Result<()> {
156 let p: &OsStr = p.as_ref();
157 let p = CString::new(p.as_bytes())?;
159 match libc::chdir(p.as_ptr()) == (0 as c_int) {
161 false => Err(io::Error::last_os_error()),
166 pub struct SplitPaths<'a> {
167 iter: iter::Map<slice::Split<'a, u8, fn(&u8) -> bool>, fn(&'a [u8]) -> PathBuf>,
170 pub fn split_paths(unparsed: &OsStr) -> SplitPaths<'_> {
171 fn bytes_to_path(b: &[u8]) -> PathBuf {
172 PathBuf::from(<OsStr as OsStrExt>::from_bytes(b))
174 fn is_separator(b: &u8) -> bool {
177 let unparsed = unparsed.as_bytes();
180 .split(is_separator as fn(&u8) -> bool)
181 .map(bytes_to_path as fn(&[u8]) -> PathBuf),
185 impl<'a> Iterator for SplitPaths<'a> {
187 fn next(&mut self) -> Option<PathBuf> {
190 fn size_hint(&self) -> (usize, Option<usize>) {
191 self.iter.size_hint()
196 pub struct JoinPathsError;
198 pub fn join_paths<I, T>(paths: I) -> Result<OsString, JoinPathsError>
200 I: Iterator<Item = T>,
203 let mut joined = Vec::new();
205 for (i, path) in paths.enumerate() {
206 let path = path.as_ref().as_bytes();
208 joined.push(PATH_SEPARATOR)
210 if path.contains(&PATH_SEPARATOR) {
211 return Err(JoinPathsError);
213 joined.extend_from_slice(path);
215 Ok(OsStringExt::from_vec(joined))
218 impl fmt::Display for JoinPathsError {
219 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
220 write!(f, "path segment contains separator `{}`", char::from(PATH_SEPARATOR))
224 impl StdError for JoinPathsError {
226 fn description(&self) -> &str {
227 "failed to join paths"
231 #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))]
232 pub fn current_exe() -> io::Result<PathBuf> {
235 libc::CTL_KERN as c_int,
236 libc::KERN_PROC as c_int,
237 libc::KERN_PROC_PATHNAME as c_int,
243 mib.len() as libc::c_uint,
250 return Err(io::Error::last_os_error());
252 let mut v: Vec<u8> = Vec::with_capacity(sz);
255 mib.len() as libc::c_uint,
256 v.as_mut_ptr() as *mut libc::c_void,
262 return Err(io::Error::last_os_error());
264 v.set_len(sz - 1); // chop off trailing NUL
265 Ok(PathBuf::from(OsString::from_vec(v)))
269 #[cfg(target_os = "netbsd")]
270 pub fn current_exe() -> io::Result<PathBuf> {
271 fn sysctl() -> io::Result<PathBuf> {
273 let mib = [libc::CTL_KERN, libc::KERN_PROC_ARGS, -1, libc::KERN_PROC_PATHNAME];
274 let mut path_len: usize = 0;
277 mib.len() as libc::c_uint,
284 return Err(io::Error::new_const(
285 io::ErrorKind::Other,
286 &"KERN_PROC_PATHNAME sysctl returned zero-length string",
289 let mut path: Vec<u8> = Vec::with_capacity(path_len);
292 mib.len() as libc::c_uint,
293 path.as_ptr() as *mut libc::c_void,
298 path.set_len(path_len - 1); // chop off NUL
299 Ok(PathBuf::from(OsString::from_vec(path)))
302 fn procfs() -> io::Result<PathBuf> {
303 let curproc_exe = path::Path::new("/proc/curproc/exe");
304 if curproc_exe.is_file() {
305 return crate::fs::read_link(curproc_exe);
307 Err(io::Error::new_const(
308 io::ErrorKind::Other,
309 &"/proc/curproc/exe doesn't point to regular file.",
312 sysctl().or_else(|_| procfs())
315 #[cfg(target_os = "openbsd")]
316 pub fn current_exe() -> io::Result<PathBuf> {
318 let mut mib = [libc::CTL_KERN, libc::KERN_PROC_ARGS, libc::getpid(), libc::KERN_PROC_ARGV];
319 let mib = mib.as_mut_ptr();
320 let mut argv_len = 0;
321 cvt(libc::sysctl(mib, 4, ptr::null_mut(), &mut argv_len, ptr::null_mut(), 0))?;
322 let mut argv = Vec::<*const libc::c_char>::with_capacity(argv_len as usize);
323 cvt(libc::sysctl(mib, 4, argv.as_mut_ptr() as *mut _, &mut argv_len, ptr::null_mut(), 0))?;
324 argv.set_len(argv_len as usize);
325 if argv[0].is_null() {
326 return Err(io::Error::new_const(io::ErrorKind::Other, &"no current exe available"));
328 let argv0 = CStr::from_ptr(argv[0]).to_bytes();
329 if argv0[0] == b'.' || argv0.iter().any(|b| *b == b'/') {
330 crate::fs::canonicalize(OsStr::from_bytes(argv0))
332 Ok(PathBuf::from(OsStr::from_bytes(argv0)))
337 #[cfg(any(target_os = "linux", target_os = "android", target_os = "emscripten"))]
338 pub fn current_exe() -> io::Result<PathBuf> {
339 match crate::fs::read_link("/proc/self/exe") {
340 Err(ref e) if e.kind() == io::ErrorKind::NotFound => Err(io::Error::new_const(
341 io::ErrorKind::Other,
342 &"no /proc/self/exe available. Is /proc mounted?",
348 #[cfg(any(target_os = "macos", target_os = "ios"))]
349 pub fn current_exe() -> io::Result<PathBuf> {
351 fn _NSGetExecutablePath(buf: *mut libc::c_char, bufsize: *mut u32) -> libc::c_int;
355 _NSGetExecutablePath(ptr::null_mut(), &mut sz);
357 return Err(io::Error::last_os_error());
359 let mut v: Vec<u8> = Vec::with_capacity(sz as usize);
360 let err = _NSGetExecutablePath(v.as_mut_ptr() as *mut i8, &mut sz);
362 return Err(io::Error::last_os_error());
364 v.set_len(sz as usize - 1); // chop off trailing NUL
365 Ok(PathBuf::from(OsString::from_vec(v)))
369 #[cfg(any(target_os = "solaris", target_os = "illumos"))]
370 pub fn current_exe() -> io::Result<PathBuf> {
372 fn getexecname() -> *const c_char;
375 let path = getexecname();
377 Err(io::Error::last_os_error())
379 let filename = CStr::from_ptr(path).to_bytes();
380 let path = PathBuf::from(<OsStr as OsStrExt>::from_bytes(filename));
382 // Prepend a current working directory to the path if
383 // it doesn't contain an absolute pathname.
384 if filename[0] == b'/' { Ok(path) } else { getcwd().map(|cwd| cwd.join(path)) }
389 #[cfg(target_os = "haiku")]
390 pub fn current_exe() -> io::Result<PathBuf> {
391 // Use Haiku's image info functions
398 init_routine: *mut libc::c_void, // function pointer
399 term_routine: *mut libc::c_void, // function pointer
402 name: [libc::c_char; 1024], // MAXPATHLEN
403 text: *mut libc::c_void,
404 data: *mut libc::c_void,
413 fn _get_next_image_info(
416 info: *mut image_info,
421 let mut info: image_info = mem::zeroed();
422 let mut cookie: i32 = 0;
423 // the executable can be found at team id 0
425 _get_next_image_info(0, &mut cookie, &mut info, mem::size_of::<image_info>() as i32);
427 use crate::io::ErrorKind;
428 Err(io::Error::new_const(ErrorKind::Other, &"Error getting executable path"))
430 let name = CStr::from_ptr(info.name.as_ptr()).to_bytes();
431 Ok(PathBuf::from(OsStr::from_bytes(name)))
436 #[cfg(target_os = "redox")]
437 pub fn current_exe() -> io::Result<PathBuf> {
438 crate::fs::read_to_string("sys:exe").map(PathBuf::from)
441 #[cfg(any(target_os = "fuchsia", target_os = "l4re"))]
442 pub fn current_exe() -> io::Result<PathBuf> {
443 use crate::io::ErrorKind;
444 Err(io::Error::new_const(ErrorKind::Unsupported, &"Not yet implemented!"))
447 #[cfg(target_os = "vxworks")]
448 pub fn current_exe() -> io::Result<PathBuf> {
455 let exe_path = env::args().next().unwrap();
456 let path = path::Path::new(&exe_path);
461 iter: vec::IntoIter<(OsString, OsString)>,
464 impl !Send for Env {}
465 impl !Sync for Env {}
467 impl Iterator for Env {
468 type Item = (OsString, OsString);
469 fn next(&mut self) -> Option<(OsString, OsString)> {
472 fn size_hint(&self) -> (usize, Option<usize>) {
473 self.iter.size_hint()
477 #[cfg(target_os = "macos")]
478 pub unsafe fn environ() -> *mut *const *const c_char {
480 fn _NSGetEnviron() -> *mut *const *const c_char;
485 #[cfg(not(target_os = "macos"))]
486 pub unsafe fn environ() -> *mut *const *const c_char {
488 static mut environ: *const *const c_char;
490 ptr::addr_of_mut!(environ)
493 static ENV_LOCK: StaticRWLock = StaticRWLock::new();
495 pub fn env_read_lock() -> RWLockReadGuard {
496 ENV_LOCK.read_with_guard()
499 /// Returns a vector of (variable, value) byte-vector pairs for all the
500 /// environment variables of the current process.
501 pub fn env() -> Env {
503 let _guard = env_read_lock();
504 let mut environ = *environ();
505 let mut result = Vec::new();
506 if !environ.is_null() {
507 while !(*environ).is_null() {
508 if let Some(key_value) = parse(CStr::from_ptr(*environ).to_bytes()) {
509 result.push(key_value);
511 environ = environ.add(1);
514 return Env { iter: result.into_iter() };
517 fn parse(input: &[u8]) -> Option<(OsString, OsString)> {
518 // Strategy (copied from glibc): Variable name and value are separated
519 // by an ASCII equals sign '='. Since a variable name must not be
520 // empty, allow variable names starting with an equals sign. Skip all
522 if input.is_empty() {
525 let pos = memchr::memchr(b'=', &input[1..]).map(|p| p + 1);
528 OsStringExt::from_vec(input[..p].to_vec()),
529 OsStringExt::from_vec(input[p + 1..].to_vec()),
535 pub fn getenv(k: &OsStr) -> io::Result<Option<OsString>> {
536 // environment variables with a nul byte can't be set, so their value is
537 // always None as well
538 let k = CString::new(k.as_bytes())?;
540 let _guard = env_read_lock();
541 let s = libc::getenv(k.as_ptr()) as *const libc::c_char;
542 let ret = if s.is_null() {
545 Some(OsStringExt::from_vec(CStr::from_ptr(s).to_bytes().to_vec()))
551 pub fn setenv(k: &OsStr, v: &OsStr) -> io::Result<()> {
552 let k = CString::new(k.as_bytes())?;
553 let v = CString::new(v.as_bytes())?;
556 let _guard = ENV_LOCK.write_with_guard();
557 cvt(libc::setenv(k.as_ptr(), v.as_ptr(), 1)).map(drop)
561 pub fn unsetenv(n: &OsStr) -> io::Result<()> {
562 let nbuf = CString::new(n.as_bytes())?;
565 let _guard = ENV_LOCK.write_with_guard();
566 cvt(libc::unsetenv(nbuf.as_ptr())).map(drop)
570 pub fn page_size() -> usize {
571 unsafe { libc::sysconf(libc::_SC_PAGESIZE) as usize }
574 pub fn temp_dir() -> PathBuf {
575 crate::env::var_os("TMPDIR").map(PathBuf::from).unwrap_or_else(|| {
576 if cfg!(target_os = "android") {
577 PathBuf::from("/data/local/tmp")
579 PathBuf::from("/tmp")
584 pub fn home_dir() -> Option<PathBuf> {
585 return crate::env::var_os("HOME").or_else(|| unsafe { fallback() }).map(PathBuf::from);
588 target_os = "android",
590 target_os = "emscripten",
592 target_os = "vxworks"
594 unsafe fn fallback() -> Option<OsString> {
598 target_os = "android",
600 target_os = "emscripten",
602 target_os = "vxworks"
604 unsafe fn fallback() -> Option<OsString> {
605 let amt = match libc::sysconf(libc::_SC_GETPW_R_SIZE_MAX) {
606 n if n < 0 => 512 as usize,
609 let mut buf = Vec::with_capacity(amt);
610 let mut passwd: libc::passwd = mem::zeroed();
611 let mut result = ptr::null_mut();
612 match libc::getpwuid_r(
619 0 if !result.is_null() => {
620 let ptr = passwd.pw_dir as *const _;
621 let bytes = CStr::from_ptr(ptr).to_bytes().to_vec();
622 Some(OsStringExt::from_vec(bytes))
629 pub fn exit(code: i32) -> ! {
630 unsafe { libc::exit(code as c_int) }
633 pub fn getpid() -> u32 {
634 unsafe { libc::getpid() as u32 }
637 pub fn getppid() -> u32 {
638 unsafe { libc::getppid() as u32 }
641 #[cfg(all(target_env = "gnu", not(target_os = "vxworks")))]
642 pub fn glibc_version() -> Option<(usize, usize)> {
643 if let Some(Ok(version_str)) = glibc_version_cstr().map(CStr::to_str) {
644 parse_glibc_version(version_str)
650 #[cfg(all(target_env = "gnu", not(target_os = "vxworks")))]
651 fn glibc_version_cstr() -> Option<&'static CStr> {
653 fn gnu_get_libc_version() -> *const libc::c_char
655 if let Some(f) = gnu_get_libc_version.get() {
656 unsafe { Some(CStr::from_ptr(f())) }
662 // Returns Some((major, minor)) if the string is a valid "x.y" version,
663 // ignoring any extra dot-separated parts. Otherwise return None.
664 #[cfg(all(target_env = "gnu", not(target_os = "vxworks")))]
665 fn parse_glibc_version(version: &str) -> Option<(usize, usize)> {
666 let mut parsed_ints = version.split('.').map(str::parse::<usize>).fuse();
667 match (parsed_ints.next(), parsed_ints.next()) {
668 (Some(Ok(major)), Some(Ok(minor))) => Some((major, minor)),