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    #[cfg(all(target_arch = "aarch64", target_os = "none"))]
169    // SAFETY: `brk #0` triggers an immediate hardware trap in EL0.
170    unsafe {
171        core::arch::asm!("brk #0", options(noreturn, nostack, nomem));
172    }
173    #[cfg(not(all(target_arch = "aarch64", target_os = "none")))]
174    loop {
175        core::hint::spin_loop();
176    }
177}
178
179/// Returns the process ID (`PID`) of the calling process.
180#[must_use]
181pub fn getpid() -> i32 {
182    // SAFETY: `GETPID` has no memory side effects.
183    unsafe { syscall0(nr::GETPID).unwrap_or(0) as i32 }
184}
185
186/// Returns the caller's thread ID (`TID`).
187#[must_use]
188pub fn gettid() -> i32 {
189    // SAFETY: `GETTID` has no memory side effects.
190    unsafe { syscall0(nr::GETTID).unwrap_or(0) as i32 }
191}
192
193/// Returns the real user ID of the calling process.
194#[must_use]
195pub fn getuid() -> u32 {
196    // SAFETY: `GETUID` has no memory side effects.
197    unsafe { syscall0(nr::GETUID).unwrap_or(0) as u32 }
198}
199
200/// Returns the effective user ID of the calling process.
201#[must_use]
202pub fn geteuid() -> u32 {
203    // SAFETY: `GETEUID` has no memory side effects.
204    unsafe { syscall0(nr::GETEUID).unwrap_or(0) as u32 }
205}
206
207/// Returns the real group ID of the calling process.
208#[must_use]
209pub fn getgid() -> u32 {
210    // SAFETY: `GETGID` has no memory side effects.
211    unsafe { syscall0(nr::GETGID).unwrap_or(0) as u32 }
212}
213
214/// Returns the effective group ID of the calling process.
215#[must_use]
216pub fn getegid() -> u32 {
217    // SAFETY: `GETEGID` has no memory side effects.
218    unsafe { syscall0(nr::GETEGID).unwrap_or(0) as u32 }
219}
220
221/// Sets the process group ID (`pgid`) of the process specified by `pid`.
222pub fn setpgid(pid: i32, pgid: i32) -> SysResult<()> {
223    // SAFETY: `SETPGID` takes two scalar PID arguments.
224    unsafe {
225        syscall2(nr::SETPGID, pid as usize, pgid as usize)?;
226    }
227    Ok(())
228}
229
230/// Creates a session and sets the process group ID.
231pub fn setsid() -> SysResult<i32> {
232    // SAFETY: `SETSID` takes no arguments.
233    unsafe { syscall0(nr::SETSID).map(|v| v as i32) }
234}
235
236/// Sets the calling process's file mode creation mask (`umask`) and returns the previous mask.
237pub fn umask(mask: u32) -> u32 {
238    // SAFETY: `UMASK` takes a scalar mode mask and always succeeds.
239    unsafe { syscall1(nr::UMASK, mask as usize).unwrap_or(0) as u32 }
240}
241
242/// Gets resource limits for `resource`.
243pub fn getrlimit(resource: u32) -> SysResult<Rlimit> {
244    let mut rlim = Rlimit::default();
245    // SAFETY: `rlim` is a valid stack `Rlimit` for the kernel to write into.
246    unsafe {
247        syscall2(
248            nr::GETRLIMIT,
249            resource as usize,
250            core::ptr::from_mut(&mut rlim) as usize,
251        )?;
252    }
253    Ok(rlim)
254}
255
256/// Sets resource limits for `resource` to `rlim`.
257pub fn setrlimit(resource: u32, rlim: &Rlimit) -> SysResult<()> {
258    // SAFETY: `rlim` is a valid shared reference to an `Rlimit`.
259    unsafe {
260        syscall2(
261            nr::SETRLIMIT,
262            resource as usize,
263            core::ptr::from_ref(rlim) as usize,
264        )?;
265    }
266    Ok(())
267}
268
269/// Gets resource usage measures for `who` (`RUSAGE_SELF` or `RUSAGE_CHILDREN`).
270pub fn getrusage(who: i32) -> SysResult<Rusage> {
271    let mut usage = Rusage::default();
272    // SAFETY: `usage` is a valid stack `Rusage` for the kernel to populate.
273    unsafe {
274        syscall2(
275            nr::GETRUSAGE,
276            who as usize,
277            core::ptr::from_mut(&mut usage) as usize,
278        )?;
279    }
280    Ok(usage)
281}
282
283/// Yields the processor to the scheduler.
284pub fn sched_yield() {
285    // SAFETY: `SCHED_YIELD` has no memory arguments or unsafe invariants.
286    let _ = unsafe { syscall0(nr::SCHED_YIELD) };
287}
288
289/// Sends signal `sig` to `pid`.
290pub fn kill(pid: i32, sig: i32) -> SysResult<()> {
291    // SAFETY: `KILL` takes scalar `pid` and `sig` arguments.
292    unsafe {
293        syscall2(nr::KILL, pid as usize, sig as usize)?;
294    }
295    Ok(())
296}
297
298/// Examines and changes a signal action using raw pointers.
299///
300/// # Safety
301///
302/// `act` must be null or point to a valid kernel `sigaction` of matching `sigsetsize`;
303/// `oldact` must be null or point to writable memory for a kernel `sigaction`.
304pub unsafe fn rt_sigaction_raw(
305    signum: i32,
306    act: *const u8,
307    oldact: *mut u8,
308    sigsetsize: usize,
309) -> SysResult<()> {
310    // SAFETY: Caller guarantees `act`, `oldact`, and `sigsetsize` are valid.
311    unsafe {
312        syscall4(
313            nr::RT_SIGACTION,
314            signum as usize,
315            act as usize,
316            oldact as usize,
317            sigsetsize,
318        )?;
319    }
320    Ok(())
321}
322
323#[cfg(all(target_arch = "aarch64", target_os = "none"))]
324#[unsafe(naked)]
325unsafe extern "C" fn default_sigrestorer() -> ! {
326    core::arch::naked_asm!(
327        "mov x8, #{nr_sigreturn}",
328        "svc #0",
329        "brk #0",
330        nr_sigreturn = const nr::RT_SIGRETURN,
331    );
332}
333
334/// Examines and changes a signal action using typed [`KernelSigAction`] structures.
335///
336/// # Safety
337///
338/// If `act` installs a signal handler function address (`sa_handler` not `SIG_DFL` or `SIG_IGN`),
339/// that address must be a valid, async-signal-safe `extern "C"` handler following the target ABI.
340pub unsafe fn sigaction(
341    signum: i32,
342    act: Option<&KernelSigAction>,
343    oldact: Option<&mut KernelSigAction>,
344) -> SysResult<()> {
345    let effective: KernelSigAction;
346    let act_ptr = match act {
347        Some(a) => {
348            let mut tmp = *a;
349            if tmp.sa_handler > SIG_IGN && tmp.sa_restorer == 0 {
350                tmp.sa_flags |= SA_RESTORER;
351                #[cfg(all(target_arch = "aarch64", target_os = "none"))]
352                {
353                    tmp.sa_restorer = default_sigrestorer as *const () as usize;
354                }
355                #[cfg(not(all(target_arch = "aarch64", target_os = "none")))]
356                {
357                    tmp.sa_restorer = 1;
358                }
359            }
360            effective = tmp;
361            core::ptr::from_ref(&effective).cast::<u8>()
362        }
363        None => core::ptr::null(),
364    };
365    let old_ptr = oldact.map_or(core::ptr::null_mut(), |o| {
366        core::ptr::from_mut(o).cast::<u8>()
367    });
368    // SAFETY: `act_ptr` and `old_ptr` are derived from valid `KernelSigAction` references
369    // with `KERNEL_SIGSET_BYTES == 8`, and caller guarantees handler safety.
370    unsafe { rt_sigaction_raw(signum, act_ptr, old_ptr, KERNEL_SIGSET_BYTES) }
371}
372
373/// Creates a child process via `clone(SIGCHLD, 0, 0, 0, 0)`.
374pub fn fork() -> SysResult<i32> {
375    // SAFETY: `clone` with `flags = SIGCHLD` and zero `sp` duplicates the current process
376    // identically to `fork()`.
377    unsafe { syscall5(nr::CLONE, SIGCHLD as usize, 0, 0, 0, 0).map(|v| v as i32) }
378}
379
380/// Executes the program pointed to by `prog` with argument and environment pointer arrays.
381///
382/// # Safety
383///
384/// `prog` must be a valid NUL-terminated C string, and `argv` / `envp` must be valid
385/// null-terminated arrays of NUL-terminated C string pointers.
386pub unsafe fn execve_raw(
387    prog: *const u8,
388    argv: *const *const u8,
389    envp: *const *const u8,
390) -> SysResult<()> {
391    // SAFETY: Caller guarantees `prog`, `argv`, and `envp` are valid C string tables.
392    unsafe {
393        syscall3(nr::EXECVE, prog as usize, argv as usize, envp as usize)?;
394    }
395    Ok(())
396}
397
398/// Waits for state changes in a child process via `wait4(pid, status, options, null)` with an
399/// optional status out-pointer.
400pub fn waitpid_opt(pid: i32, status: Option<&mut i32>, options: i32) -> SysResult<i32> {
401    let status_ptr = status.map_or(0, |s| core::ptr::from_mut(s) as usize);
402    // SAFETY: `status_ptr` is either null (0) or a valid mutable `i32` reference, and `rusage` is null (0).
403    unsafe { syscall4(nr::WAIT4, pid as usize, status_ptr, options as usize, 0).map(|v| v as i32) }
404}
405
406/// Waits for state changes in a child process via `wait4(pid, status, options, null)`.
407pub fn waitpid(pid: i32, status: &mut i32, options: i32) -> SysResult<i32> {
408    waitpid_opt(pid, Some(status), options)
409}
410
411#[cfg(test)]
412mod tests {
413    use super::*;
414    use crate::raw::with_mock_syscall;
415
416    #[test]
417    fn fork_invokes_clone_with_sigchld_and_wait_macros_decode_status() {
418        let child_pid = with_mock_syscall(
419            |sysno, args| {
420                assert_eq!(sysno, nr::CLONE);
421                assert_eq!(args[0], SIGCHLD as usize);
422                assert_eq!(args[1], 0);
423                assert_eq!(args[2], 0);
424                assert_eq!(args[3], 0);
425                assert_eq!(args[4], 0);
426                Ok(1234)
427            },
428            || fork().unwrap(),
429        );
430        assert_eq!(child_pid, 1234);
431
432        let status_exit_7 = 7 << 8;
433        assert!(wifexited(status_exit_7));
434        assert_eq!(wexitstatus(status_exit_7), 7);
435        assert_eq!(wtermsig(status_exit_7), 0);
436
437        let status_sig_9 = SIGKILL;
438        assert!(!wifexited(status_sig_9));
439        assert_eq!(wtermsig(status_sig_9), SIGKILL);
440    }
441
442    #[test]
443    fn kernel_sigaction_layout_restorer_and_waitpid_opt() {
444        assert_eq!(size_of::<KernelSigAction>(), 32);
445
446        let act = KernelSigAction {
447            sa_handler: 0x1234,
448            sa_flags: SA_RESTART,
449            sa_restorer: 0,
450            sa_mask: KernelSigSet::default(),
451        };
452        with_mock_syscall(
453            |sysno, args| {
454                assert_eq!(sysno, nr::RT_SIGACTION);
455                assert_eq!(args[0], SIGTERM as usize);
456                assert_eq!(args[3], KERNEL_SIGSET_BYTES);
457                let passed = unsafe { &*(args[1] as *const KernelSigAction) };
458                assert_ne!(passed.sa_flags & SA_RESTORER, 0);
459                assert_ne!(passed.sa_restorer, 0);
460                Ok(0)
461            },
462            || unsafe { sigaction(SIGTERM, Some(&act), None).unwrap() },
463        );
464
465        let waited = with_mock_syscall(
466            |sysno, args| {
467                assert_eq!(sysno, nr::WAIT4);
468                assert_eq!(args[0], 42);
469                assert_eq!(args[1], 0);
470                assert_eq!(args[2], 0);
471                assert_eq!(args[3], 0);
472                Ok(42)
473            },
474            || waitpid_opt(42, None, 0).unwrap(),
475        );
476        assert_eq!(waited, 42);
477    }
478}