Skip to main content

libc_rs/
process.rs

1//! Process lifecycle, credentials, signals, resource limits, and wait syscalls.
2
3use core::mem::size_of;
4
5use crate::errno::SysResult;
6use crate::raw::{nr, syscall0, syscall1, syscall2, syscall3, syscall4, syscall5};
7use crate::time::Timeval;
8
9/// Hangup detected on controlling terminal or death of controlling process.
10pub const SIGHUP: i32 = 1;
11/// Interrupt from keyboard (`Ctrl-C`).
12pub const SIGINT: i32 = 2;
13/// Quit from keyboard.
14pub const SIGQUIT: i32 = 3;
15/// Illegal instruction.
16pub const SIGILL: i32 = 4;
17/// Abort signal.
18pub const SIGABRT: i32 = 6;
19/// Bus error (bad memory access).
20pub const SIGBUS: i32 = 7;
21/// Floating-point exception.
22pub const SIGFPE: i32 = 8;
23/// Kill signal (cannot be caught or ignored).
24pub const SIGKILL: i32 = 9;
25/// Invalid memory reference (segmentation fault).
26pub const SIGSEGV: i32 = 11;
27/// Broken pipe: write to pipe with no readers.
28pub const SIGPIPE: i32 = 13;
29/// Timer signal from `alarm`.
30pub const SIGALRM: i32 = 14;
31/// Termination signal.
32pub const SIGTERM: i32 = 15;
33/// Child stopped or terminated.
34pub const SIGCHLD: i32 = 17;
35
36/// Do not receive notification when child processes stop.
37pub const SA_NOCLDSTOP: usize = 1;
38/// Do not transform children into zombies when they terminate.
39pub const SA_NOCLDWAIT: usize = 2;
40/// Invoke signal-catching function with three arguments instead of one.
41pub const SA_SIGINFO: usize = 4;
42/// Signal trampoline restorer flag.
43pub const SA_RESTORER: usize = 0x0400_0000;
44/// Call the signal handler on an alternate signal stack.
45pub const SA_ONSTACK: usize = 0x0800_0000;
46/// Restart syscalls if interrupted by this signal handler.
47pub const SA_RESTART: usize = 0x1000_0000;
48/// Do not prevent the signal from being received from within its own handler.
49pub const SA_NODEFER: usize = 0x4000_0000;
50/// Restore the signal action to the default upon entry to the signal handler.
51pub const SA_RESETHAND: usize = 0x8000_0000;
52
53/// Default signal disposition.
54pub const SIG_DFL: usize = 0;
55/// Ignore signal disposition.
56pub const SIG_IGN: usize = 1;
57
58/// Return immediately if no child has exited.
59pub const WNOHANG: i32 = 1;
60/// Also return if a child has stopped.
61pub const WUNTRACED: i32 = 2;
62
63/// CPU time limit in seconds.
64pub const RLIMIT_CPU: u32 = 0;
65/// Maximum size of the process stack in bytes.
66pub const RLIMIT_STACK: u32 = 3;
67/// Value one greater than the maximum file descriptor number that can be opened.
68pub const RLIMIT_NOFILE: u32 = 7;
69/// Unlimited resource limit value.
70pub const RLIM_INFINITY: u64 = u64::MAX;
71
72/// Return resource usage for the calling process.
73pub const RUSAGE_SELF: i32 = 0;
74/// Return resource usage for terminated and waited-for children.
75pub const RUSAGE_CHILDREN: i32 = -1;
76
77/// Size in bytes of the kernel signal mask (`sigset_t` = 64 bits = 8 bytes).
78pub const KERNEL_SIGSET_BYTES: usize = 8;
79
80/// Returns `true` if wait status `s` indicates normal termination (`exit`).
81#[must_use]
82pub const fn wifexited(s: i32) -> bool {
83    (s & 0x7f) == 0
84}
85
86/// Extracts the low 8 bits of the exit code from a wait status `s`.
87#[must_use]
88pub const fn wexitstatus(s: i32) -> i32 {
89    (s >> 8) & 0xff
90}
91
92/// Extracts the terminating signal number from a wait status `s`.
93#[must_use]
94pub const fn wtermsig(s: i32) -> i32 {
95    s & 0x7f
96}
97
98/// 64-bit kernel signal set (`sigset_t`) for `rt_sigaction` and `rt_sigprocmask`.
99#[repr(C)]
100#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
101pub struct KernelSigSet {
102    pub bits: [u64; 1],
103}
104
105/// AArch64 kernel `struct sigaction` layout (32 bytes: `sa_handler`, `sa_flags`, `sa_restorer`, `sa_mask`).
106#[repr(C)]
107#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
108pub struct KernelSigAction {
109    pub sa_handler: usize,
110    pub sa_flags: usize,
111    pub sa_restorer: usize,
112    pub sa_mask: KernelSigSet,
113}
114
115/// Resource soft and hard limits (`struct rlimit`).
116#[repr(C)]
117#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
118pub struct Rlimit {
119    pub rlim_cur: u64,
120    pub rlim_max: u64,
121}
122
123/// Process resource usage statistics (`struct rusage`).
124#[repr(C)]
125#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
126pub struct Rusage {
127    pub ru_utime: Timeval,
128    pub ru_stime: Timeval,
129    pub ru_maxrss: i64,
130    pub ru_ixrss: i64,
131    pub ru_idrss: i64,
132    pub ru_isrss: i64,
133    pub ru_minflt: i64,
134    pub ru_majflt: i64,
135    pub ru_nswap: i64,
136    pub ru_inblock: i64,
137    pub ru_oublock: i64,
138    pub ru_msgsnd: i64,
139    pub ru_msgrcv: i64,
140    pub ru_nsignals: i64,
141    pub ru_nvcsw: i64,
142    pub ru_nivcsw: i64,
143}
144
145const _: () = {
146    assert!(size_of::<KernelSigSet>() == KERNEL_SIGSET_BYTES);
147    assert!(size_of::<KernelSigAction>() == 32);
148    assert!(size_of::<Rlimit>() == 16);
149    assert!(size_of::<Rusage>() == 144);
150};
151
152/// Terminates the calling thread with exit status `code`.
153pub fn exit_thread(code: i32) -> ! {
154    // SAFETY: `EXIT` terminates the current thread and does not access memory.
155    let _ = unsafe { syscall1(nr::EXIT, code as usize) };
156    abort()
157}
158
159/// Terminates all threads in the calling process with exit status `code`.
160pub fn exit_group(code: i32) -> ! {
161    // SAFETY: `EXIT_GROUP` terminates the process and does not access memory.
162    let _ = unsafe { syscall1(nr::EXIT_GROUP, code as usize) };
163    abort()
164}
165
166/// Immediately traps/aborts execution without unwinding.
167pub fn abort() -> ! {
168    let _ = kill(getpid(), SIGABRT);
169    // SAFETY: `EXIT_GROUP` terminates all threads in the calling process.
170    let _ = unsafe { syscall1(nr::EXIT_GROUP, 134) };
171    crate::raw::trap_abort()
172}
173
174/// Returns the process ID (`PID`) of the calling process.
175#[must_use]
176pub fn getpid() -> i32 {
177    // SAFETY: `GETPID` has no memory side effects.
178    unsafe { syscall0(nr::GETPID).unwrap_or(0) as i32 }
179}
180
181/// Returns the caller's thread ID (`TID`).
182#[must_use]
183pub fn gettid() -> i32 {
184    // SAFETY: `GETTID` has no memory side effects.
185    unsafe { syscall0(nr::GETTID).unwrap_or(0) as i32 }
186}
187
188/// Returns the real user ID of the calling process.
189#[must_use]
190pub fn getuid() -> u32 {
191    // SAFETY: `GETUID` has no memory side effects.
192    unsafe { syscall0(nr::GETUID).unwrap_or(0) as u32 }
193}
194
195/// Returns the effective user ID of the calling process.
196#[must_use]
197pub fn geteuid() -> u32 {
198    // SAFETY: `GETEUID` has no memory side effects.
199    unsafe { syscall0(nr::GETEUID).unwrap_or(0) as u32 }
200}
201
202/// Returns the real group ID of the calling process.
203#[must_use]
204pub fn getgid() -> u32 {
205    // SAFETY: `GETGID` has no memory side effects.
206    unsafe { syscall0(nr::GETGID).unwrap_or(0) as u32 }
207}
208
209/// Returns the effective group ID of the calling process.
210#[must_use]
211pub fn getegid() -> u32 {
212    // SAFETY: `GETEGID` has no memory side effects.
213    unsafe { syscall0(nr::GETEGID).unwrap_or(0) as u32 }
214}
215
216/// Sets the process group ID (`pgid`) of the process specified by `pid`.
217pub fn setpgid(pid: i32, pgid: i32) -> SysResult<()> {
218    // SAFETY: `SETPGID` takes two scalar PID arguments.
219    unsafe {
220        syscall2(nr::SETPGID, pid as usize, pgid as usize)?;
221    }
222    Ok(())
223}
224
225/// Creates a session and sets the process group ID.
226pub fn setsid() -> SysResult<i32> {
227    // SAFETY: `SETSID` takes no arguments.
228    unsafe { syscall0(nr::SETSID).map(|v| v as i32) }
229}
230
231/// Sets the calling process's file mode creation mask (`umask`) and returns the previous mask.
232pub fn umask(mask: u32) -> u32 {
233    // SAFETY: `UMASK` takes a scalar mode mask and always succeeds.
234    unsafe { syscall1(nr::UMASK, mask as usize).unwrap_or(0) as u32 }
235}
236
237/// Gets resource limits for `resource`.
238pub fn getrlimit(resource: u32) -> SysResult<Rlimit> {
239    let mut rlim = Rlimit::default();
240    // SAFETY: `rlim` is a valid stack `Rlimit` for the kernel to write into.
241    unsafe {
242        syscall2(
243            nr::GETRLIMIT,
244            resource as usize,
245            core::ptr::from_mut(&mut rlim) as usize,
246        )?;
247    }
248    Ok(rlim)
249}
250
251/// Sets resource limits for `resource` to `rlim`.
252pub fn setrlimit(resource: u32, rlim: &Rlimit) -> SysResult<()> {
253    // SAFETY: `rlim` is a valid shared reference to an `Rlimit`.
254    unsafe {
255        syscall2(
256            nr::SETRLIMIT,
257            resource as usize,
258            core::ptr::from_ref(rlim) as usize,
259        )?;
260    }
261    Ok(())
262}
263
264/// Gets resource usage measures for `who` (`RUSAGE_SELF` or `RUSAGE_CHILDREN`).
265pub fn getrusage(who: i32) -> SysResult<Rusage> {
266    let mut usage = Rusage::default();
267    // SAFETY: `usage` is a valid stack `Rusage` for the kernel to populate.
268    unsafe {
269        syscall2(
270            nr::GETRUSAGE,
271            who as usize,
272            core::ptr::from_mut(&mut usage) as usize,
273        )?;
274    }
275    Ok(usage)
276}
277
278/// Yields the processor to the scheduler.
279pub fn sched_yield() {
280    // SAFETY: `SCHED_YIELD` has no memory arguments or unsafe invariants.
281    let _ = unsafe { syscall0(nr::SCHED_YIELD) };
282}
283
284/// Sends signal `sig` to `pid`.
285pub fn kill(pid: i32, sig: i32) -> SysResult<()> {
286    // SAFETY: `KILL` takes scalar `pid` and `sig` arguments.
287    unsafe {
288        syscall2(nr::KILL, pid as usize, sig as usize)?;
289    }
290    Ok(())
291}
292
293/// Examines and changes a signal action using raw pointers.
294///
295/// # Safety
296///
297/// `act` must be null or point to a valid kernel `sigaction` of matching `sigsetsize`;
298/// `oldact` must be null or point to writable memory for a kernel `sigaction`.
299pub unsafe fn rt_sigaction_raw(
300    signum: i32,
301    act: *const u8,
302    oldact: *mut u8,
303    sigsetsize: usize,
304) -> SysResult<()> {
305    // SAFETY: Caller guarantees `act`, `oldact`, and `sigsetsize` are valid.
306    unsafe {
307        syscall4(
308            nr::RT_SIGACTION,
309            signum as usize,
310            act as usize,
311            oldact as usize,
312            sigsetsize,
313        )?;
314    }
315    Ok(())
316}
317
318/// Examines and changes a signal action using typed [`KernelSigAction`] structures.
319///
320/// # Safety
321///
322/// If `act` installs a signal handler function address (`sa_handler` not `SIG_DFL` or `SIG_IGN`),
323/// that address must be a valid, async-signal-safe `extern "C"` handler following the target ABI.
324pub unsafe fn sigaction(
325    signum: i32,
326    act: Option<&KernelSigAction>,
327    oldact: Option<&mut KernelSigAction>,
328) -> SysResult<()> {
329    let effective: KernelSigAction;
330    let act_ptr = match act {
331        Some(a) => {
332            let mut tmp = *a;
333            if tmp.sa_handler > SIG_IGN && tmp.sa_restorer == 0 {
334                tmp.sa_flags |= SA_RESTORER;
335                #[cfg(all(target_arch = "aarch64", target_os = "none"))]
336                {
337                    tmp.sa_restorer = crate::raw::default_sigrestorer as *const () as usize;
338                }
339                #[cfg(not(all(target_arch = "aarch64", target_os = "none")))]
340                {
341                    tmp.sa_restorer = 1;
342                }
343            }
344            effective = tmp;
345            core::ptr::from_ref(&effective).cast::<u8>()
346        }
347        None => core::ptr::null(),
348    };
349    let old_ptr = oldact.map_or(core::ptr::null_mut(), |o| {
350        core::ptr::from_mut(o).cast::<u8>()
351    });
352    // SAFETY: `act_ptr` and `old_ptr` are derived from valid `KernelSigAction` references
353    // with `KERNEL_SIGSET_BYTES == 8`, and caller guarantees handler safety.
354    unsafe { rt_sigaction_raw(signum, act_ptr, old_ptr, KERNEL_SIGSET_BYTES) }
355}
356
357/// Creates a child process via `clone(SIGCHLD, 0, 0, 0, 0)`.
358pub fn fork() -> SysResult<i32> {
359    // SAFETY: `clone` with `flags = SIGCHLD` and zero `sp` duplicates the current process
360    // identically to `fork()`.
361    unsafe { syscall5(nr::CLONE, SIGCHLD as usize, 0, 0, 0, 0).map(|v| v as i32) }
362}
363
364/// Executes the program pointed to by `prog` with argument and environment pointer arrays.
365///
366/// # Safety
367///
368/// `prog` must be a valid NUL-terminated C string, and `argv` / `envp` must be valid
369/// null-terminated arrays of NUL-terminated C string pointers.
370pub unsafe fn execve_raw(
371    prog: *const u8,
372    argv: *const *const u8,
373    envp: *const *const u8,
374) -> SysResult<()> {
375    // SAFETY: Caller guarantees `prog`, `argv`, and `envp` are valid C string tables.
376    unsafe {
377        syscall3(nr::EXECVE, prog as usize, argv as usize, envp as usize)?;
378    }
379    Ok(())
380}
381
382/// Waits for state changes in a child process via `wait4(pid, status, options, null)` with an
383/// optional status out-pointer.
384pub fn waitpid_opt(pid: i32, status: Option<&mut i32>, options: i32) -> SysResult<i32> {
385    let status_ptr = status.map_or(0, |s| core::ptr::from_mut(s) as usize);
386    // SAFETY: `status_ptr` is either null (0) or a valid mutable `i32` reference, and `rusage` is null (0).
387    unsafe { syscall4(nr::WAIT4, pid as usize, status_ptr, options as usize, 0).map(|v| v as i32) }
388}
389
390/// Waits for state changes in a child process via `wait4(pid, status, options, null)`.
391pub fn waitpid(pid: i32, status: &mut i32, options: i32) -> SysResult<i32> {
392    waitpid_opt(pid, Some(status), options)
393}
394
395#[cfg(test)]
396mod tests {
397    use super::*;
398    use crate::raw::with_mock_syscall;
399
400    #[test]
401    fn fork_invokes_clone_with_sigchld_and_wait_macros_decode_status() {
402        let child_pid = with_mock_syscall(
403            |sysno, args| {
404                assert_eq!(sysno, nr::CLONE);
405                assert_eq!(args[0], SIGCHLD as usize);
406                assert_eq!(args[1], 0);
407                assert_eq!(args[2], 0);
408                assert_eq!(args[3], 0);
409                assert_eq!(args[4], 0);
410                Ok(1234)
411            },
412            || fork().unwrap(),
413        );
414        assert_eq!(child_pid, 1234);
415
416        let status_exit_7 = 7 << 8;
417        assert!(wifexited(status_exit_7));
418        assert_eq!(wexitstatus(status_exit_7), 7);
419        assert_eq!(wtermsig(status_exit_7), 0);
420
421        let status_sig_9 = SIGKILL;
422        assert!(!wifexited(status_sig_9));
423        assert_eq!(wtermsig(status_sig_9), SIGKILL);
424    }
425
426    #[test]
427    fn kernel_sigaction_layout_restorer_and_waitpid_opt() {
428        assert_eq!(size_of::<KernelSigAction>(), 32);
429
430        let act = KernelSigAction {
431            sa_handler: 0x1234,
432            sa_flags: SA_RESTART,
433            sa_restorer: 0,
434            sa_mask: KernelSigSet::default(),
435        };
436        with_mock_syscall(
437            |sysno, args| {
438                assert_eq!(sysno, nr::RT_SIGACTION);
439                assert_eq!(args[0], SIGTERM as usize);
440                assert_eq!(args[3], KERNEL_SIGSET_BYTES);
441                let passed = unsafe { &*(args[1] as *const KernelSigAction) };
442                assert_ne!(passed.sa_flags & SA_RESTORER, 0);
443                assert_ne!(passed.sa_restorer, 0);
444                Ok(0)
445            },
446            || unsafe { sigaction(SIGTERM, Some(&act), None).unwrap() },
447        );
448
449        let waited = with_mock_syscall(
450            |sysno, args| {
451                assert_eq!(sysno, nr::WAIT4);
452                assert_eq!(args[0], 42);
453                assert_eq!(args[1], 0);
454                assert_eq!(args[2], 0);
455                assert_eq!(args[3], 0);
456                Ok(42)
457            },
458            || waitpid_opt(42, None, 0).unwrap(),
459        );
460        assert_eq!(waited, 42);
461    }
462}