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