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