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