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