Debian Codegraph @

third_party/rust/rustix/src/runtime.rs

raw
1 //! Experimental low-level implementation details for libc-like runtime
2 //! libraries such as [Origin].
3 //!
4 //! ⚠ These are not normal functions. ⚠
5 //!
6 //! - Some of the functions in this module cannot be used in a process which
7 //! also has a libc present. This can be true even for functions that have
8 //! the same name as a libc function that Rust code can use.
9 //!
10 //! - Some of the functions in this module don't behave exactly the same way
11 //! as functions in libc with similar names. Sometimes information about the
12 //! differences is included in the Linux documentation under “C
13 //! library/kernel differences” sections. But not always.
14 //!
15 //! - The safety requirements of the functions in this module are not fully
16 //! documented.
17 //!
18 //! - The API for these functions is not considered stable, and this module is
19 //! `doc(hidden)`.
20 //!
21 //! ⚠ Caution is indicated. ⚠
22 //!
23 //! These functions are for implementing thread-local storage (TLS), managing
24 //! threads, loaded libraries, and other process-wide resources. Most of
25 //! `rustix` doesn't care about what other libraries are linked into the
26 //! program or what they're doing, but the features in this module generally
27 //! can only be used by one entity within a process.
28 //!
29 //! [Origin]: https://github.com/sunfishcode/origin#readme
30 //!
31 //! # Safety
32 //!
33 //! This module is intended to be used for implementing a runtime library such
34 //! as libc. Use of these features for any other purpose is likely to create
35 //! serious problems.
36 #![allow(unsafe_code)]
37
38 use crate::backend;
39 #[cfg(linux_raw)]
40 use crate::ffi::CStr;
41 #[cfg(linux_raw)]
42 #[cfg(feature = "fs")]
43 use crate::fs::AtFlags;
44 #[cfg(linux_raw)]
45 use crate::io;
46 #[cfg(linux_raw)]
47 use crate::pid::Pid;
48 #[cfg(linux_raw)]
49 #[cfg(feature = "fs")]
50 use backend::fd::AsFd;
51 #[cfg(linux_raw)]
52 use core::ffi::c_void;
53
54 #[cfg(linux_raw)]
55 pub use crate::signal::Signal;
56
57 /// `sigaction`
58 #[cfg(linux_raw)]
59 pub type Sigaction = linux_raw_sys::general::kernel_sigaction;
60
61 /// `stack_t`
62 #[cfg(linux_raw)]
63 pub type Stack = linux_raw_sys::general::stack_t;
64
65 /// `sigset_t`
66 #[cfg(linux_raw)]
67 pub type Sigset = linux_raw_sys::general::kernel_sigset_t;
68
69 /// `siginfo_t`
70 #[cfg(linux_raw)]
71 pub type Siginfo = linux_raw_sys::general::siginfo_t;
72
73 pub use crate::timespec::{Nsecs, Secs, Timespec};
74
75 /// `SIG_*` constants for use with [`sigprocmask`].
76 #[cfg(linux_raw)]
77 #[repr(u32)]
78 pub enum How {
79 /// `SIG_BLOCK`
80 BLOCK = linux_raw_sys::general::SIG_BLOCK,
81
82 /// `SIG_UNBLOCK`
83 UNBLOCK = linux_raw_sys::general::SIG_UNBLOCK,
84
85 /// `SIG_SETMASK`
86 SETMASK = linux_raw_sys::general::SIG_SETMASK,
87 }
88
89 #[cfg(target_arch = "x86")]
90 #[inline]
91 pub unsafe fn set_thread_area(u_info: &mut UserDesc) -> io::Result<()> {
92 backend::runtime::syscalls::tls::set_thread_area(u_info)
93 }
94
95 #[cfg(target_arch = "arm")]
96 #[inline]
97 pub unsafe fn arm_set_tls(data: *mut c_void) -> io::Result<()> {
98 backend::runtime::syscalls::tls::arm_set_tls(data)
99 }
100
101 /// `prctl(PR_SET_FS, data)`—Set the x86-64 `fs` register.
102 ///
103 /// # Safety
104 ///
105 /// This is a very low-level feature for implementing threading libraries.
106 /// See the references links above.
107 #[cfg(target_arch = "x86_64")]
108 #[inline]
109 pub unsafe fn set_fs(data: *mut c_void) {
110 backend::runtime::syscalls::tls::set_fs(data)
111 }
112
113 /// Set the x86-64 thread ID address.
114 ///
115 /// # Safety
116 ///
117 /// This is a very low-level feature for implementing threading libraries.
118 /// See the references links above.
119 #[inline]
120 pub unsafe fn set_tid_address(data: *mut c_void) -> Pid {
121 backend::runtime::syscalls::tls::set_tid_address(data)
122 }
123
124 #[cfg(linux_raw)]
125 #[cfg(target_arch = "x86")]
126 pub use backend::runtime::tls::UserDesc;
127
128 /// `syscall(SYS_exit, status)`—Exit the current thread.
129 ///
130 /// # Safety
131 ///
132 /// This is a very low-level feature for implementing threading libraries.
133 #[inline]
134 pub unsafe fn exit_thread(status: i32) -> ! {
135 backend::runtime::syscalls::tls::exit_thread(status)
136 }
137
138 /// Exit all the threads in the current process' thread group.
139 ///
140 /// This is equivalent to `_exit` and `_Exit` in libc.
141 ///
142 /// This does not call any `__cxa_atexit`, `atexit`, or any other destructors.
143 /// Most programs should use [`std::process::exit`] instead of calling this
144 /// directly.
145 ///
146 /// # References
147 /// - [POSIX `_Exit`]
148 /// - [Linux `exit_group`]
149 /// - [Linux `_Exit`]
150 ///
151 /// [POSIX `_Exit`]: https://pubs.opengroup.org/onlinepubs/9799919799/functions/_Exit.html
152 /// [Linux `exit_group`]: https://man7.org/linux/man-pages/man2/exit_group.2.html
153 /// [Linux `_Exit`]: https://man7.org/linux/man-pages/man2/_Exit.2.html
154 #[doc(alias = "_exit")]
155 #[doc(alias = "_Exit")]
156 #[inline]
157 pub fn exit_group(status: i32) -> ! {
158 backend::runtime::syscalls::exit_group(status)
159 }
160
161 /// `EXIT_SUCCESS` for use with [`exit_group`].
162 ///
163 /// # References
164 /// - [POSIX]
165 /// - [Linux]
166 ///
167 /// [POSIX]: https://pubs.opengroup.org/onlinepubs/9799919799/basedefs/stdlib.h.html
168 /// [Linux]: https://man7.org/linux/man-pages/man3/exit.3.html
169 pub const EXIT_SUCCESS: i32 = backend::c::EXIT_SUCCESS;
170
171 /// `EXIT_FAILURE` for use with [`exit_group`].
172 ///
173 /// # References
174 /// - [POSIX]
175 /// - [Linux]
176 ///
177 /// [POSIX]: https://pubs.opengroup.org/onlinepubs/9799919799/basedefs/stdlib.h.html
178 /// [Linux]: https://man7.org/linux/man-pages/man3/exit.3.html
179 pub const EXIT_FAILURE: i32 = backend::c::EXIT_FAILURE;
180
181 /// Return fields from the main executable segment headers ("phdrs") relevant
182 /// to initializing TLS provided to the program at startup.
183 ///
184 /// `addr` will always be non-null, even when the TLS data is absent, so that
185 /// the `addr` and `file_size` parameters are suitable for creating a slice
186 /// with `slice::from_raw_parts`.
187 #[inline]
188 pub fn startup_tls_info() -> StartupTlsInfo {
189 backend::runtime::tls::startup_tls_info()
190 }
191
192 /// `(getauxval(AT_PHDR), getauxval(AT_PHENT), getauxval(AT_PHNUM))`—Returns
193 /// the address, ELF segment header size, and number of ELF segment headers for
194 /// the main executable.
195 ///
196 /// # References
197 /// - [Linux]
198 ///
199 /// [Linux]: https://man7.org/linux/man-pages/man3/getauxval.3.html
200 #[inline]
201 pub fn exe_phdrs() -> (*const c_void, usize, usize) {
202 backend::param::auxv::exe_phdrs()
203 }
204
205 /// `getauxval(AT_ENTRY)`—Returns the address of the program entrypoint.
206 ///
207 /// Most code interested in the program entrypoint address should instead use a
208 /// symbol reference to `_start`. That will be properly PC-relative or
209 /// relocated if needed, and will come with appropriate pointer type and
210 /// pointer provenance.
211 ///
212 /// This function is intended only for use in code that implements those
213 /// relocations, to compute the ASLR offset. It has type `usize`, so it doesn't
214 /// carry any provenance, and it shouldn't be used to dereference memory.
215 ///
216 /// # References
217 /// - [Linux]
218 ///
219 /// [Linux]: https://man7.org/linux/man-pages/man3/getauxval.3.html
220 #[inline]
221 pub fn entry() -> usize {
222 backend::param::auxv::entry()
223 }
224
225 /// `getauxval(AT_RANDOM)`—Returns the address of 16 pseudorandom bytes.
226 ///
227 /// These bytes are for use by libc. For anything else, use the `rand` crate.
228 ///
229 /// # References
230 /// - [Linux]
231 ///
232 /// [Linux]: https://man7.org/linux/man-pages/man3/getauxval.3.html
233 #[inline]
234 pub fn random() -> *const [u8; 16] {
235 backend::param::auxv::random()
236 }
237
238 #[cfg(linux_raw)]
239 pub use backend::runtime::tls::StartupTlsInfo;
240
241 /// `fork()`—Creates a new process by duplicating the calling process.
242 ///
243 /// On success, the pid of the child process is returned in the parent, and
244 /// `None` is returned in the child.
245 ///
246 /// Unlike its POSIX and libc counterparts, this `fork` does not invoke any
247 /// handlers (such as those registered with `pthread_atfork`).
248 ///
249 /// The program environment in the child after a `fork` and before an `execve`
250 /// is very special. All code that executes in this environment must avoid:
251 ///
252 /// - Acquiring any other locks that are held in other threads on the parent
253 /// at the time of the `fork`, as the child only contains one thread, and
254 /// attempting to acquire such locks will deadlock (though this is [not
255 /// considered unsafe]).
256 ///
257 /// - Performing any dynamic allocation using the global allocator, since
258 /// global allocators may use locks to ensure thread safety, and their locks
259 /// may not be released in the child process, so attempts to allocate may
260 /// deadlock (as described in the previous point).
261 ///
262 /// - Accessing any external state which the parent assumes it has exclusive
263 /// access to, such as a file protected by a file lock, as this could
264 /// corrupt the external state.
265 ///
266 /// - Accessing any random-number-generator state inherited from the parent,
267 /// as the parent may have the same state and generate the same random
268 /// numbers, which may violate security invariants.
269 ///
270 /// - Accessing any thread runtime state, since this function does not update
271 /// the thread id in the thread runtime, so thread runtime functions could
272 /// cause undefined behavior.
273 ///
274 /// - Accessing any memory shared with the parent, such as a [`MAP_SHARED`]
275 /// mapping, even with anonymous or [`memfd_create`] mappings, as this could
276 /// cause undefined behavior.
277 ///
278 /// - Calling any C function which isn't known to be [async-signal-safe], as
279 /// that could cause undefined behavior. The extent to which this also
280 /// applies to Rust functions is unclear at this time.
281 ///
282 /// - And more.
283 ///
284 /// # Safety
285 ///
286 /// The child must avoid accessing any memory shared with the parent in a
287 /// way that invokes undefined behavior. It must avoid accessing any threading
288 /// runtime functions in a way that invokes undefined behavior. And it must
289 /// avoid invoking any undefined behavior through any function that is not
290 /// guaranteed to be async-signal-safe. But, what does async-signal-safe even
291 /// mean in a Rust program? This documentation does not have all the answers.
292 ///
293 /// So you're on your own. And on top of all the troubles with `fork` in
294 /// general, this wrapper implementation is highly experimental.
295 ///
296 /// # References
297 /// - [POSIX]
298 /// - [Linux]
299 ///
300 /// # Literary interlude
301 ///
302 /// > Do not jump on ancient uncles.
303 /// > Do not yell at average mice.
304 /// > Do not wear a broom to breakfast.
305 /// > Do not ask a snake’s advice.
306 /// > Do not bathe in chocolate pudding.
307 /// > Do not talk to bearded bears.
308 /// > Do not smoke cigars on sofas.
309 /// > Do not dance on velvet chairs.
310 /// > Do not take a whale to visit
311 /// > Russell’s mother’s cousin’s yacht.
312 /// > And whatever else you do do
313 /// > It is better you
314 /// > Do not.
315 ///
316 /// — “Rules”, by Karla Kuskin
317 ///
318 /// [`MAP_SHARED`]: https://pubs.opengroup.org/onlinepubs/9799919799/functions/mmap.html
319 /// [not considered unsafe]: https://doc.rust-lang.org/reference/behavior-not-considered-unsafe.html#deadlocks
320 /// [`memfd_create`]: https://man7.org/linux/man-pages/man2/memfd_create.2.html
321 /// [POSIX]: https://pubs.opengroup.org/onlinepubs/9799919799/functions/fork.html
322 /// [Linux]: https://man7.org/linux/man-pages/man2/fork.2.html
323 /// [async-signal-safe]: https://pubs.opengroup.org/onlinepubs/9799919799/functions/V2_chap02.html#tag_15_04_03
324 pub unsafe fn fork() -> io::Result<Fork> {
325 backend::runtime::syscalls::fork()
326 }
327
328 /// Regular Unix `fork` doesn't tell the child its own PID because it assumes
329 /// the child can just do `getpid`. That's true, but it's more fun if it
330 /// doesn't have to.
331 pub enum Fork {
332 /// This is returned in the child process after a `fork`. It holds the PID
333 /// of the child.
334 Child(Pid),
335
336 /// This is returned in the parent process after a `fork`. It holds the PID
337 /// of the child.
338 Parent(Pid),
339 }
340
341 /// `execveat(dirfd, path.as_c_str(), argv, envp, flags)`—Execute a new
342 /// command using the current process.
343 ///
344 /// # Safety
345 ///
346 /// The `argv` and `envp` pointers must point to NUL-terminated arrays, and
347 /// their contents must be pointers to NUL-terminated byte arrays.
348 ///
349 /// # References
350 /// - [Linux]
351 ///
352 /// [Linux]: https://man7.org/linux/man-pages/man2/execveat.2.html
353 #[inline]
354 #[cfg(feature = "fs")]
355 #[cfg_attr(docsrs, doc(cfg(feature = "fs")))]
356 pub unsafe fn execveat<Fd: AsFd>(
357 dirfd: Fd,
358 path: &CStr,
359 argv: *const *const u8,
360 envp: *const *const u8,
361 flags: AtFlags,
362 ) -> io::Errno {
363 backend::runtime::syscalls::execveat(dirfd.as_fd(), path, argv, envp, flags)
364 }
365
366 /// `execve(path.as_c_str(), argv, envp)`—Execute a new command using the
367 /// current process.
368 ///
369 /// # Safety
370 ///
371 /// The `argv` and `envp` pointers must point to NUL-terminated arrays, and
372 /// their contents must be pointers to NUL-terminated byte arrays.
373 ///
374 /// # References
375 /// - [Linux]
376 ///
377 /// [Linux]: https://man7.org/linux/man-pages/man2/execve.2.html
378 #[inline]
379 pub unsafe fn execve(path: &CStr, argv: *const *const u8, envp: *const *const u8) -> io::Errno {
380 backend::runtime::syscalls::execve(path, argv, envp)
381 }
382
383 /// `sigaction(signal, &new, &old)`—Modify or query a signal handler.
384 ///
385 /// # Safety
386 ///
387 /// You're on your own. And on top of all the troubles with signal handlers,
388 /// this implementation is highly experimental. Even further, it differs from
389 /// the libc `sigaction` in several non-obvious and unsafe ways.
390 ///
391 /// # References
392 /// - [POSIX]
393 /// - [Linux]
394 ///
395 /// [POSIX]: https://pubs.opengroup.org/onlinepubs/9799919799/functions/sigaction.html
396 /// [Linux]: https://man7.org/linux/man-pages/man2/sigaction.2.html
397 #[inline]
398 pub unsafe fn sigaction(signal: Signal, new: Option<Sigaction>) -> io::Result<Sigaction> {
399 backend::runtime::syscalls::sigaction(signal, new)
400 }
401
402 /// `sigaltstack(new, old)`—Modify or query a signal stack.
403 ///
404 /// # Safety
405 ///
406 /// You're on your own. And on top of all the troubles with signal handlers,
407 /// this implementation is highly experimental.
408 ///
409 /// # References
410 /// - [POSIX]
411 /// - [Linux]
412 ///
413 /// [POSIX]: https://pubs.opengroup.org/onlinepubs/9799919799/functions/sigaltstack.html
414 /// [Linux]: https://man7.org/linux/man-pages/man2/sigaltstack.2.html
415 #[inline]
416 pub unsafe fn sigaltstack(new: Option<Stack>) -> io::Result<Stack> {
417 backend::runtime::syscalls::sigaltstack(new)
418 }
419
420 /// `tkill(tid, sig)`—Send a signal to a thread.
421 ///
422 /// # Safety
423 ///
424 /// You're on your own. And on top of all the troubles with signal handlers,
425 /// this implementation is highly experimental. Also, this is not `tgkill`, so
426 /// the warning about the hazard of recycled thread ID's applies.
427 ///
428 /// # References
429 /// - [Linux]
430 ///
431 /// [Linux]: https://man7.org/linux/man-pages/man2/tkill.2.html
432 #[inline]
433 pub unsafe fn tkill(tid: Pid, sig: Signal) -> io::Result<()> {
434 backend::runtime::syscalls::tkill(tid, sig)
435 }
436
437 /// `rt_sigprocmask(how, set, oldset)`—Adjust the process signal mask.
438 ///
439 /// # Safety
440 ///
441 /// You're on your own. And on top of all the troubles with signal handlers,
442 /// this implementation is highly experimental. Even further, it differs from
443 /// the libc `sigprocmask` in several non-obvious and unsafe ways.
444 ///
445 /// # References
446 /// - [Linux `rt_sigprocmask`]
447 /// - [Linux `pthread_sigmask`]
448 ///
449 /// [Linux `rt_sigprocmask`]: https://man7.org/linux/man-pages/man2/rt_sigprocmask.2.html
450 /// [Linux `pthread_sigmask`]: https://man7.org/linux/man-pages/man3/pthread_sigmask.3.html
451 #[inline]
452 #[doc(alias = "pthread_sigmask")]
453 #[doc(alias = "rt_sigprocmask")]
454 pub unsafe fn sigprocmask(how: How, set: Option<&Sigset>) -> io::Result<Sigset> {
455 backend::runtime::syscalls::sigprocmask(how, set)
456 }
457
458 /// `sigpending()`—Query the pending signals.
459 ///
460 /// # References
461 /// - [Linux `sigpending`]
462 ///
463 /// [Linux `sigpending`]: https://man7.org/linux/man-pages/man2/sigpending.2.html
464 #[inline]
465 pub fn sigpending() -> Sigset {
466 backend::runtime::syscalls::sigpending()
467 }
468
469 /// `sigsuspend(set)`—Suspend the calling thread and wait for signals.
470 ///
471 /// # References
472 /// - [Linux `sigsuspend`]
473 ///
474 /// [Linux `sigsuspend`]: https://man7.org/linux/man-pages/man2/sigsuspend.2.html
475 #[inline]
476 pub fn sigsuspend(set: &Sigset) -> io::Result<()> {
477 backend::runtime::syscalls::sigsuspend(set)
478 }
479
480 /// `sigwait(set)`—Wait for signals.
481 ///
482 /// # Safety
483 ///
484 /// If code elsewhere in the process is depending on delivery of a signal to
485 /// prevent it from executing some code, this could cause it to miss that
486 /// signal and execute that code.
487 ///
488 /// # References
489 /// - [Linux]
490 ///
491 /// [Linux]: https://man7.org/linux/man-pages/man3/sigwait.3.html
492 #[inline]
493 pub unsafe fn sigwait(set: &Sigset) -> io::Result<Signal> {
494 backend::runtime::syscalls::sigwait(set)
495 }
496
497 /// `sigwaitinfo(set)`—Wait for signals, returning a [`Siginfo`].
498 ///
499 /// # Safety
500 ///
501 /// If code elsewhere in the process is depending on delivery of a signal to
502 /// prevent it from executing some code, this could cause it to miss that
503 /// signal and execute that code.
504 ///
505 /// # References
506 /// - [Linux]
507 ///
508 /// [Linux]: https://man7.org/linux/man-pages/man2/sigwaitinfo.2.html
509 #[inline]
510 pub unsafe fn sigwaitinfo(set: &Sigset) -> io::Result<Siginfo> {
511 backend::runtime::syscalls::sigwaitinfo(set)
512 }
513
514 /// `sigtimedwait(set)`—Wait for signals, optionally with a timeout.
515 ///
516 /// # Safety
517 ///
518 /// If code elsewhere in the process is depending on delivery of a signal to
519 /// prevent it from executing some code, this could cause it to miss that
520 /// signal and execute that code.
521 ///
522 /// # References
523 /// - [Linux]
524 ///
525 /// [Linux]: https://man7.org/linux/man-pages/man2/sigtimedwait.2.html
526 #[inline]
527 pub unsafe fn sigtimedwait(set: &Sigset, timeout: Option<Timespec>) -> io::Result<Siginfo> {
528 backend::runtime::syscalls::sigtimedwait(set, timeout)
529 }
530
531 /// `getauxval(AT_SECURE)`—Returns the Linux “secure execution” mode.
532 ///
533 /// Return a boolean value indicating whether “secure execution” mode was
534 /// requested, due to the process having elevated privileges. This includes
535 /// whether the `AT_SECURE` AUX value is set, and whether the initial real UID
536 /// and GID differ from the initial effective UID and GID.
537 ///
538 /// The meaning of “secure execution” mode is beyond the scope of this
539 /// comment.
540 ///
541 /// # References
542 /// - [Linux]
543 ///
544 /// [Linux]: https://man7.org/linux/man-pages/man3/getauxval.3.html
545 #[cfg(any(
546 linux_raw,
547 any(
548 all(target_os = "android", target_pointer_width = "64"),
549 target_os = "linux",
550 )
551 ))]
552 #[inline]
553 pub fn linux_secure() -> bool {
554 backend::param::auxv::linux_secure()
555 }
556
557 /// `brk(addr)`—Change the location of the “program break”.
558 ///
559 /// # Safety
560 ///
561 /// This is not identical to `brk` in libc. libc `brk` may have bookkeeping
562 /// that needs to be kept up to date that this doesn't keep up to date, so
563 /// don't use it unless you are implementing libc.
564 #[cfg(linux_raw)]
565 #[inline]
566 pub unsafe fn brk(addr: *mut c_void) -> io::Result<*mut c_void> {
567 backend::runtime::syscalls::brk(addr)
568 }
569
570 /// `__SIGRTMIN`—The start of the realtime signal range.
571 ///
572 /// This is the raw `SIGRTMIN` value from the OS, which is not the same as the
573 /// `SIGRTMIN` macro provided by libc. Don't use this unless you are
574 /// implementing libc.
575 #[cfg(linux_raw)]
576 pub const SIGRTMIN: u32 = linux_raw_sys::general::SIGRTMIN;
577
578 /// `__SIGRTMAX`—The last of the realtime signal range.
579 ///
580 /// This is the raw `SIGRTMAX` value from the OS, which is not the same as the
581 /// `SIGRTMAX` macro provided by libc. Don't use this unless you are
582 /// implementing libc.
583 #[cfg(linux_raw)]
584 pub const SIGRTMAX: u32 = {
585 // Use the actual `SIGRTMAX` value on platforms which define it.
586 #[cfg(not(any(
587 target_arch = "arm",
588 target_arch = "s390x",
589 target_arch = "x86",
590 target_arch = "x86_64",
591 )))]
592 {
593 linux_raw_sys::general::SIGRTMAX
594 }
595
596 // On platforms that don't, derive it from `_NSIG`.
597 #[cfg(any(
598 target_arch = "arm",
599 target_arch = "s390x",
600 target_arch = "x86",
601 target_arch = "x86_64",
602 ))]
603 {
604 linux_raw_sys::general::_NSIG - 1
605 }
606 };