rustix/
lib.rs

1//! `rustix` provides efficient memory-safe and [I/O-safe] wrappers to
2//! POSIX-like, Unix-like, Linux, and Winsock 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, _received) = 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 = 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//!  - Use `timespec` for timestamps and timeouts instead of `timeval` and
75//!    `c_int` milliseconds.
76//!
77//! Things they don't do include:
78//!  - Detecting whether functions are supported at runtime, except in specific
79//!    cases where new interfaces need to be detected to support y2038 and LFS.
80//!  - Hiding significant differences between platforms.
81//!  - Restricting ambient authorities.
82//!  - Imposing sandboxing features such as filesystem path or network address
83//!    sandboxing.
84//!
85//! See [`cap-std`], [`system-interface`], and [`io-streams`] for libraries
86//! which do hide significant differences between platforms, and [`cap-std`]
87//! which does perform sandboxing and restricts ambient authorities.
88//!
89//! [`cap-std`]: https://crates.io/crates/cap-std
90//! [`system-interface`]: https://crates.io/crates/system-interface
91//! [`io-streams`]: https://crates.io/crates/io-streams
92//! [`bitflags`]: bitflags
93//! [`AsFd`]: crate::fd::AsFd
94//! [`OwnedFd`]: crate::fd::OwnedFd
95//! [I/O-safe]: https://github.com/rust-lang/rfcs/blob/master/text/3128-io-safety.md
96//! [`Arg`]: path::Arg
97//! [support for externally defined flags]: 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(docsrs, 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(error_in_core, feature(error_in_core))]
108#![cfg_attr(all(feature = "alloc", alloc_c_string), feature(alloc_c_string))]
109#![cfg_attr(all(feature = "alloc", alloc_ffi), feature(alloc_ffi))]
110#![cfg_attr(not(feature = "std"), no_std)]
111#![cfg_attr(feature = "rustc-dep-of-std", feature(ip))]
112#![cfg_attr(feature = "rustc-dep-of-std", allow(internal_features))]
113#![cfg_attr(
114    any(feature = "rustc-dep-of-std", core_intrinsics),
115    feature(core_intrinsics)
116)]
117#![cfg_attr(asm_experimental_arch, feature(asm_experimental_arch))]
118#![cfg_attr(not(feature = "all-apis"), allow(dead_code))]
119// It is common in Linux and libc APIs for types to vary between platforms.
120#![allow(clippy::unnecessary_cast)]
121// It is common in Linux and libc APIs for types to vary between platforms.
122#![allow(clippy::useless_conversion)]
123// This clippy lint gets too many false positives.
124#![allow(clippy::needless_lifetimes)]
125// Until `unnecessary_transmutes` is recognized by our MSRV, don't warn about
126// it being unrecognized.
127#![allow(unknown_lints)]
128// Until `cast_signed` and `cast_unsigned` are supported by our MSRV, don't
129// warn about transmutes that could be changed to them.
130#![allow(unnecessary_transmutes)]
131// Redox and WASI have enough differences that it isn't worth precisely
132// conditionalizing all the `use`s for them. Similar for if we don't have
133// "all-apis".
134#![cfg_attr(
135    any(target_os = "redox", target_os = "wasi", not(feature = "all-apis")),
136    allow(unused_imports)
137)]
138// wasip2 conditionally gates stdlib APIs such as `OsStrExt`.
139// <https://github.com/rust-lang/rust/issues/130323>
140#![cfg_attr(
141    all(
142        target_os = "wasi",
143        target_env = "p2",
144        any(feature = "fs", feature = "mount", feature = "net"),
145        wasip2,
146    ),
147    feature(wasip2)
148)]
149
150#[cfg(all(feature = "alloc", feature = "rustc-dep-of-std"))]
151extern crate rustc_std_workspace_alloc as alloc;
152
153#[cfg(all(feature = "alloc", not(feature = "rustc-dep-of-std")))]
154extern crate alloc;
155
156// Use `static_assertions` macros if we have them, or a polyfill otherwise.
157#[cfg(all(test, static_assertions))]
158#[macro_use]
159#[allow(unused_imports)]
160extern crate static_assertions;
161#[cfg(all(test, not(static_assertions)))]
162#[macro_use]
163#[allow(unused_imports)]
164mod static_assertions;
165
166pub mod buffer;
167#[cfg(not(windows))]
168#[macro_use]
169pub(crate) mod cstr;
170#[macro_use]
171pub(crate) mod utils;
172// Polyfill for `std` in `no_std` builds.
173#[cfg_attr(feature = "std", path = "maybe_polyfill/std/mod.rs")]
174#[cfg_attr(not(feature = "std"), path = "maybe_polyfill/no_std/mod.rs")]
175pub(crate) mod maybe_polyfill;
176#[cfg(test)]
177#[macro_use]
178pub(crate) mod check_types;
179#[macro_use]
180pub(crate) mod bitcast;
181
182// linux_raw: Weak symbols are used by the use-libc-auxv feature for
183// glibc 2.15 support.
184//
185// libc: Weak symbols are used to call various functions available in some
186// versions of libc and not others.
187#[cfg(any(
188    all(linux_raw, feature = "use-libc-auxv"),
189    all(libc, not(any(windows, target_os = "espidf", target_os = "wasi")))
190))]
191#[macro_use]
192mod weak;
193
194// Pick the backend implementation to use.
195#[cfg_attr(libc, path = "backend/libc/mod.rs")]
196#[cfg_attr(linux_raw, path = "backend/linux_raw/mod.rs")]
197#[cfg_attr(wasi, path = "backend/wasi/mod.rs")]
198mod backend;
199
200/// Export the `*Fd` types and traits that are used in rustix's public API.
201///
202/// This module exports the types and traits from [`std::os::fd`], or polyills
203/// on Rust < 1.66 or on Windows.
204///
205/// On Windows, the polyfill consists of aliases of the socket types and
206/// traits, For example, [`OwnedSocket`] is aliased to `OwnedFd`, and so on,
207/// and there are blanket impls for `AsFd` etc. that map to `AsSocket` impls.
208/// These blanket impls suffice for using the traits, however not for
209/// implementing them, so this module also exports `AsSocket` and the other
210/// traits as-is so that users can implement them if needed.
211///
212/// [`OwnedSocket`]: https://doc.rust-lang.org/stable/std/os/windows/io/struct.OwnedSocket.html
213pub mod fd {
214    pub use super::backend::fd::*;
215}
216
217// The public API modules.
218#[cfg(feature = "event")]
219#[cfg_attr(docsrs, doc(cfg(feature = "event")))]
220pub mod event;
221pub mod ffi;
222#[cfg(not(windows))]
223#[cfg(feature = "fs")]
224#[cfg_attr(docsrs, doc(cfg(feature = "fs")))]
225pub mod fs;
226pub mod io;
227#[cfg(linux_kernel)]
228#[cfg(feature = "io_uring")]
229#[cfg_attr(docsrs, doc(cfg(feature = "io_uring")))]
230pub mod io_uring;
231pub mod ioctl;
232#[cfg(not(any(
233    windows,
234    target_os = "espidf",
235    target_os = "horizon",
236    target_os = "vita",
237    target_os = "wasi"
238)))]
239#[cfg(feature = "mm")]
240#[cfg_attr(docsrs, doc(cfg(feature = "mm")))]
241pub mod mm;
242#[cfg(linux_kernel)]
243#[cfg(feature = "mount")]
244#[cfg_attr(docsrs, doc(cfg(feature = "mount")))]
245pub mod mount;
246#[cfg(not(target_os = "wasi"))]
247#[cfg(feature = "net")]
248#[cfg_attr(docsrs, doc(cfg(feature = "net")))]
249pub mod net;
250#[cfg(not(any(windows, target_os = "espidf")))]
251#[cfg(feature = "param")]
252#[cfg_attr(docsrs, doc(cfg(feature = "param")))]
253pub mod param;
254#[cfg(not(windows))]
255#[cfg(any(feature = "fs", feature = "mount", feature = "net"))]
256#[cfg_attr(
257    docsrs,
258    doc(cfg(any(feature = "fs", feature = "mount", feature = "net")))
259)]
260pub mod path;
261#[cfg(feature = "pipe")]
262#[cfg_attr(docsrs, doc(cfg(feature = "pipe")))]
263#[cfg(not(any(windows, target_os = "wasi")))]
264pub mod pipe;
265#[cfg(not(windows))]
266#[cfg(feature = "process")]
267#[cfg_attr(docsrs, doc(cfg(feature = "process")))]
268pub mod process;
269#[cfg(not(windows))]
270#[cfg(not(target_os = "wasi"))]
271#[cfg(feature = "pty")]
272#[cfg_attr(docsrs, doc(cfg(feature = "pty")))]
273pub mod pty;
274#[cfg(not(windows))]
275#[cfg(feature = "rand")]
276#[cfg_attr(docsrs, doc(cfg(feature = "rand")))]
277pub mod rand;
278#[cfg(not(any(
279    windows,
280    target_os = "android",
281    target_os = "espidf",
282    target_os = "horizon",
283    target_os = "vita",
284    target_os = "wasi"
285)))]
286#[cfg(feature = "shm")]
287#[cfg_attr(docsrs, doc(cfg(feature = "shm")))]
288pub mod shm;
289#[cfg(not(windows))]
290#[cfg(feature = "stdio")]
291#[cfg_attr(docsrs, doc(cfg(feature = "stdio")))]
292pub mod stdio;
293#[cfg(feature = "system")]
294#[cfg(not(any(windows, target_os = "wasi")))]
295#[cfg_attr(docsrs, doc(cfg(feature = "system")))]
296pub mod system;
297#[cfg(not(any(windows, target_os = "horizon", target_os = "vita")))]
298#[cfg(feature = "termios")]
299#[cfg_attr(docsrs, doc(cfg(feature = "termios")))]
300pub mod termios;
301#[cfg(not(windows))]
302#[cfg(feature = "thread")]
303#[cfg_attr(docsrs, doc(cfg(feature = "thread")))]
304pub mod thread;
305#[cfg(not(any(windows, target_os = "espidf")))]
306#[cfg(feature = "time")]
307#[cfg_attr(docsrs, doc(cfg(feature = "time")))]
308pub mod time;
309
310// "runtime" is also a public API module, but it's only for libc-like users.
311#[cfg(not(windows))]
312#[cfg(feature = "runtime")]
313#[cfg(linux_raw)]
314#[cfg_attr(not(document_experimental_runtime_api), doc(hidden))]
315#[cfg_attr(docsrs, doc(cfg(feature = "runtime")))]
316pub mod runtime;
317
318// Declare "fs" as a non-public module if "fs" isn't enabled but we need it for
319// reading procfs.
320#[cfg(not(windows))]
321#[cfg(not(feature = "fs"))]
322#[cfg(all(
323    linux_raw,
324    not(feature = "use-libc-auxv"),
325    not(feature = "use-explicitly-provided-auxv"),
326    any(
327        feature = "param",
328        feature = "runtime",
329        feature = "thread",
330        feature = "time",
331        target_arch = "x86",
332    )
333))]
334#[cfg_attr(docsrs, doc(cfg(feature = "fs")))]
335pub(crate) mod fs;
336
337// Similarly, declare `path` as a non-public module if needed.
338#[cfg(not(windows))]
339#[cfg(not(any(feature = "fs", feature = "mount", feature = "net")))]
340#[cfg(all(
341    linux_raw,
342    not(feature = "use-libc-auxv"),
343    not(feature = "use-explicitly-provided-auxv"),
344    any(
345        feature = "param",
346        feature = "runtime",
347        feature = "thread",
348        feature = "time",
349        target_arch = "x86",
350    )
351))]
352pub(crate) mod path;
353
354// Private modules used by multiple public modules.
355#[cfg(not(any(windows, target_os = "espidf")))]
356#[cfg(any(feature = "thread", feature = "time"))]
357mod clockid;
358#[cfg(linux_kernel)]
359#[cfg(any(feature = "io_uring", feature = "runtime"))]
360mod kernel_sigset;
361#[cfg(not(any(windows, target_os = "wasi")))]
362#[cfg(any(
363    feature = "process",
364    feature = "runtime",
365    feature = "termios",
366    feature = "thread",
367    all(bsd, feature = "event"),
368    all(linux_kernel, feature = "net")
369))]
370mod pid;
371#[cfg(any(feature = "process", feature = "thread"))]
372#[cfg(linux_kernel)]
373mod prctl;
374#[cfg(not(any(windows, target_os = "espidf", target_os = "wasi")))]
375#[cfg(any(
376    feature = "io_uring",
377    feature = "process",
378    feature = "runtime",
379    all(bsd, feature = "event")
380))]
381mod signal;
382#[cfg(any(
383    feature = "fs",
384    feature = "event",
385    feature = "process",
386    feature = "runtime",
387    feature = "thread",
388    feature = "time",
389    all(feature = "event", any(bsd, linux_kernel, windows, target_os = "wasi")),
390    all(
391        linux_raw,
392        not(feature = "use-libc-auxv"),
393        not(feature = "use-explicitly-provided-auxv"),
394        any(
395            feature = "param",
396            feature = "process",
397            feature = "runtime",
398            feature = "time",
399            target_arch = "x86",
400        )
401    )
402))]
403mod timespec;
404#[cfg(not(any(windows, target_os = "wasi")))]
405#[cfg(any(
406    feature = "fs",
407    feature = "process",
408    feature = "thread",
409    all(
410        linux_raw,
411        not(feature = "use-libc-auxv"),
412        not(feature = "use-explicitly-provided-auxv"),
413        any(
414            feature = "param",
415            feature = "runtime",
416            feature = "time",
417            target_arch = "x86",
418        )
419    ),
420    all(linux_kernel, feature = "net")
421))]
422mod ugid;
423
424#[cfg(doc)]
425#[cfg_attr(docsrs, doc(cfg(doc)))]
426pub mod not_implemented;