]> git.lizzy.rs Git - rust.git/blob - library/std/src/sys/unix/os.rs
Rename ErrorKind::Unknown to Uncategorized.
[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::rwlock::{RWLockReadGuard, StaticRWLock};
24 use crate::sys_common::mutex::{StaticMutex, StaticMutexGuard};
25 use crate::vec;
26
27 use libc::{c_char, c_int, c_void};
28
29 const TMPBUF_SZ: usize = 128;
30
31 cfg_if::cfg_if! {
32     if #[cfg(target_os = "redox")] {
33         const PATH_SEPARATOR: u8 = b';';
34     } else {
35         const PATH_SEPARATOR: u8 = b':';
36     }
37 }
38
39 extern "C" {
40     #[cfg(not(any(target_os = "dragonfly", target_os = "vxworks")))]
41     #[cfg_attr(
42         any(
43             target_os = "linux",
44             target_os = "emscripten",
45             target_os = "fuchsia",
46             target_os = "l4re"
47         ),
48         link_name = "__errno_location"
49     )]
50     #[cfg_attr(
51         any(
52             target_os = "netbsd",
53             target_os = "openbsd",
54             target_os = "android",
55             target_os = "redox",
56             target_env = "newlib"
57         ),
58         link_name = "__errno"
59     )]
60     #[cfg_attr(any(target_os = "solaris", target_os = "illumos"), link_name = "___errno")]
61     #[cfg_attr(
62         any(target_os = "macos", target_os = "ios", target_os = "freebsd"),
63         link_name = "__error"
64     )]
65     #[cfg_attr(target_os = "haiku", link_name = "_errnop")]
66     fn errno_location() -> *mut c_int;
67 }
68
69 /// Returns the platform-specific value of errno
70 #[cfg(not(any(target_os = "dragonfly", target_os = "vxworks")))]
71 pub fn errno() -> i32 {
72     unsafe { (*errno_location()) as i32 }
73 }
74
75 /// Sets the platform-specific value of errno
76 #[cfg(all(not(target_os = "linux"), not(target_os = "dragonfly"), not(target_os = "vxworks")))] // needed for readdir and syscall!
77 #[allow(dead_code)] // but not all target cfgs actually end up using it
78 pub fn set_errno(e: i32) {
79     unsafe { *errno_location() = e as c_int }
80 }
81
82 #[cfg(target_os = "vxworks")]
83 pub fn errno() -> i32 {
84     unsafe { libc::errnoGet() }
85 }
86
87 #[cfg(target_os = "dragonfly")]
88 pub fn errno() -> i32 {
89     extern "C" {
90         #[thread_local]
91         static errno: c_int;
92     }
93
94     unsafe { errno as i32 }
95 }
96
97 #[cfg(target_os = "dragonfly")]
98 pub fn set_errno(e: i32) {
99     extern "C" {
100         #[thread_local]
101         static mut errno: c_int;
102     }
103
104     unsafe {
105         errno = e;
106     }
107 }
108
109 /// Gets a detailed string description for the given error number.
110 pub fn error_string(errno: i32) -> String {
111     extern "C" {
112         #[cfg_attr(any(target_os = "linux", target_env = "newlib"), link_name = "__xpg_strerror_r")]
113         fn strerror_r(errnum: c_int, buf: *mut c_char, buflen: libc::size_t) -> c_int;
114     }
115
116     let mut buf = [0 as c_char; TMPBUF_SZ];
117
118     let p = buf.as_mut_ptr();
119     unsafe {
120         if strerror_r(errno as c_int, p, buf.len()) < 0 {
121             panic!("strerror_r failure");
122         }
123
124         let p = p as *const _;
125         str::from_utf8(CStr::from_ptr(p).to_bytes()).unwrap().to_owned()
126     }
127 }
128
129 pub fn getcwd() -> io::Result<PathBuf> {
130     let mut buf = Vec::with_capacity(512);
131     loop {
132         unsafe {
133             let ptr = buf.as_mut_ptr() as *mut libc::c_char;
134             if !libc::getcwd(ptr, buf.capacity()).is_null() {
135                 let len = CStr::from_ptr(buf.as_ptr() as *const libc::c_char).to_bytes().len();
136                 buf.set_len(len);
137                 buf.shrink_to_fit();
138                 return Ok(PathBuf::from(OsString::from_vec(buf)));
139             } else {
140                 let error = io::Error::last_os_error();
141                 if error.raw_os_error() != Some(libc::ERANGE) {
142                     return Err(error);
143                 }
144             }
145
146             // Trigger the internal buffer resizing logic of `Vec` by requiring
147             // more space than the current capacity.
148             let cap = buf.capacity();
149             buf.set_len(cap);
150             buf.reserve(1);
151         }
152     }
153 }
154
155 pub fn chdir(p: &path::Path) -> io::Result<()> {
156     let p: &OsStr = p.as_ref();
157     let p = CString::new(p.as_bytes())?;
158     if unsafe { libc::chdir(p.as_ptr()) } != 0 {
159         return Err(io::Error::last_os_error());
160     }
161     Ok(())
162 }
163
164 pub struct SplitPaths<'a> {
165     iter: iter::Map<slice::Split<'a, u8, fn(&u8) -> bool>, fn(&'a [u8]) -> PathBuf>,
166 }
167
168 pub fn split_paths(unparsed: &OsStr) -> SplitPaths<'_> {
169     fn bytes_to_path(b: &[u8]) -> PathBuf {
170         PathBuf::from(<OsStr as OsStrExt>::from_bytes(b))
171     }
172     fn is_separator(b: &u8) -> bool {
173         *b == PATH_SEPARATOR
174     }
175     let unparsed = unparsed.as_bytes();
176     SplitPaths {
177         iter: unparsed
178             .split(is_separator as fn(&u8) -> bool)
179             .map(bytes_to_path as fn(&[u8]) -> PathBuf),
180     }
181 }
182
183 impl<'a> Iterator for SplitPaths<'a> {
184     type Item = PathBuf;
185     fn next(&mut self) -> Option<PathBuf> {
186         self.iter.next()
187     }
188     fn size_hint(&self) -> (usize, Option<usize>) {
189         self.iter.size_hint()
190     }
191 }
192
193 #[derive(Debug)]
194 pub struct JoinPathsError;
195
196 pub fn join_paths<I, T>(paths: I) -> Result<OsString, JoinPathsError>
197 where
198     I: Iterator<Item = T>,
199     T: AsRef<OsStr>,
200 {
201     let mut joined = Vec::new();
202
203     for (i, path) in paths.enumerate() {
204         let path = path.as_ref().as_bytes();
205         if i > 0 {
206             joined.push(PATH_SEPARATOR)
207         }
208         if path.contains(&PATH_SEPARATOR) {
209             return Err(JoinPathsError);
210         }
211         joined.extend_from_slice(path);
212     }
213     Ok(OsStringExt::from_vec(joined))
214 }
215
216 impl fmt::Display for JoinPathsError {
217     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
218         write!(f, "path segment contains separator `{}`", char::from(PATH_SEPARATOR))
219     }
220 }
221
222 impl StdError for JoinPathsError {
223     #[allow(deprecated)]
224     fn description(&self) -> &str {
225         "failed to join paths"
226     }
227 }
228
229 #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))]
230 pub fn current_exe() -> io::Result<PathBuf> {
231     unsafe {
232         let mut mib = [
233             libc::CTL_KERN as c_int,
234             libc::KERN_PROC as c_int,
235             libc::KERN_PROC_PATHNAME as c_int,
236             -1 as c_int,
237         ];
238         let mut sz = 0;
239         cvt(libc::sysctl(
240             mib.as_mut_ptr(),
241             mib.len() as libc::c_uint,
242             ptr::null_mut(),
243             &mut sz,
244             ptr::null_mut(),
245             0,
246         ))?;
247         if sz == 0 {
248             return Err(io::Error::last_os_error());
249         }
250         let mut v: Vec<u8> = Vec::with_capacity(sz);
251         cvt(libc::sysctl(
252             mib.as_mut_ptr(),
253             mib.len() as libc::c_uint,
254             v.as_mut_ptr() as *mut libc::c_void,
255             &mut sz,
256             ptr::null_mut(),
257             0,
258         ))?;
259         if sz == 0 {
260             return Err(io::Error::last_os_error());
261         }
262         v.set_len(sz - 1); // chop off trailing NUL
263         Ok(PathBuf::from(OsString::from_vec(v)))
264     }
265 }
266
267 #[cfg(target_os = "netbsd")]
268 pub fn current_exe() -> io::Result<PathBuf> {
269     fn sysctl() -> io::Result<PathBuf> {
270         unsafe {
271             let mib = [libc::CTL_KERN, libc::KERN_PROC_ARGS, -1, libc::KERN_PROC_PATHNAME];
272             let mut path_len: usize = 0;
273             cvt(libc::sysctl(
274                 mib.as_ptr(),
275                 mib.len() as libc::c_uint,
276                 ptr::null_mut(),
277                 &mut path_len,
278                 ptr::null(),
279                 0,
280             ))?;
281             if path_len <= 1 {
282                 return Err(io::Error::new_const(
283                     io::ErrorKind::Uncategorized,
284                     &"KERN_PROC_PATHNAME sysctl returned zero-length string",
285                 ));
286             }
287             let mut path: Vec<u8> = Vec::with_capacity(path_len);
288             cvt(libc::sysctl(
289                 mib.as_ptr(),
290                 mib.len() as libc::c_uint,
291                 path.as_ptr() as *mut libc::c_void,
292                 &mut path_len,
293                 ptr::null(),
294                 0,
295             ))?;
296             path.set_len(path_len - 1); // chop off NUL
297             Ok(PathBuf::from(OsString::from_vec(path)))
298         }
299     }
300     fn procfs() -> io::Result<PathBuf> {
301         let curproc_exe = path::Path::new("/proc/curproc/exe");
302         if curproc_exe.is_file() {
303             return crate::fs::read_link(curproc_exe);
304         }
305         Err(io::Error::new_const(
306             io::ErrorKind::Uncategorized,
307             &"/proc/curproc/exe doesn't point to regular file.",
308         ))
309     }
310     sysctl().or_else(|_| procfs())
311 }
312
313 #[cfg(target_os = "openbsd")]
314 pub fn current_exe() -> io::Result<PathBuf> {
315     unsafe {
316         let mut mib = [libc::CTL_KERN, libc::KERN_PROC_ARGS, libc::getpid(), libc::KERN_PROC_ARGV];
317         let mib = mib.as_mut_ptr();
318         let mut argv_len = 0;
319         cvt(libc::sysctl(mib, 4, ptr::null_mut(), &mut argv_len, ptr::null_mut(), 0))?;
320         let mut argv = Vec::<*const libc::c_char>::with_capacity(argv_len as usize);
321         cvt(libc::sysctl(mib, 4, argv.as_mut_ptr() as *mut _, &mut argv_len, ptr::null_mut(), 0))?;
322         argv.set_len(argv_len as usize);
323         if argv[0].is_null() {
324             return Err(io::Error::new_const(
325                 io::ErrorKind::Uncategorized,
326                 &"no current exe available",
327             ));
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::Uncategorized,
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::Uncategorized, &"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 }
464
465 impl !Send for Env {}
466 impl !Sync for Env {}
467
468 impl Iterator for Env {
469     type Item = (OsString, OsString);
470     fn next(&mut self) -> Option<(OsString, OsString)> {
471         self.iter.next()
472     }
473     fn size_hint(&self) -> (usize, Option<usize>) {
474         self.iter.size_hint()
475     }
476 }
477
478 #[cfg(target_os = "macos")]
479 pub unsafe fn environ() -> *mut *const *const c_char {
480     extern "C" {
481         fn _NSGetEnviron() -> *mut *const *const c_char;
482     }
483     _NSGetEnviron()
484 }
485
486 #[cfg(not(target_os = "macos"))]
487 pub unsafe fn environ() -> *mut *const *const c_char {
488     extern "C" {
489         static mut environ: *const *const c_char;
490     }
491     ptr::addr_of_mut!(environ)
492 }
493
494 static ENV_LOCK: StaticRWLock = StaticRWLock::new();
495
496 pub fn env_read_lock() -> RWLockReadGuard {
497     ENV_LOCK.read_with_guard()
498 }
499
500 /// Returns a vector of (variable, value) byte-vector pairs for all the
501 /// environment variables of the current process.
502 pub fn env() -> Env {
503     unsafe {
504         let _guard = env_read_lock();
505         let mut environ = *environ();
506         let mut result = Vec::new();
507         if !environ.is_null() {
508             while !(*environ).is_null() {
509                 if let Some(key_value) = parse(CStr::from_ptr(*environ).to_bytes()) {
510                     result.push(key_value);
511                 }
512                 environ = environ.add(1);
513             }
514         }
515         return Env { iter: result.into_iter() };
516     }
517
518     fn parse(input: &[u8]) -> Option<(OsString, OsString)> {
519         // Strategy (copied from glibc): Variable name and value are separated
520         // by an ASCII equals sign '='. Since a variable name must not be
521         // empty, allow variable names starting with an equals sign. Skip all
522         // malformed lines.
523         if input.is_empty() {
524             return None;
525         }
526         let pos = memchr::memchr(b'=', &input[1..]).map(|p| p + 1);
527         pos.map(|p| {
528             (
529                 OsStringExt::from_vec(input[..p].to_vec()),
530                 OsStringExt::from_vec(input[p + 1..].to_vec()),
531             )
532         })
533     }
534 }
535
536 pub fn getenv(k: &OsStr) -> io::Result<Option<OsString>> {
537     // environment variables with a nul byte can't be set, so their value is
538     // always None as well
539     let k = CString::new(k.as_bytes())?;
540     unsafe {
541         let _guard = env_read_lock();
542         let s = libc::getenv(k.as_ptr()) as *const libc::c_char;
543         let ret = if s.is_null() {
544             None
545         } else {
546             Some(OsStringExt::from_vec(CStr::from_ptr(s).to_bytes().to_vec()))
547         };
548         Ok(ret)
549     }
550 }
551
552 pub fn setenv(k: &OsStr, v: &OsStr) -> io::Result<()> {
553     let k = CString::new(k.as_bytes())?;
554     let v = CString::new(v.as_bytes())?;
555
556     unsafe {
557         let _guard = ENV_LOCK.write_with_guard();
558         cvt(libc::setenv(k.as_ptr(), v.as_ptr(), 1)).map(drop)
559     }
560 }
561
562 pub fn unsetenv(n: &OsStr) -> io::Result<()> {
563     let nbuf = CString::new(n.as_bytes())?;
564
565     unsafe {
566         let _guard = ENV_LOCK.write_with_guard();
567         cvt(libc::unsetenv(nbuf.as_ptr())).map(drop)
568     }
569 }
570
571 pub fn page_size() -> usize {
572     unsafe { libc::sysconf(libc::_SC_PAGESIZE) as usize }
573 }
574
575 pub fn temp_dir() -> PathBuf {
576     crate::env::var_os("TMPDIR").map(PathBuf::from).unwrap_or_else(|| {
577         if cfg!(target_os = "android") {
578             PathBuf::from("/data/local/tmp")
579         } else {
580             PathBuf::from("/tmp")
581         }
582     })
583 }
584
585 pub fn home_dir() -> Option<PathBuf> {
586     return crate::env::var_os("HOME").or_else(|| unsafe { fallback() }).map(PathBuf::from);
587
588     #[cfg(any(
589         target_os = "android",
590         target_os = "ios",
591         target_os = "emscripten",
592         target_os = "redox",
593         target_os = "vxworks"
594     ))]
595     unsafe fn fallback() -> Option<OsString> {
596         None
597     }
598     #[cfg(not(any(
599         target_os = "android",
600         target_os = "ios",
601         target_os = "emscripten",
602         target_os = "redox",
603         target_os = "vxworks"
604     )))]
605     unsafe fn fallback() -> Option<OsString> {
606         let amt = match libc::sysconf(libc::_SC_GETPW_R_SIZE_MAX) {
607             n if n < 0 => 512 as usize,
608             n => n as usize,
609         };
610         let mut buf = Vec::with_capacity(amt);
611         let mut passwd: libc::passwd = mem::zeroed();
612         let mut result = ptr::null_mut();
613         match libc::getpwuid_r(
614             libc::getuid(),
615             &mut passwd,
616             buf.as_mut_ptr(),
617             buf.capacity(),
618             &mut result,
619         ) {
620             0 if !result.is_null() => {
621                 let ptr = passwd.pw_dir as *const _;
622                 let bytes = CStr::from_ptr(ptr).to_bytes().to_vec();
623                 Some(OsStringExt::from_vec(bytes))
624             }
625             _ => None,
626         }
627     }
628 }
629
630 pub fn exit(code: i32) -> ! {
631     unsafe { libc::exit(code as c_int) }
632 }
633
634 pub fn getpid() -> u32 {
635     unsafe { libc::getpid() as u32 }
636 }
637
638 pub fn getppid() -> u32 {
639     unsafe { libc::getppid() as u32 }
640 }
641
642 #[cfg(all(target_env = "gnu", not(target_os = "vxworks")))]
643 pub fn glibc_version() -> Option<(usize, usize)> {
644     if let Some(Ok(version_str)) = glibc_version_cstr().map(CStr::to_str) {
645         parse_glibc_version(version_str)
646     } else {
647         None
648     }
649 }
650
651 #[cfg(all(target_env = "gnu", not(target_os = "vxworks")))]
652 fn glibc_version_cstr() -> Option<&'static CStr> {
653     weak! {
654         fn gnu_get_libc_version() -> *const libc::c_char
655     }
656     if let Some(f) = gnu_get_libc_version.get() {
657         unsafe { Some(CStr::from_ptr(f())) }
658     } else {
659         None
660     }
661 }
662
663 // Returns Some((major, minor)) if the string is a valid "x.y" version,
664 // ignoring any extra dot-separated parts. Otherwise return None.
665 #[cfg(all(target_env = "gnu", not(target_os = "vxworks")))]
666 fn parse_glibc_version(version: &str) -> Option<(usize, usize)> {
667     let mut parsed_ints = version.split('.').map(str::parse::<usize>).fuse();
668     match (parsed_ints.next(), parsed_ints.next()) {
669         (Some(Ok(major)), Some(Ok(minor))) => Some((major, minor)),
670         _ => None,
671     }
672 }