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