]> git.lizzy.rs Git - rust.git/blob - library/std/src/sys/unix/os.rs
Rollup merge of #98218 - kpreid:nostdarc, 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(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::cvt;
22 use crate::sys::fd;
23 use crate::sys::memchr;
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", target_os = "watchos"),
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 = "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 #[allow(dead_code)]
101 pub fn set_errno(e: i32) {
102     extern "C" {
103         #[thread_local]
104         static mut errno: c_int;
105     }
106
107     unsafe {
108         errno = e;
109     }
110 }
111
112 /// Gets a detailed string description for the given error number.
113 pub fn error_string(errno: i32) -> String {
114     extern "C" {
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;
117     }
118
119     let mut buf = [0 as c_char; TMPBUF_SZ];
120
121     let p = buf.as_mut_ptr();
122     unsafe {
123         if strerror_r(errno as c_int, p, buf.len()) < 0 {
124             panic!("strerror_r failure");
125         }
126
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()
131     }
132 }
133
134 #[cfg(target_os = "espidf")]
135 pub fn getcwd() -> io::Result<PathBuf> {
136     Ok(PathBuf::from("/"))
137 }
138
139 #[cfg(not(target_os = "espidf"))]
140 pub fn getcwd() -> io::Result<PathBuf> {
141     let mut buf = Vec::with_capacity(512);
142     loop {
143         unsafe {
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();
147                 buf.set_len(len);
148                 buf.shrink_to_fit();
149                 return Ok(PathBuf::from(OsString::from_vec(buf)));
150             } else {
151                 let error = io::Error::last_os_error();
152                 if error.raw_os_error() != Some(libc::ERANGE) {
153                     return Err(error);
154                 }
155             }
156
157             // Trigger the internal buffer resizing logic of `Vec` by requiring
158             // more space than the current capacity.
159             let cap = buf.capacity();
160             buf.set_len(cap);
161             buf.reserve(1);
162         }
163     }
164 }
165
166 #[cfg(target_os = "espidf")]
167 pub fn chdir(p: &path::Path) -> io::Result<()> {
168     super::unsupported::unsupported()
169 }
170
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());
177     }
178     Ok(())
179 }
180
181 pub struct SplitPaths<'a> {
182     iter: iter::Map<slice::Split<'a, u8, fn(&u8) -> bool>, fn(&'a [u8]) -> PathBuf>,
183 }
184
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))
188     }
189     fn is_separator(b: &u8) -> bool {
190         *b == PATH_SEPARATOR
191     }
192     let unparsed = unparsed.as_bytes();
193     SplitPaths {
194         iter: unparsed
195             .split(is_separator as fn(&u8) -> bool)
196             .map(bytes_to_path as fn(&[u8]) -> PathBuf),
197     }
198 }
199
200 impl<'a> Iterator for SplitPaths<'a> {
201     type Item = PathBuf;
202     fn next(&mut self) -> Option<PathBuf> {
203         self.iter.next()
204     }
205     fn size_hint(&self) -> (usize, Option<usize>) {
206         self.iter.size_hint()
207     }
208 }
209
210 #[derive(Debug)]
211 pub struct JoinPathsError;
212
213 pub fn join_paths<I, T>(paths: I) -> Result<OsString, JoinPathsError>
214 where
215     I: Iterator<Item = T>,
216     T: AsRef<OsStr>,
217 {
218     let mut joined = Vec::new();
219
220     for (i, path) in paths.enumerate() {
221         let path = path.as_ref().as_bytes();
222         if i > 0 {
223             joined.push(PATH_SEPARATOR)
224         }
225         if path.contains(&PATH_SEPARATOR) {
226             return Err(JoinPathsError);
227         }
228         joined.extend_from_slice(path);
229     }
230     Ok(OsStringExt::from_vec(joined))
231 }
232
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))
236     }
237 }
238
239 impl StdError for JoinPathsError {
240     #[allow(deprecated)]
241     fn description(&self) -> &str {
242         "failed to join paths"
243     }
244 }
245
246 #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))]
247 pub fn current_exe() -> io::Result<PathBuf> {
248     unsafe {
249         let mut mib = [
250             libc::CTL_KERN as c_int,
251             libc::KERN_PROC as c_int,
252             libc::KERN_PROC_PATHNAME as c_int,
253             -1 as c_int,
254         ];
255         let mut sz = 0;
256         cvt(libc::sysctl(
257             mib.as_mut_ptr(),
258             mib.len() as libc::c_uint,
259             ptr::null_mut(),
260             &mut sz,
261             ptr::null_mut(),
262             0,
263         ))?;
264         if sz == 0 {
265             return Err(io::Error::last_os_error());
266         }
267         let mut v: Vec<u8> = Vec::with_capacity(sz);
268         cvt(libc::sysctl(
269             mib.as_mut_ptr(),
270             mib.len() as libc::c_uint,
271             v.as_mut_ptr() as *mut libc::c_void,
272             &mut sz,
273             ptr::null_mut(),
274             0,
275         ))?;
276         if sz == 0 {
277             return Err(io::Error::last_os_error());
278         }
279         v.set_len(sz - 1); // chop off trailing NUL
280         Ok(PathBuf::from(OsString::from_vec(v)))
281     }
282 }
283
284 #[cfg(target_os = "netbsd")]
285 pub fn current_exe() -> io::Result<PathBuf> {
286     fn sysctl() -> io::Result<PathBuf> {
287         unsafe {
288             let mib = [libc::CTL_KERN, libc::KERN_PROC_ARGS, -1, libc::KERN_PROC_PATHNAME];
289             let mut path_len: usize = 0;
290             cvt(libc::sysctl(
291                 mib.as_ptr(),
292                 mib.len() as libc::c_uint,
293                 ptr::null_mut(),
294                 &mut path_len,
295                 ptr::null(),
296                 0,
297             ))?;
298             if path_len <= 1 {
299                 return Err(io::const_io_error!(
300                     io::ErrorKind::Uncategorized,
301                     "KERN_PROC_PATHNAME sysctl returned zero-length string",
302                 ));
303             }
304             let mut path: Vec<u8> = Vec::with_capacity(path_len);
305             cvt(libc::sysctl(
306                 mib.as_ptr(),
307                 mib.len() as libc::c_uint,
308                 path.as_ptr() as *mut libc::c_void,
309                 &mut path_len,
310                 ptr::null(),
311                 0,
312             ))?;
313             path.set_len(path_len - 1); // chop off NUL
314             Ok(PathBuf::from(OsString::from_vec(path)))
315         }
316     }
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);
321         }
322         Err(io::const_io_error!(
323             io::ErrorKind::Uncategorized,
324             "/proc/curproc/exe doesn't point to regular file.",
325         ))
326     }
327     sysctl().or_else(|_| procfs())
328 }
329
330 #[cfg(target_os = "openbsd")]
331 pub fn current_exe() -> io::Result<PathBuf> {
332     unsafe {
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",
344             ));
345         }
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))
349         } else {
350             Ok(PathBuf::from(OsStr::from_bytes(argv0)))
351         }
352     }
353 }
354
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?",
361         )),
362         other => other,
363     }
364 }
365
366 #[cfg(any(target_os = "macos", target_os = "ios", target_os = "watchos"))]
367 pub fn current_exe() -> io::Result<PathBuf> {
368     unsafe {
369         let mut sz: u32 = 0;
370         libc::_NSGetExecutablePath(ptr::null_mut(), &mut sz);
371         if sz == 0 {
372             return Err(io::Error::last_os_error());
373         }
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);
376         if err != 0 {
377             return Err(io::Error::last_os_error());
378         }
379         v.set_len(sz as usize - 1); // chop off trailing NUL
380         Ok(PathBuf::from(OsString::from_vec(v)))
381     }
382 }
383
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") {
387         Ok(path)
388     } else {
389         unsafe {
390             let path = libc::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::const_io_error!(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(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!"))
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(any(target_os = "espidf", target_os = "horizon"))]
452 pub fn current_exe() -> io::Result<PathBuf> {
453     super::unsupported::unsupported()
454 }
455
456 #[cfg(target_os = "fuchsia")]
457 pub fn current_exe() -> io::Result<PathBuf> {
458     use crate::io::ErrorKind;
459
460     #[cfg(test)]
461     use realstd::env;
462
463     #[cfg(not(test))]
464     use crate::env;
465
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"
469     ))?;
470     let path = PathBuf::from(exe_path);
471
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) }
474 }
475
476 pub struct Env {
477     iter: vec::IntoIter<(OsString, OsString)>,
478 }
479
480 impl !Send for Env {}
481 impl !Sync for Env {}
482
483 impl Iterator for Env {
484     type Item = (OsString, OsString);
485     fn next(&mut self) -> Option<(OsString, OsString)> {
486         self.iter.next()
487     }
488     fn size_hint(&self) -> (usize, Option<usize>) {
489         self.iter.size_hint()
490     }
491 }
492
493 #[cfg(target_os = "macos")]
494 pub unsafe fn environ() -> *mut *const *const c_char {
495     libc::_NSGetEnviron() as *mut *const *const c_char
496 }
497
498 #[cfg(not(target_os = "macos"))]
499 pub unsafe fn environ() -> *mut *const *const c_char {
500     extern "C" {
501         static mut environ: *const *const c_char;
502     }
503     ptr::addr_of_mut!(environ)
504 }
505
506 static ENV_LOCK: RwLock<()> = RwLock::new(());
507
508 pub fn env_read_lock() -> impl Drop {
509     ENV_LOCK.read().unwrap_or_else(PoisonError::into_inner)
510 }
511
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 {
515     unsafe {
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);
523                 }
524                 environ = environ.add(1);
525             }
526         }
527         return Env { iter: result.into_iter() };
528     }
529
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
534         // malformed lines.
535         if input.is_empty() {
536             return None;
537         }
538         let pos = memchr::memchr(b'=', &input[1..]).map(|p| p + 1);
539         pos.map(|p| {
540             (
541                 OsStringExt::from_vec(input[..p].to_vec()),
542                 OsStringExt::from_vec(input[p + 1..].to_vec()),
543             )
544         })
545     }
546 }
547
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()?;
552     unsafe {
553         let _guard = env_read_lock();
554         let s = libc::getenv(k.as_ptr()) as *const libc::c_char;
555         if s.is_null() {
556             None
557         } else {
558             Some(OsStringExt::from_vec(CStr::from_ptr(s).to_bytes().to_vec()))
559         }
560     }
561 }
562
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())?;
566
567     unsafe {
568         let _guard = ENV_LOCK.write();
569         cvt(libc::setenv(k.as_ptr(), v.as_ptr(), 1)).map(drop)
570     }
571 }
572
573 pub fn unsetenv(n: &OsStr) -> io::Result<()> {
574     let nbuf = CString::new(n.as_bytes())?;
575
576     unsafe {
577         let _guard = ENV_LOCK.write();
578         cvt(libc::unsetenv(nbuf.as_ptr())).map(drop)
579     }
580 }
581
582 #[cfg(not(target_os = "espidf"))]
583 pub fn page_size() -> usize {
584     unsafe { libc::sysconf(libc::_SC_PAGESIZE) as usize }
585 }
586
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")
591         } else {
592             PathBuf::from("/tmp")
593         }
594     })
595 }
596
597 pub fn home_dir() -> Option<PathBuf> {
598     return crate::env::var_os("HOME").or_else(|| unsafe { fallback() }).map(PathBuf::from);
599
600     #[cfg(any(
601         target_os = "android",
602         target_os = "ios",
603         target_os = "watchos",
604         target_os = "emscripten",
605         target_os = "redox",
606         target_os = "vxworks",
607         target_os = "espidf",
608         target_os = "horizon"
609     ))]
610     unsafe fn fallback() -> Option<OsString> {
611         None
612     }
613     #[cfg(not(any(
614         target_os = "android",
615         target_os = "ios",
616         target_os = "watchos",
617         target_os = "emscripten",
618         target_os = "redox",
619         target_os = "vxworks",
620         target_os = "espidf",
621         target_os = "horizon"
622     )))]
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,
626             n => n as usize,
627         };
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(
632             libc::getuid(),
633             &mut passwd,
634             buf.as_mut_ptr(),
635             buf.capacity(),
636             &mut result,
637         ) {
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))
642             }
643             _ => None,
644         }
645     }
646 }
647
648 pub fn exit(code: i32) -> ! {
649     unsafe { libc::exit(code as c_int) }
650 }
651
652 pub fn getpid() -> u32 {
653     unsafe { libc::getpid() as u32 }
654 }
655
656 pub fn getppid() -> u32 {
657     unsafe { libc::getppid() as u32 }
658 }
659
660 #[cfg(all(target_os = "linux", target_env = "gnu"))]
661 pub fn glibc_version() -> Option<(usize, usize)> {
662     extern "C" {
663         fn gnu_get_libc_version() -> *const libc::c_char;
664     }
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)
668     } else {
669         None
670     }
671 }
672
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)),
680         _ => None,
681     }
682 }