]> git.lizzy.rs Git - rust.git/blob - library/std/src/sys/unix/os.rs
Auto merge of #82585 - TrolledWoods:master, r=dtolnay
[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::marker::PhantomData;
16 use crate::mem;
17 use crate::memchr;
18 use crate::path::{self, PathBuf};
19 use crate::ptr;
20 use crate::slice;
21 use crate::str;
22 use crate::sys::cvt;
23 use crate::sys::fd;
24 use crate::sys::rwlock::{RWLockReadGuard, StaticRWLock};
25 use crate::sys_common::mutex::{StaticMutex, StaticMutexGuard};
26 use crate::vec;
27
28 use libc::{c_char, c_int, c_void};
29
30 const TMPBUF_SZ: usize = 128;
31
32 cfg_if::cfg_if! {
33     if #[cfg(target_os = "redox")] {
34         const PATH_SEPARATOR: u8 = b';';
35     } else {
36         const PATH_SEPARATOR: u8 = b':';
37     }
38 }
39
40 extern "C" {
41     #[cfg(not(any(target_os = "dragonfly", target_os = "vxworks")))]
42     #[cfg_attr(
43         any(
44             target_os = "linux",
45             target_os = "emscripten",
46             target_os = "fuchsia",
47             target_os = "l4re"
48         ),
49         link_name = "__errno_location"
50     )]
51     #[cfg_attr(
52         any(
53             target_os = "netbsd",
54             target_os = "openbsd",
55             target_os = "android",
56             target_os = "redox",
57             target_env = "newlib"
58         ),
59         link_name = "__errno"
60     )]
61     #[cfg_attr(any(target_os = "solaris", target_os = "illumos"), link_name = "___errno")]
62     #[cfg_attr(
63         any(target_os = "macos", target_os = "ios", target_os = "freebsd"),
64         link_name = "__error"
65     )]
66     #[cfg_attr(target_os = "haiku", link_name = "_errnop")]
67     fn errno_location() -> *mut c_int;
68 }
69
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 }
74 }
75
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 }
81 }
82
83 #[cfg(target_os = "vxworks")]
84 pub fn errno() -> i32 {
85     unsafe { libc::errnoGet() }
86 }
87
88 #[cfg(target_os = "dragonfly")]
89 pub fn errno() -> i32 {
90     extern "C" {
91         #[thread_local]
92         static errno: c_int;
93     }
94
95     unsafe { errno as i32 }
96 }
97
98 #[cfg(target_os = "dragonfly")]
99 pub fn set_errno(e: i32) {
100     extern "C" {
101         #[thread_local]
102         static mut errno: c_int;
103     }
104
105     unsafe {
106         errno = e;
107     }
108 }
109
110 /// Gets a detailed string description for the given error number.
111 pub fn error_string(errno: i32) -> String {
112     extern "C" {
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;
115     }
116
117     let mut buf = [0 as c_char; TMPBUF_SZ];
118
119     let p = buf.as_mut_ptr();
120     unsafe {
121         if strerror_r(errno as c_int, p, buf.len()) < 0 {
122             panic!("strerror_r failure");
123         }
124
125         let p = p as *const _;
126         str::from_utf8(CStr::from_ptr(p).to_bytes()).unwrap().to_owned()
127     }
128 }
129
130 pub fn getcwd() -> io::Result<PathBuf> {
131     let mut buf = Vec::with_capacity(512);
132     loop {
133         unsafe {
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();
137                 buf.set_len(len);
138                 buf.shrink_to_fit();
139                 return Ok(PathBuf::from(OsString::from_vec(buf)));
140             } else {
141                 let error = io::Error::last_os_error();
142                 if error.raw_os_error() != Some(libc::ERANGE) {
143                     return Err(error);
144                 }
145             }
146
147             // Trigger the internal buffer resizing logic of `Vec` by requiring
148             // more space than the current capacity.
149             let cap = buf.capacity();
150             buf.set_len(cap);
151             buf.reserve(1);
152         }
153     }
154 }
155
156 pub fn chdir(p: &path::Path) -> io::Result<()> {
157     let p: &OsStr = p.as_ref();
158     let p = CString::new(p.as_bytes())?;
159     unsafe {
160         match libc::chdir(p.as_ptr()) == (0 as c_int) {
161             true => Ok(()),
162             false => Err(io::Error::last_os_error()),
163         }
164     }
165 }
166
167 pub struct SplitPaths<'a> {
168     iter: iter::Map<slice::Split<'a, u8, fn(&u8) -> bool>, fn(&'a [u8]) -> PathBuf>,
169 }
170
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))
174     }
175     fn is_separator(b: &u8) -> bool {
176         *b == PATH_SEPARATOR
177     }
178     let unparsed = unparsed.as_bytes();
179     SplitPaths {
180         iter: unparsed
181             .split(is_separator as fn(&u8) -> bool)
182             .map(bytes_to_path as fn(&[u8]) -> PathBuf),
183     }
184 }
185
186 impl<'a> Iterator for SplitPaths<'a> {
187     type Item = PathBuf;
188     fn next(&mut self) -> Option<PathBuf> {
189         self.iter.next()
190     }
191     fn size_hint(&self) -> (usize, Option<usize>) {
192         self.iter.size_hint()
193     }
194 }
195
196 #[derive(Debug)]
197 pub struct JoinPathsError;
198
199 pub fn join_paths<I, T>(paths: I) -> Result<OsString, JoinPathsError>
200 where
201     I: Iterator<Item = T>,
202     T: AsRef<OsStr>,
203 {
204     let mut joined = Vec::new();
205
206     for (i, path) in paths.enumerate() {
207         let path = path.as_ref().as_bytes();
208         if i > 0 {
209             joined.push(PATH_SEPARATOR)
210         }
211         if path.contains(&PATH_SEPARATOR) {
212             return Err(JoinPathsError);
213         }
214         joined.extend_from_slice(path);
215     }
216     Ok(OsStringExt::from_vec(joined))
217 }
218
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))
222     }
223 }
224
225 impl StdError for JoinPathsError {
226     #[allow(deprecated)]
227     fn description(&self) -> &str {
228         "failed to join paths"
229     }
230 }
231
232 #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))]
233 pub fn current_exe() -> io::Result<PathBuf> {
234     unsafe {
235         let mut mib = [
236             libc::CTL_KERN as c_int,
237             libc::KERN_PROC as c_int,
238             libc::KERN_PROC_PATHNAME as c_int,
239             -1 as c_int,
240         ];
241         let mut sz = 0;
242         cvt(libc::sysctl(
243             mib.as_mut_ptr(),
244             mib.len() as libc::c_uint,
245             ptr::null_mut(),
246             &mut sz,
247             ptr::null_mut(),
248             0,
249         ))?;
250         if sz == 0 {
251             return Err(io::Error::last_os_error());
252         }
253         let mut v: Vec<u8> = Vec::with_capacity(sz);
254         cvt(libc::sysctl(
255             mib.as_mut_ptr(),
256             mib.len() as libc::c_uint,
257             v.as_mut_ptr() as *mut libc::c_void,
258             &mut sz,
259             ptr::null_mut(),
260             0,
261         ))?;
262         if sz == 0 {
263             return Err(io::Error::last_os_error());
264         }
265         v.set_len(sz - 1); // chop off trailing NUL
266         Ok(PathBuf::from(OsString::from_vec(v)))
267     }
268 }
269
270 #[cfg(target_os = "netbsd")]
271 pub fn current_exe() -> io::Result<PathBuf> {
272     fn sysctl() -> io::Result<PathBuf> {
273         unsafe {
274             let mib = [libc::CTL_KERN, libc::KERN_PROC_ARGS, -1, libc::KERN_PROC_PATHNAME];
275             let mut path_len: usize = 0;
276             cvt(libc::sysctl(
277                 mib.as_ptr(),
278                 mib.len() as libc::c_uint,
279                 ptr::null_mut(),
280                 &mut path_len,
281                 ptr::null(),
282                 0,
283             ))?;
284             if path_len <= 1 {
285                 return Err(io::Error::new_const(
286                     io::ErrorKind::Other,
287                     &"KERN_PROC_PATHNAME sysctl returned zero-length string",
288                 ));
289             }
290             let mut path: Vec<u8> = Vec::with_capacity(path_len);
291             cvt(libc::sysctl(
292                 mib.as_ptr(),
293                 mib.len() as libc::c_uint,
294                 path.as_ptr() as *mut libc::c_void,
295                 &mut path_len,
296                 ptr::null(),
297                 0,
298             ))?;
299             path.set_len(path_len - 1); // chop off NUL
300             Ok(PathBuf::from(OsString::from_vec(path)))
301         }
302     }
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);
307         }
308         Err(io::Error::new_const(
309             io::ErrorKind::Other,
310             &"/proc/curproc/exe doesn't point to regular file.",
311         ))
312     }
313     sysctl().or_else(|_| procfs())
314 }
315
316 #[cfg(target_os = "openbsd")]
317 pub fn current_exe() -> io::Result<PathBuf> {
318     unsafe {
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"));
328         }
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))
332         } else {
333             Ok(PathBuf::from(OsStr::from_bytes(argv0)))
334         }
335     }
336 }
337
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?",
344         )),
345         other => other,
346     }
347 }
348
349 #[cfg(any(target_os = "macos", target_os = "ios"))]
350 pub fn current_exe() -> io::Result<PathBuf> {
351     extern "C" {
352         fn _NSGetExecutablePath(buf: *mut libc::c_char, bufsize: *mut u32) -> libc::c_int;
353     }
354     unsafe {
355         let mut sz: u32 = 0;
356         _NSGetExecutablePath(ptr::null_mut(), &mut sz);
357         if sz == 0 {
358             return Err(io::Error::last_os_error());
359         }
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);
362         if err != 0 {
363             return Err(io::Error::last_os_error());
364         }
365         v.set_len(sz as usize - 1); // chop off trailing NUL
366         Ok(PathBuf::from(OsString::from_vec(v)))
367     }
368 }
369
370 #[cfg(any(target_os = "solaris", target_os = "illumos"))]
371 pub fn current_exe() -> io::Result<PathBuf> {
372     extern "C" {
373         fn getexecname() -> *const c_char;
374     }
375     unsafe {
376         let path = getexecname();
377         if path.is_null() {
378             Err(io::Error::last_os_error())
379         } else {
380             let filename = CStr::from_ptr(path).to_bytes();
381             let path = PathBuf::from(<OsStr as OsStrExt>::from_bytes(filename));
382
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)) }
386         }
387     }
388 }
389
390 #[cfg(target_os = "haiku")]
391 pub fn current_exe() -> io::Result<PathBuf> {
392     // Use Haiku's image info functions
393     #[repr(C)]
394     struct image_info {
395         id: i32,
396         type_: i32,
397         sequence: i32,
398         init_order: i32,
399         init_routine: *mut libc::c_void, // function pointer
400         term_routine: *mut libc::c_void, // function pointer
401         device: libc::dev_t,
402         node: libc::ino_t,
403         name: [libc::c_char; 1024], // MAXPATHLEN
404         text: *mut libc::c_void,
405         data: *mut libc::c_void,
406         text_size: i32,
407         data_size: i32,
408         api_version: i32,
409         abi: i32,
410     }
411
412     unsafe {
413         extern "C" {
414             fn _get_next_image_info(
415                 team_id: i32,
416                 cookie: *mut i32,
417                 info: *mut image_info,
418                 size: i32,
419             ) -> i32;
420         }
421
422         let mut info: image_info = mem::zeroed();
423         let mut cookie: i32 = 0;
424         // the executable can be found at team id 0
425         let result =
426             _get_next_image_info(0, &mut cookie, &mut info, mem::size_of::<image_info>() as i32);
427         if result != 0 {
428             use crate::io::ErrorKind;
429             Err(io::Error::new_const(ErrorKind::Other, &"Error getting executable path"))
430         } else {
431             let name = CStr::from_ptr(info.name.as_ptr()).to_bytes();
432             Ok(PathBuf::from(OsStr::from_bytes(name)))
433         }
434     }
435 }
436
437 #[cfg(target_os = "redox")]
438 pub fn current_exe() -> io::Result<PathBuf> {
439     crate::fs::read_to_string("sys:exe").map(PathBuf::from)
440 }
441
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!"))
446 }
447
448 #[cfg(target_os = "vxworks")]
449 pub fn current_exe() -> io::Result<PathBuf> {
450     #[cfg(test)]
451     use realstd::env;
452
453     #[cfg(not(test))]
454     use crate::env;
455
456     let exe_path = env::args().next().unwrap();
457     let path = path::Path::new(&exe_path);
458     path.canonicalize()
459 }
460
461 pub struct Env {
462     iter: vec::IntoIter<(OsString, OsString)>,
463     _dont_send_or_sync_me: PhantomData<*mut ()>,
464 }
465
466 impl Iterator for Env {
467     type Item = (OsString, OsString);
468     fn next(&mut self) -> Option<(OsString, OsString)> {
469         self.iter.next()
470     }
471     fn size_hint(&self) -> (usize, Option<usize>) {
472         self.iter.size_hint()
473     }
474 }
475
476 #[cfg(target_os = "macos")]
477 pub unsafe fn environ() -> *mut *const *const c_char {
478     extern "C" {
479         fn _NSGetEnviron() -> *mut *const *const c_char;
480     }
481     _NSGetEnviron()
482 }
483
484 #[cfg(not(target_os = "macos"))]
485 pub unsafe fn environ() -> *mut *const *const c_char {
486     extern "C" {
487         static mut environ: *const *const c_char;
488     }
489     ptr::addr_of_mut!(environ)
490 }
491
492 static ENV_LOCK: StaticRWLock = StaticRWLock::new();
493
494 pub fn env_read_lock() -> RWLockReadGuard {
495     ENV_LOCK.read_with_guard()
496 }
497
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 {
501     unsafe {
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);
509                 }
510                 environ = environ.add(1);
511             }
512         }
513         return Env { iter: result.into_iter(), _dont_send_or_sync_me: PhantomData };
514     }
515
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
520         // malformed lines.
521         if input.is_empty() {
522             return None;
523         }
524         let pos = memchr::memchr(b'=', &input[1..]).map(|p| p + 1);
525         pos.map(|p| {
526             (
527                 OsStringExt::from_vec(input[..p].to_vec()),
528                 OsStringExt::from_vec(input[p + 1..].to_vec()),
529             )
530         })
531     }
532 }
533
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())?;
538     unsafe {
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() {
542             None
543         } else {
544             Some(OsStringExt::from_vec(CStr::from_ptr(s).to_bytes().to_vec()))
545         };
546         Ok(ret)
547     }
548 }
549
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())?;
553
554     unsafe {
555         let _guard = ENV_LOCK.write_with_guard();
556         cvt(libc::setenv(k.as_ptr(), v.as_ptr(), 1)).map(drop)
557     }
558 }
559
560 pub fn unsetenv(n: &OsStr) -> io::Result<()> {
561     let nbuf = CString::new(n.as_bytes())?;
562
563     unsafe {
564         let _guard = ENV_LOCK.write_with_guard();
565         cvt(libc::unsetenv(nbuf.as_ptr())).map(drop)
566     }
567 }
568
569 pub fn page_size() -> usize {
570     unsafe { libc::sysconf(libc::_SC_PAGESIZE) as usize }
571 }
572
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")
577         } else {
578             PathBuf::from("/tmp")
579         }
580     })
581 }
582
583 pub fn home_dir() -> Option<PathBuf> {
584     return crate::env::var_os("HOME").or_else(|| unsafe { fallback() }).map(PathBuf::from);
585
586     #[cfg(any(
587         target_os = "android",
588         target_os = "ios",
589         target_os = "emscripten",
590         target_os = "redox",
591         target_os = "vxworks"
592     ))]
593     unsafe fn fallback() -> Option<OsString> {
594         None
595     }
596     #[cfg(not(any(
597         target_os = "android",
598         target_os = "ios",
599         target_os = "emscripten",
600         target_os = "redox",
601         target_os = "vxworks"
602     )))]
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,
606             n => n as usize,
607         };
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(
612             libc::getuid(),
613             &mut passwd,
614             buf.as_mut_ptr(),
615             buf.capacity(),
616             &mut result,
617         ) {
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))
622             }
623             _ => None,
624         }
625     }
626 }
627
628 pub fn exit(code: i32) -> ! {
629     unsafe { libc::exit(code as c_int) }
630 }
631
632 pub fn getpid() -> u32 {
633     unsafe { libc::getpid() as u32 }
634 }
635
636 pub fn getppid() -> u32 {
637     unsafe { libc::getppid() as u32 }
638 }
639
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)
644     } else {
645         None
646     }
647 }
648
649 #[cfg(all(target_env = "gnu", not(target_os = "vxworks")))]
650 fn glibc_version_cstr() -> Option<&'static CStr> {
651     weak! {
652         fn gnu_get_libc_version() -> *const libc::c_char
653     }
654     if let Some(f) = gnu_get_libc_version.get() {
655         unsafe { Some(CStr::from_ptr(f())) }
656     } else {
657         None
658     }
659 }
660
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)),
668         _ => None,
669     }
670 }