Debian Codegraph @

third_party/rust/rustix/src/backend/libc/io/syscalls.rs

raw
1 //! libc syscalls supporting `rustix::io`.
2
3 use crate::backend::c;
4 #[cfg(not(target_os = "wasi"))]
5 use crate::backend::conv::ret_discarded_fd;
6 use crate::backend::conv::{borrowed_fd, ret, ret_c_int, ret_owned_fd, ret_usize};
7 use crate::fd::{AsFd, BorrowedFd, OwnedFd, RawFd};
8 #[cfg(not(any(
9 target_os = "aix",
10 target_os = "espidf",
11 target_os = "nto",
12 target_os = "vita",
13 target_os = "wasi"
14 )))]
15 use crate::io::DupFlags;
16 #[cfg(linux_kernel)]
17 use crate::io::ReadWriteFlags;
18 use crate::io::{self, FdFlags};
19 use crate::ioctl::{IoctlOutput, RawOpcode};
20 use core::cmp::min;
21 #[cfg(all(feature = "fs", feature = "net"))]
22 use libc_errno::errno;
23 #[cfg(not(any(target_os = "espidf", target_os = "horizon")))]
24 use {
25 crate::backend::MAX_IOV,
26 crate::io::{IoSlice, IoSliceMut},
27 };
28
29 pub(crate) unsafe fn read(fd: BorrowedFd<'_>, buf: *mut u8, len: usize) -> io::Result<usize> {
30 ret_usize(c::read(borrowed_fd(fd), buf.cast(), min(len, READ_LIMIT)))
31 }
32
33 pub(crate) fn write(fd: BorrowedFd<'_>, buf: &[u8]) -> io::Result<usize> {
34 unsafe {
35 ret_usize(c::write(
36 borrowed_fd(fd),
37 buf.as_ptr().cast(),
38 min(buf.len(), READ_LIMIT),
39 ))
40 }
41 }
42
43 pub(crate) unsafe fn pread(
44 fd: BorrowedFd<'_>,
45 buf: *mut u8,
46 len: usize,
47 offset: u64,
48 ) -> io::Result<usize> {
49 let len = min(len, READ_LIMIT);
50
51 // Silently cast; we'll get `EINVAL` if the value is negative.
52 let offset = offset as i64;
53
54 // ESP-IDF and Vita don't support 64-bit offsets.
55 #[cfg(any(target_os = "espidf", target_os = "vita"))]
56 let offset: i32 = offset.try_into().map_err(|_| io::Errno::OVERFLOW)?;
57
58 ret_usize(c::pread(borrowed_fd(fd), buf.cast(), len, offset))
59 }
60
61 pub(crate) fn pwrite(fd: BorrowedFd<'_>, buf: &[u8], offset: u64) -> io::Result<usize> {
62 let len = min(buf.len(), READ_LIMIT);
63
64 // Silently cast; we'll get `EINVAL` if the value is negative.
65 let offset = offset as i64;
66
67 // ESP-IDF and Vita don't support 64-bit offsets.
68 #[cfg(any(target_os = "espidf", target_os = "vita"))]
69 let offset: i32 = offset.try_into().map_err(|_| io::Errno::OVERFLOW)?;
70
71 unsafe { ret_usize(c::pwrite(borrowed_fd(fd), buf.as_ptr().cast(), len, offset)) }
72 }
73
74 #[cfg(not(any(target_os = "espidf", target_os = "horizon")))]
75 pub(crate) fn readv(fd: BorrowedFd<'_>, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
76 unsafe {
77 ret_usize(c::readv(
78 borrowed_fd(fd),
79 bufs.as_ptr().cast::<c::iovec>(),
80 min(bufs.len(), MAX_IOV) as c::c_int,
81 ))
82 }
83 }
84
85 #[cfg(not(any(target_os = "espidf", target_os = "horizon")))]
86 pub(crate) fn writev(fd: BorrowedFd<'_>, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
87 unsafe {
88 ret_usize(c::writev(
89 borrowed_fd(fd),
90 bufs.as_ptr().cast::<c::iovec>(),
91 min(bufs.len(), MAX_IOV) as c::c_int,
92 ))
93 }
94 }
95
96 #[cfg(not(any(
97 target_os = "espidf",
98 target_os = "haiku",
99 target_os = "horizon",
100 target_os = "nto",
101 target_os = "redox",
102 target_os = "solaris",
103 target_os = "vita"
104 )))]
105 pub(crate) fn preadv(
106 fd: BorrowedFd<'_>,
107 bufs: &mut [IoSliceMut<'_>],
108 offset: u64,
109 ) -> io::Result<usize> {
110 // Silently cast; we'll get `EINVAL` if the value is negative.
111 let offset = offset as i64;
112 unsafe {
113 ret_usize(c::preadv(
114 borrowed_fd(fd),
115 bufs.as_ptr().cast::<c::iovec>(),
116 min(bufs.len(), MAX_IOV) as c::c_int,
117 offset,
118 ))
119 }
120 }
121
122 #[cfg(not(any(
123 target_os = "espidf",
124 target_os = "haiku",
125 target_os = "nto",
126 target_os = "horizon",
127 target_os = "redox",
128 target_os = "solaris",
129 target_os = "vita"
130 )))]
131 pub(crate) fn pwritev(fd: BorrowedFd<'_>, bufs: &[IoSlice<'_>], offset: u64) -> io::Result<usize> {
132 // Silently cast; we'll get `EINVAL` if the value is negative.
133 let offset = offset as i64;
134 unsafe {
135 ret_usize(c::pwritev(
136 borrowed_fd(fd),
137 bufs.as_ptr().cast::<c::iovec>(),
138 min(bufs.len(), MAX_IOV) as c::c_int,
139 offset,
140 ))
141 }
142 }
143
144 #[cfg(linux_kernel)]
145 pub(crate) fn preadv2(
146 fd: BorrowedFd<'_>,
147 bufs: &mut [IoSliceMut<'_>],
148 offset: u64,
149 flags: ReadWriteFlags,
150 ) -> io::Result<usize> {
151 // Silently cast; we'll get `EINVAL` if the value is negative.
152 let offset = offset as i64;
153 unsafe {
154 ret_usize(c::preadv2(
155 borrowed_fd(fd),
156 bufs.as_ptr().cast::<c::iovec>(),
157 min(bufs.len(), MAX_IOV) as c::c_int,
158 offset,
159 bitflags_bits!(flags),
160 ))
161 }
162 }
163
164 #[cfg(linux_kernel)]
165 pub(crate) fn pwritev2(
166 fd: BorrowedFd<'_>,
167 bufs: &[IoSlice<'_>],
168 offset: u64,
169 flags: ReadWriteFlags,
170 ) -> io::Result<usize> {
171 // Silently cast; we'll get `EINVAL` if the value is negative.
172 let offset = offset as i64;
173 unsafe {
174 ret_usize(c::pwritev2(
175 borrowed_fd(fd),
176 bufs.as_ptr().cast::<c::iovec>(),
177 min(bufs.len(), MAX_IOV) as c::c_int,
178 offset,
179 bitflags_bits!(flags),
180 ))
181 }
182 }
183
184 // These functions are derived from Rust's library/std/src/sys/unix/fd.rs at
185 // revision 326ef470a8b379a180d6dc4bbef08990698a737a.
186
187 // The maximum read limit on most POSIX-like systems is `SSIZE_MAX`, with the
188 // manual page quoting that if the count of bytes to read is greater than
189 // `SSIZE_MAX` the result is “unspecified”.
190 //
191 // On macOS, however, apparently the 64-bit libc is either buggy or
192 // intentionally showing odd behavior by rejecting any read with a size larger
193 // than or equal to `INT_MAX`. To handle both of these the read size is capped
194 // on both platforms.
195 #[cfg(target_os = "macos")]
196 const READ_LIMIT: usize = c::c_int::MAX as usize - 1;
197 #[cfg(not(target_os = "macos"))]
198 const READ_LIMIT: usize = c::ssize_t::MAX as usize;
199
200 pub(crate) unsafe fn close(raw_fd: RawFd) {
201 let _ = c::close(raw_fd as c::c_int);
202 }
203
204 #[cfg(feature = "try_close")]
205 pub(crate) unsafe fn try_close(raw_fd: RawFd) -> io::Result<()> {
206 ret(c::close(raw_fd as c::c_int))
207 }
208
209 #[inline]
210 pub(crate) unsafe fn ioctl(
211 fd: BorrowedFd<'_>,
212 request: RawOpcode,
213 arg: *mut c::c_void,
214 ) -> io::Result<IoctlOutput> {
215 ret_c_int(c::ioctl(borrowed_fd(fd), request, arg))
216 }
217
218 #[inline]
219 pub(crate) unsafe fn ioctl_readonly(
220 fd: BorrowedFd<'_>,
221 request: RawOpcode,
222 arg: *mut c::c_void,
223 ) -> io::Result<IoctlOutput> {
224 ioctl(fd, request, arg)
225 }
226
227 #[cfg(not(any(target_os = "redox", target_os = "wasi")))]
228 #[cfg(all(feature = "fs", feature = "net"))]
229 pub(crate) fn is_read_write(fd: BorrowedFd<'_>) -> io::Result<(bool, bool)> {
230 use core::mem::MaybeUninit;
231
232 let (mut read, mut write) = crate::fs::fd::_is_file_read_write(fd)?;
233 let mut not_socket = false;
234 if read {
235 // Do a `recv` with `PEEK` and `DONTWAIT` for 1 byte. A 0 indicates
236 // the read side is shut down; an `EWOULDBLOCK` indicates the read
237 // side is still open.
238 match unsafe {
239 c::recv(
240 borrowed_fd(fd),
241 MaybeUninit::<[u8; 1]>::uninit()
242 .as_mut_ptr()
243 .cast::<c::c_void>(),
244 1,
245 c::MSG_PEEK | c::MSG_DONTWAIT,
246 )
247 } {
248 0 => read = false,
249 -1 => {
250 #[allow(unreachable_patterns)] // `EAGAIN` may equal `EWOULDBLOCK`
251 match errno().0 {
252 c::EAGAIN | c::EWOULDBLOCK => (),
253 c::ENOTSOCK => not_socket = true,
254 err => return Err(io::Errno(err)),
255 }
256 }
257 _ => (),
258 }
259 }
260 if write && !not_socket {
261 // Do a `send` with `DONTWAIT` for 0 bytes. An `EPIPE` indicates
262 // the write side is shut down.
263 if unsafe { c::send(borrowed_fd(fd), [].as_ptr(), 0, c::MSG_DONTWAIT) } == -1 {
264 #[allow(unreachable_patterns)] // `EAGAIN` may equal `EWOULDBLOCK`
265 match errno().0 {
266 c::EAGAIN | c::EWOULDBLOCK | c::ENOTSOCK => (),
267 c::EPIPE => write = false,
268 err => return Err(io::Errno(err)),
269 }
270 }
271 }
272 Ok((read, write))
273 }
274
275 #[cfg(target_os = "wasi")]
276 #[cfg(all(feature = "fs", feature = "net"))]
277 pub(crate) fn is_read_write(_fd: BorrowedFd<'_>) -> io::Result<(bool, bool)> {
278 todo!("Implement is_read_write for WASI in terms of fd_fdstat_get");
279 }
280
281 pub(crate) fn fcntl_getfd(fd: BorrowedFd<'_>) -> io::Result<FdFlags> {
282 let flags = unsafe { ret_c_int(c::fcntl(borrowed_fd(fd), c::F_GETFD))? };
283 Ok(FdFlags::from_bits_retain(bitcast!(flags)))
284 }
285
286 pub(crate) fn fcntl_setfd(fd: BorrowedFd<'_>, flags: FdFlags) -> io::Result<()> {
287 unsafe { ret(c::fcntl(borrowed_fd(fd), c::F_SETFD, flags.bits())) }
288 }
289
290 #[cfg(not(any(target_os = "espidf", target_os = "wasi")))]
291 pub(crate) fn fcntl_dupfd_cloexec(fd: BorrowedFd<'_>, min: RawFd) -> io::Result<OwnedFd> {
292 unsafe { ret_owned_fd(c::fcntl(borrowed_fd(fd), c::F_DUPFD_CLOEXEC, min)) }
293 }
294
295 #[cfg(target_os = "espidf")]
296 pub(crate) fn fcntl_dupfd(fd: BorrowedFd<'_>, min: RawFd) -> io::Result<OwnedFd> {
297 unsafe { ret_owned_fd(c::fcntl(borrowed_fd(fd), c::F_DUPFD, min)) }
298 }
299
300 #[cfg(not(target_os = "wasi"))]
301 pub(crate) fn dup(fd: BorrowedFd<'_>) -> io::Result<OwnedFd> {
302 unsafe { ret_owned_fd(c::dup(borrowed_fd(fd))) }
303 }
304
305 #[allow(clippy::needless_pass_by_ref_mut)]
306 #[cfg(not(target_os = "wasi"))]
307 pub(crate) fn dup2(fd: BorrowedFd<'_>, new: &mut OwnedFd) -> io::Result<()> {
308 unsafe { ret_discarded_fd(c::dup2(borrowed_fd(fd), borrowed_fd(new.as_fd()))) }
309 }
310
311 #[allow(clippy::needless_pass_by_ref_mut)]
312 #[cfg(not(any(
313 apple,
314 target_os = "aix",
315 target_os = "android",
316 target_os = "dragonfly",
317 target_os = "espidf",
318 target_os = "haiku",
319 target_os = "horizon",
320 target_os = "nto",
321 target_os = "redox",
322 target_os = "vita",
323 target_os = "wasi",
324 )))]
325 pub(crate) fn dup3(fd: BorrowedFd<'_>, new: &mut OwnedFd, flags: DupFlags) -> io::Result<()> {
326 unsafe {
327 ret_discarded_fd(c::dup3(
328 borrowed_fd(fd),
329 borrowed_fd(new.as_fd()),
330 bitflags_bits!(flags),
331 ))
332 }
333 }
334
335 #[cfg(any(
336 apple,
337 target_os = "android",
338 target_os = "dragonfly",
339 target_os = "haiku",
340 target_os = "redox",
341 ))]
342 pub(crate) fn dup3(fd: BorrowedFd<'_>, new: &mut OwnedFd, _flags: DupFlags) -> io::Result<()> {
343 // Android 5.0 has `dup3`, but libc doesn't have bindings. Emulate it
344 // using `dup2`. We don't need to worry about the difference between
345 // `dup2` and `dup3` when the file descriptors are equal because we
346 // have an `&mut OwnedFd` which means `fd` doesn't alias it.
347 dup2(fd, new)
348 }