Skip to main content

libc_rs/
process.rs

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