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