Debian Codegraph @

src/cutils/mod.rs

raw symbols SCIP
1 use std::{
2 ffi::{CStr, OsStr, OsString, c_char, c_int, c_long},
3 os::{
4 fd::{AsRawFd, BorrowedFd},
5 unix::prelude::OsStrExt,
6 },
7 };
8
9 pub fn cerr<Int: Copy + TryInto<c_long>>(res: Int) -> std::io::Result<Int> {
10 match res.try_into() {
11 Ok(-1) => Err(std::io::Error::last_os_error()),
12 _ => Ok(res),
13 }
14 }
15
16 unsafe extern "C" {
17 #[cfg_attr(
18 any(target_os = "macos", target_os = "ios", target_os = "freebsd"),
19 link_name = "__error"
20 )]
21 #[cfg_attr(
22 any(target_os = "openbsd", target_os = "netbsd", target_os = "android"),
23 link_name = "__errno"
24 )]
25 #[cfg_attr(target_os = "linux", link_name = "__errno_location")]
26 safe fn errno_location() -> *mut c_int;
27 }
28
29 pub fn set_errno(no: c_int) {
30 // SAFETY: errno_location is a thread-local pointer to an integer, so we are the only writers
31 unsafe { *errno_location() = no };
32 }
33
34 pub fn sysconf(name: c_int) -> Option<c_long> {
35 set_errno(0);
36 // SAFETY: sysconf will always respond with 0 or -1 for every input
37 cerr(unsafe { libc::sysconf(name) }).ok()
38 }
39
40 /// Create a Rust string copy from a C string pointer
41 /// WARNING: This uses `to_string_lossy` so should not be used for data where
42 /// information loss is unacceptable (use `os_string_from_ptr` instead)
43 ///
44 /// # Safety
45 /// This function assumes that the pointer is either a null pointer or that
46 /// it points to a valid NUL-terminated C string.
47 pub unsafe fn string_from_ptr(ptr: *const c_char) -> String {
48 if ptr.is_null() {
49 String::new()
50 } else {
51 // SAFETY: the function contract says that CStr::from_ptr is safe
52 let cstr = unsafe { CStr::from_ptr(ptr) };
53 cstr.to_string_lossy().to_string()
54 }
55 }
56
57 /// Create an `OsString` copy from a C string pointer.
58 ///
59 /// # Safety
60 /// This function assumes that the pointer is either a null pointer or that
61 /// it points to a valid NUL-terminated C string.
62 pub unsafe fn os_string_from_ptr(ptr: *const c_char) -> OsString {
63 if ptr.is_null() {
64 OsString::new()
65 } else {
66 // SAFETY: the function contract says that CStr::from_ptr is safe
67 let cstr = unsafe { CStr::from_ptr(ptr) };
68 OsStr::from_bytes(cstr.to_bytes()).to_owned()
69 }
70 }
71
72 fn fstat_mode_any<const MASK: libc::mode_t>(fildes: &BorrowedFd) -> bool {
73 const {
74 assert!(MASK & libc::S_IFMT == MASK);
75 }
76
77 // The Rust standard library doesn't have FileTypeExt on Std{in,out,err}, so we
78 // can't just use FileTypeExt::is_char_device and have to resort to libc::fstat.
79 let mut maybe_stat = std::mem::MaybeUninit::<libc::stat>::uninit();
80
81 // SAFETY: we are passing fstat a pointer to valid memory
82 if unsafe { libc::fstat(fildes.as_raw_fd(), maybe_stat.as_mut_ptr()) } == 0 {
83 // SAFETY: if `fstat` returned 0, maybe_stat will be initialized
84 let mode = unsafe { maybe_stat.assume_init() }.st_mode;
85
86 // To complicate matters further, the S_ISCHR macro isn't in libc as well.
87 (mode & MASK) != 0
88 } else {
89 false
90 }
91 }
92
93 /// Rust's standard library IsTerminal just directly calls isatty, which
94 /// we don't want since this performs IOCTL calls on them and file descriptors are under
95 /// the control of the user; so this checks if they are a character device first.
96 pub fn safe_isatty(fildes: BorrowedFd) -> bool {
97 let is_char_device = fstat_mode_any::<{ libc::S_IFCHR }>(&fildes);
98
99 if is_char_device {
100 // SAFETY: isatty will return 0 or 1
101 unsafe { libc::isatty(fildes.as_raw_fd()) != 0 }
102 } else {
103 false
104 }
105 }
106
107 /// Check whether the file descriptor is a pipe or socket
108 pub fn is_fifo_or_sock(fildes: BorrowedFd) -> bool {
109 fstat_mode_any::<{ libc::S_IFIFO | libc::S_IFSOCK }>(&fildes)
110 }
111
112 /// Dynamically obtain the correct buffer size (within bounds)
113 pub fn dynamic_fill<T: Default + Copy, E>(
114 range: std::ops::Range<usize>,
115 mut fill: impl FnMut(&mut [T]) -> Result<Option<usize>, E>,
116 ) -> Result<Option<Vec<T>>, E> {
117 let mut buffer = vec![T::default(); range.start];
118 loop {
119 match fill(&mut buffer)? {
120 Some(len) => {
121 buffer.resize_with(len, || {
122 panic!("closure returned a buffer size that was larger than the input, this should not happen")
123 });
124
125 return Ok(Some(buffer));
126 }
127
128 None => {
129 if buffer.len() >= range.end {
130 return Ok(None);
131 } else {
132 buffer.resize_with(std::cmp::min(buffer.len() * 2, range.end), T::default)
133 }
134 }
135 }
136 }
137 }
138
139 #[allow(clippy::undocumented_unsafe_blocks)]
140 #[cfg(test)]
141 mod test {
142
143 use super::{dynamic_fill, os_string_from_ptr, string_from_ptr};
144
145 #[test]
146 fn miri_test_str_to_ptr() {
147 let strp = |ptr| unsafe { string_from_ptr(ptr) };
148 assert_eq!(strp(std::ptr::null()), "");
149 assert_eq!(strp(c"".as_ptr()), "");
150 assert_eq!(strp(c"hello".as_ptr()), "hello");
151 }
152
153 #[test]
154 fn miri_test_os_str_to_ptr() {
155 let strp = |ptr| unsafe { os_string_from_ptr(ptr) };
156 assert_eq!(strp(std::ptr::null()), "");
157 assert_eq!(strp(c"".as_ptr()), "");
158 assert_eq!(strp(c"hello".as_ptr()), "hello");
159 }
160
161 #[test]
162 fn test_tty() {
163 use crate::system::term::Pty;
164 use std::fs::File;
165 use std::os::fd::{AsFd, BorrowedFd};
166 assert!(!super::safe_isatty(File::open("/bin/sh").unwrap().as_fd()));
167 assert!(!super::safe_isatty(unsafe {
168 BorrowedFd::borrow_raw(-837492)
169 }));
170 let pty = Pty::open().unwrap();
171 assert!(super::safe_isatty(pty.leader.as_fd()));
172 assert!(super::safe_isatty(pty.follower.as_fd()));
173 }
174
175 #[test]
176 fn test_dynamic_fill() {
177 assert_eq!(
178 dynamic_fill(1..50, |buf: &mut [u8]| Ok::<_, ()>({
179 assert!(buf.len() < 50);
180 (buf.len() >= 23).then_some(23)
181 }))
182 .unwrap()
183 .unwrap()
184 .len(),
185 23
186 );
187
188 assert_eq!(
189 dynamic_fill(1..50, |buf: &mut [u8]| Ok::<_, ()>({
190 assert!(buf.len() <= 50);
191 (buf.len() >= 50).then_some(23)
192 }))
193 .unwrap()
194 .unwrap()
195 .len(),
196 23
197 );
198
199 assert!(
200 dynamic_fill(1..50, |buf: &mut [u8]| Ok::<_, ()>({
201 assert!(buf.len() <= 50);
202 None
203 }))
204 .unwrap()
205 .is_none()
206 );
207
208 assert!(
209 dynamic_fill(1..50, |buf: &mut [u8]| {
210 assert!(buf.len() == 1);
211 Err(())
212 })
213 .is_err()
214 );
215 }
216 }