nix/sys/uio.rs
1//! Vectored I/O
2
3use crate::Result;
4use crate::errno::Errno;
5use libc::{self, c_int, c_void, size_t, off_t};
6use std::io::{IoSlice, IoSliceMut};
7use std::marker::PhantomData;
8use std::os::unix::io::RawFd;
9
10/// Low-level vectored write to a raw file descriptor
11///
12/// See also [writev(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/writev.html)
13pub fn writev(fd: RawFd, iov: &[IoSlice<'_>]) -> Result<usize> {
14 // SAFETY: to quote the documentation for `IoSlice`:
15 //
16 // [IoSlice] is semantically a wrapper around a &[u8], but is
17 // guaranteed to be ABI compatible with the iovec type on Unix
18 // platforms.
19 //
20 // Because it is ABI compatible, a pointer cast here is valid
21 let res = unsafe { libc::writev(fd, iov.as_ptr() as *const libc::iovec, iov.len() as c_int) };
22
23 Errno::result(res).map(|r| r as usize)
24}
25
26/// Low-level vectored read from a raw file descriptor
27///
28/// See also [readv(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/readv.html)
29pub fn readv(fd: RawFd, iov: &mut [IoSliceMut<'_>]) -> Result<usize> {
30 // SAFETY: same as in writev(), IoSliceMut is ABI-compatible with iovec
31 let res = unsafe { libc::readv(fd, iov.as_ptr() as *const libc::iovec, iov.len() as c_int) };
32
33 Errno::result(res).map(|r| r as usize)
34}
35
36/// Write to `fd` at `offset` from buffers in `iov`.
37///
38/// Buffers in `iov` will be written in order until all buffers have been written
39/// or an error occurs. The file offset is not changed.
40///
41/// See also: [`writev`](fn.writev.html) and [`pwrite`](fn.pwrite.html)
42#[cfg(not(target_os = "redox"))]
43#[cfg_attr(docsrs, doc(cfg(all())))]
44pub fn pwritev(fd: RawFd, iov: &[IoSlice<'_>],
45 offset: off_t) -> Result<usize> {
46
47 #[cfg(target_env = "uclibc")]
48 let offset = offset as libc::off64_t; // uclibc doesn't use off_t
49
50 // SAFETY: same as in writev()
51 let res = unsafe {
52 libc::pwritev(fd, iov.as_ptr() as *const libc::iovec, iov.len() as c_int, offset)
53 };
54
55 Errno::result(res).map(|r| r as usize)
56}
57
58/// Read from `fd` at `offset` filling buffers in `iov`.
59///
60/// Buffers in `iov` will be filled in order until all buffers have been filled,
61/// no more bytes are available, or an error occurs. The file offset is not
62/// changed.
63///
64/// See also: [`readv`](fn.readv.html) and [`pread`](fn.pread.html)
65#[cfg(not(target_os = "redox"))]
66#[cfg_attr(docsrs, doc(cfg(all())))]
67pub fn preadv(fd: RawFd, iov: &mut [IoSliceMut<'_>],
68 offset: off_t) -> Result<usize> {
69 #[cfg(target_env = "uclibc")]
70 let offset = offset as libc::off64_t; // uclibc doesn't use off_t
71
72 // SAFETY: same as in readv()
73 let res = unsafe {
74 libc::preadv(fd, iov.as_ptr() as *const libc::iovec, iov.len() as c_int, offset)
75 };
76
77 Errno::result(res).map(|r| r as usize)
78}
79
80/// Low-level write to a file, with specified offset.
81///
82/// See also [pwrite(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/pwrite.html)
83// TODO: move to unistd
84pub fn pwrite(fd: RawFd, buf: &[u8], offset: off_t) -> Result<usize> {
85 let res = unsafe {
86 libc::pwrite(fd, buf.as_ptr() as *const c_void, buf.len() as size_t,
87 offset)
88 };
89
90 Errno::result(res).map(|r| r as usize)
91}
92
93/// Low-level read from a file, with specified offset.
94///
95/// See also [pread(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/pread.html)
96// TODO: move to unistd
97pub fn pread(fd: RawFd, buf: &mut [u8], offset: off_t) -> Result<usize>{
98 let res = unsafe {
99 libc::pread(fd, buf.as_mut_ptr() as *mut c_void, buf.len() as size_t,
100 offset)
101 };
102
103 Errno::result(res).map(|r| r as usize)
104}
105
106/// A slice of memory in a remote process, starting at address `base`
107/// and consisting of `len` bytes.
108///
109/// This is the same underlying C structure as `IoSlice`,
110/// except that it refers to memory in some other process, and is
111/// therefore not represented in Rust by an actual slice as `IoSlice` is. It
112/// is used with [`process_vm_readv`](fn.process_vm_readv.html)
113/// and [`process_vm_writev`](fn.process_vm_writev.html).
114#[cfg(any(target_os = "linux", target_os = "android"))]
115#[cfg_attr(docsrs, doc(cfg(all())))]
116#[repr(C)]
117#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
118pub struct RemoteIoVec {
119 /// The starting address of this slice (`iov_base`).
120 pub base: usize,
121 /// The number of bytes in this slice (`iov_len`).
122 pub len: usize,
123}
124
125/// A vector of buffers.
126///
127/// Vectored I/O methods like [`writev`] and [`readv`] use this structure for
128/// both reading and writing. Each `IoVec` specifies the base address and
129/// length of an area in memory.
130#[deprecated(
131 since = "0.24.0",
132 note = "`IoVec` is no longer used in the public interface, use `IoSlice` or `IoSliceMut` instead"
133)]
134#[repr(transparent)]
135#[allow(renamed_and_removed_lints)]
136#[allow(clippy::unknown_clippy_lints)]
137// Clippy false positive: https://github.com/rust-lang/rust-clippy/issues/8867
138#[allow(clippy::derive_partial_eq_without_eq)]
139#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
140pub struct IoVec<T>(pub(crate) libc::iovec, PhantomData<T>);
141
142#[allow(deprecated)]
143impl<T> IoVec<T> {
144 /// View the `IoVec` as a Rust slice.
145 #[deprecated(
146 since = "0.24.0",
147 note = "Use the `Deref` impl of `IoSlice` or `IoSliceMut` instead"
148 )]
149 #[inline]
150 pub fn as_slice(&self) -> &[u8] {
151 use std::slice;
152
153 unsafe {
154 slice::from_raw_parts(
155 self.0.iov_base as *const u8,
156 self.0.iov_len)
157 }
158 }
159}
160
161#[allow(deprecated)]
162impl<'a> IoVec<&'a [u8]> {
163 /// Create an `IoVec` from a Rust slice.
164 #[deprecated(
165 since = "0.24.0",
166 note = "Use `IoSlice::new` instead"
167 )]
168 pub fn from_slice(buf: &'a [u8]) -> IoVec<&'a [u8]> {
169 IoVec(libc::iovec {
170 iov_base: buf.as_ptr() as *mut c_void,
171 iov_len: buf.len() as size_t,
172 }, PhantomData)
173 }
174}
175
176#[allow(deprecated)]
177impl<'a> IoVec<&'a mut [u8]> {
178 /// Create an `IoVec` from a mutable Rust slice.
179 #[deprecated(
180 since = "0.24.0",
181 note = "Use `IoSliceMut::new` instead"
182 )]
183 pub fn from_mut_slice(buf: &'a mut [u8]) -> IoVec<&'a mut [u8]> {
184 IoVec(libc::iovec {
185 iov_base: buf.as_ptr() as *mut c_void,
186 iov_len: buf.len() as size_t,
187 }, PhantomData)
188 }
189}
190
191// The only reason IoVec isn't automatically Send+Sync is because libc::iovec
192// contains raw pointers.
193#[allow(deprecated)]
194unsafe impl<T> Send for IoVec<T> where T: Send {}
195#[allow(deprecated)]
196unsafe impl<T> Sync for IoVec<T> where T: Sync {}
197
198feature! {
199#![feature = "process"]
200
201/// Write data directly to another process's virtual memory
202/// (see [`process_vm_writev`(2)]).
203///
204/// `local_iov` is a list of [`IoSlice`]s containing the data to be written,
205/// and `remote_iov` is a list of [`RemoteIoVec`]s identifying where the
206/// data should be written in the target process. On success, returns the
207/// number of bytes written, which will always be a whole
208/// number of `remote_iov` chunks.
209///
210/// This requires the same permissions as debugging the process using
211/// [ptrace]: you must either be a privileged process (with
212/// `CAP_SYS_PTRACE`), or you must be running as the same user as the
213/// target process and the OS must have unprivileged debugging enabled.
214///
215/// This function is only available on Linux and Android(SDK23+).
216///
217/// [`process_vm_writev`(2)]: https://man7.org/linux/man-pages/man2/process_vm_writev.2.html
218/// [ptrace]: ../ptrace/index.html
219/// [`IoSlice`]: https://doc.rust-lang.org/std/io/struct.IoSlice.html
220/// [`RemoteIoVec`]: struct.RemoteIoVec.html
221#[cfg(all(any(target_os = "linux", target_os = "android"), not(target_env = "uclibc")))]
222pub fn process_vm_writev(
223 pid: crate::unistd::Pid,
224 local_iov: &[IoSlice<'_>],
225 remote_iov: &[RemoteIoVec]) -> Result<usize>
226{
227 let res = unsafe {
228 libc::process_vm_writev(pid.into(),
229 local_iov.as_ptr() as *const libc::iovec, local_iov.len() as libc::c_ulong,
230 remote_iov.as_ptr() as *const libc::iovec, remote_iov.len() as libc::c_ulong, 0)
231 };
232
233 Errno::result(res).map(|r| r as usize)
234}
235
236/// Read data directly from another process's virtual memory
237/// (see [`process_vm_readv`(2)]).
238///
239/// `local_iov` is a list of [`IoSliceMut`]s containing the buffer to copy
240/// data into, and `remote_iov` is a list of [`RemoteIoVec`]s identifying
241/// where the source data is in the target process. On success,
242/// returns the number of bytes written, which will always be a whole
243/// number of `remote_iov` chunks.
244///
245/// This requires the same permissions as debugging the process using
246/// [`ptrace`]: you must either be a privileged process (with
247/// `CAP_SYS_PTRACE`), or you must be running as the same user as the
248/// target process and the OS must have unprivileged debugging enabled.
249///
250/// This function is only available on Linux and Android(SDK23+).
251///
252/// [`process_vm_readv`(2)]: https://man7.org/linux/man-pages/man2/process_vm_readv.2.html
253/// [`ptrace`]: ../ptrace/index.html
254/// [`IoSliceMut`]: https://doc.rust-lang.org/std/io/struct.IoSliceMut.html
255/// [`RemoteIoVec`]: struct.RemoteIoVec.html
256#[cfg(all(any(target_os = "linux", target_os = "android"), not(target_env = "uclibc")))]
257pub fn process_vm_readv(
258 pid: crate::unistd::Pid,
259 local_iov: &mut [IoSliceMut<'_>],
260 remote_iov: &[RemoteIoVec]) -> Result<usize>
261{
262 let res = unsafe {
263 libc::process_vm_readv(pid.into(),
264 local_iov.as_ptr() as *const libc::iovec, local_iov.len() as libc::c_ulong,
265 remote_iov.as_ptr() as *const libc::iovec, remote_iov.len() as libc::c_ulong, 0)
266 };
267
268 Errno::result(res).map(|r| r as usize)
269}
270}