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