Debian Codegraph @

.cargo/vendor/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 #[inline]
205 pub(crate) unsafe fn ioctl(
206 fd: BorrowedFd<'_>,
207 request: RawOpcode,
208 arg: *mut c::c_void,
209 ) -> io::Result<IoctlOutput> {
210 ret_c_int(c::ioctl(borrowed_fd(fd), request, arg))
211 }
212
213 #[inline]
214 pub(crate) unsafe fn ioctl_readonly(
215 fd: BorrowedFd<'_>,
216 request: RawOpcode,
217 arg: *mut c::c_void,
218 ) -> io::Result<IoctlOutput> {
219 ioctl(fd, request, arg)
220 }
221
222 #[cfg(not(any(target_os = "redox", target_os = "wasi")))]
223 #[cfg(all(feature = "fs", feature = "net"))]
224 pub(crate) fn is_read_write(fd: BorrowedFd<'_>) -> io::Result<(bool, bool)> {
225 use core::mem::MaybeUninit;
226
227 let (mut read, mut write) = crate::fs::fd::_is_file_read_write(fd)?;
228 let mut not_socket = false;
229 if read {
230 // Do a `recv` with `PEEK` and `DONTWAIT` for 1 byte. A 0 indicates
231 // the read side is shut down; an `EWOULDBLOCK` indicates the read
232 // side is still open.
233 match unsafe {
234 c::recv(
235 borrowed_fd(fd),
236 MaybeUninit::<[u8; 1]>::uninit()
237 .as_mut_ptr()
238 .cast::<c::c_void>(),
239 1,
240 c::MSG_PEEK | c::MSG_DONTWAIT,
241 )
242 } {
243 0 => read = false,
244 -1 => {
245 #[allow(unreachable_patterns)] // `EAGAIN` may equal `EWOULDBLOCK`
246 match errno().0 {
247 c::EAGAIN | c::EWOULDBLOCK => (),
248 c::ENOTSOCK => not_socket = true,
249 err => return Err(io::Errno(err)),
250 }
251 }
252 _ => (),
253 }
254 }
255 if write && !not_socket {
256 // Do a `send` with `DONTWAIT` for 0 bytes. An `EPIPE` indicates
257 // the write side is shut down.
258 if unsafe { c::send(borrowed_fd(fd), [].as_ptr(), 0, c::MSG_DONTWAIT) } == -1 {
259 #[allow(unreachable_patterns)] // `EAGAIN` may equal `EWOULDBLOCK`
260 match errno().0 {
261 c::EAGAIN | c::EWOULDBLOCK | c::ENOTSOCK => (),
262 c::EPIPE => write = false,
263 err => return Err(io::Errno(err)),
264 }
265 }
266 }
267 Ok((read, write))
268 }
269
270 #[cfg(target_os = "wasi")]
271 #[cfg(all(feature = "fs", feature = "net"))]
272 pub(crate) fn is_read_write(_fd: BorrowedFd<'_>) -> io::Result<(bool, bool)> {
273 todo!("Implement is_read_write for WASI in terms of fd_fdstat_get");
274 }
275
276 pub(crate) fn fcntl_getfd(fd: BorrowedFd<'_>) -> io::Result<FdFlags> {
277 let flags = unsafe { ret_c_int(c::fcntl(borrowed_fd(fd), c::F_GETFD))? };
278 Ok(FdFlags::from_bits_retain(bitcast!(flags)))
279 }
280
281 pub(crate) fn fcntl_setfd(fd: BorrowedFd<'_>, flags: FdFlags) -> io::Result<()> {
282 unsafe { ret(c::fcntl(borrowed_fd(fd), c::F_SETFD, flags.bits())) }
283 }
284
285 #[cfg(not(any(target_os = "espidf", target_os = "wasi")))]
286 pub(crate) fn fcntl_dupfd_cloexec(fd: BorrowedFd<'_>, min: RawFd) -> io::Result<OwnedFd> {
287 unsafe { ret_owned_fd(c::fcntl(borrowed_fd(fd), c::F_DUPFD_CLOEXEC, min)) }
288 }
289
290 #[cfg(target_os = "espidf")]
291 pub(crate) fn fcntl_dupfd(fd: BorrowedFd<'_>, min: RawFd) -> io::Result<OwnedFd> {
292 unsafe { ret_owned_fd(c::fcntl(borrowed_fd(fd), c::F_DUPFD, min)) }
293 }
294
295 #[cfg(not(target_os = "wasi"))]
296 pub(crate) fn dup(fd: BorrowedFd<'_>) -> io::Result<OwnedFd> {
297 unsafe { ret_owned_fd(c::dup(borrowed_fd(fd))) }
298 }
299
300 #[allow(clippy::needless_pass_by_ref_mut)]
301 #[cfg(not(target_os = "wasi"))]
302 pub(crate) fn dup2(fd: BorrowedFd<'_>, new: &mut OwnedFd) -> io::Result<()> {
303 unsafe { ret_discarded_fd(c::dup2(borrowed_fd(fd), borrowed_fd(new.as_fd()))) }
304 }
305
306 #[allow(clippy::needless_pass_by_ref_mut)]
307 #[cfg(not(any(
308 apple,
309 target_os = "aix",
310 target_os = "android",
311 target_os = "dragonfly",
312 target_os = "espidf",
313 target_os = "haiku",
314 target_os = "horizon",
315 target_os = "nto",
316 target_os = "redox",
317 target_os = "vita",
318 target_os = "wasi",
319 )))]
320 pub(crate) fn dup3(fd: BorrowedFd<'_>, new: &mut OwnedFd, flags: DupFlags) -> io::Result<()> {
321 unsafe {
322 ret_discarded_fd(c::dup3(
323 borrowed_fd(fd),
324 borrowed_fd(new.as_fd()),
325 bitflags_bits!(flags),
326 ))
327 }
328 }
329
330 #[cfg(any(
331 apple,
332 target_os = "android",
333 target_os = "dragonfly",
334 target_os = "haiku",
335 target_os = "redox",
336 ))]
337 pub(crate) fn dup3(fd: BorrowedFd<'_>, new: &mut OwnedFd, _flags: DupFlags) -> io::Result<()> {
338 // Android 5.0 has `dup3`, but libc doesn't have bindings. Emulate it
339 // using `dup2`. We don't need to worry about the difference between
340 // `dup2` and `dup3` when the file descriptors are equal because we
341 // have an `&mut OwnedFd` which means `fd` doesn't alias it.
342 dup2(fd, new)
343 }