rustix/ioctl/mod.rs
1//! Unsafe `ioctl` API.
2//!
3//! Unix systems expose a number of `ioctl`'s. `ioctl`s have been adopted as a
4//! general purpose system call for making calls into the kernel. In addition
5//! to the wide variety of system calls that are included by default in the
6//! kernel, many drivers expose their own `ioctl`'s for controlling their
7//! behavior, some of which are proprietary. Therefore it is impossible to make
8//! a safe interface for every `ioctl` call, as they all have wildly varying
9//! semantics.
10//!
11//! This module provides an unsafe interface to write your own `ioctl` API. To
12//! start, create a type that implements [`Ioctl`]. Then, pass it to [`ioctl`]
13//! to make the `ioctl` call.
14
15#![allow(unsafe_code)]
16
17use crate::fd::{AsFd, BorrowedFd};
18use crate::ffi as c;
19use crate::io::Result;
20
21#[cfg(any(linux_kernel, bsd))]
22use core::mem;
23
24pub use patterns::*;
25
26mod patterns;
27
28#[cfg(linux_kernel)]
29mod linux;
30
31#[cfg(bsd)]
32mod bsd;
33
34#[cfg(linux_kernel)]
35use linux as platform;
36
37#[cfg(bsd)]
38use bsd as platform;
39
40/// Perform an `ioctl` call.
41///
42/// `ioctl` was originally intended to act as a way of modifying the behavior
43/// of files, but has since been adopted as a general purpose system call for
44/// making calls into the kernel. In addition to the default calls exposed by
45/// generic file descriptors, many drivers expose their own `ioctl` calls for
46/// controlling their behavior, some of which are proprietary.
47///
48/// This crate exposes many other `ioctl` interfaces with safe and idiomatic
49/// wrappers, like [`ioctl_fionbio`] and [`ioctl_fionread`]. It is recommended
50/// to use those instead of this function, as they are safer and more
51/// idiomatic. For other cases, implement the [`Ioctl`] API and pass it to this
52/// function.
53///
54/// See documentation for [`Ioctl`] for more information.
55///
56/// [`ioctl_fionbio`]: crate::io::ioctl_fionbio
57/// [`ioctl_fionread`]: crate::io::ioctl_fionread
58///
59/// # Safety
60///
61/// While [`Ioctl`] takes much of the unsafety out of `ioctl` calls, callers
62/// must still ensure that the opcode value, operand type, and data access
63/// correctly reflect what's in the device driver servicing the call. `ioctl`
64/// calls form a protocol between the userspace `ioctl` callers and the device
65/// drivers in the kernel, and safety depends on both sides agreeing and
66/// upholding the expectations of the other.
67///
68/// # References
69/// - [Linux]
70/// - [Winsock]
71/// - [FreeBSD]
72/// - [NetBSD]
73/// - [OpenBSD]
74/// - [Apple]
75/// - [Solaris]
76/// - [illumos]
77///
78/// [Linux]: https://man7.org/linux/man-pages/man2/ioctl.2.html
79/// [Winsock]: https://learn.microsoft.com/en-us/windows/win32/api/winsock/nf-winsock-ioctlsocket
80/// [FreeBSD]: https://man.freebsd.org/cgi/man.cgi?query=ioctl&sektion=2
81/// [NetBSD]: https://man.netbsd.org/ioctl.2
82/// [OpenBSD]: https://man.openbsd.org/ioctl.2
83/// [Apple]: https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/ioctl.2.html
84/// [Solaris]: https://docs.oracle.com/cd/E23824_01/html/821-1463/ioctl-2.html
85/// [illumos]: https://illumos.org/man/2/ioctl
86#[inline]
87pub unsafe fn ioctl<F: AsFd, I: Ioctl>(fd: F, mut ioctl: I) -> Result<I::Output> {
88 let fd = fd.as_fd();
89 let request = ioctl.opcode();
90 let arg = ioctl.as_ptr();
91
92 // SAFETY: The variant of `Ioctl` asserts that this is a valid IOCTL call
93 // to make.
94 let output = if I::IS_MUTATING {
95 _ioctl(fd, request, arg)?
96 } else {
97 _ioctl_readonly(fd, request, arg)?
98 };
99
100 // SAFETY: The variant of `Ioctl` asserts that this is a valid pointer to
101 // the output data.
102 I::output_from_ptr(output, arg)
103}
104
105unsafe fn _ioctl(fd: BorrowedFd<'_>, request: Opcode, arg: *mut c::c_void) -> Result<IoctlOutput> {
106 crate::backend::io::syscalls::ioctl(fd, request, arg)
107}
108
109unsafe fn _ioctl_readonly(
110 fd: BorrowedFd<'_>,
111 request: Opcode,
112 arg: *mut c::c_void,
113) -> Result<IoctlOutput> {
114 crate::backend::io::syscalls::ioctl_readonly(fd, request, arg)
115}
116
117/// A trait defining the properties of an `ioctl` command.
118///
119/// Objects implementing this trait can be passed to [`ioctl`] to make an
120/// `ioctl` call. The contents of the object represent the inputs to the
121/// `ioctl` call. The inputs must be convertible to a pointer through the
122/// `as_ptr` method. In most cases, this involves either casting a number to a
123/// pointer, or creating a pointer to the actual data. The latter case is
124/// necessary for `ioctl` calls that modify userspace data.
125///
126/// # Safety
127///
128/// This trait is unsafe to implement because it is impossible to guarantee
129/// that the `ioctl` call is safe. The `ioctl` call may be proprietary, or it
130/// may be unsafe to call in certain circumstances.
131///
132/// By implementing this trait, you guarantee that:
133///
134/// - The `ioctl` call expects the input provided by `as_ptr` and produces the
135/// output as indicated by `output`.
136/// - That `output_from_ptr` can safely take the pointer from `as_ptr` and
137/// cast it to the correct type, *only* after the `ioctl` call.
138/// - That the return value of `opcode` uniquely identifies the `ioctl` call.
139/// - That, for whatever platforms you are targeting, the `ioctl` call is safe
140/// to make.
141/// - If `IS_MUTATING` is false, that no userspace data will be modified by
142/// the `ioctl` call.
143pub unsafe trait Ioctl {
144 /// The type of the output data.
145 ///
146 /// Given a pointer, one should be able to construct an instance of this
147 /// type.
148 type Output;
149
150 /// Does the `ioctl` mutate any data in the userspace?
151 ///
152 /// If the `ioctl` call does not mutate any data in the userspace, then
153 /// making this `false` enables optimizations that can make the call
154 /// faster. When in doubt, set this to `true`.
155 ///
156 /// # Safety
157 ///
158 /// This should only be set to `false` if the `ioctl` call does not mutate
159 /// any data in the userspace. Undefined behavior may occur if this is set
160 /// to `false` when it should be `true`.
161 const IS_MUTATING: bool;
162
163 /// Get the opcode used by this `ioctl` command.
164 ///
165 /// There are different types of opcode depending on the operation. See
166 /// documentation for [`opcode`] for more information.
167 fn opcode(&self) -> Opcode;
168
169 /// Get a pointer to the data to be passed to the `ioctl` command.
170 ///
171 /// See trait-level documentation for more information.
172 fn as_ptr(&mut self) -> *mut c::c_void;
173
174 /// Cast the output data to the correct type.
175 ///
176 /// # Safety
177 ///
178 /// The `extract_output` value must be the resulting value after a
179 /// successful `ioctl` call, and `out` is the direct return value of an
180 /// `ioctl` call that did not fail. In this case `extract_output` is the
181 /// pointer that was passed to the `ioctl` call.
182 unsafe fn output_from_ptr(
183 out: IoctlOutput,
184 extract_output: *mut c::c_void,
185 ) -> Result<Self::Output>;
186}
187
188/// Const functions for computing opcode values.
189///
190/// Linux's headers define macros such as `_IO`, `_IOR`, `_IOW`, and `_IOWR`
191/// for defining ioctl values in a structured way that encode whether they
192/// are reading and/or writing, and other information about the ioctl. The
193/// functions in this module correspond to those macros.
194///
195/// If you're writing a driver and defining your own ioctl numbers, it's
196/// recommended to use these functions to compute them.
197#[cfg(any(linux_kernel, bsd))]
198pub mod opcode {
199 use super::*;
200
201 /// Create a new opcode from a direction, group, number, and size.
202 ///
203 /// This corresponds to the C macro `_IOC(direction, group, number, size)`
204 #[doc(alias = "_IOC")]
205 #[inline]
206 pub const fn from_components(
207 direction: Direction,
208 group: u8,
209 number: u8,
210 data_size: usize,
211 ) -> Opcode {
212 assert!(data_size <= Opcode::MAX as usize, "data size is too large");
213
214 platform::compose_opcode(
215 direction,
216 group as Opcode,
217 number as Opcode,
218 data_size as Opcode,
219 )
220 }
221
222 /// Create a new opcode from a group, a number, that uses no data.
223 ///
224 /// This corresponds to the C macro `_IO(group, number)`.
225 #[doc(alias = "_IO")]
226 #[inline]
227 pub const fn none(group: u8, number: u8) -> Opcode {
228 from_components(Direction::None, group, number, 0)
229 }
230
231 /// Create a new reading opcode from a group, a number and the type of
232 /// data.
233 ///
234 /// This corresponds to the C macro `_IOR(group, number, T)`.
235 #[doc(alias = "_IOR")]
236 #[inline]
237 pub const fn read<T>(group: u8, number: u8) -> Opcode {
238 from_components(Direction::Read, group, number, mem::size_of::<T>())
239 }
240
241 /// Create a new writing opcode from a group, a number and the type of
242 /// data.
243 ///
244 /// This corresponds to the C macro `_IOW(group, number, T)`.
245 #[doc(alias = "_IOW")]
246 #[inline]
247 pub const fn write<T>(group: u8, number: u8) -> Opcode {
248 from_components(Direction::Write, group, number, mem::size_of::<T>())
249 }
250
251 /// Create a new reading and writing opcode from a group, a number and the
252 /// type of data.
253 ///
254 /// This corresponds to the C macro `_IOWR(group, number, T)`.
255 #[doc(alias = "_IOWR")]
256 #[inline]
257 pub const fn read_write<T>(group: u8, number: u8) -> Opcode {
258 from_components(Direction::ReadWrite, group, number, mem::size_of::<T>())
259 }
260}
261
262/// The direction that an `ioctl` is going.
263///
264/// The direction is relative to userspace: `Read` means reading data from the
265/// kernel, and `Write` means the kernel writing data to userspace.
266#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
267pub enum Direction {
268 /// None of the above.
269 None,
270
271 /// Read data from the kernel.
272 Read,
273
274 /// Write data to the kernel.
275 Write,
276
277 /// Read and write data to the kernel.
278 ReadWrite,
279}
280
281/// The type used by the `ioctl` to signify the output.
282pub type IoctlOutput = c::c_int;
283
284/// The type used by the `ioctl` to signify the command.
285pub type Opcode = _Opcode;
286
287// Under raw Linux, this is an `unsigned int`.
288#[cfg(linux_raw)]
289type _Opcode = c::c_uint;
290
291// On libc Linux with GNU libc or uclibc, this is an `unsigned long`.
292#[cfg(all(
293 not(linux_raw),
294 target_os = "linux",
295 any(target_env = "gnu", target_env = "uclibc")
296))]
297type _Opcode = c::c_ulong;
298
299// Musl uses `c_int`.
300#[cfg(all(
301 not(linux_raw),
302 target_os = "linux",
303 not(target_env = "gnu"),
304 not(target_env = "uclibc")
305))]
306type _Opcode = c::c_int;
307
308// Android uses `c_int`.
309#[cfg(all(not(linux_raw), target_os = "android"))]
310type _Opcode = c::c_int;
311
312// BSD, Haiku, Hurd, Redox, and Vita use `unsigned long`.
313#[cfg(any(
314 bsd,
315 target_os = "redox",
316 target_os = "haiku",
317 target_os = "horizon",
318 target_os = "hurd",
319 target_os = "vita"
320))]
321type _Opcode = c::c_ulong;
322
323// AIX, Emscripten, Fuchsia, Solaris, and WASI use a `int`.
324#[cfg(any(
325 solarish,
326 target_os = "aix",
327 target_os = "fuchsia",
328 target_os = "emscripten",
329 target_os = "nto",
330 target_os = "wasi"
331))]
332type _Opcode = c::c_int;
333
334// ESP-IDF uses a `c_uint`.
335#[cfg(target_os = "espidf")]
336type _Opcode = c::c_uint;
337
338// Windows has `ioctlsocket`, which uses `i32`.
339#[cfg(windows)]
340type _Opcode = i32;
341
342#[cfg(linux_kernel)]
343#[cfg(not(any(target_arch = "sparc", target_arch = "sparc64")))]
344#[cfg(test)]
345mod tests {
346 use super::*;
347
348 #[test]
349 fn test_opcode_funcs() {
350 // `TUNGETDEVNETNS` is defined as `_IO('T', 227)`.
351 assert_eq!(
352 linux_raw_sys::ioctl::TUNGETDEVNETNS as Opcode,
353 opcode::none(b'T', 227)
354 );
355 // `FS_IOC_GETVERSION` is defined as `_IOR('v', 1, long)`.
356 assert_eq!(
357 linux_raw_sys::ioctl::FS_IOC_GETVERSION as Opcode,
358 opcode::read::<c::c_long>(b'v', 1)
359 );
360 // `TUNSETNOCSUM` is defined as `_IOW('T', 200, int)`.
361 assert_eq!(
362 linux_raw_sys::ioctl::TUNSETNOCSUM as Opcode,
363 opcode::write::<c::c_int>(b'T', 200)
364 );
365 // `FIFREEZE` is defined as `_IOWR('X', 119, int)`.
366 assert_eq!(
367 linux_raw_sys::ioctl::FIFREEZE as Opcode,
368 opcode::read_write::<c::c_int>(b'X', 119)
369 );
370 }
371}