rustix/
lib.rs

1//! `rustix` provides efficient memory-safe and [I/O-safe] wrappers to
2//! POSIX-like, Unix-like, Linux, and Winsock2 syscall-like APIs, with
3//! configurable backends.
4//!
5//! With rustix, you can write code like this:
6//!
7//! ```
8//! # #[cfg(feature = "net")]
9//! # fn read(sock: std::net::TcpStream, buf: &mut [u8]) -> std::io::Result<()> {
10//! # use rustix::net::RecvFlags;
11//! let nread: usize = rustix::net::recv(&sock, buf, RecvFlags::PEEK)?;
12//! # let _ = nread;
13//! # Ok(())
14//! # }
15//! ```
16//!
17//! instead of like this:
18//!
19//! ```
20//! # #[cfg(feature = "net")]
21//! # fn read(sock: std::net::TcpStream, buf: &mut [u8]) -> std::io::Result<()> {
22//! # #[cfg(unix)]
23//! # use std::os::unix::io::AsRawFd;
24//! # #[cfg(target_os = "wasi")]
25//! # use std::os::wasi::io::AsRawFd;
26//! # #[cfg(windows)]
27//! # use windows_sys::Win32::Networking::WinSock as libc;
28//! # #[cfg(windows)]
29//! # use std::os::windows::io::AsRawSocket;
30//! # const MSG_PEEK: i32 = libc::MSG_PEEK;
31//! let nread: usize = unsafe {
32//!     #[cfg(any(unix, target_os = "wasi"))]
33//!     let raw = sock.as_raw_fd();
34//!     #[cfg(windows)]
35//!     let raw = sock.as_raw_socket();
36//!     match libc::recv(
37//!         raw as _,
38//!         buf.as_mut_ptr().cast(),
39//!         buf.len().try_into().unwrap_or(i32::MAX as _),
40//!         MSG_PEEK,
41//!     ) {
42//!         -1 => return Err(std::io::Error::last_os_error()),
43//!         nread => nread as usize,
44//!     }
45//! };
46//! # let _ = nread;
47//! # Ok(())
48//! # }
49//! ```
50//!
51//! rustix's APIs perform the following tasks:
52//!  - Error values are translated to [`Result`]s.
53//!  - Buffers are passed as Rust slices.
54//!  - Out-parameters are presented as return values.
55//!  - Path arguments use [`Arg`], so they accept any string type.
56//!  - File descriptors are passed and returned via [`AsFd`] and [`OwnedFd`]
57//!    instead of bare integers, ensuring I/O safety.
58//!  - Constants use `enum`s and [`bitflags`] types, and enable [support for
59//!    externally defined flags].
60//!  - Multiplexed functions (eg. `fcntl`, `ioctl`, etc.) are de-multiplexed.
61//!  - Variadic functions (eg. `openat`, etc.) are presented as non-variadic.
62//!  - Functions that return strings automatically allocate sufficient memory
63//!    and retry the syscall as needed to determine the needed length.
64//!  - Functions and types which need `l` prefixes or `64` suffixes to enable
65//!    large-file support (LFS) are used automatically. File sizes and offsets
66//!    are always presented as `u64` and `i64`.
67//!  - Behaviors that depend on the sizes of C types like `long` are hidden.
68//!  - In some places, more human-friendly and less historical-accident names
69//!    are used (and documentation aliases are used so that the original names
70//!    can still be searched for).
71//!  - Provide y2038 compatibility, on platforms which support this.
72//!  - Correct selected platform bugs, such as behavioral differences when
73//!    running under seccomp.
74//!
75//! Things they don't do include:
76//!  - Detecting whether functions are supported at runtime, except in specific
77//!    cases where new interfaces need to be detected to support y2038 and LFS.
78//!  - Hiding significant differences between platforms.
79//!  - Restricting ambient authorities.
80//!  - Imposing sandboxing features such as filesystem path or network address
81//!    sandboxing.
82//!
83//! See [`cap-std`], [`system-interface`], and [`io-streams`] for libraries
84//! which do hide significant differences between platforms, and [`cap-std`]
85//! which does perform sandboxing and restricts ambient authorities.
86//!
87//! [`cap-std`]: https://crates.io/crates/cap-std
88//! [`system-interface`]: https://crates.io/crates/system-interface
89//! [`io-streams`]: https://crates.io/crates/io-streams
90//! [`getrandom`]: https://crates.io/crates/getrandom
91//! [`bitflags`]: https://crates.io/crates/bitflags
92//! [`AsFd`]: https://doc.rust-lang.org/stable/std/os/fd/trait.AsFd.html
93//! [`OwnedFd`]: https://doc.rust-lang.org/stable/std/os/fd/struct.OwnedFd.html
94//! [I/O-safe]: https://github.com/rust-lang/rfcs/blob/master/text/3128-io-safety.md
95//! [`Result`]: https://doc.rust-lang.org/stable/std/result/enum.Result.html
96//! [`Arg`]: https://docs.rs/rustix/*/rustix/path/trait.Arg.html
97//! [support for externally defined flags]: https://docs.rs/bitflags/*/bitflags/#externally-defined-flags
98
99#![deny(missing_docs)]
100#![allow(stable_features)]
101#![cfg_attr(linux_raw, deny(unsafe_code))]
102#![cfg_attr(rustc_attrs, feature(rustc_attrs))]
103#![cfg_attr(doc_cfg, feature(doc_cfg))]
104#![cfg_attr(all(wasi_ext, target_os = "wasi", feature = "std"), feature(wasi_ext))]
105#![cfg_attr(core_ffi_c, feature(core_ffi_c))]
106#![cfg_attr(core_c_str, feature(core_c_str))]
107#![cfg_attr(all(feature = "alloc", alloc_c_string), feature(alloc_c_string))]
108#![cfg_attr(all(feature = "alloc", alloc_ffi), feature(alloc_ffi))]
109#![cfg_attr(not(feature = "std"), no_std)]
110#![cfg_attr(feature = "rustc-dep-of-std", feature(ip))]
111#![cfg_attr(feature = "rustc-dep-of-std", allow(internal_features))]
112#![cfg_attr(
113    any(feature = "rustc-dep-of-std", core_intrinsics),
114    feature(core_intrinsics)
115)]
116#![cfg_attr(asm_experimental_arch, feature(asm_experimental_arch))]
117#![cfg_attr(not(feature = "all-apis"), allow(dead_code))]
118// It is common in Linux and libc APIs for types to vary between platforms.
119#![allow(clippy::unnecessary_cast)]
120// It is common in Linux and libc APIs for types to vary between platforms.
121#![allow(clippy::useless_conversion)]
122// Redox and WASI have enough differences that it isn't worth precisely
123// conditionalizing all the `use`s for them. Similar for if we don't have
124// "all-apis".
125#![cfg_attr(
126    any(target_os = "redox", target_os = "wasi", not(feature = "all-apis")),
127    allow(unused_imports)
128)]
129
130#[cfg(all(feature = "alloc", not(feature = "rustc-dep-of-std")))]
131extern crate alloc;
132
133// Use `static_assertions` macros if we have them, or a polyfill otherwise.
134#[cfg(all(test, static_assertions))]
135#[macro_use]
136#[allow(unused_imports)]
137extern crate static_assertions;
138#[cfg(all(test, not(static_assertions)))]
139#[macro_use]
140#[allow(unused_imports)]
141mod static_assertions;
142
143// Internal utilities.
144#[cfg(not(windows))]
145#[macro_use]
146pub(crate) mod cstr;
147#[macro_use]
148pub(crate) mod utils;
149// Polyfill for `std` in `no_std` builds.
150#[cfg_attr(feature = "std", path = "maybe_polyfill/std/mod.rs")]
151#[cfg_attr(not(feature = "std"), path = "maybe_polyfill/no_std/mod.rs")]
152pub(crate) mod maybe_polyfill;
153#[cfg(test)]
154#[macro_use]
155pub(crate) mod check_types;
156#[macro_use]
157pub(crate) mod bitcast;
158
159// linux_raw: Weak symbols are used by the use-libc-auxv feature for
160// glibc 2.15 support.
161//
162// libc: Weak symbols are used to call various functions available in some
163// versions of libc and not others.
164#[cfg(any(
165    all(linux_raw, feature = "use-libc-auxv"),
166    all(libc, not(any(windows, target_os = "espidf", target_os = "wasi")))
167))]
168#[macro_use]
169mod weak;
170
171// Pick the backend implementation to use.
172#[cfg_attr(libc, path = "backend/libc/mod.rs")]
173#[cfg_attr(linux_raw, path = "backend/linux_raw/mod.rs")]
174#[cfg_attr(wasi, path = "backend/wasi/mod.rs")]
175mod backend;
176
177/// Export the `*Fd` types and traits that are used in rustix's public API.
178///
179/// Users can use this to avoid needing to import anything else to use the same
180/// versions of these types and traits.
181pub mod fd {
182    use super::backend;
183
184    // Re-export `AsSocket` etc. too, as users can't implement `AsFd` etc. on
185    // Windows due to them having blanket impls on Windows, so users must
186    // implement `AsSocket` etc.
187    #[cfg(windows)]
188    pub use backend::fd::{AsRawSocket, AsSocket, FromRawSocket, IntoRawSocket};
189
190    pub use backend::fd::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd, OwnedFd, RawFd};
191}
192
193// The public API modules.
194#[cfg(feature = "event")]
195#[cfg_attr(doc_cfg, doc(cfg(feature = "event")))]
196pub mod event;
197#[cfg(not(windows))]
198pub mod ffi;
199#[cfg(not(windows))]
200#[cfg(feature = "fs")]
201#[cfg_attr(doc_cfg, doc(cfg(feature = "fs")))]
202pub mod fs;
203pub mod io;
204#[cfg(linux_kernel)]
205#[cfg(feature = "io_uring")]
206#[cfg_attr(doc_cfg, doc(cfg(feature = "io_uring")))]
207pub mod io_uring;
208pub mod ioctl;
209#[cfg(not(any(windows, target_os = "espidf", target_os = "vita", target_os = "wasi")))]
210#[cfg(feature = "mm")]
211#[cfg_attr(doc_cfg, doc(cfg(feature = "mm")))]
212pub mod mm;
213#[cfg(linux_kernel)]
214#[cfg(feature = "mount")]
215#[cfg_attr(doc_cfg, doc(cfg(feature = "mount")))]
216pub mod mount;
217#[cfg(not(any(target_os = "redox", target_os = "wasi")))]
218#[cfg(feature = "net")]
219#[cfg_attr(doc_cfg, doc(cfg(feature = "net")))]
220pub mod net;
221#[cfg(not(any(windows, target_os = "espidf")))]
222#[cfg(feature = "param")]
223#[cfg_attr(doc_cfg, doc(cfg(feature = "param")))]
224pub mod param;
225#[cfg(not(windows))]
226#[cfg(any(feature = "fs", feature = "mount", feature = "net"))]
227#[cfg_attr(
228    doc_cfg,
229    doc(cfg(any(feature = "fs", feature = "mount", feature = "net")))
230)]
231pub mod path;
232#[cfg(feature = "pipe")]
233#[cfg_attr(doc_cfg, doc(cfg(feature = "pipe")))]
234#[cfg(not(any(windows, target_os = "wasi")))]
235pub mod pipe;
236#[cfg(not(windows))]
237#[cfg(feature = "process")]
238#[cfg_attr(doc_cfg, doc(cfg(feature = "process")))]
239pub mod process;
240#[cfg(feature = "procfs")]
241#[cfg(linux_kernel)]
242#[cfg_attr(doc_cfg, doc(cfg(feature = "procfs")))]
243pub mod procfs;
244#[cfg(not(windows))]
245#[cfg(not(target_os = "wasi"))]
246#[cfg(feature = "pty")]
247#[cfg_attr(doc_cfg, doc(cfg(feature = "pty")))]
248pub mod pty;
249#[cfg(not(windows))]
250#[cfg(feature = "rand")]
251#[cfg_attr(doc_cfg, doc(cfg(feature = "rand")))]
252pub mod rand;
253#[cfg(not(any(
254    windows,
255    target_os = "android",
256    target_os = "espidf",
257    target_os = "vita",
258    target_os = "wasi"
259)))]
260#[cfg(feature = "shm")]
261#[cfg_attr(doc_cfg, doc(cfg(feature = "shm")))]
262pub mod shm;
263#[cfg(not(windows))]
264#[cfg(feature = "stdio")]
265#[cfg_attr(doc_cfg, doc(cfg(feature = "stdio")))]
266pub mod stdio;
267#[cfg(feature = "system")]
268#[cfg(not(any(windows, target_os = "wasi")))]
269#[cfg_attr(doc_cfg, doc(cfg(feature = "system")))]
270pub mod system;
271#[cfg(not(any(windows, target_os = "vita")))]
272#[cfg(feature = "termios")]
273#[cfg_attr(doc_cfg, doc(cfg(feature = "termios")))]
274pub mod termios;
275#[cfg(not(windows))]
276#[cfg(feature = "thread")]
277#[cfg_attr(doc_cfg, doc(cfg(feature = "thread")))]
278pub mod thread;
279#[cfg(not(any(windows, target_os = "espidf")))]
280#[cfg(feature = "time")]
281#[cfg_attr(doc_cfg, doc(cfg(feature = "time")))]
282pub mod time;
283
284// "runtime" is also a public API module, but it's only for libc-like users.
285#[cfg(not(windows))]
286#[cfg(feature = "runtime")]
287#[cfg(linux_raw)]
288#[cfg_attr(not(document_experimental_runtime_api), doc(hidden))]
289#[cfg_attr(doc_cfg, doc(cfg(feature = "runtime")))]
290pub mod runtime;
291
292// Temporarily provide some mount functions for use in the fs module for
293// backwards compatibility.
294#[cfg(linux_kernel)]
295#[cfg(all(feature = "fs", not(feature = "mount")))]
296pub(crate) mod mount;
297
298// Declare "fs" as a non-public module if "fs" isn't enabled but we need it for
299// reading procfs.
300#[cfg(not(windows))]
301#[cfg(not(feature = "fs"))]
302#[cfg(all(
303    linux_raw,
304    not(feature = "use-libc-auxv"),
305    not(feature = "use-explicitly-provided-auxv"),
306    any(
307        feature = "param",
308        feature = "runtime",
309        feature = "time",
310        target_arch = "x86",
311    )
312))]
313#[cfg_attr(doc_cfg, doc(cfg(feature = "fs")))]
314pub(crate) mod fs;
315
316// Similarly, declare `path` as a non-public module if needed.
317#[cfg(not(windows))]
318#[cfg(not(any(feature = "fs", feature = "mount", feature = "net")))]
319#[cfg(all(
320    linux_raw,
321    not(feature = "use-libc-auxv"),
322    not(feature = "use-explicitly-provided-auxv"),
323    any(
324        feature = "param",
325        feature = "runtime",
326        feature = "time",
327        target_arch = "x86",
328    )
329))]
330pub(crate) mod path;
331
332// Private modules used by multiple public modules.
333#[cfg(not(any(windows, target_os = "espidf")))]
334#[cfg(any(feature = "thread", feature = "time", target_arch = "x86"))]
335mod clockid;
336#[cfg(not(any(windows, target_os = "wasi")))]
337#[cfg(any(
338    feature = "procfs",
339    feature = "process",
340    feature = "runtime",
341    feature = "termios",
342    feature = "thread",
343    all(bsd, feature = "event"),
344    all(linux_kernel, feature = "net")
345))]
346mod pid;
347#[cfg(any(feature = "process", feature = "thread"))]
348#[cfg(linux_kernel)]
349mod prctl;
350#[cfg(not(any(windows, target_os = "espidf", target_os = "wasi")))]
351#[cfg(any(feature = "process", feature = "runtime", all(bsd, feature = "event")))]
352mod signal;
353#[cfg(not(windows))]
354#[cfg(any(
355    feature = "fs",
356    feature = "runtime",
357    feature = "thread",
358    feature = "time",
359    all(
360        linux_raw,
361        not(feature = "use-libc-auxv"),
362        not(feature = "use-explicitly-provided-auxv"),
363        any(
364            feature = "param",
365            feature = "runtime",
366            feature = "time",
367            target_arch = "x86",
368        )
369    )
370))]
371mod timespec;
372#[cfg(not(any(windows, target_os = "wasi")))]
373#[cfg(any(
374    feature = "fs",
375    feature = "process",
376    feature = "thread",
377    all(
378        linux_raw,
379        not(feature = "use-libc-auxv"),
380        not(feature = "use-explicitly-provided-auxv"),
381        any(
382            feature = "param",
383            feature = "runtime",
384            feature = "time",
385            target_arch = "x86",
386        )
387    ),
388    all(linux_kernel, feature = "net")
389))]
390mod ugid;