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};
15 use crate::marker::PhantomData;
18 use crate::path::{self, PathBuf};
24 use crate::sys_common::mutex::{StaticMutex, StaticMutexGuard};
25 use crate::sys_common::rwlock::{RWLockReadGuard, StaticRWLock};
28 use libc::{c_char, c_int, c_void};
30 const TMPBUF_SZ: usize = 128;
33 if #[cfg(target_os = "redox")] {
34 const PATH_SEPARATOR: u8 = b';';
36 const PATH_SEPARATOR: u8 = b':';
41 #[cfg(not(any(target_os = "dragonfly", target_os = "vxworks")))]
45 target_os = "emscripten",
46 target_os = "fuchsia",
49 link_name = "__errno_location"
54 target_os = "openbsd",
55 target_os = "android",
61 #[cfg_attr(any(target_os = "solaris", target_os = "illumos"), link_name = "___errno")]
63 any(target_os = "macos", target_os = "ios", target_os = "freebsd"),
66 #[cfg_attr(target_os = "haiku", link_name = "_errnop")]
67 fn errno_location() -> *mut c_int;
70 /// Returns the platform-specific value of errno
71 #[cfg(not(any(target_os = "dragonfly", target_os = "vxworks")))]
72 pub fn errno() -> i32 {
73 unsafe { (*errno_location()) as i32 }
76 /// Sets the platform-specific value of errno
77 #[cfg(all(not(target_os = "linux"), not(target_os = "dragonfly"), not(target_os = "vxworks")))] // needed for readdir and syscall!
78 #[allow(dead_code)] // but not all target cfgs actually end up using it
79 pub fn set_errno(e: i32) {
80 unsafe { *errno_location() = e as c_int }
83 #[cfg(target_os = "vxworks")]
84 pub fn errno() -> i32 {
85 unsafe { libc::errnoGet() }
88 #[cfg(target_os = "dragonfly")]
89 pub fn errno() -> i32 {
95 unsafe { errno as i32 }
98 #[cfg(target_os = "dragonfly")]
99 pub fn set_errno(e: i32) {
102 static mut errno: c_int;
110 /// Gets a detailed string description for the given error number.
111 pub fn error_string(errno: i32) -> String {
113 #[cfg_attr(any(target_os = "linux", target_env = "newlib"), link_name = "__xpg_strerror_r")]
114 fn strerror_r(errnum: c_int, buf: *mut c_char, buflen: libc::size_t) -> c_int;
117 let mut buf = [0 as c_char; TMPBUF_SZ];
119 let p = buf.as_mut_ptr();
121 if strerror_r(errno as c_int, p, buf.len()) < 0 {
122 panic!("strerror_r failure");
125 let p = p as *const _;
126 str::from_utf8(CStr::from_ptr(p).to_bytes()).unwrap().to_owned()
130 pub fn getcwd() -> io::Result<PathBuf> {
131 let mut buf = Vec::with_capacity(512);
134 let ptr = buf.as_mut_ptr() as *mut libc::c_char;
135 if !libc::getcwd(ptr, buf.capacity()).is_null() {
136 let len = CStr::from_ptr(buf.as_ptr() as *const libc::c_char).to_bytes().len();
139 return Ok(PathBuf::from(OsString::from_vec(buf)));
141 let error = io::Error::last_os_error();
142 if error.raw_os_error() != Some(libc::ERANGE) {
147 // Trigger the internal buffer resizing logic of `Vec` by requiring
148 // more space than the current capacity.
149 let cap = buf.capacity();
156 pub fn chdir(p: &path::Path) -> io::Result<()> {
157 let p: &OsStr = p.as_ref();
158 let p = CString::new(p.as_bytes())?;
160 match libc::chdir(p.as_ptr()) == (0 as c_int) {
162 false => Err(io::Error::last_os_error()),
167 pub struct SplitPaths<'a> {
168 iter: iter::Map<slice::Split<'a, u8, fn(&u8) -> bool>, fn(&'a [u8]) -> PathBuf>,
171 pub fn split_paths(unparsed: &OsStr) -> SplitPaths<'_> {
172 fn bytes_to_path(b: &[u8]) -> PathBuf {
173 PathBuf::from(<OsStr as OsStrExt>::from_bytes(b))
175 fn is_separator(b: &u8) -> bool {
178 let unparsed = unparsed.as_bytes();
181 .split(is_separator as fn(&u8) -> bool)
182 .map(bytes_to_path as fn(&[u8]) -> PathBuf),
186 impl<'a> Iterator for SplitPaths<'a> {
188 fn next(&mut self) -> Option<PathBuf> {
191 fn size_hint(&self) -> (usize, Option<usize>) {
192 self.iter.size_hint()
197 pub struct JoinPathsError;
199 pub fn join_paths<I, T>(paths: I) -> Result<OsString, JoinPathsError>
201 I: Iterator<Item = T>,
204 let mut joined = Vec::new();
206 for (i, path) in paths.enumerate() {
207 let path = path.as_ref().as_bytes();
209 joined.push(PATH_SEPARATOR)
211 if path.contains(&PATH_SEPARATOR) {
212 return Err(JoinPathsError);
214 joined.extend_from_slice(path);
216 Ok(OsStringExt::from_vec(joined))
219 impl fmt::Display for JoinPathsError {
220 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
221 write!(f, "path segment contains separator `{}`", char::from(PATH_SEPARATOR))
225 impl StdError for JoinPathsError {
227 fn description(&self) -> &str {
228 "failed to join paths"
232 #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))]
233 pub fn current_exe() -> io::Result<PathBuf> {
236 libc::CTL_KERN as c_int,
237 libc::KERN_PROC as c_int,
238 libc::KERN_PROC_PATHNAME as c_int,
244 mib.len() as libc::c_uint,
251 return Err(io::Error::last_os_error());
253 let mut v: Vec<u8> = Vec::with_capacity(sz);
256 mib.len() as libc::c_uint,
257 v.as_mut_ptr() as *mut libc::c_void,
263 return Err(io::Error::last_os_error());
265 v.set_len(sz - 1); // chop off trailing NUL
266 Ok(PathBuf::from(OsString::from_vec(v)))
270 #[cfg(target_os = "netbsd")]
271 pub fn current_exe() -> io::Result<PathBuf> {
272 fn sysctl() -> io::Result<PathBuf> {
274 let mib = [libc::CTL_KERN, libc::KERN_PROC_ARGS, -1, libc::KERN_PROC_PATHNAME];
275 let mut path_len: usize = 0;
278 mib.len() as libc::c_uint,
285 return Err(io::Error::new_const(
286 io::ErrorKind::Other,
287 &"KERN_PROC_PATHNAME sysctl returned zero-length string",
290 let mut path: Vec<u8> = Vec::with_capacity(path_len);
293 mib.len() as libc::c_uint,
294 path.as_ptr() as *mut libc::c_void,
299 path.set_len(path_len - 1); // chop off NUL
300 Ok(PathBuf::from(OsString::from_vec(path)))
303 fn procfs() -> io::Result<PathBuf> {
304 let curproc_exe = path::Path::new("/proc/curproc/exe");
305 if curproc_exe.is_file() {
306 return crate::fs::read_link(curproc_exe);
308 Err(io::Error::new_const(
309 io::ErrorKind::Other,
310 &"/proc/curproc/exe doesn't point to regular file.",
313 sysctl().or_else(|_| procfs())
316 #[cfg(target_os = "openbsd")]
317 pub fn current_exe() -> io::Result<PathBuf> {
319 let mut mib = [libc::CTL_KERN, libc::KERN_PROC_ARGS, libc::getpid(), libc::KERN_PROC_ARGV];
320 let mib = mib.as_mut_ptr();
321 let mut argv_len = 0;
322 cvt(libc::sysctl(mib, 4, ptr::null_mut(), &mut argv_len, ptr::null_mut(), 0))?;
323 let mut argv = Vec::<*const libc::c_char>::with_capacity(argv_len as usize);
324 cvt(libc::sysctl(mib, 4, argv.as_mut_ptr() as *mut _, &mut argv_len, ptr::null_mut(), 0))?;
325 argv.set_len(argv_len as usize);
326 if argv[0].is_null() {
327 return Err(io::Error::new_const(io::ErrorKind::Other, &"no current exe available"));
329 let argv0 = CStr::from_ptr(argv[0]).to_bytes();
330 if argv0[0] == b'.' || argv0.iter().any(|b| *b == b'/') {
331 crate::fs::canonicalize(OsStr::from_bytes(argv0))
333 Ok(PathBuf::from(OsStr::from_bytes(argv0)))
338 #[cfg(any(target_os = "linux", target_os = "android", target_os = "emscripten"))]
339 pub fn current_exe() -> io::Result<PathBuf> {
340 match crate::fs::read_link("/proc/self/exe") {
341 Err(ref e) if e.kind() == io::ErrorKind::NotFound => Err(io::Error::new_const(
342 io::ErrorKind::Other,
343 &"no /proc/self/exe available. Is /proc mounted?",
349 #[cfg(any(target_os = "macos", target_os = "ios"))]
350 pub fn current_exe() -> io::Result<PathBuf> {
352 fn _NSGetExecutablePath(buf: *mut libc::c_char, bufsize: *mut u32) -> libc::c_int;
356 _NSGetExecutablePath(ptr::null_mut(), &mut sz);
358 return Err(io::Error::last_os_error());
360 let mut v: Vec<u8> = Vec::with_capacity(sz as usize);
361 let err = _NSGetExecutablePath(v.as_mut_ptr() as *mut i8, &mut sz);
363 return Err(io::Error::last_os_error());
365 v.set_len(sz as usize - 1); // chop off trailing NUL
366 Ok(PathBuf::from(OsString::from_vec(v)))
370 #[cfg(any(target_os = "solaris", target_os = "illumos"))]
371 pub fn current_exe() -> io::Result<PathBuf> {
373 fn getexecname() -> *const c_char;
376 let path = getexecname();
378 Err(io::Error::last_os_error())
380 let filename = CStr::from_ptr(path).to_bytes();
381 let path = PathBuf::from(<OsStr as OsStrExt>::from_bytes(filename));
383 // Prepend a current working directory to the path if
384 // it doesn't contain an absolute pathname.
385 if filename[0] == b'/' { Ok(path) } else { getcwd().map(|cwd| cwd.join(path)) }
390 #[cfg(target_os = "haiku")]
391 pub fn current_exe() -> io::Result<PathBuf> {
392 // Use Haiku's image info functions
399 init_routine: *mut libc::c_void, // function pointer
400 term_routine: *mut libc::c_void, // function pointer
403 name: [libc::c_char; 1024], // MAXPATHLEN
404 text: *mut libc::c_void,
405 data: *mut libc::c_void,
414 fn _get_next_image_info(
417 info: *mut image_info,
422 let mut info: image_info = mem::zeroed();
423 let mut cookie: i32 = 0;
424 // the executable can be found at team id 0
426 _get_next_image_info(0, &mut cookie, &mut info, mem::size_of::<image_info>() as i32);
428 use crate::io::ErrorKind;
429 Err(io::Error::new_const(ErrorKind::Other, &"Error getting executable path"))
431 let name = CStr::from_ptr(info.name.as_ptr()).to_bytes();
432 Ok(PathBuf::from(OsStr::from_bytes(name)))
437 #[cfg(target_os = "redox")]
438 pub fn current_exe() -> io::Result<PathBuf> {
439 crate::fs::read_to_string("sys:exe").map(PathBuf::from)
442 #[cfg(any(target_os = "fuchsia", target_os = "l4re"))]
443 pub fn current_exe() -> io::Result<PathBuf> {
444 use crate::io::ErrorKind;
445 Err(io::Error::new_const(ErrorKind::Unsupported, &"Not yet implemented!"))
448 #[cfg(target_os = "vxworks")]
449 pub fn current_exe() -> io::Result<PathBuf> {
456 let exe_path = env::args().next().unwrap();
457 let path = path::Path::new(&exe_path);
462 iter: vec::IntoIter<(OsString, OsString)>,
463 _dont_send_or_sync_me: PhantomData<*mut ()>,
466 impl Iterator for Env {
467 type Item = (OsString, OsString);
468 fn next(&mut self) -> Option<(OsString, OsString)> {
471 fn size_hint(&self) -> (usize, Option<usize>) {
472 self.iter.size_hint()
476 #[cfg(target_os = "macos")]
477 pub unsafe fn environ() -> *mut *const *const c_char {
479 fn _NSGetEnviron() -> *mut *const *const c_char;
484 #[cfg(not(target_os = "macos"))]
485 pub unsafe fn environ() -> *mut *const *const c_char {
487 static mut environ: *const *const c_char;
489 ptr::addr_of_mut!(environ)
492 static ENV_LOCK: StaticRWLock = StaticRWLock::new();
494 pub fn env_read_lock() -> RWLockReadGuard {
495 ENV_LOCK.read_with_guard()
498 /// Returns a vector of (variable, value) byte-vector pairs for all the
499 /// environment variables of the current process.
500 pub fn env() -> Env {
502 let _guard = env_read_lock();
503 let mut environ = *environ();
504 let mut result = Vec::new();
505 if !environ.is_null() {
506 while !(*environ).is_null() {
507 if let Some(key_value) = parse(CStr::from_ptr(*environ).to_bytes()) {
508 result.push(key_value);
510 environ = environ.add(1);
513 return Env { iter: result.into_iter(), _dont_send_or_sync_me: PhantomData };
516 fn parse(input: &[u8]) -> Option<(OsString, OsString)> {
517 // Strategy (copied from glibc): Variable name and value are separated
518 // by an ASCII equals sign '='. Since a variable name must not be
519 // empty, allow variable names starting with an equals sign. Skip all
521 if input.is_empty() {
524 let pos = memchr::memchr(b'=', &input[1..]).map(|p| p + 1);
527 OsStringExt::from_vec(input[..p].to_vec()),
528 OsStringExt::from_vec(input[p + 1..].to_vec()),
534 pub fn getenv(k: &OsStr) -> io::Result<Option<OsString>> {
535 // environment variables with a nul byte can't be set, so their value is
536 // always None as well
537 let k = CString::new(k.as_bytes())?;
539 let _guard = env_read_lock();
540 let s = libc::getenv(k.as_ptr()) as *const libc::c_char;
541 let ret = if s.is_null() {
544 Some(OsStringExt::from_vec(CStr::from_ptr(s).to_bytes().to_vec()))
550 pub fn setenv(k: &OsStr, v: &OsStr) -> io::Result<()> {
551 let k = CString::new(k.as_bytes())?;
552 let v = CString::new(v.as_bytes())?;
555 let _guard = ENV_LOCK.write_with_guard();
556 cvt(libc::setenv(k.as_ptr(), v.as_ptr(), 1)).map(drop)
560 pub fn unsetenv(n: &OsStr) -> io::Result<()> {
561 let nbuf = CString::new(n.as_bytes())?;
564 let _guard = ENV_LOCK.write_with_guard();
565 cvt(libc::unsetenv(nbuf.as_ptr())).map(drop)
569 pub fn page_size() -> usize {
570 unsafe { libc::sysconf(libc::_SC_PAGESIZE) as usize }
573 pub fn temp_dir() -> PathBuf {
574 crate::env::var_os("TMPDIR").map(PathBuf::from).unwrap_or_else(|| {
575 if cfg!(target_os = "android") {
576 PathBuf::from("/data/local/tmp")
578 PathBuf::from("/tmp")
583 pub fn home_dir() -> Option<PathBuf> {
584 return crate::env::var_os("HOME").or_else(|| unsafe { fallback() }).map(PathBuf::from);
587 target_os = "android",
589 target_os = "emscripten",
591 target_os = "vxworks"
593 unsafe fn fallback() -> Option<OsString> {
597 target_os = "android",
599 target_os = "emscripten",
601 target_os = "vxworks"
603 unsafe fn fallback() -> Option<OsString> {
604 let amt = match libc::sysconf(libc::_SC_GETPW_R_SIZE_MAX) {
605 n if n < 0 => 512 as usize,
608 let mut buf = Vec::with_capacity(amt);
609 let mut passwd: libc::passwd = mem::zeroed();
610 let mut result = ptr::null_mut();
611 match libc::getpwuid_r(
618 0 if !result.is_null() => {
619 let ptr = passwd.pw_dir as *const _;
620 let bytes = CStr::from_ptr(ptr).to_bytes().to_vec();
621 Some(OsStringExt::from_vec(bytes))
628 pub fn exit(code: i32) -> ! {
629 unsafe { libc::exit(code as c_int) }
632 pub fn getpid() -> u32 {
633 unsafe { libc::getpid() as u32 }
636 pub fn getppid() -> u32 {
637 unsafe { libc::getppid() as u32 }
640 #[cfg(all(target_env = "gnu", not(target_os = "vxworks")))]
641 pub fn glibc_version() -> Option<(usize, usize)> {
642 if let Some(Ok(version_str)) = glibc_version_cstr().map(CStr::to_str) {
643 parse_glibc_version(version_str)
649 #[cfg(all(target_env = "gnu", not(target_os = "vxworks")))]
650 fn glibc_version_cstr() -> Option<&'static CStr> {
652 fn gnu_get_libc_version() -> *const libc::c_char
654 if let Some(f) = gnu_get_libc_version.get() {
655 unsafe { Some(CStr::from_ptr(f())) }
661 // Returns Some((major, minor)) if the string is a valid "x.y" version,
662 // ignoring any extra dot-separated parts. Otherwise return None.
663 #[cfg(all(target_env = "gnu", not(target_os = "vxworks")))]
664 fn parse_glibc_version(version: &str) -> Option<(usize, usize)> {
665 let mut parsed_ints = version.split('.').map(str::parse::<usize>).fuse();
666 match (parsed_ints.next(), parsed_ints.next()) {
667 (Some(Ok(major)), Some(Ok(minor))) => Some((major, minor)),