Debian Codegraph @

debian/missing-sources/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. Such functions
9 //! are not marked `unsafe` (unless they are unsafe for other reasons), even
10 //! though they invoke Undefined Behavior if called in a process which has a
11 //! libc present.
12 //!
13 //! - Some of the functions in this module don't behave exactly the same way
14 //! as functions in libc with similar names. Sometimes information about the
15 //! differences is included in the Linux documentation under “C
16 //! library/kernel differences” sections. But not always.
17 //!
18 //! - The safety requirements of the functions in this module are not fully
19 //! documented.
20 //!
21 //! - The API for these functions is not considered stable, and this module is
22 //! `doc(hidden)`.
23 //!
24 //! ⚠ Caution is indicated. ⚠
25 //!
26 //! These functions are for implementing thread-local storage (TLS), managing
27 //! threads, loaded libraries, and other process-wide resources. Most of
28 //! `rustix` doesn't care about what other libraries are linked into the
29 //! program or what they're doing, but the features in this module generally
30 //! can only be used by one entity within a process.
31 //!
32 //! All that said, there are some functions in this module would could
33 //! potentially be stabilized and moved to other modules. See also the
34 //! documentation for specific functions in the [`not_implemented`] module, and
35 //! the discussion in [#1314].
36 //!
37 //! [Origin]: https://github.com/sunfishcode/origin#readme
38 //! [`not_implemented`]: crate::not_implemented
39 //! [#1314]: https://github.com/bytecodealliance/rustix/issues/1314
40 //!
41 //! # Safety
42 //!
43 //! This module is intended to be used for implementing a runtime library such
44 //! as libc. Use of these features for any other purpose is likely to create
45 //! serious problems.
46 #![allow(unsafe_code)]
47
48 use crate::ffi::CStr;
49 #[cfg(feature = "fs")]
50 use crate::fs::AtFlags;
51 use crate::pid::Pid;
52 use crate::{backend, io};
53 #[cfg(feature = "fs")]
54 use backend::fd::AsFd;
55 use core::ffi::c_void;
56
57 pub use crate::kernel_sigset::KernelSigSet;
58 pub use crate::signal::Signal;
59
60 /// `kernel_sigaction`
61 ///
62 /// On some architectures, the `sa_restorer` field is omitted.
63 ///
64 /// This type does not have the same layout as `libc::sigaction`.
65 #[allow(missing_docs)]
66 #[derive(Debug, Default, Clone)]
67 #[repr(C)]
68 pub struct KernelSigaction {
69 pub sa_handler_kernel: KernelSighandler,
70 pub sa_flags: KernelSigactionFlags,
71 #[cfg(not(any(
72 target_arch = "csky",
73 target_arch = "loongarch64",
74 target_arch = "mips",
75 target_arch = "mips32r6",
76 target_arch = "mips64",
77 target_arch = "mips64r6",
78 target_arch = "riscv32",
79 target_arch = "riscv64"
80 )))]
81 pub sa_restorer: KernelSigrestore,
82 pub sa_mask: KernelSigSet,
83 }
84
85 bitflags::bitflags! {
86 /// Flags for use with [`KernelSigaction`].
87 ///
88 /// This type does not have the same layout as `sa_flags` field in
89 /// `libc::sigaction`, however the flags have the same values as their
90 /// libc counterparts.
91 #[repr(transparent)]
92 #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug, Default)]
93 pub struct KernelSigactionFlags: crate::ffi::c_ulong {
94 /// `SA_NOCLDSTOP`
95 const NOCLDSTOP = linux_raw_sys::general::SA_NOCLDSTOP as _;
96
97 /// `SA_NOCLDWAIT` (since Linux 2.6)
98 const NOCLDWAIT = linux_raw_sys::general::SA_NOCLDWAIT as _;
99
100 /// `SA_NODEFER`
101 const NODEFER = linux_raw_sys::general::SA_NODEFER as _;
102
103 /// `SA_ONSTACK`
104 const ONSTACK = linux_raw_sys::general::SA_ONSTACK as _;
105
106 /// `SA_RESETHAND`
107 const RESETHAND = linux_raw_sys::general::SA_RESETHAND as _;
108
109 /// `SA_RESTART`
110 const RESTART = linux_raw_sys::general::SA_RESTART as _;
111
112 /// `SA_RESTORER`
113 #[cfg(not(any(
114 target_arch = "csky",
115 target_arch = "loongarch64",
116 target_arch = "mips",
117 target_arch = "mips32r6",
118 target_arch = "mips64",
119 target_arch = "mips64r6",
120 target_arch = "riscv32",
121 target_arch = "riscv64"
122 )))]
123 const RESTORER = linux_raw_sys::general::SA_RESTORER as _;
124
125 /// `SA_SIGINFO` (since Linux 2.2)
126 const SIGINFO = linux_raw_sys::general::SA_SIGINFO as _;
127
128 /// `SA_UNSUPPORTED` (since Linux 5.11)
129 const UNSUPPORTED = linux_raw_sys::general::SA_UNSUPPORTED as _;
130
131 /// `SA_EXPOSE_TAGBITS` (since Linux 5.11)
132 const EXPOSE_TAGBITS = linux_raw_sys::general::SA_EXPOSE_TAGBITS as _;
133
134 /// <https://docs.rs/bitflags/*/bitflags/#externally-defined-flags>
135 const _ = !0;
136 }
137 }
138
139 /// `__sigrestore_t`
140 ///
141 /// This type differs from `libc::sigrestore_t`, but can be transmuted to it.
142 pub type KernelSigrestore = Option<unsafe extern "C" fn()>;
143
144 /// `__kernel_sighandler_t`
145 ///
146 /// This type differs from `libc::sighandler_t`, but can be transmuted to it.
147 pub type KernelSighandler = Option<unsafe extern "C" fn(arg1: crate::ffi::c_int)>;
148
149 /// Return a special “ignore” signal handler for ignoring signals.
150 ///
151 /// This isn't the `SIG_IGN` value itself; it's a function that returns the
152 /// `SIG_IGN` value.
153 ///
154 /// If you're looking for `kernel_sig_dfl`; use [`KERNEL_SIG_DFL`].
155 #[doc(alias = "SIG_IGN")]
156 #[must_use]
157 pub const fn kernel_sig_ign() -> KernelSighandler {
158 linux_raw_sys::signal_macros::sig_ign()
159 }
160
161 /// A special “default” signal handler representing the default behavior
162 /// for handling a signal.
163 ///
164 /// If you're looking for `KERNEL_SIG_IGN`; use [`kernel_sig_ign`].
165 #[doc(alias = "SIG_DFL")]
166 pub const KERNEL_SIG_DFL: KernelSighandler = linux_raw_sys::signal_macros::SIG_DFL;
167
168 /// `stack_t`
169 ///
170 /// This type is guaranteed to have the same layout as `libc::stack_t`.
171 ///
172 /// If we want to expose this in public APIs, we should encapsulate the
173 /// `linux_raw_sys` type.
174 pub use linux_raw_sys::general::stack_t as Stack;
175
176 /// `siginfo_t`
177 ///
178 /// This type is guaranteed to have the same layout as `libc::siginfo_t`.
179 ///
180 /// If we want to expose this in public APIs, we should encapsulate the
181 /// `linux_raw_sys` type.
182 pub use linux_raw_sys::general::siginfo_t as Siginfo;
183
184 pub use crate::timespec::{Nsecs, Secs, Timespec};
185
186 /// `SIG_*` constants for use with [`kernel_sigprocmask`].
187 #[repr(u32)]
188 pub enum How {
189 /// `SIG_BLOCK`
190 BLOCK = linux_raw_sys::general::SIG_BLOCK,
191
192 /// `SIG_UNBLOCK`
193 UNBLOCK = linux_raw_sys::general::SIG_UNBLOCK,
194
195 /// `SIG_SETMASK`
196 SETMASK = linux_raw_sys::general::SIG_SETMASK,
197 }
198
199 #[cfg(target_arch = "x86")]
200 #[inline]
201 pub unsafe fn set_thread_area(u_info: &mut UserDesc) -> io::Result<()> {
202 backend::runtime::syscalls::tls::set_thread_area(u_info)
203 }
204
205 #[cfg(target_arch = "arm")]
206 #[inline]
207 pub unsafe fn arm_set_tls(data: *mut c_void) -> io::Result<()> {
208 backend::runtime::syscalls::tls::arm_set_tls(data)
209 }
210
211 /// `prctl(PR_SET_FS, data)`—Set the x86-64 `fs` register.
212 ///
213 /// # Safety
214 ///
215 /// This is a very low-level feature for implementing threading libraries.
216 /// See the references links above.
217 #[cfg(target_arch = "x86_64")]
218 #[inline]
219 pub unsafe fn set_fs(data: *mut c_void) {
220 backend::runtime::syscalls::tls::set_fs(data)
221 }
222
223 /// Set the x86-64 thread ID address.
224 ///
225 /// # Safety
226 ///
227 /// This is a very low-level feature for implementing threading libraries.
228 /// See the references links above.
229 #[inline]
230 pub unsafe fn set_tid_address(data: *mut c_void) -> Pid {
231 backend::runtime::syscalls::tls::set_tid_address(data)
232 }
233
234 #[cfg(target_arch = "x86")]
235 pub use backend::runtime::tls::UserDesc;
236
237 /// `syscall(SYS_exit, status)`—Exit the current thread.
238 ///
239 /// # Safety
240 ///
241 /// This is a very low-level feature for implementing threading libraries.
242 #[inline]
243 pub unsafe fn exit_thread(status: i32) -> ! {
244 backend::runtime::syscalls::tls::exit_thread(status)
245 }
246
247 /// Exit all the threads in the current process' thread group.
248 ///
249 /// This is equivalent to `_exit` and `_Exit` in libc.
250 ///
251 /// This does not call any `__cxa_atexit`, `atexit`, or any other destructors.
252 /// Most programs should use [`std::process::exit`] instead of calling this
253 /// directly.
254 ///
255 /// # References
256 /// - [POSIX `_Exit`]
257 /// - [Linux `exit_group`]
258 /// - [Linux `_Exit`]
259 ///
260 /// [POSIX `_Exit`]: https://pubs.opengroup.org/onlinepubs/9799919799/functions/_Exit.html
261 /// [Linux `exit_group`]: https://man7.org/linux/man-pages/man2/exit_group.2.html
262 /// [Linux `_Exit`]: https://man7.org/linux/man-pages/man2/_Exit.2.html
263 #[doc(alias = "_exit", alias = "_Exit")]
264 #[inline]
265 pub fn exit_group(status: i32) -> ! {
266 backend::runtime::syscalls::exit_group(status)
267 }
268
269 /// `EXIT_SUCCESS` for use with [`exit_group`].
270 ///
271 /// # References
272 /// - [POSIX]
273 /// - [Linux]
274 ///
275 /// [POSIX]: https://pubs.opengroup.org/onlinepubs/9799919799/basedefs/stdlib.h.html
276 /// [Linux]: https://man7.org/linux/man-pages/man3/exit.3.html
277 pub const EXIT_SUCCESS: i32 = backend::c::EXIT_SUCCESS;
278
279 /// `EXIT_FAILURE` for use with [`exit_group`].
280 ///
281 /// # References
282 /// - [POSIX]
283 /// - [Linux]
284 ///
285 /// [POSIX]: https://pubs.opengroup.org/onlinepubs/9799919799/basedefs/stdlib.h.html
286 /// [Linux]: https://man7.org/linux/man-pages/man3/exit.3.html
287 pub const EXIT_FAILURE: i32 = backend::c::EXIT_FAILURE;
288
289 /// `(getauxval(AT_PHDR), getauxval(AT_PHENT), getauxval(AT_PHNUM))`—Returns
290 /// the address, ELF segment header size, and number of ELF segment headers for
291 /// the main executable.
292 ///
293 /// # References
294 /// - [Linux]
295 ///
296 /// [Linux]: https://man7.org/linux/man-pages/man3/getauxval.3.html
297 #[inline]
298 pub fn exe_phdrs() -> (*const c_void, usize, usize) {
299 backend::param::auxv::exe_phdrs()
300 }
301
302 /// `getauxval(AT_ENTRY)`—Returns the address of the program entrypoint.
303 ///
304 /// Most code interested in the program entrypoint address should instead use a
305 /// symbol reference to `_start`. That will be properly PC-relative or
306 /// relocated if needed, and will come with appropriate pointer type and
307 /// pointer provenance.
308 ///
309 /// This function is intended only for use in code that implements those
310 /// relocations, to compute the ASLR offset. It has type `usize`, so it doesn't
311 /// carry any provenance, and it shouldn't be used to dereference memory.
312 ///
313 /// # References
314 /// - [Linux]
315 ///
316 /// [Linux]: https://man7.org/linux/man-pages/man3/getauxval.3.html
317 #[inline]
318 pub fn entry() -> usize {
319 backend::param::auxv::entry()
320 }
321
322 /// `getauxval(AT_RANDOM)`—Returns the address of 16 pseudorandom bytes.
323 ///
324 /// These bytes are for use by libc. For anything else, use the `rand` crate.
325 ///
326 /// # References
327 /// - [Linux]
328 ///
329 /// [Linux]: https://man7.org/linux/man-pages/man3/getauxval.3.html
330 #[inline]
331 pub fn random() -> *const [u8; 16] {
332 backend::param::auxv::random()
333 }
334
335 /// `fork()`—Creates a new process by duplicating the calling process.
336 ///
337 /// On success, `Fork::ParentOf` containing the pid of the child process is
338 /// returned in the parent, and `Fork::Child` containing the pid of the child
339 /// process is returned in the child.
340 ///
341 /// Unlike its POSIX and libc counterparts, this `fork` does not invoke any
342 /// handlers (such as those registered with `pthread_atfork`).
343 ///
344 /// The program environment in the child after a `fork` and before an `execve`
345 /// is very special. All code that executes in this environment must avoid:
346 ///
347 /// - Acquiring any other locks that are held in other threads on the parent
348 /// at the time of the `fork`, as the child only contains one thread, and
349 /// attempting to acquire such locks will deadlock (though this is [not
350 /// considered unsafe]).
351 ///
352 /// - Performing any dynamic allocation using the global allocator, since
353 /// global allocators may use locks to ensure thread safety, and their locks
354 /// may not be released in the child process, so attempts to allocate may
355 /// deadlock (as described in the previous point).
356 ///
357 /// - Accessing any external state which the parent assumes it has exclusive
358 /// access to, such as a file protected by a file lock, as this could
359 /// corrupt the external state.
360 ///
361 /// - Accessing any random-number-generator state inherited from the parent,
362 /// as the parent may have the same state and generate the same random
363 /// numbers, which may violate security invariants.
364 ///
365 /// - Accessing any thread runtime state, since this function does not update
366 /// the thread id in the thread runtime, so thread runtime functions could
367 /// cause undefined behavior.
368 ///
369 /// - Accessing any memory shared with the parent, such as a [`MAP_SHARED`]
370 /// mapping, even with anonymous or [`memfd_create`] mappings, as this could
371 /// cause undefined behavior.
372 ///
373 /// - Calling any C function which isn't known to be [async-signal-safe], as
374 /// that could cause undefined behavior. The extent to which this also
375 /// applies to Rust functions is unclear at this time.
376 ///
377 /// - And more.
378 ///
379 /// # Safety
380 ///
381 /// The child must avoid accessing any memory shared with the parent in a
382 /// way that invokes undefined behavior. It must avoid accessing any threading
383 /// runtime functions in a way that invokes undefined behavior. And it must
384 /// avoid invoking any undefined behavior through any function that is not
385 /// guaranteed to be async-signal-safe. But, what does async-signal-safe even
386 /// mean in a Rust program? This documentation does not have all the answers.
387 ///
388 /// So you're on your own. And on top of all the troubles with `fork` in
389 /// general, this wrapper implementation is highly experimental.
390 ///
391 /// # References
392 /// - [POSIX]
393 /// - [Linux]
394 ///
395 /// # Literary interlude
396 ///
397 /// > Do not jump on ancient uncles.
398 /// > Do not yell at average mice.
399 /// > Do not wear a broom to breakfast.
400 /// > Do not ask a snake’s advice.
401 /// > Do not bathe in chocolate pudding.
402 /// > Do not talk to bearded bears.
403 /// > Do not smoke cigars on sofas.
404 /// > Do not dance on velvet chairs.
405 /// > Do not take a whale to visit
406 /// > Russell’s mother’s cousin’s yacht.
407 /// > And whatever else you do do
408 /// > It is better you
409 /// > Do not.
410 ///
411 /// — “Rules”, by Karla Kuskin
412 ///
413 /// [`MAP_SHARED`]: https://pubs.opengroup.org/onlinepubs/9799919799/functions/mmap.html
414 /// [not considered unsafe]: https://doc.rust-lang.org/reference/behavior-not-considered-unsafe.html#deadlocks
415 /// [`memfd_create`]: https://man7.org/linux/man-pages/man2/memfd_create.2.html
416 /// [POSIX]: https://pubs.opengroup.org/onlinepubs/9799919799/functions/fork.html
417 /// [Linux]: https://man7.org/linux/man-pages/man2/fork.2.html
418 /// [async-signal-safe]: https://pubs.opengroup.org/onlinepubs/9799919799/functions/V2_chap02.html#tag_15_04_03
419 pub unsafe fn kernel_fork() -> io::Result<Fork> {
420 backend::runtime::syscalls::kernel_fork()
421 }
422
423 /// Regular Unix `fork` doesn't tell the child its own PID because it assumes
424 /// the child can just do `getpid`. That's true, but it's more fun if it
425 /// doesn't have to.
426 pub enum Fork {
427 /// This is returned in the child process after a `fork`. It holds the PID
428 /// of the child.
429 Child(Pid),
430
431 /// This is returned in the parent process after a `fork`. It holds the PID
432 /// of the child.
433 ParentOf(Pid),
434 }
435
436 /// `execveat(dirfd, path.as_c_str(), argv, envp, flags)`—Execute a new
437 /// command using the current process.
438 ///
439 /// Taking raw-pointers-to-raw-pointers is convenient for c-scape, but we
440 /// should think about potentially a more Rust-idiomatic API if this is ever
441 /// made public.
442 ///
443 /// # Safety
444 ///
445 /// The `argv` and `envp` pointers must point to NUL-terminated arrays, and
446 /// their contents must be pointers to NUL-terminated byte arrays.
447 ///
448 /// # References
449 /// - [Linux]
450 ///
451 /// [Linux]: https://man7.org/linux/man-pages/man2/execveat.2.html
452 #[inline]
453 #[cfg(feature = "fs")]
454 #[cfg_attr(docsrs, doc(cfg(feature = "fs")))]
455 #[must_use]
456 pub unsafe fn execveat<Fd: AsFd>(
457 dirfd: Fd,
458 path: &CStr,
459 argv: *const *const u8,
460 envp: *const *const u8,
461 flags: AtFlags,
462 ) -> io::Errno {
463 backend::runtime::syscalls::execveat(dirfd.as_fd(), path, argv, envp, flags)
464 }
465
466 /// `execve(path.as_c_str(), argv, envp)`—Execute a new command using the
467 /// current process.
468 ///
469 /// Taking raw-pointers-to-raw-pointers is convenient for c-scape, but we
470 /// should think about potentially a more Rust-idiomatic API if this is ever
471 /// made public.
472 ///
473 /// # Safety
474 ///
475 /// The `argv` and `envp` pointers must point to NUL-terminated arrays, and
476 /// their contents must be pointers to NUL-terminated byte arrays.
477 ///
478 /// # References
479 /// - [Linux]
480 ///
481 /// [Linux]: https://man7.org/linux/man-pages/man2/execve.2.html
482 #[inline]
483 #[must_use]
484 pub unsafe fn execve(path: &CStr, argv: *const *const u8, envp: *const *const u8) -> io::Errno {
485 backend::runtime::syscalls::execve(path, argv, envp)
486 }
487
488 /// `sigaction(signal, &new, &old)`—Modify and/or query a signal handler.
489 ///
490 /// # Safety
491 ///
492 /// You're on your own. And on top of all the troubles with signal handlers,
493 /// this implementation is highly experimental. Even further, it differs from
494 /// the libc `sigaction` in several non-obvious and unsafe ways.
495 ///
496 /// # References
497 /// - [POSIX]
498 /// - [Linux]
499 ///
500 /// [POSIX]: https://pubs.opengroup.org/onlinepubs/9799919799/functions/sigaction.html
501 /// [Linux]: https://man7.org/linux/man-pages/man2/sigaction.2.html
502 #[inline]
503 pub unsafe fn kernel_sigaction(
504 signal: Signal,
505 new: Option<KernelSigaction>,
506 ) -> io::Result<KernelSigaction> {
507 backend::runtime::syscalls::kernel_sigaction(signal, new)
508 }
509
510 /// `sigaltstack(new, old)`—Modify and/or query a signal stack.
511 ///
512 /// # Safety
513 ///
514 /// The memory region described by `new` must readable and writable and larger
515 /// than the platform minimum signal stack size, and must have a guard region
516 /// that conforms to the platform conventions for stack guard regions. The
517 /// flags in `new` must be valid. This function does not diagnose all the
518 /// errors that libc `sigaltstack` functions are documented as diagnosing.
519 ///
520 /// While the memory region pointed to by `new` is registered as a signal
521 /// stack, it must remain readable and writable, and must not be mutated in
522 /// any way other than by having a signal handler run in it, and must not be
523 /// the referent of a Rust reference from outside the signal handler.
524 ///
525 /// If code elsewhere in the program is depending on signal handlers being run
526 /// on a particular stack, this could break that code's assumptions. And if the
527 /// caller is depending on signal handlers being run on the stack specified in
528 /// the call, its assumptions could be broken by code elsewhere in the program
529 /// calling this function.
530 ///
531 /// There are probably things out there that assume that all alternate signal
532 /// stack registration goes through libc, and this does not go through libc.
533 ///
534 /// There may be further safety hazards not yet documented here.
535 ///
536 /// # References
537 /// - [POSIX]
538 /// - [Linux]
539 ///
540 /// [POSIX]: https://pubs.opengroup.org/onlinepubs/9799919799/functions/sigaltstack.html
541 /// [Linux]: https://man7.org/linux/man-pages/man2/sigaltstack.2.html
542 #[inline]
543 pub unsafe fn kernel_sigaltstack(new: Option<Stack>) -> io::Result<Stack> {
544 backend::runtime::syscalls::kernel_sigaltstack(new)
545 }
546
547 /// `tkill(tid, sig)`—Send a signal to a thread.
548 ///
549 /// # Safety
550 ///
551 /// Causing an individual thread to abruptly terminate without involving the
552 /// process' thread runtime (such as the libpthread or the libc) evokes
553 /// undefined behavior.
554 ///
555 /// Also, this is not `tgkill`, so the warning about the hazard of recycled
556 /// thread IDs applies.
557 ///
558 /// There may be further safety hazards not yet documented here.
559 ///
560 /// # References
561 /// - [Linux]
562 ///
563 /// [Linux]: https://man7.org/linux/man-pages/man2/tkill.2.html
564 #[inline]
565 pub unsafe fn tkill(tid: Pid, sig: Signal) -> io::Result<()> {
566 backend::runtime::syscalls::tkill(tid, sig)
567 }
568
569 /// `rt_sigprocmask(how, set, oldset)`—Adjust the process signal mask.
570 ///
571 /// If this is ever exposed publicly, we should think about whether it should
572 /// mask out signals reserved by libc.
573 ///
574 /// # Safety
575 ///
576 /// If there is a libc in the process, the `set` must not contain any signal
577 /// reserved by the libc.
578 ///
579 /// If code elsewhere in the program is depending on delivery of a signal for
580 /// any reason, for example to prevent it from executing some code, this could
581 /// cause it to miss that signal, and for example execute that code. And if the
582 /// caller is depending on delivery of a signal for any reason, its assumptions
583 /// could be broken by code elsewhere in the program calling this function.
584 ///
585 /// There may be further safety hazards not yet documented here.
586 ///
587 /// # References
588 /// - [Linux `rt_sigprocmask`]
589 /// - [Linux `pthread_sigmask`]
590 ///
591 /// [Linux `rt_sigprocmask`]: https://man7.org/linux/man-pages/man2/rt_sigprocmask.2.html
592 /// [Linux `pthread_sigmask`]: https://man7.org/linux/man-pages/man3/pthread_sigmask.3.html
593 #[inline]
594 #[doc(alias = "pthread_sigmask")]
595 #[doc(alias = "rt_sigprocmask")]
596 pub unsafe fn kernel_sigprocmask(how: How, set: Option<&KernelSigSet>) -> io::Result<KernelSigSet> {
597 backend::runtime::syscalls::kernel_sigprocmask(how, set)
598 }
599
600 /// `sigpending()`—Query the pending signals.
601 ///
602 /// If this is ever exposed publicly, we should think about whether it should
603 /// mask out signals reserved by libc.
604 ///
605 /// # References
606 /// - [Linux `sigpending`]
607 ///
608 /// [Linux `sigpending`]: https://man7.org/linux/man-pages/man2/sigpending.2.html
609 #[inline]
610 pub fn kernel_sigpending() -> KernelSigSet {
611 backend::runtime::syscalls::kernel_sigpending()
612 }
613
614 /// `sigsuspend(set)`—Suspend the calling thread and wait for signals.
615 ///
616 /// If this is ever exposed publicly, we should think about whether it should
617 /// be made to fail if given signals reserved by libc.
618 ///
619 /// # References
620 /// - [Linux `sigsuspend`]
621 ///
622 /// [Linux `sigsuspend`]: https://man7.org/linux/man-pages/man2/sigsuspend.2.html
623 #[inline]
624 pub fn kernel_sigsuspend(set: &KernelSigSet) -> io::Result<()> {
625 backend::runtime::syscalls::kernel_sigsuspend(set)
626 }
627
628 /// `sigwait(set)`—Wait for signals.
629 ///
630 /// If this is ever exposed publicly, we should think about whether it should
631 /// mask out signals reserved by libc.
632 ///
633 /// # Safety
634 ///
635 /// If there is a libc in the process, the `set` must not contain any signal
636 /// reserved by the libc.
637 ///
638 /// If code elsewhere in the program is depending on delivery of a signal for
639 /// any reason, for example to prevent it from executing some code, this could
640 /// cause it to miss that signal, and for example execute that code. And if the
641 /// caller is depending on delivery of a signal for any reason, its assumptions
642 /// could be broken by code elsewhere in the program calling this function.
643 ///
644 /// There may be further safety hazards not yet documented here.
645 ///
646 /// # References
647 /// - [Linux]
648 ///
649 /// [Linux]: https://man7.org/linux/man-pages/man3/sigwait.3.html
650 #[inline]
651 pub unsafe fn kernel_sigwait(set: &KernelSigSet) -> io::Result<Signal> {
652 backend::runtime::syscalls::kernel_sigwait(set)
653 }
654
655 /// `sigwaitinfo(set)`—Wait for signals, returning a [`Siginfo`].
656 ///
657 /// If this is ever exposed publicly, we should think about whether it should
658 /// mask out signals reserved by libc.
659 ///
660 /// # Safety
661 ///
662 /// If there is a libc in the process, the `set` must not contain any signal
663 /// reserved by the libc.
664 ///
665 /// If code elsewhere in the program is depending on delivery of a signal for
666 /// any reason, for example to prevent it from executing some code, this could
667 /// cause it to miss that signal, and for example execute that code. And if the
668 /// caller is depending on delivery of a signal for any reason, its assumptions
669 /// could be broken by code elsewhere in the program calling this function.
670 ///
671 /// There may be further safety hazards not yet documented here.
672 ///
673 /// # References
674 /// - [Linux]
675 ///
676 /// [Linux]: https://man7.org/linux/man-pages/man2/sigwaitinfo.2.html
677 #[inline]
678 pub unsafe fn kernel_sigwaitinfo(set: &KernelSigSet) -> io::Result<Siginfo> {
679 backend::runtime::syscalls::kernel_sigwaitinfo(set)
680 }
681
682 /// `sigtimedwait(set)`—Wait for signals, optionally with a timeout.
683 ///
684 /// If this is ever exposed publicly, we should think about whether it should
685 /// mask out signals reserved by libc.
686 ///
687 /// # Safety
688 ///
689 /// If there is a libc in the process, the `set` must not contain any signal
690 /// reserved by the libc.
691 ///
692 /// If code elsewhere in the program is depending on delivery of a signal for
693 /// any reason, for example to prevent it from executing some code, this could
694 /// cause it to miss that signal, and for example execute that code. And if the
695 /// caller is depending on delivery of a signal for any reason, its assumptions
696 /// could be broken by code elsewhere in the program calling this function.
697 ///
698 /// There may be further safety hazards not yet documented here.
699 ///
700 /// # References
701 /// - [Linux]
702 ///
703 /// [Linux]: https://man7.org/linux/man-pages/man2/sigtimedwait.2.html
704 #[inline]
705 pub unsafe fn kernel_sigtimedwait(
706 set: &KernelSigSet,
707 timeout: Option<&Timespec>,
708 ) -> io::Result<Siginfo> {
709 backend::runtime::syscalls::kernel_sigtimedwait(set, timeout)
710 }
711
712 /// `getauxval(AT_SECURE)`—Returns the Linux “secure execution” mode.
713 ///
714 /// Return a boolean value indicating whether “secure execution” mode was
715 /// requested, due to the process having elevated privileges. This includes
716 /// whether the `AT_SECURE` AUX value is set, and whether the initial real UID
717 /// and GID differ from the initial effective UID and GID.
718 ///
719 /// The meaning of “secure execution” mode is beyond the scope of this
720 /// comment.
721 ///
722 /// # References
723 /// - [Linux]
724 ///
725 /// [Linux]: https://man7.org/linux/man-pages/man3/getauxval.3.html
726 #[inline]
727 pub fn linux_secure() -> bool {
728 backend::param::auxv::linux_secure()
729 }
730
731 /// `brk(addr)`—Change the location of the “program break”.
732 ///
733 /// # Safety
734 ///
735 /// This is not identical to `brk` in libc. libc `brk` may have bookkeeping
736 /// that needs to be kept up to date that this doesn't keep up to date, so
737 /// don't use it unless you know your code won't share a process with a libc
738 /// (perhaps because you yourself are implementing a libc).
739 #[inline]
740 pub unsafe fn kernel_brk(addr: *mut c_void) -> io::Result<*mut c_void> {
741 backend::runtime::syscalls::kernel_brk(addr)
742 }
743
744 /// `SIGRTMIN`—The start of the raw OS “real-time” signal range.
745 ///
746 /// This is the raw `SIGRTMIN` value from the OS, which is not the same as the
747 /// `SIGRTMIN` macro provided by libc. Don't use this unless you know your code
748 /// won't share a process with a libc (perhaps because you yourself are
749 /// implementing a libc).
750 pub const KERNEL_SIGRTMIN: i32 = linux_raw_sys::general::SIGRTMIN as i32;
751
752 /// `SIGRTMAX`—The last of the raw OS “real-time” signal range.
753 ///
754 /// This is the raw `SIGRTMAX` value from the OS, which is not the same as the
755 /// `SIGRTMAX` macro provided by libc. Don't use this unless you know your code
756 /// won't share a process with a libc (perhaps because you yourself are
757 /// implementing a libc).
758 pub const KERNEL_SIGRTMAX: i32 = {
759 // Use the actual `SIGRTMAX` value on platforms which define it.
760 #[cfg(not(any(
761 target_arch = "arm",
762 target_arch = "s390x",
763 target_arch = "x86",
764 target_arch = "x86_64",
765 )))]
766 {
767 linux_raw_sys::general::SIGRTMAX as i32
768 }
769
770 // On platforms that don't, derive it from `_NSIG`.
771 //
772 // In the Linux kernel headers, `_NSIG` refers to the number of signals
773 // known to the kernel. It's 64 on most architectures.
774 //
775 // In libc headers, `_NSIG` refers to the exclusive upper bound of the
776 // signals known to the kernel. It's 65 on most architectures.
777 //
778 // This discrepancy arises because a signal value of 0 is used as a
779 // sentinel, and the first `sigset_t` bit is signal 1 instead of 0. The
780 // Linux kernel headers and libc headers disagree on the interpretation of
781 // `_NSIG` as a result.
782 //
783 // Here, we use the Linux kernel header value.
784 #[cfg(any(
785 target_arch = "arm",
786 target_arch = "s390x",
787 target_arch = "x86",
788 target_arch = "x86_64",
789 ))]
790 {
791 linux_raw_sys::general::_NSIG as i32
792 }
793 };
794
795 #[cfg(test)]
796 mod tests {
797 use super::*;
798
799 #[test]
800 fn test_assumptions() {
801 assert!(libc::SIGSYS < KERNEL_SIGRTMIN);
802 assert!(KERNEL_SIGRTMIN <= libc::SIGRTMIN());
803
804 // POSIX guarantees at least 8 RT signals.
805 assert!(libc::SIGRTMIN() + 8 <= KERNEL_SIGRTMAX);
806
807 // POSIX guarantees at least 8 RT signals, and it's not uncommon for
808 // libc implementations to reserve up to 3 for their own purposes.
809 assert!(KERNEL_SIGRTMIN + 8 + 3 <= KERNEL_SIGRTMAX);
810
811 assert!(KERNEL_SIGRTMAX <= libc::SIGRTMAX());
812 assert!(libc::SIGRTMAX() as u32 <= linux_raw_sys::general::_NSIG);
813
814 assert!(KERNEL_SIGRTMAX as usize - 1 < core::mem::size_of::<KernelSigSet>() * 8);
815 }
816
817 #[test]
818 fn test_layouts_matching_libc() {
819 use linux_raw_sys::general::siginfo__bindgen_ty_1__bindgen_ty_1;
820
821 // c-scape assumes rustix's `Siginfo` matches libc's. We don't use
822 // check_types macros because we want to test compatibility with actual
823 // libc, not the `crate::backend::c` which might be our own
824 // implementation.
825 assert_eq_size!(Siginfo, libc::siginfo_t);
826 assert_eq_align!(Siginfo, libc::siginfo_t);
827 assert_eq!(
828 memoffset::span_of!(Siginfo, ..),
829 memoffset::span_of!(Siginfo, __bindgen_anon_1)
830 );
831 assert_eq!(
832 memoffset::span_of!(siginfo__bindgen_ty_1__bindgen_ty_1, si_signo),
833 memoffset::span_of!(libc::siginfo_t, si_signo)
834 );
835 assert_eq!(
836 memoffset::span_of!(siginfo__bindgen_ty_1__bindgen_ty_1, si_errno),
837 memoffset::span_of!(libc::siginfo_t, si_errno)
838 );
839 assert_eq!(
840 memoffset::span_of!(siginfo__bindgen_ty_1__bindgen_ty_1, si_code),
841 memoffset::span_of!(libc::siginfo_t, si_code)
842 );
843
844 // c-scape assumes rustix's `Stack` matches libc's. Similar to above.
845 assert_eq_size!(Stack, libc::stack_t);
846 assert_eq_align!(Stack, libc::stack_t);
847 assert_eq!(
848 memoffset::span_of!(Stack, ss_sp),
849 memoffset::span_of!(libc::stack_t, ss_sp)
850 );
851 assert_eq!(
852 memoffset::span_of!(Stack, ss_flags),
853 memoffset::span_of!(libc::stack_t, ss_flags)
854 );
855 assert_eq!(
856 memoffset::span_of!(Stack, ss_size),
857 memoffset::span_of!(libc::stack_t, ss_size)
858 );
859 }
860
861 #[test]
862 fn test_layouts_matching_kernel() {
863 use linux_raw_sys::general as c;
864
865 // Rustix's versions of these must match the kernel's versions.
866 // Some architectures have `sa_restorer`.
867 #[cfg(not(any(
868 target_arch = "csky",
869 target_arch = "loongarch64",
870 target_arch = "mips",
871 target_arch = "mips32r6",
872 target_arch = "mips64",
873 target_arch = "mips64r6",
874 target_arch = "riscv32",
875 target_arch = "riscv64"
876 )))]
877 check_renamed_struct!(
878 KernelSigaction,
879 kernel_sigaction,
880 sa_handler_kernel,
881 sa_flags,
882 sa_restorer,
883 sa_mask
884 );
885 // Some architectures omit `sa_restorer`.
886 #[cfg(any(
887 target_arch = "csky",
888 target_arch = "loongarch64",
889 target_arch = "mips",
890 target_arch = "mips32r6",
891 target_arch = "mips64",
892 target_arch = "mips64r6",
893 target_arch = "riscv32",
894 target_arch = "riscv64"
895 ))]
896 check_renamed_struct!(
897 KernelSigaction,
898 kernel_sigaction,
899 sa_handler_kernel,
900 sa_flags,
901 sa_mask
902 );
903 assert_eq_size!(KernelSigactionFlags, crate::ffi::c_ulong);
904 assert_eq_align!(KernelSigactionFlags, crate::ffi::c_ulong);
905 check_renamed_type!(KernelSigrestore, __sigrestore_t);
906 check_renamed_type!(KernelSighandler, __kernel_sighandler_t);
907
908 assert_eq!(
909 libc::SA_NOCLDSTOP,
910 KernelSigactionFlags::NOCLDSTOP.bits() as _
911 );
912 assert_eq!(
913 libc::SA_NOCLDWAIT,
914 KernelSigactionFlags::NOCLDWAIT.bits() as _
915 );
916 assert_eq!(libc::SA_NODEFER, KernelSigactionFlags::NODEFER.bits() as _);
917 assert_eq!(libc::SA_ONSTACK, KernelSigactionFlags::ONSTACK.bits() as _);
918 assert_eq!(
919 libc::SA_RESETHAND,
920 KernelSigactionFlags::RESETHAND.bits() as _
921 );
922 assert_eq!(libc::SA_RESTART, KernelSigactionFlags::RESTART.bits() as _);
923 assert_eq!(libc::SA_SIGINFO, KernelSigactionFlags::SIGINFO.bits() as _);
924 }
925 }